PHP Manual
PHP Manual。内容保持上游原样。
Appendices
About the manual
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. 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]
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, PHP 7)
strlen -- Get string length
Description
strlen ( string $string ) : int
Returns the length of given string.
Part
Description
strlen
The function name.
(PHP 4, PHP 5, PHP 7)
strlen() has been around in all versions of PHP 4, 5 and 7
( 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
int (i.e. the length of a string is measured in numbers).
Explanation of a function definition
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, ENTITY on success (if the
needle was found in the
haystack)ENTITY (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 have default values; if the default value is unknown, it is shown as
?. The manual states that the
strict parameter defaults to boolean ENTITY. See the manual page on each function for details on how they work.
In addition the ENTITY (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 = null,
int $flags = 0 , int $offset = 0 ) : int|false
In this example, we can see the third optional parameter
ENTITY$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, PHP 7)
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 7.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
7.3.1 as an example, the 7 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 ENTITY 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 several ways everyone can help improve this documentation.
If an error is found in this manual, in any language, please report them using the issue tracker of the respective language repository at ENTITY; for instance, errors in the English manual should be reported at ENTITYdoc-en/issues. All documentation related problems, including those about manual formats, should be submitted as bug reports.
[!NOTE]
Please don't abuse the issue trackers 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'.
It is also possible to submit pull requests to the Github mirror of the documentation repository.
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 ENTITY.
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 ENTITY for additional details. The XML source code may be downloaded from git and viewed at ENTITYdoc-en.
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 ENTITYdoc-en 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 . The mailing list address is
ENTITY. 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: ENTITY.
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.
Alias
Canonical function name
Extension used
_
gettext
Gettext
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
fputs
fwrite
Base syntax
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_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
ldap_close
ldap_unbind
LDAP
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
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
ociassignelem
OCICollection::assignElem
OCI8
ocibindbyname
oci_bind_by_name
OCI8
ocicancel
oci_cancel
OCI8
ocicloselob
OCILob::close
OCI8
ocicollappend
OCICollection::append
OCI8
ocicollassign
OCICollection::assign
OCI8
ocicollmax
OCICollection::max
OCI8
ocicollsize
OCICollection::size
OCI8
ocicolltrim
OCICollection::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
OCICollection::free
OCI8
ocifreecursor
oci_free_statement
OCI8
ocifreedesc
oci_free_descriptor
OCI8
ocifreestatement
oci_free_statement
OCI8
ocigetelem
OCICollection::getElem
OCI8
ociinternaldebug
oci_internal_debug
OCI8
ociloadlob
OCILob::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
OCILob::save
OCI8
ocisavelobfile
OCILob::import
OCI8
ociserverversion
oci_server_version
OCI8
ocisetprefetch
oci_set_prefetch
OCI8
ocistatementtype
oci_statement_type
OCI8
ociwritelobtofile
OCILob::export
OCI8
ociwritetemporarylob
OCILob::writeTemporary
OCI8
odbc_do
odbc_exec
ODBC
odbc_field_precision
odbc_field_len
ODBC
pg_clientencoding
pg_client_encoding
PostgreSQL
pg_setclientencoding
pg_set_client_encoding
PostgreSQL
pg_exec
pg_query
PostgreSQL
pos
current
Base syntax
recode
recode_string
Recode
show_source
highlight_file
Base syntax
sizeof
count
Base syntax
snmpwalkoid
snmprealwalk
SNMP
strchr
strstr
Base syntax
Aliases
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
int. ENTITY is a
bool 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 ENTITY, will have a result of ENTITY. (i.e.
NAN != NAN and
NAN !== NAN) Examples of operations that produce
NAN include
sqrt(-1),
asin(2), and
acosh(0).
Expression
gettype
empty
is_null
isset
bool :
if($x)
$x = "";
string
ENTITY
ENTITY
ENTITY
ENTITY
$x = null;
NULL
ENTITY
ENTITY
ENTITY
ENTITY
var $x;
NULL
ENTITY
ENTITY
ENTITY
ENTITY
$x is undefined
NULL
ENTITY
ENTITY
ENTITY
ENTITY
$x = [];
array
ENTITY
ENTITY
ENTITY
ENTITY
$x = ['a', 'b'];
array
ENTITY
ENTITY
ENTITY
ENTITY
$x = false;
bool
ENTITY
ENTITY
ENTITY
ENTITY
$x = true;
bool
ENTITY
ENTITY
ENTITY
ENTITY
$x = 1;
int
ENTITY
ENTITY
ENTITY
ENTITY
$x = 42;
int
ENTITY
ENTITY
ENTITY
ENTITY
$x = 0;
int
ENTITY
ENTITY
ENTITY
ENTITY
$x = -1;
int
ENTITY
ENTITY
ENTITY
ENTITY
$x = "1";
string
ENTITY
ENTITY
ENTITY
ENTITY
$x = "0";
string
ENTITY
ENTITY
ENTITY
ENTITY
$x = "-1";
string
ENTITY
ENTITY
ENTITY
ENTITY
$x = "php";
string
ENTITY
ENTITY
ENTITY
ENTITY
$x = "true";
string
ENTITY
ENTITY
ENTITY
ENTITY
$x = "false";
string
ENTITY
ENTITY
ENTITY
ENTITY
Comparisons of
$x with PHP functions
ENTITY
ENTITY
1
0
-1
"1"
"0"
"-1"
ENTITY
[]
"php"
""
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
1
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
0
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY*
ENTITY*
-1
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"1"
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"0"
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"-1"
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
[]
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"php"
ENTITY
ENTITY
ENTITY
ENTITY*
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
""
ENTITY
ENTITY
ENTITY
ENTITY*
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
Loose comparisons with
== {#types.comparisions-loose}
* ENTITY prior to PHP 8.0.0.
ENTITY
ENTITY
1
0
-1
"1"
"0"
"-1"
ENTITY
[]
"php"
""
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
1
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
0
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
-1
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"1"
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"0"
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"-1"
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
[]
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
"php"
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
""
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
Strict comparisons with
=== {#type.comparisons-strict}
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
ENTITY ENTITY ENTITY
misc
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. Note that if installing manpages under PREFIX (default), choose the GNU style in order for them to be found in the search path of
manpath utility.
--with-pear=DIR
Install PEAR in DIR (default PREFIX/lib/php).
--without-pear
Do not install PEAR.
--enable-zend-max-execution-timers
Use POSIX per-thread timers for max_execution_time tracking instead of the process-wide
setitimer(). These timers measure elapsed time (
CLOCK_BOOTTIME, or
CLOCK_MONOTONIC on FreeBSD), whereas the default
setitimer(ITIMER_PROF) measures CPU time, so time spent sleeping or waiting on I/O counts towards the limit. Requires
timer_create() support: available on Linux, and on FreeBSD as of PHP 8.4.0. Available since PHP 8.1.0. Enabled by default for ZTS builds since PHP 8.3.0.
--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-versioning
Export only required symbols. See INSTALL for more information.
php
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 ENTITY, defaults to
PREFIX/lib.
--disable-short-tags
Disable the short-form ENTITY? start tag by default.
--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.
--enable-zts
Enables thread safety. Prior to PHP 8.0.0 on non-Windows systems, the option was called
--enable-maintainer-zts.
servers
SAPI options
The following list contains the available SAPIENTITYs (
Server Application Programming Interface) for PHP.
--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.
--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.
--enable-embed[=TYPE]
Enable building of the embedded SAPI library. TYPE is either
shared or
static, which defaults to
shared.
--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.
--disable-cgi
Disable building CGI version of PHP.
This argument also enables FastCGI.
Debugging in PHP
About debugging in PHP
PHP is shipped with a basic command line interactive debugger, phpdbg.
Most IDEs have support for Xdebug, a free debug tool, which allows for single step debugging your PHP applications.
About manual examples
It should be noted that many examples in the PHP documentation omit error and exception handling for clarity and brevity.
This does not mean that error handling should be omitted for production code as it can lead to TypeErrors being thrown, failure values being coerced, such as ENTITY into an empty string, or assumptions being violated which might cause difficult to track bugs. Some extensions provide complete examples where error handling is included to demonstrate correct usage of the various functions and methods provided by the extension.
extensions
ENTITY
ENTITY
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
ENTITY
ENTITY
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
ENTITY
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
ENTITY
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
ENTITY
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
ENTITY
ENTITY
???
???
???
???
???
???
ENTITY
???
???
???
???
???
???
???
???
???
List of Available 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.
string.rot13
string.toupper
Use of this filter is equivalent to processing all stream data through the
strtoupper function.
string.toupper
string.tolower
Use of this filter is equivalent to processing all stream data through the
strtolower function.
string.tolower
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.
ENTITY
string.strip_tags
");
fwrite($fp, "bolded text enlarged to a
level 1 heading
\n");
fclose($fp);
/* Outputs: bolded text 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, "bolded text enlarged to a
level 1 heading
\n");
fclose($fp);
/* Outputs: bolded text 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.
convert.base64-encode ENTITY convert.base64-decode
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 function. 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.
convert.quoted-printable-encode ENTITY convert.quoted-printable-decode
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.ENTITYinput-encodingENTITY.ENTITYoutput-encodingENTITY or
convert.iconv.ENTITYinput-encodingENTITY/ENTITYoutput-encodingENTITY (both notations are semantically equivalent).
convert.iconv.*
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. The
zlib.deflate filter implements the compression methods
DEFLATE,
ZLIB and
GZIP depending on the value of the
window parameter. The 4 lower bits of the window parameter set the size of the internal “history buffer” used, being the base-2 logarithm of its size in a range from 8 up to 15. The meaning of the others bits of the window parameter can be set as described below.
DEFLATE (RFC 1951) is a raw compression algorithm without header, without checksum. It is performed when the window parameter is set in the range from -9 up to -15. This compression algorithm is the base for all the formats generated by the
zlib.deflate filter. The corresponding functions that operate directly on strings are
gzdeflate and
gzinflate.
ZLIB (RFC 1950) applies the
DEFLATE algorithm and adds a 2 bytes header and 4 bytes trailer containing the Adler32 checksum of the uncompressed data in big-endian byte order:
ZLIB = ZLIBHEADER(2B) DEFLATE ADLER32(4B) The 2 bytes header, read as 16 bit unsigned number in big-endian order, must be multiple of 31. This format is generated when the window parameter is set in the range from 8 up to 15. The corresponding functions that operate directly on strings are
gzcompress and
gzuncompress.
GZIP (RFC 1952) applies the
DEFLATE algorithm adding an header and a trailer with the
CRC32 checksum of the uncompressed data and their length, both in little-endian byte ordering:
GZIP = GZIPHEADER(10B) DEFLATE CRC32(4B) LENGTH(4B) This is the format of the
.gz files, with the
GZIPHEADER containing in the order the
GZIP signature (
\x1f\x8B), the compression method (
\x08), a zero flag byte, a zero modification time on 4 bytes, an extra-flags byte that depends on the compression level, and the operating system set to the current system (
\x00 = FAT filesystem,
\x03 = Unix, etc.). This format is generated when the window parameter is set in the range from 9+16=25 up to 15+16=31. Note that there is a limit of 4GB to the maximum length of the uncompressed data; beyond this limit, only the modulo 2^32 of the actual length is stored in the
LENGTH part. The corresponding functions that operate directly on strings are
gzencode and
gzdecode; the
gzopen function allows to read and write
.gz files.
With the
zlib.inflate filter, only the
window parameter is allowed; any other parameter (
memory,
level) is ignored. Be $W the base-2 log of the history buffer size, so that 2^$W bytes are allocated by the decompressor. For the ZLIB format this value must be greater or equal to the one recorded in the header, which is checked at decompression time; for the other formats it only has to be large enough for the match distances actually present in the data. The range is 9 ≤ $W ≤ 15. If unknown, $W=15 is the safer choice.
DEFLATE (RFC 1951): use window=-$W, with $W being a value not less than that used for compression. If unknown, set window=-15.
ZLIB (RFC 1950): use window=$W. The value of $W is available from the same ZLIB header, otherwise set window=15.
GZIP (RFC 1952): use window=$W+16. A GZIP header carries no window size, so set window=31 unless the value used for compression is known.
ZLIB or GZIP: use window=$W+32 for automatic header detection, so that both the formats can be recognized and decompressed; window=15+32=47 is the safer choice.
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 if zlib support is enabled.
zlib.deflate and
zlib.inflate
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.
*/
?>
zlib.deflate simple
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 ENTITY value, instructs the bzip library to perform decompression in a minimal memory footprint at the cost of speed.
bzip2.* compression filters are available if bz2 support is enabled.
bzip2.compress and
bzip2.decompress
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 file is 3288 bytes long.
The compressed file is 1488 bytes long.
*/
?>
Encryption Filters
Encryption filters are especially useful for file/stream encryption.
mcrypt.* and mdecrypt.*
ENTITY
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:
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
mcrypt filter parameters
Encrypt/Decrypt with Blowfish
'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;
?>
Encrypt file using AES-128 CBC with SHA256 HMAC
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']; }
}
History of PHP and Related Projects
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 PHP/FI Code
Hey, you are using Netscape!
Sorry, that record does not exist
Welcome !
You have credits left in your account.
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.
PHP 6
The plan for PHP 6 was to feature deep support for Unicode in the engine and language. This work was later abandoned, but other features that had been targeted for PHP 6 were instead incorporated into PHP 5.3 (namespaces) and PHP 5.4 (trait, "short" array syntax).
PHP 7
PHP 7.0 was released in 2015, and featured another major version of the core,
Zend Engine 3.0, which included significant performance improvements (up to twice as fast as PHP 5.6) and memory usage, consistent 64-bit support, improvements to exceptions, a secure random number generator, the null coalescing operator (??), anonymous classes, and other features.
Later releases of the PHP 7 series introduced more language features such as the short list syntax (7.1), object parameter and return type declaration (7.2), a new flexible heredoc and nowdoc syntax (7.3), typed properties (7.4), and a new foreign function interface (7.4).
PHP 8
First released in 2020, PHP 8.0 was another major update of the PHP language. It contained many new features and optimizations including named arguments, union types, attributes, constructor property promotion,
match expressions, the nullsafe operator (
?->), a new optimizing JIT compiler, and improvements in the type system, error handling, and consistency.
Later releases of the PHP 8 series introduced new language features including enumerations (8.1), fibers (8.1), readonly classes (8.2), Disjunctive Normal Form (DNF) Types (8.2), and typed class constants (8.3).
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!
Description of core ENTITY directives
This list includes the core ENTITY 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 ENTITY is not loaded; the values for the production and development ENTITY may vary.
Language Options
ENTITY
ENTITY
ENTITY
ENTITY
short_open_tag
"1"
INI_PERDIR
precision
"14"
INI_ALL
serialize_precision
"-1"
INI_ALL
Prior to PHP 7.1.0, the default value was 17.
disable_functions
""
INI_SYSTEM only
disable_classes
""
ENTITY only
Removed as of PHP 8.5.0
exit_on_timeout
""
INI_ALL
expose_php
"1"
ENTITY only
hard_timeout
"2"
INI_SYSTEM
Available as of PHP 7.1.0.
zend.exception_ignore_args
"0"
INI_ALL
Available as of PHP 7.4.0
zend.multibyte
"0"
INI_ALL
zend.script_encoding
NULL
INI_ALL
zend.detect_unicode
NULL
INI_ALL
zend.signal_check
"0"
INI_SYSTEM
zend.assertions
"1"
INI_ALL with restrictions
zend.exception_string_param_max_len
"15"
INI_ALL
Available as of PHP 8.0.0.
Language and Misc Configuration Options
ENTITY
short_open_tag
bool
Tells PHP whether the short form (
ENTITY? ?ENTITY) 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
ENTITY?xml ?ENTITY inline. Otherwise, you can print it with PHP, for example:
ENTITY?php echo 'ENTITY?xml version="1.0"?ENTITY'; ?ENTITY. Also, if disabled, you must use the long form of the PHP open tag (
ENTITY?php ?ENTITY).
[!NOTE]
This directive does not affect the shorthand
ENTITY?=, which is always available.
precision
int
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
int
The number of significant digits stored while serializing floating point numbers.
-1 means that an enhanced algorithm for rounding such numbers will be used.
expose_php
bool
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).
disable_functions
string
This directive allows certain functions to be disabled. It takes a comma-delimited list of function names. As of PHP 8.0.0, disabling a function removes its definition, allowing userland to redefine it. Prior to PHP 8.0.0, disabling a function just prevented the function from being invoked.
Only internal functions can be disabled using this directive. User-defined functions are unaffected.
This directive must be set in ENTITY. It cannot be set in ENTITY.
[!WARNING]
This directive can be circumvented and should not be considered a sufficient security measure for shared hosting environments.
disable_classes
string
This directive allows certain classes to be disabled. It takes a comma-delimited list of class names. Disabling a class just prevents the class's instantiation.
Only internal classes can be disabled using this directive. User-defined classes are unaffected.
This directive must be set in ENTITY. It cannot be set in ENTITY.
[!WARNING]
This directive can be circumvented and should not be considered a sufficient security measure for shared hosting environments.
ENTITY
zend.assertions
int
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.exception_string_param_max_len
int
The maximum length of string function arguments in stringified stack traces. Must range between
"0" and
"1000000".
hard_timeout
int
When the timeout set in max_execution_time has been hit, the PHP runtime will tear down resources gracefully. If something gets stuck while this happens, the hard timeout will tick for the set amount of seconds. When the hard timeout is hit, PHP will exit ungracefully. When set to 0, the hard timeout will never activate.
When PHP stops from a hard timeout, it will look something like this:
Fatal error: Maximum execution time of 30+2 seconds exceeded (terminated) in Unknown on line 0
zend.exception_ignore_args
bool
Excludes arguments from stack traces generated from exceptions.
zend.multibyte
bool
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_encoding to mbstring.internal_encoding, as if
mb_convert_encoding would have been called.
zend.detect_unicode
bool
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
bool
To check for replaced signal handlers on shutdown.
exit_on_timeout
bool
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
ENTITY
ENTITY
ENTITY
ENTITY
memory_limit
"128M"
INI_ALL
max_memory_limit
"-1"
INI_SYSTEM
Available as of PHP 8.5.0
memory_hard_limit_percent
ENTITY
INI_ALL
Available as of PHP 8.5.12, 8.4.27, 8.3.36 and 8.2.35
Resource Limits
ENTITY
memory_limit
int
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.
As of PHP 8.5.12, 8.4.27, 8.3.36 and 8.2.35, this is a soft limit: an allocation that crosses it is, in most cases, allowed to complete before the fatal error is raised, so the memory usage of a process may briefly exceed
memory_limit. A separate hard limit, controlled by memory_hard_limit_percent, bounds how far it may be exceeded.
ENTITY
max_memory_limit
int
Available as of PHP 8.5.0. This startup-only setting controls the maximum value that memory_limit may be configured to, either at startup or at runtime (e.g. via
ini_set). Setting memory_limit to a value exceeding
max_memory_limit results in a warning and the value being capped. Set to
-1 (the default) to impose no upper bound.
ENTITY
memory_hard_limit_percent
int
Available as of PHP 8.5.12, 8.4.27, 8.3.36 and 8.2.35. Sets a hard memory limit, expressed as a percentage of memory_limit. For example, with
memory_limit=128M and
memory_hard_limit_percent=150, the hard limit is
192M. Unlike memory_limit, the hard limit can never be exceeded.
[!WARNING]
This directive was introduced in the security releases of 21 October 2026, which fix two critical vulnerabilities (CVE-2026-109618, CVE-2026-109619) that can allow unauthenticated remote code execution, one of them triggered through out-of-memory handling. If this directive is not recognized, the PHP version in use is affected by these vulnerabilities and must be updated immediately. See the security advisory for details.
When an allocation exceeds memory_limit (the soft limit), the memory is still allocated, and the usual fatal error is raised once the engine reaches a safe point. Shutdown functions registered with
register_shutdown_function still run.
When an allocation would exceed the hard limit, the process is terminated immediately with exit status
137. A message is written directly to the standard error stream, looking something like this:
Hard memory limit of 201326592 bytes exhausted
The message does not go through the error handling mechanism, so it is not passed to error handlers or written to the error_log. No further PHP code runs: shutdown functions, destructors and output buffer handlers are all skipped.
The value must be
100 or greater, or
-1.
When unset (the default) or set to
-1, the hard limit is twice memory_limit if memory_limit is
1G or less, and memory_limit plus
1G otherwise. For example, with the default
memory_limit=128M, the hard limit is
256M, and with
memory_limit=4G it is
5G. If memory_limit is set to
-1, there is no hard limit either.
[!CAUTION]
A value of
100 makes the hard limit equal to memory_limit, which turns most out-of-memory conditions into an immediate termination of the process instead of a fatal error. Shutdown-time work such as logging, releasing locks or finishing a response will then never run on out-of-memory.
[!NOTE]
Because the process exits without producing output, in multi-request environments such as PHP-FPM the worker serving the request is terminated and the client receives no response from PHP; the process manager starts a replacement worker. Exit status
137 is also the status reported for a process killed by
SIGKILL, for example by the kernel OOM killer or a container runtime, so check the standard error stream to tell the cases apart.
See also: max_execution_time.
Performance Tuning
ENTITY
ENTITY
ENTITY
ENTITY
realpath_cache_size
"4M"
INI_SYSTEM
Prior to PHP 7.0.16 and 7.1.2, the default was
"16K"
realpath_cache_ttl
"120"
INI_SYSTEM
Performance Tuning
[!NOTE]
Using open_basedir will disable the realpath cache.
ENTITY
realpath_cache_size
int
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
int
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
ENTITY
ENTITY
ENTITY
ENTITY
arg_separator.output
"ENTITY"
INI_ALL
arg_separator.input
"ENTITY"
INI_PERDIR
variables_order
"EGPCS"
INI_PERDIR
request_order
""
INI_PERDIR
auto_globals_jit
"1"
INI_PERDIR
register_argc_argv
"1"
INI_PERDIR
Deprecated as of PHP 8.5.0
enable_post_data_reading
"1"
INI_PERDIR
post_max_size
"8M"
INI_PERDIR
auto_prepend_file
NULL
INI_PERDIR
auto_append_file
NULL
INI_PERDIR
default_mimetype
"text/html"
INI_ALL
default_charset
"UTF-8"
INI_ALL
input_encoding
""
INI_ALL
output_encoding
""
INI_ALL
internal_encoding
""
INI_ALL
Data Handling Configuration Options
ENTITY
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 ENTITY
$_SERVER and
$_POST, but not create
$_ENV,
$_GET, and
$_COOKIE. Setting to "" means no ENTITY will be set.
[!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
bool
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.
[!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_argc_argv
bool
Tells PHP whether to declare the argv ENTITY argc variables (that would contain the GET information).
See also command line.
ENTITY
[!NOTE]
Deriving
$_SERVER['argc'] and
$_SERVER['argv'] from the query string for non-CLI SAPIs has been deprecated. Configure
register_argc_argv=0 and switch to either
$_GET or
$_SERVER['QUERY_STRING'] to access the information, after verifying that the usage is safe.
enable_post_data_reading
bool
Disabling this option causes
$_POST and
$_FILES not to be populated. The request body remains unconsumed in php://input and can be read manually or parsed via
request_parse_body. This can be useful to proxy requests or to process the POST data in a memory efficient fashion.
post_max_size
int
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.
ENTITY
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.
ENTITYform action="edit.php?processed=1"ENTITY, 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.
ENTITY
ENTITY
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.
Changelog for
post_max_size
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
"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
This setting is used for multibyte modules such as mbstring and iconv. Default is empty.
output_encoding
string
This setting is used for multibyte modules such as mbstring and iconv. Default is empty.
internal_encoding
string
This setting is used for multibyte modules such as mbstring and iconv. Default is empty. If empty, default_charset is used.
Paths and Directories
ENTITY
ENTITY
ENTITY
ENTITY
include_path
".;/path/to/php/pear"
INI_ALL
open_basedir
NULL
INI_ALL
doc_root
NULL
INI_SYSTEM
user_dir
NULL
INI_SYSTEM
user_ini.cache_ttl
"300"
INI_SYSTEM
user_ini.filename
".user.ini"
INI_SYSTEM
extension_dir
"/path/to/php"
INI_SYSTEM
extension
NULL
ENTITY only
zend_extension
NULL
ENTITY only
cgi.check_shebang_line
"1"
INI_SYSTEM
cgi.discard_path
"0"
INI_SYSTEM
cgi.fix_pathinfo
"1"
INI_SYSTEM
cgi.force_redirect
"1"
INI_SYSTEM
cgi.nph
"0"
INI_SYSTEM
cgi.redirect_status_env
NULL
INI_SYSTEM
cgi.rfc2616_headers
"0"
INI_ALL
fastcgi.impersonate
"0"
INI_SYSTEM
fastcgi.logging
"1"
INI_SYSTEM
Paths and Directories Configuration Options
ENTITY
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 an
E_WARNING or an
E_ERROR. You may modify or set your include path at runtime using
set_include_path.
Unix include_path
include_path=".:/php/includes"
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.
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.
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, not a prefix.
The default is to allow all files to be opened.
[!NOTE]
open_basedir can be tightened at run-time. This means that if open_basedir is set to
/www/ in ENTITY 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.
As of PHP 8.3.0,
open_basedir no longer accepts a paths containing the parent directory (
..) when set at runtime using
ini_set.
[!NOTE]
Using open_basedir will set realpath_cache_size to
0 and thus disable the realpath cache.
[!WARNING]
open_basedir does not restrict access to Unix domain sockets. PHP socket functions such as
stream_socket_client and
fsockopen can connect to a Unix socket path (e.g.
unix:///var/run/docker.sock) regardless of the
open_basedir setting.
[!CAUTION]
open_basedir is just an extra safety net, that is in no way comprehensive, and can therefore not be relied upon when security is needed.
doc_root
string
PHP's "root directory" on the server. Only used if non-empty. 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
int
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. It is recommended to specify an absolute path. 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 XDebug) to load when PHP starts up.
cgi.check_shebang_line
bool
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
bool
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
bool
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
bool
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
bool
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
bool
Tells PHP what type of headers to use when sending HTTP response code. If it is disabled, PHP sends a RFC 3875 "Status:" header that is supported by Apache and other web servers. When this option is enabled, 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 disabled unless you know what you're doing.
fastcgi.impersonate
bool
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). Enable if running under IIS. Default is disabled.
fastcgi.logging
bool
Turns on SAPI logging when using FastCGI. Default is to enable logging.
File Uploads
ENTITY
ENTITY
ENTITY
ENTITY
file_uploads
"1"
INI_SYSTEM
upload_tmp_dir
NULL
INI_SYSTEM
max_input_nesting_level
64
INI_PERDIR
max_input_vars
1000
INI_PERDIR
upload_max_filesize
"2M"
INI_PERDIR
max_file_uploads
20
INI_PERDIR
File Uploads Configuration Options
ENTITY
file_uploads
bool
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
int
The maximum size of an uploaded file.
post_max_size must be larger than this value.
ENTITY
max_file_uploads
int
The maximum number of files allowed to be uploaded simultaneously. Upload fields left blank on submission do not count towards this limit.
General SQL
ENTITY
ENTITY
ENTITY
ENTITY
sql.safe_mode
"0"
INI_SYSTEM
Removed as of PHP 7.2.0
General SQL Configuration Options
ENTITY
sql.safe_mode
bool
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
ENTITY
ENTITY
ENTITY
ENTITY
windows.show_crt_warning
"0"
INI_ALL
Windows Specific Configuration Options
ENTITY
windows.show_crt_warning
bool
This directive shows the Windows CRT warnings when enabled.
List of ENTITY directives
This list includes the ENTITY directives that can be used to configure PHP.
The "ENTITY" column shows the modes determining when and where a directive may be set. See the Changeable mode values section for their definitions.
ENTITY
ENTITY
ENTITY
ENTITY
allow_url_fopen
"1"
INI_SYSTEM
allow_url_include
"0"
INI_SYSTEM
Deprecated as of PHP 7.4.0.
arg_separator.input
"ENTITY"
INI_PERDIR
arg_separator.output
"ENTITY"
INI_ALL
assert.active
"1"
INI_ALL
assert.bail
"0"
INI_ALL
assert.callback
ENTITY
INI_ALL
assert.exception
"0"
INI_ALL
assert.quiet_eval
"0"
INI_ALL
Removed as of PHP 8.0.0
assert.warning
"1"
INI_ALL
auto_append_file
ENTITY
INI_PERDIR
auto_detect_line_endings
"0"
INI_ALL
auto_globals_jit
"1"
INI_PERDIR
auto_prepend_file
ENTITY
INI_PERDIR
browscap
ENTITY
INI_SYSTEM
cgi.check_shebang_line
"1"
INI_SYSTEM
cgi.discard_path
"0"
INI_SYSTEM
cgi.fix_pathinfo
"1"
INI_SYSTEM
cgi.force_redirect
"1"
INI_SYSTEM
cgi.nph
"0"
INI_ALL
cgi.redirect_status_env
ENTITY
INI_SYSTEM
cgi.rfc2616_headers
"0"
INI_ALL
child_terminate
"0"
INI_ALL
default_charset
"UTF-8"
INI_ALL
input_encoding
""
INI_ALL
output_encoding
""
INI_ALL
internal_encoding
""
INI_ALL
default_mimetype
"text/html"
INI_ALL
default_socket_timeout
"60"
INI_ALL
disable_classes
""
ENTITY only
Removed as of PHP 8.5.0
disable_functions
""
ENTITY only
display_errors
"1"
INI_ALL
display_startup_errors
"1"
INI_ALL
Prior to PHP 8.0.0, the default value was
"0".
docref_ext
""
INI_ALL
docref_root
""
INI_ALL
doc_root
ENTITY
INI_SYSTEM
enable_dl
"1"
INI_SYSTEM
ENTITY
enable_post_data_reading
"On"
INI_PERDIR
engine
"1"
INI_ALL
error_append_string
ENTITY
INI_ALL
error_log
ENTITY
INI_ALL
error_log_mode
0o644
INI_ALL
Available as of PHP 8.2.0
error_prepend_string
ENTITY
INI_ALL
error_reporting
ENTITY
INI_ALL
exit_on_timeout
""
INI_ALL
expose_php
"1"
ENTITY only
extension
ENTITY
ENTITY only
extension_dir
"/path/to/php"
INI_SYSTEM
fastcgi.impersonate
"0"
INI_SYSTEM
fastcgi.logging
"1"
INI_SYSTEM
file_uploads
"1"
INI_SYSTEM
from
""
INI_ALL
hard_timeout
"2"
INI_SYSTEM
Available as of PHP 7.1.0.
highlight.comment
"#FF8000"
INI_ALL
highlight.default
"#0000BB"
INI_ALL
highlight.html
"#000000"
INI_ALL
highlight.keyword
"#007700"
INI_ALL
highlight.string
"#DD0000"
INI_ALL
html_errors
"1"
INI_ALL
ignore_repeated_errors
"0"
INI_ALL
ignore_repeated_source
"0"
INI_ALL
ignore_user_abort
"0"
INI_ALL
implicit_flush
"0"
INI_ALL
include_path
".:/path/to/php/pear"
INI_ALL
last_modified
"0"
INI_ALL
log_errors
"0"
INI_ALL
log_errors_max_len
"1024"
INI_ALL
mail.add_x_header
"0"
INI_PERDIR
mail.force_extra_parameters
ENTITY
INI_SYSTEM
mail.log
""
INI_PERDIR
max_execution_time
"30"
INI_ALL
max_input_nesting_level
"64"
INI_PERDIR
max_input_vars
1000
INI_PERDIR
max_input_time
"-1"
INI_PERDIR
memory_limit
"128M"
INI_ALL
memory_hard_limit_percent
ENTITY
INI_ALL
Available as of PHP 8.5.12, 8.4.27, 8.3.36 and 8.2.35.
open_basedir
ENTITY
INI_ALL
output_buffering
"0"
INI_PERDIR
output_handler
ENTITY
INI_PERDIR
post_max_size
"8M"
INI_PERDIR
precision
"14"
INI_ALL
realpath_cache_size
"16K"
INI_SYSTEM
realpath_cache_ttl
"120"
INI_SYSTEM
register_argc_argv
"1"
INI_PERDIR
Deprecated as of PHP 8.5.0
report_memleaks
"1"
INI_ALL
Deprecated as of PHP 8.5.0
report_zend_debug
"1"
INI_ALL
request_order
""
INI_PERDIR
sendmail_from
ENTITY
INI_ALL
sendmail_path
"/usr/sbin/sendmail -t -i"
INI_SYSTEM
serialize_precision
"-1"
INI_ALL
Prior to PHP 7.1.0, the default value was
17.
short_open_tag
"1"
INI_PERDIR
SMTP
"localhost"
INI_ALL
smtp_port
"25"
INI_ALL
sql.safe_mode
"0"
INI_SYSTEM
Removed as of PHP 7.2.0
syslog.facility
"LOG_USER"
INI_SYSTEM
Available as of PHP 7.3.0.
syslog.filter
"no-ctrl"
INI_ALL
Available as of PHP 7.3.0.
syslog.ident
"php"
INI_SYSTEM
Available as of PHP 7.3.0.
sys_temp_dir
""
INI_SYSTEM
track_errors
"0"
INI_ALL
Deprecated as of PHP 7.2.0, removed as of PHP 8.0.0
uploadprogress.file.filename_template
"/tmp/upt_%s.txt"
INI_ALL
upload_max_filesize
"2M"
INI_PERDIR
max_file_uploads
20
INI_SYSTEM
upload_tmp_dir
ENTITY
INI_SYSTEM
url_rewriter.hosts
""
INI_ALL
Available as of PHP 7.1.0.
url_rewriter.tags
"form="
INI_ALL
Prior to PHP 7.1.0, the default value was
"a=href,area=href,frame=src,form=,fieldset=".
user_agent
ENTITY
INI_ALL
user_dir
ENTITY
INI_SYSTEM
user_ini.cache_ttl
"300"
INI_SYSTEM
user_ini.filename
".user.ini"
INI_SYSTEM
variables_order
"EGPCS"
INI_PERDIR
windows.show_crt_warning
"0"
INI_ALL
xbithack
"0"
INI_ALL
xmlrpc_errors
"0"
INI_SYSTEM
xmlrpc_error_number
"0"
INI_ALL
yaz.keepalive
"120"
INI_ALL
yaz.log_mask
ENTITY
INI_ALL
Available as of yaz 1.0.3.
zend.assertions
"1"
INI_ALL
zend.detect_unicode
"1"
INI_ALL
zend.enable_gc
"1"
INI_ALL
zend.max_allowed_stack_size
"0"
INI_SYSTEM
Available as of PHP 8.3.0
fiber.stack_size
INI_ALL
Available as of PHP 8.1.0
zend.multibyte
"0"
INI_PERDIR
zend.reserved_stack_size
"0"
INI_SYSTEM
Available as of PHP 8.3.0
zend.script_encoding
ENTITY
INI_ALL
zend.signal_check
"0"
INI_SYSTEM
zend_extension
ENTITY
ENTITY only
Configuration options
ENTITY directives
ENTITY ENTITY ENTITY
List of ENTITY sections
This list includes the ENTITY 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 ENTITY 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.
Directives set in these sections cannot be overridden by .user.ini files or at runtime, like those set with php_admin_value.
Regardless of their order in ENTITY, [PATH=] takes precedence over [HOST=], and a deeper path over a shallower one. With PHP-FPM, these sections also take precedence over the pool configuration and FastCGI parameters, including
php_admin_value and
PHP_ADMIN_VALUE.
ENTITY
ENTITY
ENTITY
[HOST=]
INI_SYSTEM
[PATH=]
INI_SYSTEM
Sections
ENTITY
[HOST=ENTITYhostENTITY]
This section allows you to define a set of ENTITY directives that will take effect on the named host.
Activate full on-screen error reporting for dev. domain
[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On
[PATH=ENTITYpathENTITY]
This section allows you to define a set of ENTITY directives that will take effect when a script runs from the named path.
Add security script for protected areas
[PATH=/home/site/public/secure]
auto_prepend_file=security.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
"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.
"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.
"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.
"Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
"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.
"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.
"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.
"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:
to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
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.";
to Distribute and Publicly Perform the Work including as incorporated in Collections; and,
to Distribute and Publicly Perform Adaptations.
For the avoidance of doubt:
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;
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,
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:
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.
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.
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.
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.
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
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.
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.
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.
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
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.
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.
Migrating from PHP 5.5.x to PHP 5.6.x
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.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
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 ENTITY.
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 ENTITY if the attribute could not be found, like XMLReader::getAttribute.
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
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:
f();
?>
ENTITY
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
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.
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:
'foo',
'bar',
'quux',
];
}
var_dump((new C)->array);
?>
ENTITY
array(2) {
[0]=>
string(3) "bar"
[1]=>
string(4) "quux"
}
ENTITY
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
ENTITY
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 ENTITY.
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.
f()."\n";
echo C::SENTENCE;
?>
ENTITY
4
The value of THREE is 3
It is also now possible to define a constant
array using the
const keyword:
ENTITY
a
Variadic functions via
...
Variadic functions can now be implemented using the
... operator, instead of relying on
func_get_args.
ENTITY
$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.
ENTITY
6
Exponentiation via
**
A right associative
** operator has been added to support exponentiation, along with a
**= shorthand assignment operator.
ENTITY
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.
ENTITY
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:
ENTITY
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).
ENTITY
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.
prop = $val;
}
public function __debugInfo() {
return [
'propSquared' => $this->prop ** 2,
];
}
}
var_dump(new C(42));
?>
ENTITY
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.
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
ENTITY
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 ENTITY (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 ENTITY.
[
'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);
?>
ENTITY
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 parameters 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 ENTITY, a new key pair will be created when using Diffie-Hellman parameters, thereby improving forward secrecy.
single_ecdh_use
If set to ENTITY, 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.
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://
[
'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.
ENTITY
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.
ENTITY
SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify
Verifies provided SPKAC.
openssl_spki_export_challenge
Exports associated challenge from provided SPKAC.
ENTITY
challenge string
openssl_spki_export
Exports the PEM formatted RSA public key from SPKAC.
ENTITY
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcvQh9SKOPv4DwI8LwSaFx02h7
l9QCiDs6sF2GfsSTEUG61SnjQ/v4uJiLKBgbVOagj9rkSCwtTez23ATPeGaBj2Zg
ipv+tv5IXyqUP8ropXJQ5ELtbXPUN/gvw7cO5EbPHr/7eMhbpw8Gl+AfWxW5hLW8
MGw/+AwwjHBOwong/QIDAQAB
-----END PUBLIC KEY-----
Migrating from PHP 5.6.x to PHP 7.0.x
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.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
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 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
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.
ENTITY
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.
ENTITY
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
Backward incompatible changes
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
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 more complete description of how errors operate in PHP can be found on the Throwable 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.
Internal constructors always throw exceptions on failure
Previously, some internal classes would return ENTITY 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 ENTITY 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.
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
E_STRICT notices severity changes
Changes to ENTITY
Minor changes have been made to the behaviour of the ENTITY control structure, primarily around the handling of the internal array pointer and modification of the array being iterated over.
ENTITY 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 ENTITY. This is no longer the case, as shown in the following example:
ENTITY
int(1)
int(2)
bool(false)
ENTITY
int(0)
int(0)
int(0)
ENTITY by-value operates on a copy of the array
When used in the default by-value mode, ENTITY 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.
ENTITY by-reference has improved iteration behaviour
When iterating by-reference, ENTITY 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:
ENTITY
int(0)
ENTITY
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 `int` 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:
> -1);
?>
ENTITY
int(0)
ENTITY
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
int 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.
ENTITY
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)
ENTITY
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
Other backward incompatible changes
New objects cannot be assigned by reference
The result of the ENTITY statement can no longer be assigned to a variable by reference:
ENTITY
Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3
ENTITY
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
ENTITY
ENTITY
ENTITY
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:
Opening tag
Closing tag
ENTITY%
%ENTITY
ENTITY%=
%ENTITY
ENTITYscript language="php"ENTITY
ENTITY/scriptENTITY
Removed ASP and script tags
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.
callNonStaticMethodOfA();
?>
ENTITY
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) {
}
ENTITY
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
ENTITY is now a right associative operator
The ENTITY construct no longer requires parentheses, and has been changed to a right associative operator with precedence between
print and
=ENTITY. This can result in changed behaviour:
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:
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).
ENTITY
1
ENTITY
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:
$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 ENTITY, 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 ENTITY will be returned.
Fixes to custom session handler return values
Any predicate functions implemented by custom session handlers that return either ENTITY 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 continue 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.
Constant disallowed as break and continue argument
break and
continue statements no longer allow their argument to be a constant, and trigger a
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.
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. PDO_SQLSRV, PDO_ODBC, SQLSRV, Unified ODBC API
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.
Changes to `string` handling
Hexadecimal strings are no longer considered numeric
Strings containing hexadecimal numbers are no longer considered to be numeric. For example:
ENTITY
bool(true)
bool(true)
int(15)
string(2) "oo"
ENTITY
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
int:
\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.
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.
Expression
PHP 5 interpretation
PHP 7 interpretation
$$foo['bar']['baz']
${$foo['bar']['baz']}
($$foo)['bar']['baz']
$foo-ENTITY$bar['baz']
$foo-ENTITY{$bar['baz']}
($foo-ENTITY$bar)['baz']
$foo-ENTITY$bar['baz']()
$foo-ENTITY{$bar['baz']}()
($foo-ENTITY$bar)['baz']()
Foo::$bar['baz']()
Foo::{$bar['baz']}()
(Foo::$bar)['baz']()
Old and new evaluation of indirect expressions
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 ENTITY keyword. The curly brace syntax can be used to emulate the previous behaviour if required:
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:
ENTITY
array(3) {
[0]=>
int(3)
[1]=>
int(2)
[2]=>
int(1)
}
ENTITY
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:
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:
ENTITY
array(2) {
["b"]=>
&int(1)
["a"]=>
&int(1)
}
ENTITY
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.
ENTITY
Notice: Only variables should be passed by reference in /tmp/test.php on line 13
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.
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 ENTITY; otherwise it returns its second operand.
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.
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 ENTITY.
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:
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());
?>
ENTITY
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.
ENTITY
ª
ª (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.
x;};
$getXCB = $getX->bindTo(new A, 'A'); // intermediate closure
echo $getXCB();
// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A);
ENTITY
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.
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.
ENTITY
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 on the manual page of the
assert language construct.
Group
use declarations
Classes, functions and constants being imported from the same ENTITY can now be grouped together in a single ENTITY statement.
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.
getReturn(), PHP_EOL;
ENTITY
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 ENTITY construct.
ENTITY
1
2
3
4
Integer division with
intdiv
The new
intdiv function performs an integer division of its operands and returns it.
ENTITY
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:
'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)-ENTITYbar().
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
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:
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).
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
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.
Migrating from PHP 7.0.x to PHP 7.1.x
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.
ENTITY 7.0.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
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 ENTITY and no longer initializes
$_SESSION when it failed to start the session.
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
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.
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:
ENTITY
array(1) {
[10]=>
string(3) "foo"
}
ENTITY
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:
ENTITY
array(2) {
["a"]=>
&int(1)
["b"]=>
&int(1)
}
ENTITY
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
bool is given, unserialize() returns ENTITY 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 ENTITY instead of ENTITY:
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 ENTITY,
$this, or any parameter. For example, all of these function definition will result in a fatal error:
1])));
ENTITY
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.
Forbid "return;" for typed returns already at compile-time
Return statements without argument in functions which declare a return type now trigger
E_COMPILE_ERROR (unless the return type is declared as
void), even if the return statement would never be reached.
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, ENTITY can be passed as an argument, or returned as a value, respectively.
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.
ENTITY
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.
exposeFunction();
$privFunc('some value');
ENTITY
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).
1];
$obj = (object) $arr;
var_dump(
$obj,
$obj->{'0'}, // now accessible
$obj->{0} // now accessible
);
ENTITY
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:
{0} = 1;
}
};
$arr = (array) $obj;
var_dump(
$arr,
$arr[0], // now accessible
$arr['0'] // now accessible
);
ENTITY
array(1) {
[0]=> // integer key now, rather than string key
int(1)
}
int(1)
int(1)
Disallow passing ENTITY to
get_class
Previously, passing ENTITY 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).
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 bound 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.
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.
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 integral 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.
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:
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.
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=ENTITY (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
int or
float, whichever is more appropriate. Previously values were treated as
ints unconditionally.
Incoming Cookies
As of PHP 7.3.23, the names of incoming cookies are no longer url-decoded for security reasons.
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
[ENTITY$a, [$b, ENTITY$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 ENTITY.
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
$controls 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
$controls 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:
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:
\w+)', '国', $matches);
// => [0 => "国", 1 => "国", "word" => "国"];
?>
Additionally,
mb_ereg_replace now supports the
\kENTITYENTITY and
\k'' notations to reference named captures in the replacement string:
\w+)\s*', "_\k_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\kENTITYENTITY 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
Other Changes
PHP Core
Set(raw)cookie accepts $option Argument
setcookie and
setrawcookie now also support the following signature:
boolsetcookie
string``name
string``value""
array``options[] 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, with the supported filter types -
all,
no-ctrl and
ascii. Starting with PHP 7.3.8,
raw is also available, restoring the way syslog behaved in previous PHP versions. This filter will also affect calls to
syslog.
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_OPEN_READONLY.
Session Handling
session_set_cookie_params now also supports the following signature:
boolsession_set_cookie_params
array``options 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.3.x to PHP 7.4.x
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.
ENTITY 7.0.x, 7.1.x, 7.2.x and 7.3.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
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
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.
Parentheses are not required when nesting into the middle operand, as this is always unambiguous and not affected by associativity:
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 ENTITY.
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:
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.
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.
ENTITY?php tag at end of file
ENTITY?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
ENTITY?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 ENTITY 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 string '2y' (in PHP 7.4.0, 7.4.1, and 7.4.2 it was ENTITY)
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 ENTITY 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
==,
ENTITY, and so on) will now generate a warning and always return ENTITY. 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 ENTITY 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 ENTITY (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.
The values of the class constant of
ReflectionClassConstant,
ReflectionMethod and
ReflectionProperty have changed.
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, e.g.
array_walk.
(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.
Incoming Cookies
As of PHP 7.4.11, the names of incoming cookies are no longer url-decoded for security reasons.
New Classes and Interfaces
Reflection
ReflectionReference
New Features
PHP Core
Typed properties
Class properties now support type declarations.
The above example will enforce that
$user->id can only be assigned
int 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.
$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:
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
Unpacking inside arrays
Numeric literal separator
Numeric literals can contain underscores between digits.
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 ENTITY= 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 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, 'ENTITYaENTITYENTITYpENTITY') 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.
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.
proc_open now supports
redirect and
null descriptors.
&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 Functions
PHP Core
get_mangled_object_vars
password_algos
sapi_windows_set_ctrl_handler
GD
imagecreatefromtga
Multibyte String
mb_str_split
OpenSSL
openssl_x509_verify
Process Control
pcntl_unshare
SQLite3
SQLite3::backup
SQLite3Stmt::getSQL
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 executed 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
password_needs_rehash functions now accept nullable ENTITY and ENTITY 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.
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
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 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.4.x to PHP 8.0.x
This new major version brings with it a number of new features and some incompatibilities that should be tested for before switching PHP versions in production environments.
ENTITY 7.0.x, 7.1.x, 7.2.x, 7.3.x. 7.4.x.
ENTITY ENTITY ENTITY ENTITY ENTITY
Deprecated Features
PHP Core
If a parameter with a default value is followed by a required parameter, the default value has no effect. This is deprecated as of PHP 8.0.0 and can generally be resolved by dropping the default value, without a change in functionality:
One exception to this rule are parameters of the form
Type $param = null, where the null default makes the type implicitly nullable. This usage remains allowed, but it is recommended to use an explicit nullable type instead:
Calling
get_defined_functions with
exclude_disabled explicitly set to ENTITY is deprecated and no longer has an effect.
get_defined_functions will never include disabled functions.
Enchant
enchant_broker_set_dict_path and
enchant_broker_get_dict_path are deprecated, because that functionality is neither available in libenchant ENTITY 1.5 nor in libenchant-2.
enchant_dict_add_to_personal is deprecated; use
enchant_dict_add instead.
enchant_dict_is_in_session is deprecated; use
enchant_dict_is_added instead.
enchant_broker_free and
enchant_broker_free_dict are deprecated; unset the object instead.
The
ENCHANT_MYSPELL and
ENCHANT_ISPELL constants are deprecated.
LibXML
libxml_disable_entity_loader has been deprecated. As libxml 2.9.0 is now required, external entity loading is guaranteed to be disabled by default, and this function is no longer needed to protect against XXE attacks, unless the (still vulnerable)
LIBXML_NOENT is used. In that case, it is recommended to refactor the code using
libxml_set_external_entity_loader to suppress loading of external entities.
PGSQL / PDO PGSQL
The constant
PGSQL_LIBPQ_VERSION_STR now has the same value as
PGSQL_LIBPQ_VERSION, and thus is deprecated.
Function aliases in the pgsql extension have been deprecated. See the following list for which functions should be used instead:
pg_errormessage →
pg_last_error,
pg_numrows →
pg_num_rows,
pg_numfields →
pg_num_fields,
pg_cmdtuples →
pg_affected_rows,
pg_fieldname →
pg_field_name,
pg_fieldsize →
pg_field_size,
pg_fieldtype →
pg_field_type,
pg_fieldnum →
pg_field_num,
pg_result →
pg_fetch_result,
pg_fieldprtlen →
pg_field_prtlen,
pg_fieldisnull →
pg_field_is_null,
pg_freeresult →
pg_free_result,
pg_getlastoid →
pg_last_oid,
pg_locreate →
pg_lo_create,
pg_lounlink →
pg_lo_unlink,
pg_loopen →
pg_lo_open,
pg_loclose →
pg_lo_close,
pg_loread →
pg_lo_read,
pg_lowrite →
pg_lo_write,
pg_loreadall →
pg_lo_read_all,
pg_loimport →
pg_lo_import,
pg_loexport →
pg_lo_export,
pg_setclientencoding →
pg_set_client_encoding,
pg_clientencoding ->
pg_client_encoding
Standard Library
Sort comparison functions that return ENTITY or ENTITY will now throw a deprecation warning, and should be replaced with an implementation that returns an integer less than, equal to, or greater than zero.
$a > $b);
// With
usort($array, fn($a, $b) => $a <=> $b);
?>
Zip
Using an empty file as ZipArchive is deprecated. Libzip 1.6.0 does not accept empty files as valid zip archives any longer. The existing workaround will be removed in the next version.
The procedural API of Zip is deprecated. Use
ZipArchive instead. Iteration over all entries can be accomplished using ZipArchive::statIndex and a for loop:
statIndex($i); $i++) {
echo $entry['name'];
}
?>
Reflection
ReflectionFunction::isDisabled is deprecated, as it is no longer possible to create a
ReflectionFunction for a disabled function. This method now always returns ENTITY.
ReflectionParameter::getClass, ReflectionParameter::isArray, and ReflectionParameter::isCallable are deprecated. ReflectionParameter::getType and the
ReflectionType APIs should be used instead.
Backward Incompatible Changes
PHP Core
String to Number Comparison
Non-strict comparisons between numbers and non-numeric strings now work by casting the number to string and comparing the strings. Comparisons between numbers and numeric strings continue to work as before. Notably, this means that
0 == "not-a-number" is considered false now.
Comparison
Before
After
0 == "0"
ENTITY
ENTITY
0 == "0.0"
ENTITY
ENTITY
0 == "foo"
ENTITY
ENTITY
0 == ""
ENTITY
ENTITY
42 == " 42"
ENTITY
ENTITY
42 == "42foo"
ENTITY
ENTITY
Other incompatible Changes
match is now a reserved keyword.
mixed is now a reserved word, so it cannot be used to name a class, interface or trait, and is also prohibited from being used in namespaces.
Assertion failures now throw by default. If the old behavior is desired,
assert.exception=0 can be set in the INI settings.
Methods with the same name as the class are no longer interpreted as constructors. The __construct() method should be used instead.
The ability to call non-static methods statically has been removed. Thus
is_callable will fail when checking for a non-static method with a classname (must check with an object instance).
The
(real) and
(unset) casts have been removed.
The track_errors ini directive has been removed. This means that
php_errormsg is no longer available. The
error_get_last function may be used instead.
The ability to define case-insensitive constants has been removed. The third argument to
define may no longer be ENTITY.
The ability to specify an autoloader using an
__autoload function has been removed.
spl_autoload_register should be used instead.
The
errcontext argument will no longer be passed to custom error handlers set with
set_error_handler.
create_function has been removed. Anonymous functions may be used instead.
each has been removed. ENTITY or
ArrayIterator should be used instead.
The ability to unbind
this from closures that were created from a method, using Closure::fromCallable or ReflectionMethod::getClosure, has been removed.
The ability to unbind
this from proper closures that contain uses of
this has also been removed.
The ability to use
array_key_exists with objects has been removed.
isset or
property_exists may be used instead.
The behavior of
array_key_exists regarding the type of the
key parameter has been made consistent with
isset and normal array access. All key types now use the usual coercions and array/object keys throw a
TypeError.
Any array that has a number as its first numeric key will use for its next implicit key, even if is negative.
The default error_reporting level is now
E_ALL. Previously it excluded
E_NOTICE and
E_DEPRECATED.
display_startup_errors is now enabled by default.
Using
parent inside a class that has no parent will now result in a fatal compile-time error.
The
@ operator will no longer silence fatal errors (
E_ERROR,
E_CORE_ERROR,
E_COMPILE_ERROR,
E_USER_ERROR,
E_RECOVERABLE_ERROR,
E_PARSE). Error handlers that expect error_reporting to be
0 when
@ is used, should be adjusted to use a mask check instead:
Additionally, care should be taken that error messages are not displayed in production environments, which can result in information leaks. Please ensure that
display_errors=Off is used in conjunction with error logging.
#[ is no longer interpreted as the start of a comment, as this syntax is now used for attributes.
Inheritance errors due to incompatible method signatures (LSP violations) will now always generate a fatal error. Previously a warning was generated in some cases.
The precedence of the concatenation operator has changed relative to bitshifts and addition as well as subtraction.
Arguments with a default value that resolves to ENTITY at runtime will no longer implicitly mark the argument type as nullable. Either an explicit nullable type, or an explicit ENTITY default value has to be used instead.
A number of warnings have been converted into
Error exceptions:
Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings., Attempting to append an element to an array for which the PHP_INT_MAX key is already used., Attempting to use an invalid type (array or object) as an array key or string offset., Attempting to write to an array index of a scalar value., Attempting to unpack a non-array/Traversable., Attempting to access unqualified constants which are undefined. Previously, unqualified constant accesses resulted in a warning and were interpreted as strings., Passing the wrong number of arguments to a non-variadic built-in function will throw an
ArgumentCountError., Passing invalid countable types to
count will throw a
TypeError.
A number of notices have been converted into warnings:
Attempting to read an undefined variable., Attempting to read an undefined property., Attempting to read an undefined array key., Attempting to read a property of a non-object., Attempting to access an array index of a non-array., Attempting to convert an array to string., Attempting to use a resource as an array key., Attempting to use null, a boolean, or a float as a string offset., Attempting to read an out-of-bounds string offset., Attempting to assign an empty string to a string offset.
Attempting to assign multiple bytes to a string offset will now emit a warning.
Unexpected characters in source files (such as NUL bytes outside of strings) will now result in a
ParseError exception instead of a compile warning.
Uncaught exceptions now go through "clean shutdown", which means that destructors will be called after an uncaught exception.
The compile time fatal error "Only variables can be passed by reference" has been delayed until runtime, and converted into an "Argument cannot be passed by reference"
Error exception.
Some "Only variables should be passed by reference" notices have been converted to "Argument cannot be passed by reference" exception.
The generated name for anonymous classes has changed. It will now include the name of the first parent or interface:
ParentClass@anonymous
new class implements FirstInterface, SecondInterface {};
// -> FirstInterface@anonymous
new class {};
// -> class@anonymous
?>
The name shown above is still followed by a NUL byte and a unique suffix.
Non-absolute trait method references in trait alias adaptations are now required to be unambiguous:
If both
T1::func() and
T2::func() exist, this code was previously silently accepted, and func was assumed to refer to
T1::func. Now it will generate a fatal error instead, and either
T1::func or
T2::func needs to be written explicitly.
The signature of abstract methods defined in traits is now checked against the implementing class method:
Disabled functions are now treated exactly like non-existent functions. Calling a disabled function will report it as unknown, and redefining a disabled function is now possible.
data:// stream wrappers are no longer writable, which matches the documented behavior.
The arithmetic and bitwise operators
+,
-,
*,
/,
**,
%,
ENTITYENTITY,
ENTITYENTITY,
ENTITY,
|,
^,
~,
++,
-- will now consistently throw a
TypeError when one of the operands is an ENTITY, ENTITY or non-overloaded ENTITY. The only exception to this is the array
+ array merge operation, which remains supported.
Float to string casting will now always behave locale-independently.
See
printf,
number_format and NumberFormatter for ways to customize number formatting.
Support for deprecated curly braces for offset access has been removed.
Applying the final modifier on a private method will now produce a warning unless that method is the constructor.
If an object constructor
exits, the object destructor will no longer be called. This matches the behavior when the constructor throws.
Namespaced names can no longer contain whitespace: While
Foo\Bar will be recognized as a namespaced name,
Foo \ Bar will not. Conversely, reserved keywords are now permitted as namespace segments, which may also change the interpretation of code:
new\x is now the same as
constant('new\x'), not
new \x().
Nested ternaries now require explicit parentheses.
debug_backtrace and Exception::getTrace will no longer provide references to arguments. It will not be possible to change function arguments through the backtrace.
Numeric string handling has been altered to be more intuitive and less error-prone. Trailing whitespace is now allowed in numeric strings for consistency with how leading whitespace is treated. This mostly affects:
The
is_numeric function, String-to-string comparisons, Type declarations, Increment and decrement operations
The concept of a "leading-numeric string" has been mostly dropped; the cases where this remains exist in order to ease migration. Strings which emitted an
E_NOTICE "A non well-formed numeric value encountered" will now emit an
E_WARNING "A non-numeric value encountered" and all strings which emitted an
E_WARNING "A non-numeric value encountered" will now throw a
TypeError. This mostly affects:
Arithmetic operations, Bitwise operations
This
E_WARNING to
TypeError change also affects the
E_WARNING "Illegal string offset 'string'" for illegal string offsets. The behavior of explicit casts to int/float from strings has not been changed.
Magic Methods will now have their arguments and return types checked if they have them declared. The signatures should match the following list:
__call(string $name, array $arguments): mixed,
__callStatic(string $name, array $arguments): mixed,
__clone(): void,
__debugInfo(): ?array,
__get(string $name): mixed,
__invoke(mixed $arguments): mixed,
__isset(string $name): bool,
__serialize(): array,
__set(string $name, mixed $value): void,
__set_state(array $properties): object,
__sleep(): array,
__unserialize(array $data): void,
__unset(string $name): void,
__wakeup(): void
call_user_func_array array keys will now be interpreted as parameter names, instead of being silently ignored.
Declaring a function called
assert() inside a namespace is no longer allowed, and issues
E_COMPILE_ERROR. 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.
Resource to Object Migration
Several ENTITYs have been migrated to ENTITYs. Return value checks using
is_resource should be replaced with checks for ENTITY.
curl_init will now return a
CurlHandle object rather than a ENTITY. The
curl_close function no longer has an effect, instead the
CurlHandle instance is automatically destroyed if it is no longer referenced.
curl_multi_init will now return a
CurlMultiHandle object rather than a ENTITY. The
curl_multi_close function no longer has an effect, instead the
CurlMultiHandle instance is automatically destroyed if it is no longer referenced.
curl_share_init will now return a
CurlShareHandle object rather than a ENTITY. The
curl_share_close function no longer has an effect, instead the
CurlShareHandle instance is automatically destroyed if it is no longer referenced.
enchant_broker_init will now return an
EnchantBroker object rather than a ENTITY.
enchant_broker_request_dict and
enchant_broker_request_pwl_dict will now return an
EnchantDictionary object rather than a ENTITY.
The GD extension now uses
GdImage objects as the underlying data structure for images, rather than ENTITYs. The
imagedestroy function no longer has an effect; instead the
GdImage instance is automatically destroyed if it is no longer referenced.
openssl_x509_read and
openssl_csr_sign will now return an
OpenSSLCertificate object rather than a ENTITY. The
openssl_x509_free function is deprecated and no longer has an effect, instead the
OpenSSLCertificate instance is automatically destroyed if it is no longer referenced.
openssl_csr_new will now return an
OpenSSLCertificateSigningRequest object rather than a ENTITY.
openssl_pkey_new will now return an
OpenSSLAsymmetricKey object rather than a ENTITY. The
openssl_pkey_free function is deprecated and no longer has an effect, instead the
OpenSSLAsymmetricKey instance is automatically destroyed if it is no longer referenced.
shmop_open will now return a
Shmop object rather than a ENTITY. The
shmop_close function no longer has an effect, and is deprecated; instead the
Shmop instance is automatically destroyed if it is no longer referenced.
socket_create,
socket_create_listen,
socket_accept,
socket_import_stream,
socket_addrinfo_connect,
socket_addrinfo_bind, and
socket_wsaprotocol_info_import will now return a
Socket object rather than a ENTITY.
socket_addrinfo_lookup will now return an array of
AddressInfo objects rather than ENTITYs.
msg_get_queue will now return an
SysvMessageQueue object rather than a ENTITY.
sem_get will now return an
SysvSemaphore object rather than a ENTITY.
shm_attach will now return an
SysvSharedMemory object rather than a ENTITY.
xml_parser_create and
xml_parser_create_ns will now return an
XMLParser object rather than a ENTITY. The
xml_parser_free function no longer has an effect, instead the XMLParser instance is automatically destroyed if it is no longer referenced.
The XMLWriter functions now accept and return, respectively,
XMLWriter objects instead of ENTITYs.
inflate_init will now return an
InflateContext object rather than a ENTITY.
deflate_init will now return a
DeflateContext object rather than a ENTITY.
COM and .Net (Windows)
The ability to import case-insensitive constants from type libraries has been removed. The second argument to
com_load_typelib may no longer be false; com.autoregister_casesensitive may no longer be disabled; case-insensitive markers in com.typelib_file are ignored.
CURL
CURLOPT_POSTFIELDS no longer accepts objects as arrays. To interpret an object as an array, perform an explicit
(array) cast. The same applies to other options accepting arrays as well.
Date and Time
mktime and
gmmktime now require at least one argument.
time can be used to get the current timestamp.
DOM
Unimplemented classes from the DOM extension that had no behavior and contained test data have been removed. These classes have also been removed in the latest version of the DOM standard:
DOMNameList,
DomImplementationList,
DOMConfiguration,
DomError,
DomErrorHandler,
DOMImplementationSource,
DOMLocator,
DOMUserDataHandler,
DOMTypeInfo,
DOMStringExtend
Unimplemented methods from the DOM extension that had no behavior have been removed:
DOMNamedNodeMap::setNamedItem, DOMNamedNodeMap::removeNamedItem, DOMNamedNodeMap::setNamedItemNS, DOMNamedNodeMap::removeNamedItemNS, DOMText::replaceWholeText, DOMNode::compareDocumentPosition, DOMNode::isEqualNode, DOMNode::getFeature, DOMNode::setUserData, DOMNode::getUserData, DOMDocument::renameNode
Enchant
enchant_broker_list_dicts,
enchant_broker_describe and
enchant_dict_suggest will now return an empty array instead of ENTITY.
Exif
read_exif_data has been removed;
exif_read_data should be used instead.
Filter
The
FILTER_FLAG_SCHEME_REQUIRED and
FILTER_FLAG_HOST_REQUIRED flags for the
FILTER_VALIDATE_URL filter have been removed. The
scheme and
host are (and have been) always required.
The
INPUT_REQUEST and
INPUT_SESSION source for
filter_input etc. have been removed. These were never implemented and their use always generated a warning.
GD
The deprecated function
image2wbmp has been removed.
The deprecated functions
png2wbmp and
jpeg2wbmp have been removed.
The default
mode parameter of
imagecropauto no longer accepts
-1.
IMG_CROP_DEFAULT should be used instead.
On Windows,
php_gd2.dll has been renamed to
php_gd.dll.
GMP
gmp_random has been removed. One of
gmp_random_range or
gmp_random_bits should be used instead.
Iconv
iconv implementations which do not properly set
errno in case of errors are no longer supported.
IMAP
The unused
default_host argument of
imap_headerinfo has been removed.
The
imap_header function which is an alias of
imap_headerinfo has been removed.
Internationalization Functions
The deprecated constant
INTL_IDNA_VARIANT_2003 has been removed.
The deprecated
Normalizer::NONE constant has been removed.
LDAP
The deprecated functions
ldap_sort,
ldap_control_paged_result and
ldap_control_paged_result_response have been removed.
The interface of
ldap_set_rebind_proc has changed; the
callback parameter does not accept empty strings anymore; ENTITY should be used instead.
MBString
The mbstring.func_overload directive has been removed. The related
MB_OVERLOAD_MAIL,
MB_OVERLOAD_STRING, and
MB_OVERLOAD_REGEX constants have also been removed. Finally, the
"func_overload" and
"func_overload_list" entries in
mb_get_info have been removed.
mb_parse_str can no longer be used without specifying a result array.
A number of deprecated mbregex aliases have been removed. See the following list for which functions should be used instead:
mbregex_encoding →
mb_regex_encoding,
mbereg →
mb_ereg,
mberegi →
mb_eregi,
mbereg_replace →
mb_ereg_replace,
mberegi_replace →
mb_eregi_replace,
mbsplit →
mb_split,
mbereg_match →
mb_ereg_match,
mbereg_search →
mb_ereg_search,
mbereg_search_pos →
mb_ereg_search_pos,
mbereg_search_regs →
mb_ereg_search_regs,
mbereg_search_init →
mb_ereg_search_init,
mbereg_search_getregs →
mb_ereg_search_getregs,
mbereg_search_getpos →
mb_ereg_search_getpos,
mbereg_search_setpos →
mb_ereg_search_setpos
The
e modifier for
mb_ereg_replace has been removed.
mb_ereg_replace_callback should be used instead.
A non-string pattern argument to
mb_ereg_replace will now be interpreted as a string instead of an ASCII codepoint. The previous behavior may be restored with an explicit call to
chr.
The
needle argument for
mb_strpos,
mb_strrpos,
mb_stripos,
mb_strripos,
mb_strstr,
mb_stristr,
mb_strrchr and
mb_strrichr can now be empty.
The
is_hex parameter, which was not used internally, has been removed from
mb_decode_numericentity.
The legacy behavior of passing the encoding as the third argument instead of an offset for the
mb_strrpos function has been removed; an explicit
0 offset with the encoding should be provided as the fourth argument instead.
The
ISO_8859-* character encoding aliases have been replaced by
ISO8859-* aliases for better interoperability with the iconv extension. The mbregex ISO 8859 aliases with underscores (
ISO_8859_* and
ISO8859_*) have also been removed.
mb_ereg and
mb_eregi will now return boolean ENTITY on a successful match. Previously they returned integer
1 if
matches was not passed, or
max(1, strlen($matches[0])) if
matches was passed.
OCI8
The
OCI-Lob class is now called
OCILob, and the
OCI-Collection class is now called
OCICollection for name compliance enforced by PHP 8 arginfo type annotation tooling.
Several alias functions have been marked as deprecated.
oci_internal_debug and its alias
ociinternaldebug have been removed.
ODBC
odbc_connect no longer reuses connections.
The unused
flags parameter of
odbc_exec has been removed.
OpenSSL
openssl_seal and
openssl_open now require
method to be passed, as the previous default of
"RC4" is considered insecure.
Regular Expressions (Perl-Compatible)
When passing invalid escape sequences they are no longer interpreted as literals. This behavior previously required the
X modifier – which is now ignored.
PHP Data Objects
The default error handling mode has been changed from "silent" to "exceptions". See Errors and error handling for details.
The signatures of some PDO methods have changed:
PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs),
PDOStatement::setFetchMode(int $mode, mixed ...$args)
PDO ODBC
The ENTITY directive pdo_odbc.db2_instance_name has been removed.
PDO MySQL
PDO::inTransaction now reports the actual transaction state of the connection, rather than an approximation maintained by PDO. If a query that is subject to "implicit commit" is executed, PDO::inTransaction will subsequently return ENTITY, as a transaction is no longer active.
PostgreSQL
The deprecated
pg_connect syntax using multiple parameters instead of a connection string is no longer supported.
The deprecated
pg_lo_import and
pg_lo_export signature that passes the connection as the last argument is no longer supported. The connection should be passed as first argument instead.
pg_fetch_all will now return an empty array instead of ENTITY for result sets with zero rows.
Phar
Metadata associated with a phar will no longer be automatically unserialized, to fix potential security vulnerabilities due to object instantiation, autoloading, etc.
Reflection
The method signatures
ReflectionClass::newInstance($args),
ReflectionFunction::invoke($args),
ReflectionMethod::invoke($object, $args)
have been changed to:
ReflectionClass::newInstance(...$args),
ReflectionFunction::invoke(...$args),
ReflectionMethod::invoke($object, ...$args)
Code that must be compatible with both PHP 7 and PHP 8 can use the following signatures to be compatible with both versions:
ReflectionClass::newInstance($arg = null, ...$args),
ReflectionFunction::invoke($arg = null, ...$args),
ReflectionMethod::invoke($object, $arg = null, ...$args)
The ReflectionType::__toString method will now return a complete debug representation of the type, and is no longer deprecated. In particular the result will include a nullability indicator for nullable types. The format of the return value is not stable and may change between PHP versions.
Reflection export() methods have been removed. Instead reflection objects can be cast to string.
ReflectionMethod::isConstructor and ReflectionMethod::isDestructor now also return ENTITY for __construct() and __destruct() methods of interfaces. Previously, this would only be true for methods of classes and traits.
ReflectionType::isBuiltin method has been moved to
ReflectionNamedType.
ReflectionUnionType does not have it.
Sockets
The deprecated
AI_IDN_ALLOW_UNASSIGNED and
AI_IDN_USE_STD3_ASCII_RULES
flags for
socket_addrinfo_lookup have been removed.
Standard PHP Library (SPL)
SplFileObject::fgetss has been removed.
SplFileObject::seek now always seeks to the beginning of the line. Previously, positions
ENTITY=1 sought to the beginning of the next line.
SplHeap::compare now specifies a method signature. Inheriting classes implementing this method will now have to use a compatible method signature.
SplDoublyLinkedList::push, SplDoublyLinkedList::unshift and SplQueue::enqueue now return
void instead of ENTITY.
spl_autoload_register will now always throw a
TypeError on invalid arguments, therefore the second argument
do_throw is ignored and a notice will be emitted if it is set to ENTITY.
SplFixedArray is now an IteratorAggregate and not an Iterator. SplFixedArray::rewind, SplFixedArray::current, SplFixedArray::key, SplFixedArray::next, and SplFixedArray::valid have been removed. In their place, SplFixedArray::getIterator has been added. Any code which uses explicit iteration over SplFixedArray must now obtain an Iterator through SplFixedArray::getIterator. This means that
SplFixedArray is now safe to use in nested loops.
Standard Library
assert will no longer evaluate string arguments, instead they will be treated like any other argument.
assert($a == $b) should be used instead of
assert('$a == $b'). The assert.quiet_eval ini directive and the
ASSERT_QUIET_EVAL constant have also been removed, as they would no longer have any effect.
parse_str can no longer be used without specifying a result array.
The string.strip_tags filter has been removed.
The
needle argument of
strpos,
strrpos,
stripos,
strripos,
strstr,
strchr,
strrchr, and
stristr will now always be interpreted as a string. Previously non-string needles were interpreted as an ASCII code point. An explicit call to
chr can be used to restore the previous behavior.
The
needle argument for
strpos,
strrpos,
stripos,
strripos,
strstr,
stristr and
strrchr can now be empty.
The
length argument for
substr,
substr_count,
substr_compare, and
iconv_substr can now be ENTITY. ENTITY values will behave as if no length argument was provided and will therefore return the remainder of the string instead of an empty string.
The
length argument for
array_splice can now be ENTITY. ENTITY values will behave identically to omitting the argument, thus removing everything from the
offset to the end of the array.
The
args argument of
vsprintf,
vfprintf, and
vprintf must now be an array. Previously any type was accepted.
The
'salt' option of
password_hash is no longer supported. If the
'salt' option is used a warning is generated, the provided salt is ignored, and a generated salt is used instead.
The
quotemeta function will now return an empty string if an empty string was passed. Previously ENTITY was returned.
The following functions have been removed:
hebrevc,
convert_cyr_string,
money_format,
ezmlm_hash,
restore_include_path,
get_magic_quotes_gpc,
get_magic_quotes_runtime,
fgetss
FILTER_SANITIZE_MAGIC_QUOTES has been removed.
Calling
implode with parameters in a reverse order
($pieces, $glue) is no longer supported.
parse_url will now distinguish absent and empty queries and fragments:
http://example.com/foo → query = null, fragment = null,
http://example.com/foo? → query = "", fragment = null,
http://example.com/foo# → query = null, fragment = "",
http://example.com/foo?# → query = "", fragment = "" Previously all cases resulted in query and fragment being ENTITY.
var_dump and
debug_zval_dump will now print floating-point numbers using serialize_precision rather than precision. In a default configuration, this means that floating-point numbers are now printed with full accuracy by these debugging functions.
If the array returned by __sleep() contains non-existing properties, these are now silently ignored. Previously, such properties would have been serialized as if they had the value ENTITY.
The default locale on startup is now always
"C". No locales are inherited from the environment by default. Previously,
LC_ALL was set to
"C", while
LC_CTYPE was inherited from the environment. However, some functions did not respect the inherited locale without an explicit
setlocale call. An explicit
setlocale call is now always required if a locale component should be changed from the default.
The deprecated DES fallback in
crypt has been removed. If an unknown salt format is passed to
crypt, the function will fail with
*0 instead of falling back to a weak DES hash now.
Specifying out of range rounds for SHA256/SHA512
crypt will now fail with
*0 instead of clamping to the closest limit. This matches glibc behavior.
The result of sorting functions may have changed, if the array contains elements that compare as equal.
Any functions accepting callbacks that are not explicitly specified to accept parameters by reference will now warn if a callback with reference parameters is used. Examples include
array_filter and
array_reduce. This was already the case for most, but not all, functions previously.
The HTTP stream wrapper as used by functions like
file_get_contents now advertises HTTP/1.1 rather than HTTP/1.0 by default. This does not change the behavior of the client, but may cause servers to respond differently. To retain the old behavior, set the
'protocol_version' stream context option, e.g.
['protocol_version' => '1.0']]);
echo file_get_contents('http://example.org', false, $ctx);
?>
Calling
crypt without an explicit salt is no longer supported. If you would like to produce a strong hash with an auto-generated salt, use
password_hash instead.
substr,
mb_substr,
iconv_substr and
grapheme_substr now consistently clamp out-of-bounds offsets to the string boundary. Previously, ENTITY was returned instead of the empty string in some cases.
On Windows, the program execution functions (
proc_open,
exec,
popen etc.) using the shell, now consistently execute
%comspec% /s /c "$commandline", which has the same effect as executing
$commandline (without additional quotes).
Sysvsem
The
auto_release parameter of
sem_get was changed to accept bool values rather than int.
Tidy
The
use_include_path parameter, which was not used internally, has been removed from
tidy_repair_string.
tidy::repairString and tidy::repairFile became static methods.
Tokenizer
T_COMMENT tokens will no longer include a trailing newline. The newline will instead be part of a following
T_WHITESPACE token. It should be noted that
T_COMMENT is not always followed by whitespace, it may also be followed by
T_CLOSE_TAG or end-of-file.
Namespaced names are now represented using the
T_NAME_QUALIFIED (
Foo\Bar),
T_NAME_FULLY_QUALIFIED (
\Foo\Bar) and
T_NAME_RELATIVE (
namespace\Foo\Bar) tokens.
T_NS_SEPARATOR is only used for standalone namespace separators, and only syntactially valid in conjunction with group use declarations.
XMLReader
XMLReader::open and XMLReader::XML are now static methods. They can still be called as instance methods, but inheriting classes need to declare them as static if they override these methods.
XML-RPC
The XML-RPC extension has been moved to PECL and is no longer part of the PHP distribution.
Zip
ZipArchive::OPSYS_Z_CPM has been removed (this name was a typo). Use
ZipArchive::OPSYS_CPM instead.
Zlib
gzgetss has been removed.
zlib.output_compression is no longer automatically disabled for
Content-Type: image/*.
Windows PHP Test Packs
The test runner has been renamed from
run-test.php to
run-tests.php, to match its name in php-src.
New Classes and Interfaces
cURL
CurlHandle
CurlMultiHandle
CurlShareHandle
Enchant
EnchantBroker
EnchantDictionary
GD
GdImage
OpenSSL
OpenSSLAsymmetricKey
OpenSSLCertificate
OpenSSLCertificateSigningRequest
Shmop
Shmop
Sockets
AddressInfo
Socket
System V
SysvMessageQueue
SysvSemaphore
SysvSharedMemory
XML Parser
XMLParser
XMLWriter
XMLWriter
Zlib
DeflateContext
InflateContext
New Features
PHP Core
Named Arguments
Support for Named Arguments has been added.
Attributes
Support for Attributes has been added.
Constructor Property Promotion
Support for constructor property promotion (declaring properties in the constructor signature) has been added.
Union Types
Support for union types has been added.
Match Expression
Support for
match expressions has been added.
Nullsafe Operator
Support for the nullsafe operator (
?->) has been added.
Other new Features
The WeakMap class has been added.
The
ValueError class has been added.
Any number of function parameters may now be replaced by a variadic argument, as long as the types are compatible. For example, the following code is now allowed:
static (as in "late static binding") can now be used as a return type:
It is now possible to fetch the class name of an object using
$object::class. The result is the same as
get_class($object).
ENTITY and ENTITY can now be used with arbitrary expressions, using
new (expression)(...$args) and
$obj instanceof (expression).
Some consistency fixes to variable syntax have been applied, for example writing
Foo::BAR::$baz is now allowed.
Added Stringable interface, which is automatically implemented if a class defines a __toString() method.
Traits can now define abstract private methods. Such methods must be implemented by the class using the trait.
throw can now be used as an expression. That allows usages like:
throw new Exception('Exception in arrow function');
$user = $session->user ?? throw new Exception('Must have user');
An optional trailing comma is now allowed in parameter lists.
get_resource_id has been added, which returns the same value as
(int) $resource. It provides the same functionality under a clearer API.
The
InternalIterator has been added.
Date and Time
DateTime::createFromInterface and DateTimeImmutable::createFromInterface have been added.
The DateTime format specifier
p has been added, which is the same as
P but returns
Z rather than
+00:00 for UTC.
DOM
DOMParentNode and DOMChildNode with new traversal and manipulation APIs have been added.
Filter
FILTER_VALIDATE_BOOL has been added as an alias for
FILTER_VALIDATE_BOOLEAN. The new name is preferred, as it uses the canonical type name.
Enchant
enchant_dict_add,
enchant_dict_is_added, and
LIBENCHANT_VERSION have been added.
FPM
Added a new option
pm.status_listen that allows getting the status from different endpoint (e.g. port or UDS file) which is useful for getting the status when all children are busy with serving long running requests.
Hash
HashContext objects can now be serialized.
Internationalization Functions
The
IntlDateFormatter::RELATIVE_FULL,
IntlDateFormatter::RELATIVE_LONG,
IntlDateFormatter::RELATIVE_MEDIUM, and
IntlDateFormatter::RELATIVE_SHORT constants have been added.
LDAP
ldap_count_references has been added, which returns the number of reference messages in a search result.
OPcache
If the opcache.record_warnings ini setting is enabled, OPcache will record compile-time warnings and replay them on the next include, even if it is served from cache.
OpenSSL
Added Cryptographic Message Syntax (CMS) (RFC 5652) support composed of functions for encryption, decryption, signing, verifying and reading. The API is similar to the API for PKCS #7 functions with an addition of new encoding constants:
OPENSSL_ENCODING_DER,
OPENSSL_ENCODING_SMIME and
OPENSSL_ENCODING_PEM:
openssl_cms_encrypt encrypts the message in the file with the certificates and outputs the result to the supplied file.,
openssl_cms_decrypt that decrypts the S/MIME message in the file and outputs the results to the supplied file.,
openssl_cms_read that exports the CMS file to an array of PEM certificates.,
openssl_cms_sign that signs the MIME message in the file with a cert and key and output the result to the supplied file.,
openssl_cms_verify that verifies that the data block is intact, the signer is who they say they are, and returns the certs of the signers.
Regular Expressions (Perl-Compatible)
preg_last_error_msg has been added, which returns a human-readable message for the last PCRE error. It complements
preg_last_error, which returns an integer enum value instead.
Reflection
The following methods can now return information about default values of parameters of internal functions:
ReflectionParameter::isDefaultValueAvailable, ReflectionParameter::getDefaultValue, ReflectionParameter::isDefaultValueConstant, ReflectionParameter::getDefaultValueConstantName
SQLite3
SQLite3::setAuthorizer and respective class constants have been added to set a userland callback that will be used to authorize or not an action on the database.
Standard Library
str_contains,
str_starts_with and
str_ends_with have been added, which check whether
haystack contains, starts with or ends with
needle, respectively.
fdiv has been added, which performs a floating-point division under IEEE 754 semantics. Division by zero is considered well-defined and will return one of
Inf,
-Inf or
NaN.
get_debug_type has been added, which returns a type useful for error messages. Unlike
gettype, it uses canonical type names, returns class names for objects, and indicates the resource type for resources.
printf and friends now support the
%h and
%H format specifiers. These are the same as
%g and
%G, but always use
"." as the decimal separator, rather than determining it through the
LC_NUMERIC locale.
printf and friends now support using
"*" as width or precision, in which case the width/precision is passed as an argument to printf. This also allows using precision
-1 with
%g,
%G,
%h and
%H. For example, the following code can be used to reproduce PHP's default floating point formatting:
proc_open now supports pseudo-terminal (PTY) descriptors. The following attaches
stdin,
stdout and
stderr to the same PTY:
proc_open now supports socket pair descriptors. The following attaches a distinct socket pair to
stdin,
stdout and
stderr:
Unlike pipes, sockets do not suffer from blocking I/O issues on Windows. However, not all programs may work correctly with stdio sockets.
Sorting functions are now stable, which means that equal-comparing elements will retain their original order.
array_diff,
array_intersect and their variations can now be used with a single array as argument. This means that usages like the following are now possible:
The
flag parameter of
ob_implicit_flush was changed to accept a
bool rather than an
int.
Tokenizer
PhpToken adds an object-based interface to the tokenizer. It provides a more uniform and ergonomic representation, while being more memory efficient and faster.
Zip
The Zip extension has been updated to version 1.19.1.
New ZipArchive::setMtimeName and ZipArchive::setMtimeIndex to set the modification time of an entry.
New ZipArchive::registerProgressCallback to provide updates during archive close.
New ZipArchive::registerCancelCallback to allow cancellation during archive close.
New ZipArchive::replaceFile to replace an entry content.
New ZipArchive::isCompressionMethodSupported to check optional compression features.
New ZipArchive::isEncryptionMethodSupported to check optional encryption features.
The
ZipArchive::lastId property to get the index value of the last added entry has been added.
Errors can now be checked after an archive has been closed using the
ZipArchive::status and
ZipArchive::statusSys properties, or the ZipArchive::getStatusString method.
The
'remove_path' option of ZipArchive::addGlob and ZipArchive::addPattern is now treated as an arbitrary string prefix (for consistency with the
'add_path' option), whereas formerly it was treated as a directory name.
Optional compression / encryption features are now listed in phpinfo.
Other Changes
Changes in SAPI Modules
Apache2Handler
The PHP module has been renamed from
php7_module to
php_module.
Changed Functions
Reflection
ReflectionClass::getConstants and ReflectionClass::getReflectionConstants results can be now filtered via a new parameter
filter. Three new constants were added to be used with it:
ReflectionClassConstant::IS_PUBLIC,
ReflectionClassConstant::IS_PROTECTED,
ReflectionClassConstant::IS_PRIVATE
Standard
The math functions
abs,
ceil,
floor and
round now properly heed the
strict_types directive. Previously, they coerced the first argument even in strict type mode.
Zip
The ZipArchive::addGlob and ZipArchive::addPattern methods accept more values in the
options array argument:
flags,
comp_method,
comp_flags,
env_method,
enc_password
ZipArchive::addEmptyDir, ZipArchive::addFile and ZipArchive::addFromString methods have a new
flags argument. This allows managing name encoding (
ZipArchive::FL_ENC_*) and entry replacement (
ZipArchive::FL_OVERWRITE).
ZipArchive::extractTo now restores the file modification time.
Other Changes to Extensions
CURL
The CURL extension now requires at least libcurl 7.29.0.
The deprecated parameter
version of
curl_version has been removed.
Date and Time
DatePeriod now implements IteratorAggregate (instead of Traversable).
DOM
DOMNamedNodeMap and
DOMNodeList now implement IteratorAggregate (instead of Traversable).
Intl
IntlBreakIterator and
ResourceBundle now implement IteratorAggregate (instead of Traversable).
Enchant
The enchant extension now uses libenchant-2 by default when available. libenchant version 1 is still supported but is deprecated and could be removed in the future.
GD
The
num_points parameter of
imagepolygon,
imageopenpolygon and
imagefilledpolygon is now optional, i.e. these functions may be called with either 3 or 4 arguments. If the argument is omitted, it is calculated as
count($points)/2.
The function
imagegetinterpolation to get the current interpolation method has been added.
JSON
The JSON extension cannot be disabled anymore and is always an integral part of any PHP build, similar to the date extension.
MBString
The Unicode data tables have been updated to version 13.0.0.
PDO
PDOStatement now implements IteratorAggregate (instead of Traversable).
LibXML
The minimum required libxml version is now 2.9.0. This means that external entity loading is now guaranteed to be disabled by default, and no extra steps need to be taken to protect against XXE attacks.
MySQLi / PDO MySQL
When mysqlnd is not used (which is the default and recommended option), the minimum supported libmysqlclient version is now 5.5.
mysqli_result now implements IteratorAggregate (instead of Traversable).
PGSQL / PDO PGSQL
The PGSQL and PDO PGSQL extensions now require at least libpq 9.1.
Readline
Calling
readline_completion_function before the interactive prompt starts (e.g. in auto_prepend_file) will now override the default interactive prompt completion function. Previously,
readline_completion_function only worked when called after starting the interactive prompt.
SimpleXML
SimpleXMLElement now implements RecursiveIterator and absorbed the functionality of
SimpleXMLIterator.
SimpleXMLIterator is an empty extension of
SimpleXMLElement.
Changes to INI File Handling
com.dotnet_version is a new INI directive to choose the version of the .NET framework to use for
dotnet objects.
zend.exception_string_param_max_len is a new INI directive to set the maximum string length in an argument of a stringified stack strace.
EBCDIC
EBCDIC targets are no longer supported, though it's unlikely that they were still working in the first place.
Performance
A Just-In-Time (JIT) compiler has been added to the opcache extension.
array_slice on an array without gaps will no longer scan the whole array to find the start offset. This may significantly reduce the runtime of the function with large offsets and small lengths.
strtolower now uses a SIMD implementation when using the
"C"
LC_CTYPE locale (which is the default).
Migrating from PHP 8.0.x to PHP 8.1.x
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.
ENTITY 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
New Global Constants
cURL
CURLOPT_DOH_URL
CURLOPT_ISSUERCERT_BLOB
CURLOPT_PROXY_ISSUERCERT
CURLOPT_PROXY_ISSUERCERT_BLOB
CURLOPT_PROXY_SSLCERT_BLOB
CURLOPT_PROXY_SSLKEY_BLOB
CURLOPT_SSLCERT_BLOB
CURLOPT_SSLKEY_BLOB
GD
IMG_AVIF
IMG_WEBP_LOSSLESS
MySQLi
MYSQLI_REFRESH_REPLICA
This constant has been added as a replacement for
MYSQLI_REFRESH_SLAVE, in line with an upstream change in MySQL. The old constant is still available for backwards-compatibility reasons, but may be deprecated/removed in the future.
PCNTL
PRIO_DARWIN_BG
PRIO_DARWIN_THREAD
POSIX
POSIX_RLIMIT_KQUEUES
POSIX_RLIMIT_NPTS
Sockets
The following socket options are now defined if they are supported:
SO_ACCEPTFILTER
SO_DONTTRUNC
SO_WANTMORE
SO_MARK
TCP_DEFER_ACCEPT
Sodium
SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES
SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES
SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES
SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES
SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES
SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES
SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES
SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES
Standard
IMAGETYPE_AVIF
Tokenizer
T_READONLY
Deprecated Features
PHP Core
Implementing Serializable without
__serialize and
__unserialize
Either only the new methods should be implemented, if no support for PHP prior to version 7.4 is provided, or both should be implemented.
Passing ENTITY to non-nullable parameters of built-in functions
Scalar types for built-in functions are nullable by default. This behaviour is deprecated to align with the behaviour of user-defined functions, where scalar types need to be marked as nullable explicitly.
Implicit incompatible ENTITY to ENTITY conversions
The implicit conversion of ENTITY to ENTITY which leads to a loss in precision is now deprecated. This affects ENTITY keys, ENTITY type declarations in coercive mode, and operators working on ENTITYs.
Calling a static element on a trait
Calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.
Returning a non-ENTITY from
__sleep
Returning a value which is not an ENTITY from __sleep() now generates a diagnostic.
Returning by reference from a
void function
Such a function is contradictory, and already emits the following
E_NOTICE when called:
Only variable references should be returned by reference.
Autovivification from ENTITY
Autovivification is the process of creating a new ENTITY when appending to a value. Autovivification is prohibited from scalar values, ENTITY however was an exception. This is now deprecated.
[!NOTE]
Autovivification from ENTITY and undefined values is still allowed:
ctype
Verifying non-string arguments
Passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to ENTITY or an explicit call to
chr should be made. All
ctype_*() functions are affected.
Date
date_sunrise and
date_sunset have been deprecated in favor of
date_sun_info.
strptime has been deprecated. Use
date_parse_from_format instead (for locale-independent parsing), or IntlDateFormatter::parse (for locale-dependent parsing).
strftime and
gmstrftime have been deprecated. Use
date instead (for locale-independent formatting), or IntlDateFormatter::format (for locale-dependent formatting).
Filter
The
FILTER_SANITIZE_STRING and
FILTER_SANITIZE_STRIPPED filters are deprecated.
The filter.default INI directive is deprecated.
GD
The
num_points of
imagepolygon,
imageopenpolygon and
imagefilledpolygon has been deprecated.
Hash
The
mhash,
mhash_keygen_s2k,
mhash_count,
mhash_get_block_size, and
mhash_get_hash_name functions have been deprecated. Use the
hash_*() functions instead.
IMAP
The
NIL constant has been deprecated. Use
0 instead.
Intl
Calling IntlCalendar::roll with a ENTITY argument is deprecated. Use
1 and
-1 instead of ENTITY and ENTITY respectively.
Multibyte String
Calling
mb_check_encoding without any arguments is deprecated.
MySQLi
The mysqli_driver::$driver_version property has been deprecated. It was meaningless and outdated, use
PHP_VERSION_ID instead.
Calling mysqli::get_client_info or
mysqli_get_client_info with the
mysqli argument has been deprecated. Call
mysqli_get_client_info without any arguments to obtain the version information of the client library.
The mysqli::init method has been deprecated. Replace calls to parent::init with parent::__construct.
OCI8
The oci8.old_oci_close_semantics INI directive is deprecated.
ODBC
odbc_result_all has been deprecated.
PDO
The
PDO::FETCH_SERIALIZE fetch mode has been deprecated.
PgSQL
Not passing the connection argument to all
pgsql_*() functions has been deprecated.
SOAP
The
ssl_method option of SoapClient::__construct has been deprecated in favor of SSL stream context options.
Standard
Calling
key,
current,
next,
prev,
reset, or
end on ENTITYs is deprecated. Either convert the ENTITY to an ENTITY using
get_mangled_object_vars first, or use the methods provided by a class that implements Iterator, such as
ArrayIterator, instead.
The auto_detect_line_endings INI directive is deprecated. If necessary, handle
"\r" line breaks manually instead.
The
FILE_BINARY and
FILE_TEXT constants have been deprecated. They never had any effect.
Backward Incompatible Changes
PHP Core
$GLOBALS Access Restrictions
Access to the
$GLOBALS array is now subject to a number of restrictions. Read and write access to individual array elements like
$GLOBALS['var'] continues to work as-is. Read-only access to the entire
$GLOBALS array also continues to be supported. However, write access to the entire
$GLOBALS array is no longer supported. For example,
array_pop($GLOBALS) will result in an error.
Usage of static Variables in Inherited Methods
When a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method.
This means that static variables in methods now behave the same way as static properties.
Optional parameters specified before required parameters
An optional parameter specified before required parameters is now always treated as required, even when called using named arguments. As of PHP 8.0.0, but prior to PHP 8.1.0, the below emits a deprecation notice on the definition, but runs successfully when called. As of PHP 8.1.0, an error of class
ArgumentCountError is thrown, as it would be when called with positional arguments.
getMessage(), "\n";
}
?>
ENTITY
Deprecated: Required parameter $flavour follows optional parameter $container
in example.php on line 3
Making a bowl of raspberry yogurt.
ENTITY
Deprecated: Optional parameter $container declared before required parameter
$flavour is implicitly treated as a required parameter in example.php on line 3
ArgumentCountError - makeyogurt(): Argument #1 ($container) not passed
Note that a default value of ENTITY can be used before required parameters to specify a nullable type, but the parameter will still be required.
Return Type Compatibility with Internal Classes
Most non-final internal methods now require overriding methods to declare a compatible return type, otherwise a deprecated notice is emitted during inheritance validation. In case the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a
ReturnTypeWillChange attribute can be added to silence the deprecation notice.
New Keywords
readonly is a keyword now. However, it still may be used as function name.
never is now a reserved word, so it cannot be used to name a class, interface or trait, and is also prohibited from being used in namespaces.
Resource to Object Migration
Several ENTITYs have been migrated to ENTITYs. Return value checks using
is_resource should be replaced with checks for ENTITY.
The FileInfo functions now accept and return
finfo objects instead of
fileinfo ENTITYs.
The FTP functions now accept and return
FTP\Connection objects instead of
ftp ENTITYs.
The IMAP functions now accept and return
IMAP\Connection objects instead of
imap ENTITYs.
The LDAP functions now accept and return
LDAP\Connection objects instead of
ldap link ENTITYs.
The LDAP functions now accept and return
LDAP\Result objects instead of
ldap result ENTITYs.
The LDAP functions now accept and return
LDAP\ResultEntry objects instead of
ldap result entry ENTITYs.
The PgSQL functions now accept and return
PgSql\Connection objects instead of
pgsql link ENTITYs.
The PgSQL functions now accept and return
PgSql\Result objects instead of
pgsql result ENTITYs.
The PgSQL functions now accept and return
PgSql\Lob objects instead of
pgsql large object ENTITYs.
The PSpell functions now accept and return
PSpell\Dictionary objects instead of
pspell ENTITYs.
The PSpell functions now accept and return
PSpell\Config objects instead of
pspell config ENTITYs.
MySQLi
mysqli_fetch_fields, and
mysqli_fetch_field_direct will now always return
0 for the max_length. This information can be computed by iterating over the result set, and taking the maximum length. This is what PHP was doing internally previously.
The
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH option no longer has any effect.
The
MYSQLI_STORE_RESULT_COPY_DATA option no longer has any effect. Passing any value to the
mode parameter of mysqli::store_result no longer has any effect.
mysqli::connect now returns ENTITY instead of ENTITY on success.
The default error handling mode has been changed from "silent" to "exceptions" See the MySQLi reporting mode page for more details on what this entails, and how to explicitly set this attribute. To restore the previous behaviour use:
mysqli_report(MYSQLI_REPORT_OFF);
Classes extending mysqli_stmt::execute are now required to specify the additional optional parameter.
MySQLnd
The mysqlnd.fetch_data_copy INI directive has been removed. This should not result in user-visible behavior changes.
OpenSSL
EC private keys will now be exported in PKCS#8 format rather than traditional format, just like all other keys.
openssl_pkcs7_encrypt and
openssl_cms_encrypt will now default to using AES-128-CBC rather than RC2-40. The RC2-40 cipher is considered insecure and not enabled by default by OpenSSL 3.
PHP Data Objects
PDO::ATTR_STRINGIFY_FETCHES now stringifies values of type ENTITY to
"0" or
"1". Previously ENTITYs were not stringified.
Calling PDOStatement::bindColumn with
PDO::PARAM_LOB will now constantly bind a stream result when
PDO::ATTR_STRINGIFY_FETCHES is not enabled. Previously, the result would either be a stream or a string depending on the used database driver and the time the binding is performed.
MySQL Driver
Integers and floats in result sets will now be returned using native PHP types instead of ENTITYs when using emulated prepared statements. This matches the behavior of native prepared statements. The previous behaviour can be restored by enabling the
PDO::ATTR_STRINGIFY_FETCHES option.
SQLite Driver
Integers and floats in results sets will now be returned using native PHP types. The previous behaviour can be restored by enabling the
PDO::ATTR_STRINGIFY_FETCHES option.
Phar
To comply with the ArrayAccess interface, Phar::offsetUnset and PharData::offsetUnset no longer return a ENTITY.
Standard
version_compare no longer accepts undocumented operator abbreviations.
htmlspecialchars,
htmlentities,
htmlspecialchars_decode,
html_entity_decode, and
get_html_translation_table now use
ENT_QUOTES | ENT_SUBSTITUTE rather than
ENT_COMPAT by default. This means that
' is escaped to
ENTITY#039; while previously nothing was done. Additionally, malformed UTF-8 will be replaced by a Unicode substitution character, instead of resulting in an empty string.
debug_zval_dump now prints the refcount of a reference wrappers with their refcount, instead of only prepending
ENTITY to the value. This more accurately models reference representation since PHP 7.0.
debug_zval_dump now prints
interned instead of a dummy refcount for interned strings and immutable arrays.
Standard PHP Library (SPL)
SplFixedArray, will now be JSON encoded like an ENTITY
New Classes and Interfaces
cURL
CURLStringFile
FileInfo
finfo
FTP
FTP\Connection
IMAP
IMAP\Connection
Intl
IntlDatePatternGenerator
LDAP
LDAP\Connection
LDAP\Result
LDAP\ResultEntry
PgSQL
PgSql\Connection
PgSql\Lob
PgSql\Result
PSpell
PSpell\Config
PSpell\Dictionary
Reflection
ReflectionFiber
New Features
PHP Core
Integer Octal Literal Prefix
Octal integers can now use an explicit
0o/
0O prefix in integer literals, similarly to binary and hexadecimal integer literals.
Array Unpacking with String Keys
Added support for array unpacking with strings keys.
'b'];
$arr2 = [...$arr1, 'c' => 'd']; //[1, 'a' => 'b', 'c' => 'd']
?>
Named Argument After Argument Unpacking
It is now possible to specify named arguments after an argument unpack. e.g. foo(...$args, named: $arg).
full-path Key for File Uploads
File uploads now provide an additional
full_path key, which contains the full path (rather than just the basename) of the uploaded file. This is intended for use in conjunction with "upload webkitdirectory".
Enumerations
Support for Enumerations has been added.
Fibers
Support for Fibers has been added.
First Class Callable Syntax
Closures for callables can now be created using the syntax
myFunc(...), which is identical to
Closure::fromCallable('myFunc').
[!NOTE]
The
... is part of the syntax, and not an omission.
Intersection Types
Support for intersection types has been added.
[!CAUTION]
Intersection types cannot be used together with union types
Never type
A new return only type ENTITY has been added. This indicates that a function either
exit, throws an exception, or doesn't terminate.
ENTITY in Initializers
It is now possible to use
new ClassName() expressions as the default value of a parameter, static variable, global constant initializers, and as attribute arguments. Objects can also be passed to
define now.
Readonly properties
Support for readonly has been added.
Final class constants
Added support for the final modifier for class constants. Also, interface constants become overridable by default.
CURL
Added the
CURLOPT_DOH_URL option.
Added options for blob certificate when libcurl ENTITY= 7.71.0:
CURLOPT_ISSUERCERT_BLOB
CURLOPT_PROXY_ISSUERCERT
CURLOPT_PROXY_ISSUERCERT_BLOB
CURLOPT_PROXY_SSLCERT_BLOB
CURLOPT_PROXY_SSLKEY_BLOB
CURLOPT_SSLCERT_BLOB
CURLOPT_SSLKEY_BLOB
Added
CURLStringFile, which can be used to post a file from a ENTITY rather than a file:
$file]);
?>
FPM
Added openmetrics status format. It can be used by Prometheus to fetch FPM metrics.
Added new pool option for the dynamic process manager called
pm.max_spawn_rate. It allows to start a number of children at a faster rate when dynamic pm is selected. The default value is
32 which was the previous hard coded value.
GD
Avif support is now available through
imagecreatefromavif and
imageavif, if libgd has been built with Avif support.
Hash
The following functions
hash,
hash_file, and
hash_init now support an additional optional
options argument, which can be used to pass algorithm specific data.
MurmurHash3
Added support for
MurmurHash3 with streaming support. The following variants are implemented:
murmur3a, 32-bit hash
murmur3c, 128-bit hash for x86
murmur3f, 128-bit hash for x64
The initial hash state can be passed through the
seed key in the
options array, for example:
42]);
echo $h, "\n";
?>
A valid seed value is within the range from
0 to the platform defined
UINT_MAX, usually
4294967295.
xxHash
Added support for
xxHash. The following variants are implemented:
xxh32, 32-bit hash
xxh64, 64-bit hash
xxh3, 64-bit hash
xxh128, 128-bit hash
The initial hash state can be passed through the
seed key in the
options array, for example:
42]);
echo $h, "\n";
?>
Secret usage is supported through passing the
secret key in the
options array, too:
"at least 136 bytes long secret here"]);
echo $h, "\n";
?>
The quality of the custom secret is crucial for the quality of the resulting hash. It is highly recommended for the secret to use the best possible entropy.
MySQLi
New INI directive
mysqli.local_infile_directory
The mysqli.local_infile_directory INI directive has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if mysqli.allow_local_infile is not enabled, as all directories are allowed in that case.
Binding parameters in execute
It is now possible to bind parameters by passing them as an array to mysqli_stmt::execute. All values will be bound as strings. Only list arrays are allowed. This new feature is not available when MySQLi is compiled with libmysqlclient.
prepare('INSERT INTO users(id, name) VALUES(?,?)');
$stmt->execute([1, $username]);
?>
New method mysqli_result::fetch_column
mysqli_result::fetch_column has been added to allow fetching a single scalar value from the result set. The new method accepts an optional 0-based
column parameter of type ENTITY specifying which column to fetch from.
query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_column();
?>
PDO
The
PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY attribute has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if
PDO::MYSQL_ATTR_LOCAL_INFILE is not enabled, as all directories are allowed in that case.
PDO_SQLite
SQLite's
"file:" DSN syntax is now supported, which allows specifying additional flags. This feature is not available if open_basedir is set.
POSIX
Added
POSIX_RLIMIT_KQUEUES and
POSIX_RLIMIT_NPTS. These rlimits are only available on FreeBSD.
Standard
fputcsv now accepts a new
eol argument which allows to define a custom End of Line sequence, the default remains the same and is
"\n".
SPL
SplFileObject::fputcsv now accepts a new
eol argument which allows to define a custom End of Line sequence, the default remains the same and is
"\n".
New Functions
PHP Core
array_is_list
GD
imagecreatefromavif
imageavif
MySQLi
mysqli_result::fetch_column
mysqli_fetch_column
Process Control
pcntl_rfork
Reflection
ReflectionFunctionAbstract::getClosureUsedVariables
Standard
fsync
fdatasync
Sodium
XChaCha20
sodium_crypto_stream_xchacha20
sodium_crypto_stream_xchacha20_keygen
sodium_crypto_stream_xchacha20_xor
Ristretto255
Ristretto255 functions are available as of libsodium 1.0.18.
sodium_crypto_core_ristretto255_add
sodium_crypto_core_ristretto255_from_hash
sodium_crypto_core_ristretto255_is_valid_point
sodium_crypto_core_ristretto255_random
sodium_crypto_core_ristretto255_scalar_add
sodium_crypto_core_ristretto255_scalar_complement
sodium_crypto_core_ristretto255_scalar_invert
sodium_crypto_core_ristretto255_scalar_mul
sodium_crypto_core_ristretto255_scalar_negate
sodium_crypto_core_ristretto255_scalar_random
sodium_crypto_core_ristretto255_scalar_reduce
sodium_crypto_core_ristretto255_scalar_sub
sodium_crypto_core_ristretto255_sub
sodium_crypto_scalarmult_ristretto255
sodium_crypto_scalarmult_ristretto255_base
Other Changes
Changes in SAPI Modules
CLI
Using
-a without the readline extension will now result in an error. Previously,
-a without readline had the same behavior as calling
php without any arguments, apart from printing an additional
"Interactive mode enabled" message. This mode was not interactive.
PHPDBG
Remote functionality from phpdbg has been removed.
Changed Functions
Core
The order of properties used in ENTITY,
var_dump,
serialize, object comparison, etc. was changed. Properties are now ordered naturally according to their declaration and inheritance. Properties declared in a base class are going to be before the child properties.
This order is consistent with internal layout of properties in
zend_object structure and repeats the order in
default_properties_table[] and
properties_info_table[]. The old order was not documented and was caused by class inheritance implementation details.
Filter
The
FILTER_FLAG_ALLOW_OCTAL flag of the
FILTER_VALIDATE_INT filter now accept octal string with the leading octal prefix (
"0o"/
"0O").
GMP
All GMP functions now accept octal string with the leading octal prefix (
"0o"/
"0O").
PDO ODBC
PDO::getAttribute with
PDO::ATTR_SERVER_INFO and
PDO::ATTR_SERVER_VERSION now return values instead of throwing
PDOException.
Reflection
ReflectionProperty::setAccessible and ReflectionMethod::setAccessible no longer have an effect. Properties and methods are now always considered accessible via Reflection.
Standard
syslog is now binary safe.
Other Changes to Extensions
GD
imagewebp can now do lossless WebP encoding by passing
IMG_WEBP_LOSSLESS as the quality.
This constant is only defined, if the used libgd supports lossless WebP encoding.
MySQLi
mysqli_stmt::next_result and mysqli::fetch_all are now available when linking against libmysqlclient.
OpenSSL
The OpenSSL extension now requires at least OpenSSL version 1.0.2.
OpenSSL 3.0 is now supported. Be aware that many ciphers are no longer enabled by default (part of the legacy provider), and that parameter validation (e.g. minimum key sizes) is stricter now.
Phar
SHA256 is now used by default for signatures.
Added support for OpenSSL_SHA256 and OpenSSL_SHA512 signatures.
SNMP
Added support for SHA256 and SHA512 for the security protocol.
Standard
--with-password-argon2 now uses pkg-config to detect libargon2. As such, an alternative libargon2 location should now be specified using
PKG_CONFIG_PATH.
Changes to INI File Handling
The log_errors_max_len INI directive has been removed. It no longer had an effect since PHP 8.0.0.
A leading dollar in a quoted string can now be escaped:
"\${" will now be interpreted as a string with contents
${.
Backslashes in double quoted strings are now more consistently treated as escape characters. Previously,
"foo\\" followed by something other than a newline was not considered as a terminated string. It is now interpreted as a string with contents
foo\. However, as an exception, the string
"foo\" followed by a newline will continue to be treated as a valid string with contents
foo\ rather than an unterminated string. This exception exists to support naive uses of Windows file paths such as
"C:\foo\".
Migrating from PHP 8.1.x to PHP 8.2.x
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.
ENTITY 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
New Global Constants
COM
DISP_E_PARAMNOTFOUND
LOCALE_NEUTRAL
cURL
CURLALTSVC_H1 (libcurl >= 7.64.1)
CURLALTSVC_H2 (libcurl >= 7.64.1)
CURLALTSVC_H3 (libcurl >= 7.64.1)
CURLALTSVC_READONLYFILE (libcurl >= 7.64.1)
CURLAUTH_AWS_SIGV4 (libcurl >= 7.75.0)
CURLE_PROXY (libcurl >= 7.73.0)
CURLFTPMETHOD_DEFAULT
CURLHSTS_ENABLE (libcurl >= 7.74.0)
CURLHSTS_READONLYFILE (libcurl >= 7.74.0)
CURLINFO_PROXY_ERROR (libcurl >= 7.73.0)
CURLINFO_REFERER (libcurl >= 7.76.0)
CURLINFO_RETRY_AFTER (libcurl >= 7.66.0)
CURLMOPT_MAX_CONCURRENT_STREAMS (libcurl >= 7.67.0)
CURLOPT_ALTSVC_CTRL (libcurl >= 7.64.1)
CURLOPT_ALTSVC (libcurl >= 7.64.1)
CURLOPT_AWS_SIGV4 (libcurl >= 7.75.0)
CURLOPT_CAINFO_BLOB (libcurl >= 7.77.0)
CURLOPT_DOH_SSL_VERIFYHOST (libcurl >= 7.76.0)
CURLOPT_DOH_SSL_VERIFYPEER (libcurl >= 7.76.0)
CURLOPT_DOH_SSL_VERIFYSTATUS (libcurl >= 7.76.0)
CURLOPT_HSTS_CTRL (libcurl >= 7.74.0)
CURLOPT_HSTS (libcurl >= 7.74.0)
CURLOPT_MAIL_RCPT_ALLLOWFAILS (libcurl >= 7.69.0)
CURLOPT_MAXAGE_CONN (libcurl >= 7.65.0)
CURLOPT_MAXFILESIZE_LARGE
CURLOPT_MAXLIFETIME_CONN (libcurl >= 7.80.0)
CURLOPT_PROXY_CAINFO_BLOB (libcurl >= 7.77.0)
CURLOPT_SASL_AUTHZID (libcurl >= 7.66.0)
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 (libcurl >= 7.80.0)
CURLOPT_SSL_EC_CURVES (libcurl >= 7.73.0)
CURLOPT_UPKEEP_INTERVAL_MS (libcurl >= 7.62.0)
CURLOPT_UPLOAD_BUFFERSIZE (libcurl >= 7.62.0)
CURLOPT_XFERINFOFUNCTION (libcurl >= 7.32.0)
CURLPROTO_MQTT (libcurl >= 7.71.0)
CURLPX_BAD_ADDRESS_TYPE (libcurl >= 7.73.0)
CURLPX_BAD_VERSION (libcurl >= 7.73.0)
CURLPX_CLOSED (libcurl >= 7.73.0)
CURLPX_GSSAPI (libcurl >= 7.73.0)
CURLPX_GSSAPI_PERMSG (libcurl >= 7.73.0)
CURLPX_GSSAPI_PROTECTION (libcurl >= 7.73.0)
CURLPX_IDENTD_DIFFER (libcurl >= 7.73.0)
CURLPX_IDENTD (libcurl >= 7.73.0)
CURLPX_LONG_HOSTNAME (libcurl >= 7.73.0)
CURLPX_LONG_PASSWD (libcurl >= 7.73.0)
CURLPX_LONG_USER (libcurl >= 7.73.0)
CURLPX_NO_AUTH (libcurl >= 7.73.0)
CURLPX_OK (libcurl >= 7.73.0)
CURLPX_RECV_ADDRESS (libcurl >= 7.73.0)
CURLPX_RECV_AUTH (libcurl >= 7.73.0)
CURLPX_RECV_CONNECT (libcurl >= 7.73.0)
CURLPX_RECV_REQACK (libcurl >= 7.73.0)
CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED (libcurl >= 7.73.0)
CURLPX_REPLY_COMMAND_NOT_SUPPORTED (libcurl >= 7.73.0)
CURLPX_REPLY_CONNECTION_REFUSED (libcurl >= 7.73.0)
CURLPX_REPLY_GENERAL_SERVER_FAILURE (libcurl >= 7.73.0)
CURLPX_REPLY_HOST_UNREACHABLE (libcurl >= 7.73.0)
CURLPX_REPLY_NETWORK_UNREACHABLE (libcurl >= 7.73.0)
CURLPX_REPLY_NOT_ALLOWED (libcurl >= 7.73.0)
CURLPX_REPLY_TTL_EXPIRED (libcurl >= 7.73.0)
CURLPX_REPLY_UNASSIGNED (libcurl >= 7.73.0)
CURLPX_REQUEST_FAILED (libcurl >= 7.73.0)
CURLPX_RESOLVE_HOST (libcurl >= 7.73.0)
CURLPX_SEND_AUTH (libcurl >= 7.73.0)
CURLPX_SEND_CONNECT (libcurl >= 7.73.0)
CURLPX_SEND_REQUEST (libcurl >= 7.73.0)
CURLPX_UNKNOWN_FAIL (libcurl >= 7.73.0)
CURLPX_UNKNOWN_MODE (libcurl >= 7.73.0)
CURLPX_USER_REJECTED (libcurl >= 7.73.0)
CURLSSLOPT_AUTO_CLIENT_CERT (libcurl >= 7.77.0)
CURLSSLOPT_NATIVE_CA (libcurl >= 7.71.0)
CURLSSLOPT_NO_PARTIALCHAIN (libcurl >= 7.68.0)
CURLSSLOPT_REVOKE_BEST_EFFORT (libcurl >= 7.70.0)
CURL_VERSION_GSASL (libcurl >= 7.76.0)
CURL_VERSION_HSTS (libcurl >= 7.74.0)
CURL_VERSION_HTTP3 (libcurl >= 7.66.0)
CURL_VERSION_UNICODE (libcurl >= 7.72.0)
CURL_VERSION_ZSTD (libcurl >= 7.72.0)
DBA
DBA_LMDB_USE_SUB_DIR
DBA_LMDB_NO_SUB_DIR
Filter
FILTER_FLAG_GLOBAL_RANGE
Sockets
The following socket options are now defined if they are supported:
SO_INCOMING_CPU
SO_MEMINFO
SO_RTABLE (OpenBSD)
TCP_KEEPALIVE (MacOS)
TCP_KEEPCNT (Linux, others)
TCP_KEEPIDLE (Linux, others)
TCP_KEEPINTVL (Linux, others)
TCP_NOTSENT_LOWAT
LOCAL_CREDS_PERSISTENT (FreeBSD)
SCM_CREDS2 (FreeBSD)
LOCAL_CREDS (NetBSD)
SO_BPF_EXTENSIONS
SO_SETFIB
TCP_CONGESTION (Linux, FreeBSD)
SO_ZEROCOPY (Linux)
MSG_ZEROCOPY (Linux)
Deprecated Features
PHP Core
Usage of dynamic properties
The creation of dynamic properties is deprecated, unless the class opts in by using the
#[\AllowDynamicProperties] attribute.
stdClass allows dynamic properties. Usage of the __get()/__set() magic methods is not affected by this change. A dynamic properties deprecation warning can be addressed by: Declaring the property (preferred)., Adding the
#[\AllowDynamicProperties] attribute to the class (which also applies to all child classes)., Using a
WeakMap if additional data needs to be associated with an object which one does not own.
Relative callables
Callables that are not accepted by the
$callable() syntax (but are accepted by
call_user_func) are deprecated. In particular:
"self::method",
"parent::method",
"static::method",
["self", "method"],
["parent", "method"],
["static", "method"],
["Foo", "Bar::method"],
[new Foo, "Bar::method"] This does not affect normal method callables such as
"A::method" or
["A", "method"].
"${var}" and
"${expr}" style interpolation
The
"${var}" and
"${expr}" style of string interpolation is deprecated. Use
"$var"/"{$var}" and
"{${expr}}", respectively.
MBString
Usage of the
QPrint,
Base64,
Uuencode, and
HTML-ENTITIES 'text encodings' is deprecated for all MBString functions. Unlike all the other text encodings supported by MBString, these do not encode a sequence of Unicode codepoints, but rather a sequence of raw bytes. It is not clear what the correct return values for most MBString functions should be when one of these non-encodings is specified. Moreover, PHP has separate, built-in implementations of all of them; for example, UUencoded data can be handled using
convert_uuencode/
convert_uudecode.
SPL
The internal SplFileInfo::_bad_state_ex method has been deprecated.
Standard
utf8_encode and
utf8_decode have been deprecated.
Backward Incompatible Changes
Date
DateTime::createFromImmutable now has a tentative return type of
static, previously it was
DateTime.
DateTimeImmutable::createFromMutable now has a tentative return type of
static, previously it was
DateTimeImmutable.
number symbols in relative formats no longer accept multiple signs, e.g.
+-2.
ODBC
The ODBC extension now escapes the username and password for the case when both a connection string and username/password are passed, and the string must be appended to. Before, user values containing values needing escaping could have created a malformed connection string, or injected values from user-provided data. The escaping rules should be identical to the .NET BCL DbConnectionOptions behaviour.
PDO_ODBC
The PDO_ODBC extension also escapes the username and password when a connection string is passed. See the change to the ODBC extension for further details.
Standard
glob now returns an empty ENTITY if all paths are restricted by open_basedir. Previously it returned ENTITY. Moreover, a warning is now emitted even if only some paths are restricted by open_basedir.
FilesystemIterator::__construct: prior to PHP 8.2.0,
FilesystemIterator::SKIP_DOTS constant was always set and couldn't be disabled. In order to maintain the previous behaviour the constant must be explicitly set when using the
flags parameter. The default value from
flags parameter has not been modified.
strtolower,
strtoupper,
stristr,
stripos,
strripos,
lcfirst,
ucfirst,
ucwords, and
str_ireplace are no longer locale-sensitive. They now perform ASCII case conversion, as if the locale were "C". Localized versions of these functions are available in the MBString extension. Moreover,
array_change_key_case, and sorting with
SORT_FLAG_CASE now also use ASCII case conversion.
str_split returns an empty ENTITY for an empty ENTITY now. Previously it returned an array with a single empty string entry.
mb_str_split is not affected by this change as it was already behaving like that.
ksort and
krsort now do numeric string comparison under
SORT_REGULAR using the standard PHP 8 rules now.
var_export no longer omits the leading backslash for exported classes, i.e. these are now fully qualified.
Standard PHP Library (SPL)
The following methods now enforce their signature: SplFileInfo::_bad_state_ex, SplFileObject::getCsvControl, SplFileObject::fflush, SplFileObject::ftell, SplFileObject::fgetc, SplFileObject::fpassthru
SplFileObject::hasChildren now has a tentative return type of
false, previously it was
bool.
SplFileObject::getChildren now has a tentative return type of
null, previously it was
RecursiveIteratornull.
GlobIterator now returns an empty ENTITY if all paths are restricted by open_basedir. Previously it returned ENTITY. Moreover, a warning is now emitted even if only some paths are restricted by open_basedir.
New Features
PHP Core
SensitiveParameter Attribute
Added the
#[\SensitiveParameter] attribute to redact sensitive data in backtraces.
error_log_mode INI directive
The error_log_mode INI directive has been added which allows setting the permissions for the error log file.
Enumerations properties in constant expressions
It is now possible to fetch properties of Enumerations in constant expressions.
Type System Improvements
It is now possible to use
null and
false as stand-alone types.
The
true type has been added.
It is now possible to combine intersection and union types. The type needs to be written in DNF.
Constants in Traits
It is now possible to define constants in traits.
Readonly Classes
Support for readonly on classes has been added.
cURL
Added the
CURLINFO_EFFECTIVE_METHOD option, which returns the effective HTTP method in the return value of
curl_getinfo.
Exposed multiple new constants from libcurl 7.62 to 7.80.
Added the
curl_upkeep function to perform any connection upkeep checks.
DBA
The LMDB Driver now accepts the
DBA_LMDB_USE_SUB_DIR or
DBA_LMDB_NO_SUB_DIR flags to determine if it should create a subdirectory or not when creating a database file.
OCI8
Added the oci8.prefetch_lob_size INI directive and
oci_set_prefetch_lob function to tune LOB query performance by reducing the number of round-trips between PHP and Oracle Databases when fetching LOBS. This is usable with Oracle Database 12.2 or later.
OpenSSL
Added AEAD support for the chacha20-poly1305 algorithm.
ODBC
Added the
odbc_connection_string_is_quoted,
odbc_connection_string_should_quote, and
odbc_connection_string_quote functions. These are primarily used behind the scenes in the ODBC and PDO_ODBC extensions, but are exposed to userland for easier unit testing, and for user applications and libraries to perform quoting themselves.
PCRE
Added support for the
n (NO_AUTO_CAPTURE) modifier, which makes simple
(xyz) groups non-capturing. Only named groups like
(?ENTITYnameENTITYxyz) are capturing. This only affects which groups are capturing, it is still possible to use numbered subpattern references, and the matches array will still contain numbered results.
Random
This is a new extension which organises and consolidates existing implementations related to random number generators. New and better RNGs are available with scope issues eliminated.
New Functions
cURL
curl_upkeep
IMAP
imap_is_open
(as of PHP 8.2.1)
MySQLi
mysqli_execute_query
ODBC
odbc_connection_string_is_quoted
odbc_connection_string_should_quote
odbc_connection_string_quote
OpenSSL
openssl_cipher_key_length
Reflection
ReflectionFunction::isAnonymous
ReflectionMethod::hasPrototype
Sodium
XChaCha20
sodium_crypto_stream_xchacha20_xor_ic
Standard
memory_reset_peak_usage
ini_parse_quantity
XML
libxml_get_external_entity_loader
Other Changes
Core changes
The
iterable type is now a built-in compile time alias for
arrayTraversable. Error messages relating to
iterable will therefore now use
array|Traversable. Type Reflection is preserved for single
iterable (and
?iterable) to produce a
ReflectionNamedType with name
iterable, however usage of
iterable in union types will be converted to
array|Traversable.
The date format of sent cookies is now
'D, d M Y H:i:s \G\M\T'; previously it was
'D, d-M-Y H:i:s T'.
Changes in SAPI Modules
CLI
The STDOUT, STDERR and STDIN streams are no longer closed on resource destruction which is mostly when the CLI finishes. It is however still possible to explicitly close those streams using
fclose and similar.
Changed Functions
Core
The
strcmp,
strcasecmp,
strncmp,
strncasecmp, and
substr_compare functions, using binary safe string comparison is no longer guaranteed to return
strlen($string1) - strlen($string2) when string lengths are not equal, but may now return
-1 or
1 instead. Instead of depending on any concrete value, the return value should be compared to
0.
DBA
dba_open and
dba_popen now have the following enforced signature:
resourcefalsedba_open
string``path
string``mode
stringnull``handlerENTITY
int``permission0644
int``map_size0
intnull``flagsENTITY
dba_fetch's optional skip argument is now at the end in line with PHP userland semantics. Its signature is now:
stringfalsedba_fetch
stringarray``key
resource``handle
int``skip The overloaded signature:
stringfalsedba_fetch
stringarray``key
int``skip
resource``handle is still accepted, but it is recommended to use the new standard variant.
Random
random_bytes and
random_int now throw a
\Random\RandomException on CSPRNG failures. Previously a plain
\Exception was thrown instead.
SPL
The
iterator parameter of
iterator_to_array and
iterator_count is widened to
iterable from
Iterator, allowing arrays to be passed.
Other Changes to Extensions
Date
The properties of
DatePeriod are now properly declared.
Default timezone will fall back to UTC if the date.timezone ini setting is not set.
Intl
Instances of
IntlBreakIterator,
IntlRuleBasedBreakIterator,
IntlCodePointBreakIterator,
IntlPartsIterator,
IntlCalendar,
Collator,
IntlIterator,
UConverter,
IntlDateFormatter,
IntlDatePatternGenerator,
MessageFormatter,
ResourceBundle,
Spoofchecker,
IntlTimeZone, and
Transliterator are no longer serializable. Previously, they could be serialized, but unserialization yielded unusable objects or failed.
MySQLi
The support for libmysql has been removed and it is no longer possible to compile mysqli with libmysql. From now on, the mysqli extension can be compiled only with mysqlnd. All libmysql features unavailable in mysqlnd have been removed: The reconnect property of
mysqli_driver, The mysqli.reconnect INI directive, The
MYSQLI_IS_MARIADB constant has been deprecated
OCI8
The minimum Oracle Client library version required is now 11.2.
PCRE
NUL characters (
\0) in pattern strings are now supported.
Session
Trying to change the session.cookie_samesite INI directive while the session is active or output has already been sent will now fail and emit a warning. This aligns the behaviour with all other session INI settings.
SQLite3
sqlite3.defensive is now
INI_USER.
Standard
getimagesize now reports the actual image dimensions, bits and channels of AVIF images. Previously, the dimensions have been reported as 0x0, and bits and channels have not been reported at all.
Tidy
The properties of the
tidy class are now properly declared. And those of the
tidyNode class are now properly declared as readonly.
Zip
The Zip extension has been updated to version 1.20.0, which adds the following methods: ZipArchive::clearError, ZipArchive::getStreamName, ZipArchive::getStreamIndex
Changes to INI File Handling
Support for binary (
0b/
0B) and octal (
0o/
0O) prefixes has been added to integer INI settings. Integer INI settings that start with a zero (
0) continue to be interpreted as an octal integer.
Parsing of some ill-formatted values will now trigger a warning when this was silently ignored before. For backwards compatibility, interpretation of these values has not changed. This affects the following settings: bcmath.scale, com.code_page, default_socket_timeout, fiber.stack_size, hard_timeout, intl.error_level, ldap.max_links, max_input_nesting_level, max_input_vars, mbstring.regex_retry_limit, mbstring.regex_stack_limit, mysqli.allow_local_infile, mysqli.allow_persistent, mysqli.default_port, mysqli.max_links, mysqli.max_persistent, mysqli.rollback_on_cached_plink, mysqlnd.log_mask, mysqlnd.mempool_default_size, mysqlnd.net_read_buffer_size, mysqlnd.net_read_timeout, oci8.default_prefetch, oci8.max_persistent, oci8.persistent_timeout, oci8.ping_interval, oci8.prefetch_lob_size, oci8.privileged_connect, oci8.statement_cache_size, odbc.allow_persistent, odbc.check_persistent, odbc.max_persistent, odbc.max_links, odbc.defaultbinmode, odbc.default_cursortype, odbc.defaultlrl, opcache.consistency_checks, opcache.file_update_protection, opcache.force_restart_timeout, opcache.interned_strings_buffer, opcache.jit_bisect_limit, opcache.jit_blacklist_root_trace, opcache.jit_blacklist_side_trace, opcache.jit_debug, opcache.jit_hot_func, opcache.jit_hot_loop, opcache.jit_hot_return, opcache.jit_hot_side_exit, opcache.jit_max_exit_counters, opcache.jit_max_loop_unrolls, opcache.jit_max_polymorphic_calls, opcache.jit_max_recursive_calls, opcache.jit_max_recursive_returns, opcache.jit_max_root_traces, opcache.jit_max_side_traces, opcache.log_verbosity_level, opcache.max_file_size, opcache.opt_debug_level, opcache.optimization_level, opcache.revalidate_freq, output_buffering, pcre.backtrack_limit, pcre.recursion_limit, pgsql.max_links, pgsql.max_persistent, post_max_size, realpath_cache_size, realpath_cache_ttl, session.cache_expire, session.cookie_lifetime, session.gc_divisor, session.gc_maxlifetime, session.gc_probability, soap.wsdl_cache_limit, soap.wsdl_cache_ttl, unserialize_max_depth, upload_max_filesize, user_ini.cache_ttl, xmlrpc_error_number, zend.assertions, zlib.output_compression_level
Windows Support
Core
Windows specific error messages are no longer localized, but instead always displayed in English to better match PHP error messages.
Preliminary and highly experimental support for building on ARM64 has been added.
OCI8
Because building against Oracle Client 10g is no longer supported anyway, the configuration option
--with-oci8 has been dropped. The
--with-oci8-11g,
--with-oci8-12c and
--with-oci8-19 configuration options are still supported.
Zip
The Zip extension is upgraded to version 1.21.0, and is now built as shared library (DLL) by default.
Migrating from PHP 8.2.x to PHP 8.3.x
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.
ENTITY 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x, 8.2.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
New Global Constants
cURL
CURLINFO_CAPATH (libcurl >= 7.84.0)
CURLINFO_CAINFO (libcurl >= 7.84.0)
CURLOPT_MIME_OPTIONS (libcurl >= 7.81.0)
CURLMIMEOPT_FORMESCAPE (libcurl >= 7.81.0)
CURLOPT_WS_OPTIONS (libcurl >= 7.86.0)
CURLWS_RAW_MODE (libcurl >= 7.86.0)
CURLOPT_SSH_HOSTKEYFUNCTION (libcurl >= 7.84.0)
CURLOPT_PROTOCOLS_STR (libcurl >= 7.85.0)
CURLOPT_REDIR_PROTOCOLS_STR (libcurl >= 7.85.0)
CURLOPT_CA_CACHE_TIMEOUT (libcurl >= 7.87.0)
CURLOPT_QUICK_EXIT (libcurl >= 7.87.0)
CURLKHMATCH_OK (libcurl >= 7.19.6)
CURLKHMATCH_MISMATCH (libcurl >= 7.19.6)
CURLKHMATCH_MISSING (libcurl >= 7.19.6)
CURLKHMATCH_LAST (libcurl >= 7.19.6)
Intl
MIXED_NUMBERS (
Spoofchecker)
HIDDEN_OVERLAY (
Spoofchecker)
OpenSSL
OPENSSL_CMS_OLDMIMETYPE
PKCS7_NOOLDMIMETYPE
PCNTL
SIGINFO
PDO_ODBC
PDO_ODBC_TYPE
Posix
POSIX_SC_ARG_MAX
POSIX_SC_PAGESIZE
POSIX_SC_NPROCESSORS_CONF
POSIX_SC_NPROCESSORS_ONLN
POSIX_PC_LINK_MAX
POSIX_PC_MAX_CANON
POSIX_PC_MAX_INPUT
POSIX_PC_NAME_MAX
POSIX_PC_PATH_MAX
POSIX_PC_PIPE_BUF
POSIX_PC_CHOWN_RESTRICTED
POSIX_PC_NO_TRUNC
POSIX_PC_ALLOC_SIZE_MIN
POSIX_PC_SYMLINK_MAX
Sockets
The following socket options are now defined if they are supported:
SO_ATTACH_REUSEPORT_CBPF (Linux)
SO_DETACH_BPF (Linux)
SO_DETACH_FILTER (Linux)
TCP_QUICKACK (Linux)
IP_DONTFRAG (FreeBSD)
IP_MTU_DISCOVER (Linux)
IP_PMTUDISC_DO (Linux)
IP_PMTUDISC_DONT (Linux)
IP_PMTUDISC_WANT (Linux)
IP_PMTUDISC_PROBE (Linux)
IP_PMTUDISC_INTERFACE (Linux)
IP_PMTUDISC_OMIT (Linux)
AF_DIVERT (FreeBSD)
SOL_UDPLITE
UDPLITE_RECV_CSCOV
UDPLITE_SEND_CSCOV
SO_RERROR (NetBSD)
SO_ZEROIZE (OpenBSD)
SO_SPLICE (OpenBSD)
TCP_REPAIR (Linux)
SO_REUSEPORT_LB (FreeBSD)
IP_BIND_ADDRESS_NO_PORT (Linux)
Zip
ZipArchive::ER_DATA_LENGTH (libzip >= 1.10)
ZipArchive::ER_NOT_ALLOWED (libzip >= 1.10)
ZipArchive::AFL_RDONLY (libzip >= 1.10)
ZipArchive::AFL_IS_TORRENTZIP (libzip >= 1.10)
ZipArchive::AFL_WANT_TORRENTZIP (libzip >= 1.10)
ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE (libzip >= 1.10)
ZipArchive::FL_OPEN_FILE_NOW
ZipArchive::LENGTH_TO_END as default value for
ZipArchive::addFile and
ZipArchive::replaceFile
ZipArchive::LENGTH_UNCHECKED (libzip >= 1.10)
Deprecated Features
PHP Core
Saner Increment/Decrement operators
Using the increment operator (
++) on empty, non-numeric, or non-alphanumeric strings is now deprecated. Moreover, incrementing non-numeric strings is soft deprecated. That means no
E_DEPRECATED diagnostic is emitted, but this feature should not be used when producing new code. The new
str_increment function should be used instead.
Using the decrement operator (
--) on empty or non-numeric strings is now deprecated.
get_class()/get_parent_class() call without arguments
Calling
get_class and
get_parent_class without arguments is now deprecated.
DBA
Calling
dba_fetch with
dba as the 3rd argument is now deprecated.
FFI
Calling FFI::cast, FFI::new, and FFI::type statically is now deprecated.
Intl
The
U_MULTIPLE_DECIMAL_SEP*E*RATORS constant had been deprecated, using the
U_MULTIPLE_DECIMAL_SEP*A*RATORS constant instead is recommended.
The
NumberFormatter::TYPE_CURRENCY constant has been deprecated.
LDAP
Calling
ldap_connect with separate
hostname and
port is deprecated.
MBString
Passing a negative
width to
mb_strimwidth is now deprecated.
Phar
Calling Phar::setStub with a
resource and a
length is now deprecated. Such calls should be replaced by:
$phar->setStub(stream_get_contents($resource));
Random
The
MT_RAND_PHP Mt19937 variant is deprecated.
Reflection
Calling ReflectionProperty::setValue with only one parameter is deprecated. To set static properties, pass ENTITY as the first parameter.
Standard
The
assert_options function is now deprecated.
The
ASSERT_ACTIVE,
ASSERT_BAIL,
ASSERT_CALLBACK,
ASSERT_EXCEPTION, and
ASSERT_WARNING constants have been deprecated.
The
assert.* INI settings have been deprecated. See the Changes to INI File Handling page for further details.
SQLite3
Using exceptions is now preferred, warnings will be removed in the future. Calling
SQLite3::enableExceptions(false) will trigger a deprecation warning in this version.
Zip
The
ZipArchive::FL_RECOMPRESS constant is deprecated and will be removed in a future version of libzip.
Backward Incompatible Changes
PHP Core
Programs that were very close to overflowing the call stack
Programs that were very close to overflowing the call stack may now throw an
Error when using more than zend.max_allowed_stack_size-zend.reserved_stack_size bytes of stack (fiber.stack_size-zend.reserved_stack_size for fibers).
Executing proc_get_status() multiple times
Executing
proc_get_status multiple times will now always return the right value on POSIX systems. Previously, only the first call of the function returned the right value. Executing
proc_close after
proc_get_status will now also return the right exit code. Previously this would return
-1. Internally, this works by caching the result on POSIX systems. If the previous behaviour is required, it is possible to check the
"cached" key in the array returned by
proc_get_status to check whether the result was cached.
Zend Max Execution Timers
Zend Max Execution Timers is now enabled by default for ZTS builds on Linux.
Uses of traits with static properties
Uses of traits with static properties will now redeclare static properties inherited from the parent class. This will create a separate static property storage for the current class. This is analogous to adding the static property to the class directly without traits.
Assigning a negative index to an empty array
Assigning a negative index
$n to an empty array will now make sure that the next index is
$n+1 instead of
0.
Class constant visibility variance check
Class constant visibility variance is now correctly checked when inherited from interfaces.
WeakMap entries whose key maps to itself
WeakMap entries whose key maps to itself (possibly transitively) may now be removed during cycle collection if the key is not reachable except by iterating over the WeakMap (reachability via iteration is considered weak). Previously, such entries would never be automatically removed.
Date
The DateTime extension has introduced Date extension specific exceptions and errors under the
DateError and
DateException hierarchies, instead of warnings and generic exceptions. This improves error handling, at the expense of having to check for errors and exceptions.
DOM
Calling DOMChildNode::after, DOMChildNode::before, DOMChildNode::replaceWith on a node that has no parent is now a no-op instead of a hierarchy exception, which is the behaviour demanded by the DOM specification.
Using the
DOMParentNode and
DOMChildNode methods without a document now works instead of throwing a
DOM_HIERARCHY_REQUEST_ERR
DOMException. This is in line with the behaviour demanded by the DOM specification.
Calling DOMDocument::createAttributeNS without specifying a prefix would incorrectly create a default namespace, placing the element inside the namespace instead of the attribute. This bug is now fixed.
DOMDocument::createAttributeNS would previously incorrectly throw a
DOM_NAMESPACE_ERRNAMESPACE_ERR
DOMException when the prefix was already used for a different URI. It now correctly chooses a different prefix when there's a prefix name conflict.
New methods and properties were added to some DOM classes. If a userland class inherits from these classes and declare a method or property with the same name, the declarations must be compatible. Otherwise, a typical compile error about incompatible declarations will be thrown. See the list of new features and new functions for a list of the newly implemented methods and properties.
FFI
C functions that have a return type of
void now return ENTITY instead of returning the following object
object(FFI\CData:void) { }
Opcache
The opcache.consistency_checks INI directive was removed. This feature was broken with the tracing JIT, as well as with inheritance cache, and has been disabled without a way to enable it since PHP 8.1.18 and PHP 8.2.5. Both the tracing JIT and inheritance cache may modify shm after the script has been persisted by invalidating its checksum. The attempted fix skipped over the modifiable pointers but was rejected due to complexity. For this reason, it was decided to remove the feature instead.
Phar
The type of
Phar class constants are now declared.
Standard
The
range function has had various changes: A TypeError is now thrown when passing
objects,
resources, or
arrays as the boundary inputs., A more descriptive ValueError is thrown when passing
0 for
step., A ValueError is now thrown when using a negative
step for increasing ranges., If
step is a float that can be interpreted as an int, it is now done so., A ValueError is now thrown if any argument is infinity or NAN., An
E_WARNING is now emitted if
start or
end is the empty string. The value continues to be cast to the value
0., An
E_WARNING is now emitted if
start or
end has more than one byte, only if it is a non-numeric string., An
E_WARNING is now emitted if
start or
end is cast to an integer because the other boundary input is a number. (e.g.
range(5, 'z');)., An
E_WARNING is now emitted if
step is a float when trying to generate a range of characters, except if both boundary inputs are numeric strings (e.g.
range('5', '9', 0.5); does not produce a warning).,
range now produce a list of characters if one of the boundary inputs is a string digit instead of casting the other input to int (e.g.
range('9', 'A');).
", "?", "@", "A"], as of PHP 8.3.0
range('9', 'A'); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], prior to PHP 8.3.0
?>
number_format now handles negative
decimals values by rounding
num to
abs($decimals) digits before the decimal point. Previously, negative
decimals values were ignored.
The
file flags error check now catches all invalid flags. Notably
FILE_APPEND was previously silently accepted.
SNMP
The type of
SNMP class constants are now declared.
New Classes and Interfaces
Date
DateError
DateObjectError
DateRangeError
DateException
DateInvalidOperationException
DateInvalidTimeZoneException
DateMalformedIntervalStringException
DateMalformedPeriodStringException
DateMalformedStringException
Random
Random\IntervalBoundary
New Features
PHP Core
Readonly Amendments
Anonymous classes may now be marked as readonly.
Readonly properties can now be reinitialized during cloning.
Typed Class Constants
Class, interface, trait, and enum constants now support type declarations.
Closures created from magic methods
Closures created from magic methods can now accept named arguments.
The final modifier with a method from a trait
The final modifier may now be used when using a method from a trait.
Override Attribute
Added the #[\Override] attribute to check that a method exists in a parent class or implemented interface.
Fetch class constant dynamically syntax
Class constants can now be accessed dynamically using the
C::{$name} syntax.
Static variable Initializers
Static variable initializers can now contain arbitrary expressions.
Fallback value syntax for ini variables
php.ini now supports fallback/default value syntax.
= 9.6)
Random
Random\Randomizer::getBytesFromString
Random\Randomizer::nextFloat
Random\Randomizer::getFloat
Reflection
ReflectionMethod::createFromMethodName
Sockets
socket_atmark
Standard
str_increment
str_decrement
stream_context_set_options
Zip
ZipArchive::getArchiveFlag
Other Changes
Core changes
FFI
FFI::load is now allowed during preloading when opcache.preload_user is the current system user. Previously, calling FFI::load was not possible during preloading if the opcache.preload_user directive was set.
FPM
FPM CLI test now fails if the socket path is longer than supported by the OS.
Opcache
In the CLI and phpdbg SAPIs, preloading does not require the opcache.preload_user directive to be set anymore when running as root. In other SAPIs, this directive is required when running as root because preloading is done before the SAPI switches to an unprivileged user.
Streams
Blocking
fread on a socket connection returns immediately if there are any buffered data instead of waiting for more data.
A memory stream no longer fails if the seek offset is past the end. Instead, the memory will be increased on the next write and the data between the old end and the offset is filled with zero bytes, similar to how files work.
stat access operations like
file_exists and similar will now use real path instead of the actual stream path. This is consistent with stream opening.
Changes in SAPI Modules
CLI
The
STDOUT,
STDERR and
STDIN streams are no longer closed on resource destruction which is mostly when the CLI finishes. It is however still possible to explicitly close those streams using
fclose and similar.
Changed Functions
Core
gc_status has added the following 8 fields:
"running" => bool,
"protected" => bool,
"full" => bool,
"buffer_size" => int,
"application_time" => float: Total application time, in seconds (including collector_time),
"collector_time" => float: Time spent collecting cycles, in seconds (including destructor_time and free_time),
"destructor_time" => float: Time spent executing destructors during cycle collection, in seconds,
"free_time" => float: Time spent freeing values during cycle collection, in seconds
class_alias now supports creating an alias of an internal class.
Setting open_basedir at runtime using
ini_set('open_basedir', ...); no longer accepts paths containing the parent directory (
..). Previously, only paths starting with
.. were disallowed. This could easily be circumvented by prepending
./ to the path.
User exception handlers now catch exceptions during shutdown.
The resultant HTML of
highlight_string and
highlight_file has changed. Whitespace between outer HTML tags is removed. Newlines and spaces are no longer converted to HTML entities. The whole HTML is now wrapped in a
ENTITYpreENTITY tag. The outer
ENTITYspanENTITY tag has been merged with the
ENTITYcodeENTITY tag.
Calendar
easter_date now supports years from 1970 to 2,000,000,000 on 64-bit systems, previously it only supported years in the range from 1970 to 2037.
Curl
curl_getinfo now supports two new constants:
CURLINFO_CAPATH and
CURLINFO_CAINFO. If option is ENTITY, the following two additional keys are present:
"capath" and
"cainfo".
DOM
Changed DOMCharacterData::appendData tentative return type to
true.
DOMDocument::loadHTML, DOMDocument::loadHTMLFile, and DOMDocument::loadXML now have a tentative return type of
bool. Previously, this was documented as having a return type of
DOMDocument|bool, but, as of PHP 8.0.0,
DOMDocument cannot be returned as it is no longer statically callable.
Gd
The signature of
imagerotate has changed. The
ignore_transparent parameter has been removed, as it was ignored since PHP 5.5.0.
Intl
datefmt_set_timezone (and its alias IntlDateformatter::setTimeZone) now returns ENTITY on success, previously ENTITY was returned.
IntlBreakiterator::setText now returns ENTITY on failure, previously ENTITY was returned. It now returns ENTITY on success, previously ENTITY was returned.
IntlChar::enumCharNames is now returning a boolean. Previously it returned ENTITY on success and ENTITY on failure.
IntlDateFormatter::__construct throws an
U_ILLEGAL_ARGUMENT_ERROR exception when an invalid locale had been set.
MBString
mb_strtolower and
mb_convert_case implement conditional casing rules for the Greek letter sigma. For
mb_convert_case, conditional casing only applies to
MB_CASE_LOWER and
MB_CASE_TITLE modes, not to
MB_CASE_LOWER_SIMPLE and
MB_CASE_TITLE_SIMPLE.
mb_decode_mimeheader interprets underscores in QPrint-encoded MIME encoded words as required by RFC 2047; they are converted to spaces. Underscores must be encoded as
"=5F" in such MIME encoded words.
In rare cases,
mb_encode_mimeheader will transfer-encode its input string where it would pass it through as raw ASCII in PHP 8.2.
mb_encode_mimeheader no longer drops NUL (zero) bytes when QPrint-encoding the input string. This previously caused strings in certain text encodings, especially UTF-16 and UTF-32, to be corrupted by mb_encode_mimeheader.
mb_detect_encoding's "non-strict" mode now behaves as described in the documentation. Previously, it would return ENTITY if the same byte (for example, the first byte) of the input string was invalid in all candidate encodings. More generally, it would eliminate candidate encodings from consideration when an invalid byte was seen, and if the same input byte eliminated all remaining encodings still under consideration, it would return ENTITY. On the other hand, if all candidate encodings but one were eliminated from consideration, it would return the last remaining one without regard for how many encoding errors might be encountered later in the string. This is different from the behavior described in the documentation, which says: "If strict is set to false, the closest matching encoding will be returned."
mysqli
mysqli_fetch_object now raises a
ValueError instead of an
Exception when the
constructor_args argument is non empty with the class not having a constructor.
mysqli_poll now raises a
ValueError when neither the
read nor the
error arguments are passed.
mysqli_field_seek and mysqli_result::field_seek now specify the return type as
true instead of
bool.
ODBC
odbc_autocommit now accepts ENTITY for the
enable parameter. Passing ENTITY has the same behaviour as passing only 1 parameter, namely indicating if the autocommit feature is enabled or not.
PGSQL
pg_fetch_object now raises a
ValueError instead of an
Exception when the
constructor_args argument is non empty with the class not having a constructor.
pg_insert now raises a
ValueError instead of a
E_WARNING when the table specified is invalid.
pg_insert and
pg_convert raises a
ValueError or a
TypeError instead of a
E_WARNING when the value/type of a field does not match properly with a PostgreSQL's type.
The
row parameter of
pg_fetch_result,
pg_field_prtlen, and
pg_field_is_null is now nullable.
Random
Changed
mt_srand and
srand to not check the number of arguments to determine whether a random seed should be used. Passing ENTITY will generate a random seed,
0 will use zero as the seed. The functions are now consistent with Random\Engine\Mt19937::__construct.
Reflection
Return type of ReflectionClass::getStaticProperties is no longer nullable.
Standard
E_NOTICEs emitted by
unserialize have been promoted to
E_WARNING.
unserialize now emits a new
E_WARNING if the input contains unconsumed bytes.
array_pad is now only limited by the maximum number of elements an array can have. Before, it was only possible to add at most 1048576 elements at a time.
strtok raises an
E_WARNING in the case token is not provided when starting tokenization.
password_hash will now chain the underlying Random\RandomException as the ValueError's
previous Exception when salt generation fails.
If using an array as the
command for
proc_open, it must now have at least one non empty element. Otherwise a
ValueError is thrown.
proc_open returns ENTITY if
command array is invalid command instead of resource object that produces warning later. This was already the case for Windows but it is now also the case if a posix_spawn implementation is in use (most Linux, BSD and MacOS platforms). There are still some old platforms where this behavior is not changed as posix_spawn is not supported there.
array_sum and
array_product now warn when values in the array cannot be converted to int/float. Previously arrays and objects where ignored whilst every other value was cast to int. Moreover, objects that define a numeric cast (e.g. GMP) are now casted instead of ignored.
The
decimals of
number_format now properly handles negative integers. Rounding with a negative value for
decimals means that
num is rounded to
decimals significant digits before the decimal point. Previously negative
decimals were silently ignored and the number got rounded to zero decimal places.
A new
before_needle argument has been added to
strrchr. It behaves like its counterpart in the
strstr or
stristr functions.
str_getcsv and
fgetcsv now return an empty string instead of a string with a single null byte for the last field which only contains an unterminated enclosure.
Other Changes to Extensions
Core
Using the increment/decrement operators (
++/
--) on values of type
bool now emit warnings. This is because it currently has no effect, but will behave like
$bool += 1 in the future.
Using the decrement operator (
--) on values of type
null now emit warnings. This is because it currently has no effect, but will behave like
$null -= 1 in the future.
Internal objects that implement an _IS_NUMBER cast but not a do_operator handler that overrides addition and subtraction now can be incremented and decrement as if one would do
$o += 1 or
$o -= 1
DOM
The DOM lifetime mechanism has been reworked such that implicitly removed nodes can still be fetched. Previously this resulted in an exception.
SQLite3
The
SQLite3 class now throws
SQLite3Exception (extends
Exception) instead of
Exception.
The SQLite error code is now passed in the exception error code instead of being included in the error message.
Changes to INI File Handling
The
assert.* INI settings have been deprecated. This comprises the following INI settings: assert.active, assert.bail, assert.callback, assert.exception, assert.warning If the value of the setting is equal to the default value, no deprecation notice is emitted. The zend.assertions INI setting should be used instead.
zend.max_allowed_stack_size is a new INI directive to set the maximum allowed stack size. Possible values are
0 (detect the process or thread maximum stack size),
-1 (no limit), or a positive number of bytes. The default is
0. When it is not possible to detect the process or thread maximum stack size, a known system default is used. Setting this value too high has the same effect as disabling the stack size limit. Fibers use fiber.stack_size as maximum allowed stack size. An
Error is thrown when the process call stack exceeds zend.max_allowed_stack_size-zend.reserved_stack_size bytes, to prevent stack-overflow-induced segmentation faults, with the goal of making debugging easier. The stack size increases during uncontrolled recursions involving internal functions or the magic methods __toString(), __clone(), __sleep(), __destruct(). This is not related to stack buffer overflows, and is not a security feature.
zend.reserved_stack_size is a new INI directive to set the reserved stack size, in bytes. This is subtracted from the max allowed stack size, as a buffer, when checking the stack size.
Performance
DOM
Looping over a
DOMNodeList now uses caching. Therefore requesting items no longer takes quadratic time by default.
Getting text content from nodes now avoids an allocation, resulting in a performance gain.
DOMChildNode::remove now runs in O(1) performance.
Standard
The
file flags error check is now about 7% faster.
SPL
RecursiveDirectoryIterator now performs less I/O when looping over a directory.
Windows Support
Core
Minimum supported Windows version has been bumped to Windows 8 or Windows Server 2012.
Migrating from PHP 8.3.x to PHP 8.4.x
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.
ENTITY 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x, 8.2.x, 8.3.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
New Global Constants
Core
PHP_OUTPUT_HANDLER_PROCESSED
PHP_SBINDIR
cURL
CURL_HTTP_VERSION_3
CURL_HTTP_VERSION_3ONLY
CURLOPT_TCP_KEEPCNT
CURLOPT_PREREQFUNCTION
CURL_PREREQFUNC_OK
CURL_PREREQFUNC_ABORT
CURLOPT_SERVER_RESPONSE_TIMEOUT
CURLOPT_DEBUGFUNCTION
CURLINFO_TEXT
CURLINFO_HEADER_IN
CURLINFO_DATA_IN
CURLINFO_DATA_OUT
CURLINFO_SSL_DATA_OUT
CURLINFO_SSL_DATA_IN
CURLINFO_POSTTRANSFER_TIME_T
Intl
PATTERN
(
IntlDateFormatter
)
PROPERTY_IDS_UNARY_OPERATOR
(
IntlChar
)
PROPERTY_ID_COMPAT_MATH_START
PROPERTY_ID_COMPAT_MATH_CONTINUE
LDAP
LDAP_OPT_X_TLS_PROTOCOL_MAX
LDAP_OPT_X_TLS_PROTOCOL_TLS1_3
libxml
LIBXML_RECOVER
LIBXML_NO_XXE
. This is used together with
LIBXML_NOENT
when entity substitution should be performed, while disallowing external entity loading. This constant is available as of libxml2 2.13.
MySQLi
MYSQLI_TYPE_VECTOR
OpenSSL
X509_PURPOSE_OCSP_HELPER
X509_PURPOSE_TIMESTAMP_SIGN
PCNTL
SIGCKPT
(DragonFlyBSD only)
SIGCKPTEXIT
(DragonFlyBSD only)
WEXITED
WSTOPPED
WNOWAIT
P_ALL
P_PID
P_PGID
P_PIDFD
(Linux only)
P_UID
(NetBSD/FreeBSD only)
P_GID
(NetBSD/FreeBSD only)
P_SID
(NetBSD/FreeBSD only)
P_JAILID
(FreeBSD only)
PGSQL
PGSQL_TUPLES_CHUNK
POSIX
POSIX_SC_CHILD_MAX
POSIX_SC_CLK_TCK
Sockets
The following socket options are now defined if they are supported:
SO_EXCLUSIVEADDRUSE
(Windows only)
SOCK_CONN_DGRAM
(NetBSD only)
SOCK_DCCP
(NetBSD only)
TCP_SYNCNT
(Linux only)
SO_EXCLBIND
(Solaris/Illumos only)
SO_NOSIGPIPE
(macOS and FreeBSD)
SO_LINGER_SEC
(macOS only)
IP_PORTRANGE
(FreeBSD/NetBSD/OpenBSD only)
IP_PORTRANGE_DEFAULT
(FreeBSD/NetBSD/OpenBSD only)
IP_PORTRANGE_HIGH
(FreeBSD/NetBSD/OpenBSD only)
IP_PORTRANGE_LOW
(FreeBSD/NetBSD/OpenBSD only)
SOCK_NONBLOCK
SOCK_CLOEXEC
SO_BINDTOIFINDEX
Sodium
SODIUM_CRYPTO_AEAD_AEGIS128L_KEYBYTES
SODIUM_CRYPTO_AEAD_AEGIS128L_NSECBYTES
SODIUM_CRYPTO_AEAD_AEGIS128L_NPUBBYTES
SODIUM_CRYPTO_AEAD_AEGIS128L_ABYTES
SODIUM_CRYPTO_AEAD_AEGIS256_KEYBYTES
SODIUM_CRYPTO_AEAD_AEGIS256_NSECBYTES
SODIUM_CRYPTO_AEAD_AEGIS256_NPUBBYTES
SODIUM_CRYPTO_AEAD_AEGIS256_ABYTES
Tokenizer
T_PUBLIC_SET
T_PROTECTED_SET
T_PRIVATE_SET
XML
XML_OPTION_PARSE_HUGE
which allows parsing large inputs with
xml_parse
and
xml_parse_into_struct
.
Deprecated Features
PHP Core
Implicitly nullable parameter
A parameter's type is implicitly widened to accept
null if the default value for it is ENTITY.
The following code:
readonly. This was already forbidden for readonly initialization, and was an oversight in the "readonly reinitialization during cloning" implementation.
Type Change of Constants
The
PHP_DEBUG and
PHP_ZTS constants are now of type
bool. Previously they were of type
int.
Temporary Filename Length
The name of uploaded files and files created by the
tempnam function are now 13 bytes longer. The total length is still platform-dependent.
Removal of
E_STRICT error level
The
E_STRICT error level has been removed, as it was no longer in use within the PHP engine. The
E_STRICT constant has been deprecated.
Extension Class Constants which are now Typed
The following extension class constants now declare a type on their constants: Date, Intl, PDO, Reflection, SPL, Sqlite, XMLReader
Resource to Object Migration
Several ENTITYs have been migrated to ENTITYs. Return value checks using
is_resource should be replaced with checks for ENTITY, unless specified otherwise.
DBA
The DBA functions now accept and return
Dba\Connection objects instead of
dba_connection ENTITYs.
ODBC
The ODBC functions now accept and return
Odbc\Result objects instead of
odbc_result ENTITYs.
The ODBC functions now accept and return
Odbc\Connection objects instead of
odbc_connection ENTITYs.
SOAP
The SoapClient::$httpurl property is now a
Soap\Url object rather than a
soap_url ENTITY. Checks using
is_resource (i.e.
is_resource($client->httpurl)) should be replaced with checks for ENTITY (i.e.
$client->httpurl !== null).
The SoapClient::$sdl property is now a
Soap\Sdl object rather than a
soap_sdl ENTITY. Checks using
is_resource (i.e.
is_resource($client->sdl)) should be replaced with checks for ENTITY (i.e.
$client->sdl !== null).
New warnings and exceptions
New warnings and exceptions have been added which are triggered on programming errors, i.e. invalid values provided as arguments.
Curl
curl_multi_select now throws a ValueError if the
timeout parameter is less than
0 or greater than
PHP_INT_MAX.
Gd
imagejpeg,
imagewebp,
imagepng,
imageavif now throw a ValueError when an invalid
quality is passed.
imageavif will now throw a ValueError if an invalid
speed parameter value is passed.
imagescale will now throw a ValueError if the
width or
height parameters underflows/overflows.
imagescale will now throw a ValueError if an invalid
mode parameter value is passed.
imagefilter will now throw a ValueError with the
IMG_FILTER_SCATTER filter if the
sub or
plus parameters underflows/overflows.
Gettext
bind_textdomain_codeset,
textdomain,
d*gettext now throw a ValueError if
domain is the empty string.
Intl
resourcebundle_get, ResourceBundle::get, and accessing offsets on a
ResourceBundle object now throw: TypeError for invalid offset types, ValueError for an empty ENTITY, ValueError if the integer index does not fit in a signed 32 bit integer
IntlDateFormatter::__construct throws a ValueError if the
locale is invalid.
NumberFormatter::__construct throws a ValueError if the
locale is invalid.
MBString
mb_encode_numericentity and
mb_decode_numericentity now check that the
map is only composed of ENTITYs, if not a ValueError is now thrown.
mb_http_input now always throw a ValueError if
type is invalid.
mb_http_output now check that the
encoding does not contain any null bytes, if it does a ValueError is now thrown.
ODBC
odbc_fetch_row returns ENTITY when
row is less than or equal to
0. A warning is now emitted in this case.
PCNTL
The
pcntl_sigprocmask,
pcntl_sigwaitinfo, and
pcntl_sigtimedwait functions now throw: A ValueError if the
signals array is empty (except for
pcntl_sigprocmask if the
mode
SIG_SETMASK), A TypeError if a value of the
signals array is not an ENTITY, A ValueError if a value of the
signals array is not a valid signal number
The
pcntl_sigprocmask function now throws a ValueError if the
mode is not one of
SIG_BLOCK,
SIG_UNBLOCK, or
SIG_SETMASK.
The
pcntl_sigtimedwait function now throw: A ValueError if
seconds is less than
0, A ValueError if
nanoseconds is less than
0 or greater than
1e9, A ValueError if both
seconds and
nanoseconds are
0
Session
Setting a non-positive value for session.gc_divisor or a negative value for session.gc_probability now emits a warning.
SimpleXML
Calling
simplexml_import_dom with a non-XML object now throws a TypeError instead of a ValueError.
Standard
The
round function now validates the value of the
mode and throw a ValueError for invalid modes. Previously, invalid modes would have been interpreted as
PHP_ROUND_HALF_UP.
The
str_getcsv now throws ValueErrors when the
separator and
enclosure arguments are not one byte long, or if the
escape argument is not one byte long nor the empty string. This aligns the behaviour to be identical to the one of
fputcsv and
fgetcsv.
The
php_uname function now throws a ValueError if the
mode is invalid.
The
"allowed_classes" option for
unserialize now throws TypeError and ValueError if it is neither an
array of class names nor a
bool.
XMLReader
Passing an invalid character encoding to XMLReader::open or XMLReader::XML now throws a ValueError.
Passing a ENTITY containing null bytes previously emitted a warning and now throws a ValueError.
XMLWriter
Passing a ENTITY containing null bytes previously emitted a warning and now throws a ValueError.
XSL
XSLTProcessor::setParameter will now throw a ValueError when its arguments contain null bytes. This never actually worked correctly in the first place, which is why it throws an exception now.
Calling XSLTProcessor::importStyleSheet with a non-XML object now throws a TypeError instead of a ValueError.
Failure to call a PHP function callback during evaluation now throws instead of emitting a warning.
Date
number symbols in relative formats once again accept multiple signs, e.g.
+-2.
DOM
Some DOM methods previously returned ENTITY or a DOMException with code
DOM_PHP_ERR if a new node could not be allocated. They now consistently throw a DOMException with code
DOM_INVALID_STATE_ERR. This situation is extremely unlikely and the probability of being affected is low. As a result DOMImplementation::createDocument now has a tentative return type of
DOMDocument instead of
DOMDocument|false.
Previously,
DOMXPath objects could be cloned, but resulted in an unusable object. This is no longer possible, and cloning a
DOMXPath object now throws an Error.
The DOMImplementation::getFeature method has been removed.
GMP
The
GMP class is now final and cannot be extended anymore.
MBString
As of PHP 8.3.2, on invalid strings (those with encoding errors),
mb_substr and
mb_strstr interpret character indices in the same manner as most other mbstring functions. This means that character indices returned by
mb_strpos can be passed to
mb_substr.
For
SJIS-mac (MacJapanese) strings, those character indices refer to the indices of the Unicode codepoints which are produced when the string is converted to Unicode, which differ from the character indices for the
SJIS-mac characters that convert to a sequence of several codepoints.
MySQLi
The unused and undocumented constant
MYSQLI_SET_CHARSET_DIR has been removed.
The
MYSQLI_STMT_ATTR_PREFETCH_ROWS constant has been removed. The feature is unavailable with mysqlnd.
The
MYSQLI_CURSOR_TYPE_FOR_UPDATE and
MYSQLI_CURSOR_TYPE_SCROLLABLE constants have been removed. This functionality was never implemented, neither with mysqlnd nor with libmysql.
The unused
MYSQLI_TYPE_INTERVAL constant, which is currently a stub and an alias for
MYSQLI_TYPE_ENUM, has been removed.
MySQLnd
The error code reported for MySQL server wait timeouts has been changed from
2006 to
4031 for MySQL server versions 8.0.24 and above.
Opcache
The maximum value of the opcache.interned_strings_buffer setting on 64bit architectures is now
32767. Previously it was
4095.
JIT
The default configuration values for the JIT changed from
opcache.jit=tracing and
opcache.jit_buffer_size=0 to
opcache.jit=disable and
opcache.jit_buffer_size=64M, respectively.
This does not affect the default observable behavior, as the JIT is still disabled by default. However, it is now disabled through the opcache.jit setting, rather than opcache.jit_buffer_size. This may affect users who previously enabled JIT through opcache.jit_buffer_size exclusively, without also specifying a JIT mode using opcache.jit. To enable JIT compilation, set the opcache.jit config value accordingly.
If JIT compilation is enabled, PHP will now exit with a fatal error on startup if the initialization of the JIT compiler failed for any reason.
PCNTL
The
pcntl_sigprocmask,
pcntl_sigwaitinfo, and
pcntl_sigtimedwait functions now always return ENTITY on failure. In some case previously it could return the value
-1.
PCRE
The bundled pcre2lib has been updated to version 10.44. As a consequence, this means
{,3} is now recognized as a quantifier instead of as text. Furthermore, the meaning of some character classes in UCP mode has changed. Consult the PCRE2 Changelog for a full changelog.
PDO_DBLIB
The
Pdo\Dblib::ATTR_STRINGIFY_UNIQUEIDENTIFIER and
Pdo\Dblib::ATTR_DATETIME_CONVERT attributes now act as boolean attributes instead of integer attributes. Thus setting the attribute via PDO::setAttribute and retrieving it via PDO::getAttribute expects and or return a
bool.
PDO_FIREBIRD
The
PDO::ATTR_AUTOCOMMIT attribute now act as boolean attributes instead of integer attributes. Thus setting the attribute via PDO::setAttribute and retrieving it via PDO::getAttribute expects and or return a
bool.
The extension now exposes some Firebird C++ APIs, therefore building this extension now requires a C++ compiler. Moreover, the extension must now be compiled against fbclient 3.0 or higher.
PDO_MYSQL
The
PDO::ATTR_AUTOCOMMIT,
PDO::ATTR_EMULATE_PREPARES, and
PDO::MYSQL_ATTR_DIRECT_QUERY attributes now act as boolean attributes instead of integer attributes. Thus setting the attribute via PDO::setAttribute and retrieving it via PDO::getAttribute expects and or return a
bool.
PDO_PGSQL
The DSN's credentials, when set, are given priority over their PDO constructor counterparts, being closer to the documentation states.
SimpleXML
SimpleXMLElement is not only a representation of an XML element, but it is also a
RecursiveIterator. Prior to PHP 8.4.0, some of its methods (e.g. SimpleXMLElement::asXML or SimpleXMLElement::getName) and casting such instances to ENTITY would implicitly reset the iterator.
This could cause unexpected infinite loops as the iterator was rewound. For example:
123";
$xml = simplexml_load_string($xmlString);
$nodes = $xml->a->b;
foreach ($nodes as $nodeData) {
echo "nodeData: " . $nodeData . "\n";
$xml = $nodes->asXml();
}
would result in an infinite loop.
nodeData: 1
nodeData: 2
nodeData: 2
nodeData: 2
nodeData: 2
nodeData: 2
nodeData: 2
// ...
However, this behavior has now been corrected, and a
SimpleXMLElement will no longer implicitly reset the iterator data, unless explicitly rewound. Meaning the previous example would now result in:
nodeData: 1
nodeData: 2
nodeData: 3
SOAP
SoapClient::$typemap is now an
array rather than a
resource. Checks using
is_resource (i.e.
is_resource($client->typemap)) should be replaced with checks for ENTITY (i.e.
$client->typemap !== null).
The SOAP extension gained an optional dependency on the session extension. If PHP is built without the session extension and with the
--enable-rtld-now configure flag enabled, startup errors will now occur if the SOAP extension is also used. To solve this either don't use rtld-now or load the session extension.
Standard
When using
strcspn with
characters being the empty string, the length of the string is now returned instead of incorrectly stopping at the first null byte.
http_build_query now correctly handles backed enums.
stream_bucket_make_writeable and
stream_bucket_new will now return a
StreamBucket instance instead of an instance of
stdClass.
Tidy
Failures in the constructor now throw exceptions rather than emitting warnings and having a broken object.
XML
The
xml_set_*_handler functions now declare and check for an effective signature of
callablestringnull for the
handler parameters. Moreover, values of type
string that correspond to method names, of object set with
xml_set_object are now checked to see if the method exists on the class of the previously passed object. This means that
xml_set_object must now always be called prior to setting method names as
callables. Passing an empty string to disable the handler is still allowed, but deprecated.
However, as
xml_set_object and passing non-
callable strings is deprecated. It is recommended to change such instances with a
callable referring to the method directly.
New Classes, Enums, and Interfaces
Core
Deprecated
RequestParseBodyException
BCMath
BcMath\Number
DBA
Dba\Connection
DOM
Dom\HTMLDocument
Dom\XMLDocument
Dom\Document
Dom\ParentNode
Dom\ChildNode
Dom\Implementation
Dom\Node
Dom\NodeList
Dom\NamedNodeMap
Dom\DtdNamedNodeMap
Dom\HTMLCollection
Dom\AdjacentPosition
Dom\Element
Dom\HTMLElement
Dom\Attr
Dom\CharacterData
Dom\Text
Dom\CDATASection
Dom\ProcessingInstruction
Dom\Comment
Dom\DocumentType
Dom\DocumentFragment
Dom\Entity
Dom\EntityReference
Dom\Notation
Dom\TokenList
Dom\NamespaceInfo
Dom\XPath
ODBC
Odbc\Connection
Odbc\Result
PCNTL
Pcntl\QosClass
(macOS only)
PDO_DBLIB
Pdo\DbLib
PDO_FIREBIRD
Pdo\Firebird
PDO_MYSQL
Pdo\Mysql
PDO_ODBC
Pdo\Odbc
PDO_PGSQL
Pdo\Pgsql
PDO_SQLITE
Pdo\Sqlite
Reflection
ReflectionConstant
SOAP
Soap\Url
Soap\Sdl
Standard
RoundingMode
StreamBucket
New Features
PHP Core
Property Hooks
Object properties may now have additional logic associated with their
get and
set operations. Depending on the usage, that may or may not make the property virtual, that is, it has no backing value at all.
$this->firstName . ' ' . $this->lastName;
}
// All write operations go through this hook, and the result is what is written.
// Read access happens normally.
public string $firstName {
set => ucfirst(strtolower($value));
}
// All write operations go through this hook, which has to write to the backing value itself.
// Read access happens normally.
public string $lastName {
set {
if (strlen($value) < 2) {
throw new \InvalidArgumentException('Too short');
}
$this->lastName = $value;
}
}
}
$p = new Person();
$p->firstName = 'peter';
print $p->firstName; // Prints "Peter"
$p->lastName = 'Peterson';
print $p->fullName; // Prints "Peter Peterson"
$p->fullName = "Peter 'Pete' Peterson"; // Throws Error: "Property Person::$fullName is read-only"
Asymmetric Property Visibility
Object properties may now have their
set visibility controlled separately from the
get visibility.
name = $name;
}
}
Lazy Objects
It is now possible to create objects whose initialization is deferred until they are accessed. Libraries and frameworks can leverage these lazy objects to defer fetching data or dependencies required for initialization.
__construct($data);
};
$reflector = new ReflectionClass(Example::class);
$object = $reflector->newLazyGhost($initializer);
#[\Deprecated] attribute
The new
Deprecated attribute can be used to mark functions, methods, and class constants as deprecated. The behavior of functionality deprecated with this attribute matches the behavior of the existing deprecation mechanism for functionality provided by PHP itself. The only exception is that the emitted error code is
E_USER_DEPRECATED instead of
E_DEPRECATED.
Existing deprecations in functionality provided by PHP itself have been updated to use the attribute, improving the emitted error messages by including a short explanation.
Parsing RFC1867 (multipart) requests in non-POST HTTP requests
Added
request_parse_body function that allows parsing RFC1867 (multipart) requests in non-POST HTTP requests.
Chaining ENTITY expressions without parentheses
New expressions with constructor arguments are now dereferencable, meaning they allow chaining method calls, property accesses, etc. without enclosing the expression in parentheses.
Improved Debugging Info for
WeakReference
Getting the debug info for
WeakReference will now also output the object it references, or ENTITY if the reference is no longer valid.
Improved Debugging Info for
Closure
The output of Closure::__debugInfo now includes the name, file, and line of the
Closure.
Defining Identical Symbols in Different Namespace Blocks
Exiting a namespace now clears seen symbols. This allows using a symbol in a namespace block, even if a previous namespace block declared a symbol with the same name.
cURL
curl_version returns an additional
feature_list value, which is an associative array of all known cURL features, and whether they are supported (ENTITY) or not (ENTITY).
Added
CURL_HTTP_VERSION_3 and
CURL_HTTP_VERSION_3ONLY constants (available since libcurl 7.66 and 7.88) as available options for
CURLOPT_HTTP_VERSION.
Added
CURLOPT_PREREQFUNCTION as a cURL option that accepts a
callable to be called after the connection is made, but before the request is sent. This callable must return either
CURL_PREREQFUNC_OK or
CURL_PREREQFUNC_ABORT to allow or abort the request.
Added
CURLOPT_SERVER_RESPONSE_TIMEOUT, which was formerly known as
CURLOPT_FTP_RESPONSE_TIMEOUT. Both constants hold the same value.
Added
CURLOPT_DEBUGFUNCTION as a cURL option that accepts a
callable that gets called during the request lifetime with the
CurlHandle object, an integer containing the debug message type, and a string containing the debug message. The debug message type is one of the following constants:
CURLINFO_TEXT,
CURLINFO_HEADER_IN,
CURLINFO_HEADER_OUT,
CURLINFO_DATA_IN,
CURLINFO_DATA_OUT,
CURLINFO_SSL_DATA_IN,
CURLINFO_SSL_DATA_OUT Once this option is set,
CURLINFO_HEADER_OUT must not be set because it uses the same libcurl functionality.
The
curl_getinfo now returns an additional
posttransfer_time_us key, containing the number of microseconds from the start until the last byte is sent. When a redirect is followed, the time from each request is added together. This value can also be retrieved by passing
CURLINFO_POSTTRANSFER_TIME_T to the
curl_getinfo
option parameter. This requires libcurl 8.10.0 or later.
DOM
Added the Dom namespace with new classes as counterparts to the existing DOM classes (e.g.
Dom\Node is the new
DOMNode). These classes are compatible with HTML 5 and are WHATWG spec-compliant; solving long-standing bugs in the DOM extension. The old DOM classes remain available for backwards compatibility.
Added the DOMNode::compareDocumentPosition with its associated constants:
DOMNode::DOCUMENT_POSITION_DISCONNECTED,
DOMNode::DOCUMENT_POSITION_PRECEDING,
DOMNode::DOCUMENT_POSITION_FOLLOWING,
DOMNode::DOCUMENT_POSITION_CONTAINS,
DOMNode::DOCUMENT_POSITION_CONTAINED_BY,
DOMNode::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
It is now possible to pass any callable to DOMXPath::registerPhpFunctions. Furthermore, with DOMXPath::registerPhpFunctionNs, callbacks can now be registered that will use native function call syntax rather than using
php:function('name').
Intl
Added the
NumberFormatter::ROUND_HALFODD to complement the existing
NumberFormatter::ROUND_HALFEVEN functionality.
OpenSSL
Added support for Curve25519 + Curve448 based keys. Specifically x25519, ed25519, x448 and ed448 fields are supported in
openssl_pkey_new,
openssl_pkey_get_details,
openssl_sign, and
openssl_verify were extended to support those keys.
Implement PASSWORD_ARGON2 password hashing. Requires OpenSSL 3.2 and NTS build.
PCRE
The bundled pcre2lib has been updated to version 10.44. As a consequence, LoongArch JIT support has been added, spaces are now allowed between braces in Perl-compatible items, and variable-length lookbehind assertions are now supported.
With pcre2lib version 10.44, the maximum length of named capture groups has changed from
32 to
128.
Added support for the
r (PCRE2_EXTRA_CASELESS_RESTRICT) modifier, as well as the
(?r) mode modifier. When enabled along with the case-insensitive modifier (
i), the expression locks out mixing of ASCII and non-ASCII characters.
PDO
Added support for driver-specific subclasses in order to better support database-specific functionalities. The new classes are instantiatable either via calling the PDO::connect method or by instantiating one of the driver-specific subclasses directly.
Added support for driver specific SQL parsers. When a driver-specific parser is not available, the default parser is used. The default parser supports: single and double-quoted literals, with doubling as escaping mechanism, two-dashes and non-nested C-style comments
PDO_MYSQL
Added a custom parser supporting: single and double-quoted literals, with doubling and backslash as escaping mechanism, backtick literal identifiers and with doubling as escaping mechanism, two dashes followed by at least 1 whitespace, non-nested C-style comments, and hash-comments
PDO_PGSQL
Added a custom parser supporting: single and double-quoted literals, with doubling as escaping mechanism, C-style "escape" string literals (
E'string'), dollar-quoted string literals, two-dashes and C-style comments (non-nested), support for
?? as escape sequence for the
? operator
PDO_SQLITE
Added a custom parser supporting: single, double-quoted, and backtick literals, with doubling as escaping mechanism, square brackets quoting for identifiers, two-dashes and C-style comments (non-nested)
Phar
Added support for the Unix timestamp extension for Zip archives.
Readline
Added ability to change the
.php_history path through the
PHP_HISTFILE environment variable.
Reflection
ReflectionAttribute now contains a name property to improve the debugging experience.
ReflectionClassConstant::__toString and ReflectionProperty::__toString now returns the attached doc comments.
Multiple new methods and constants which are related to the lazy objects feature have been added: ReflectionClass::newLazyGhost, ReflectionClass::newLazyProxy, ReflectionClass::resetAsLazyGhost, ReflectionClass::resetAsLazyProxy, ReflectionClass::isUninitializedLazyObject, ReflectionClass::initializeLazyObject, ReflectionClass::markLazyObjectAsInitialized, ReflectionClass::getLazyInitializer, ReflectionProperty::skipLazyInitialization, ReflectionProperty::setRawValueWithoutLazyInitialization,
ReflectionClass::SKIP_INITIALIZATION_ON_SERIALIZE,
ReflectionClass::SKIP_DESTRUCTOR
SOAP
Added support for clark notation for namespaces in class map. It is now possible to specify entries in a class map with clark notation to resolve a type with a specific namespace to a specific class. For example:
'{http://example.com}foo' => 'FooClass'.
Instances of DateTimeInterface that are passed to
xsd:datetime or similar elements are now serialized as such instead of being serialized as an empty string.
Session persistence now works with a shared session module.
Standard
Added a new
RoundingMode enum with clearer naming and improved discoverability compared to the
PHP_ROUND_* constants. Moreover, four new rounding modes were added which are only available via the new
RoundingMode enum.
XSL
It is now possible to use parameters that contain both single and double quotes.
It is now possible to pass any callable to XSLTProcessor::registerPhpFunctions.
Added XSLTProcessor::$maxTemplateDepth and XSLTProcessor::$maxTemplateVars to control the recursion depth of XSL template evaluation.
Zip
Added the
ZipArchive::ER_TRUNCATED_ZIP constant, which was added in libzip 1.11.
New Functions
Core
request_parse_body
BCMath
bcceil
bcdivmod
bcfloor
bcround
Date
DateTime::createFromTimestamp
DateTime::getMicrosecond
DateTime::setMicrosecond
DateTimeImmutable::createFromTimestamp
DateTimeImmutable::getMicrosecond
DateTimeImmutable::setMicrosecond
DOM
DOMNode::compareDocumentPosition
DOMXPath::registerPhpFunctionNS
DOMXPath::quote
Hash
HashContext::__debugInfo
Intl
IntlTimeZone::getIanaID
intltz_get_iana_id
IntlDateFormatter::parseToCalendar
Spoofchecker::setAllowedChars
grapheme_str_split
MBString
mb_trim
mb_ltrim
mb_rtrim
mb_ucfirst
mb_lcfirst
Opcache
opcache_jit_blacklist
PCNTL
pcntl_getcpu
pcntl_getcpuaffinity
pcntl_getqos_class
pcntl_setns
pcntl_setqos_class
pcntl_waitid
PDO_PGSQL
Pdo\Pgsql::setNoticeCallback
PGSQL
pg_change_password
pg_jit
pg_put_copy_data
pg_put_copy_end
pg_result_memory_size
pg_set_chunked_rows_size
pg_socket_poll
Reflection
The following methods relate to the new lazy object feature: ReflectionClass::newLazyGhost, ReflectionClass::newLazyProxy, ReflectionClass::resetAsLazyGhost, ReflectionClass::resetAsLazyProxy, ReflectionClass::isUninitializedLazyObject, ReflectionClass::initializeLazyObject, ReflectionClass::markLazyObjectAsInitialized, ReflectionClass::getLazyInitializer, ReflectionProperty::skipLazyInitialization, ReflectionProperty::setRawValueWithoutLazyInitialization
ReflectionClassConstant::isDeprecated
ReflectionGenerator::isClosed
ReflectionProperty::isDynamic
Sodium
sodium_crypto_aead_aegis128l_
*
sodium_crypto_aead_aegis256_
*
SPL
SplObjectStorage::seek
SOAP
SoapServer::__getLastResponse
Standard
http_get_last_response_headers
http_clear_last_response_headers
fpow
array_all
array_any
array_find
array_find_key
Tidy
tidyNode::getNextSibling
tidyNode::getPreviousSibling
XMLReader
XMLReader::fromStream
XMLReader::fromUri
XMLReader::fromString
XMLWriter
XMLWriter::toStream
XMLWriter::toUri
XMLWriter::toMemory
XSL
XSLTProcessor::registerPhpFunctionNS
Other Changes
Core changes
Closures
Closure names have been adjusted to include the parent function's name and the line of definition to make them easier to distinguish, for example within stack traces.
Fibers
Fiber switching during destructor execution is now allowed. It was previously blocked due to conflicts with garbage collection.
Destructors may now be executed in a separate Fiber:
When garbage collection is triggered in a Fiber, destructors called by the GC are executed in a separate Fiber: the gc_destructor_fiber. If this Fiber suspends, a new one is created to execute the remaining destructors. The previous gc_destructor_fiber is not referenced anymore by the GC and may be collected if it's not referenced anywhere else. Objects whose destructor is suspended will not be collected until the destructor returns or the
Fiber is collected.
Output Handlers
Output handler status flags passed to the
flags parameter of
ob_start are now cleared.
output_add_rewrite_var now uses
url_rewriter.hosts instead of
session.trans_sid_hosts for selecting hosts that will be rewritten.
Changes in SAPI Modules
apache2handler
Support for EOL Apache 2.0 and 2.2 has been removed. Minimum required Apache version is now 2.4.
CLI
The builtin server looks for an index file recursively by traversing parent directories in case the specified file cannot be located. This process was previously skipped if the path looked like it was referring to a file, i.e. if the last path component contained a period. In that case, a 404 error was returned. The behavior has been changed to look for an index file in all cases.
FPM
Flushing headers without a body will now succeed.
Status page has a new field to display a memory peak.
The
/dev/poll
events.mechanism setting for Solaris/Illumos had been retired.
Changed Functions
Core
trigger_error and
user_error now have a return type of
true instead of
bool.
DOM
DOMDocument::registerNodeClass now has a tentative return type of
true instead of
bool. It could only ever return ENTITY in practice.
Hash
hash_update now has a tentative return type of
true instead of
bool. It could only ever return ENTITY in practice.
Intl
NumberFormatter::ROUND_TOWARD_ZERO and
NumberFormatter::ROUND_AWAY_FROM_ZERO have been added as aliases for
NumberFormatter::ROUND_DOWN and
NumberFormatter::ROUND_UP to be consistent with the new
PHP_ROUND_* modes.
ResourceBundle::get now has a tentative return type of
ResourceBundle|array|string|int|null.
The
idn_to_ascii and
idn_to_utf8 functions now always throw ValueErrors if the
domain name is empty or too long.
The
idn_to_ascii and
idn_to_utf8 functions now always throw ValueError if the
variant parameter is not
INTL_IDNA_VARIANT_UTS46.
LibXML
libxml_set_streams_context now immediately throws a TypeError when a non-stream-context resource is passed to the function, instead of throwing later when the stream context is used.
MBString
The behavior of
mb_strcut is more consistent now on invalid UTF-8 and UTF-16 strings. There is no behavioural change for valid UTF-8 and UTF-16 strings.
ODBC
The
row of
odbc_fetch_object,
odbc_fetch_array, and
odbc_fetch_into now have a default value of ENTITY, consistent with
odbc_fetch_row. Previously, the default values were
-1,
-1, and
0, respectively.
OpenSSL
The
extra_attributes in
openssl_csr_new sets the CSR attributes instead of subject DN, which incorrectly done previously.
The
dn in
openssl_csr_new allows setting an
array of values for a single entry.
New
serial_hex added to
openssl_csr_sign to allow setting serial numbers in the hexadecimal format.
Parsing ASN.1 UTCTime with
openssl_x509_parse fails if seconds are omitted for OpenSSL version below 3.2 (
-1 is returned for such fields). OpenSSL version above 3.3 did not load such certificates already.
PDO
It is now possible to fetch the value of the
PDO::ATTR_STRINGIFY_FETCHES attribute with PDO::getAttribute.
A new
Pdo\Pgsql::ATTR_RESULT_MEMORY_SIZE has been added to retrieve the memory usage of query results with PDO::getAttribute for drivers that support it.
PDO_FIREBIRD
It is now possible to fetch the value of the
FB_ATTR_DATE_FORMAT,
FB_ATTR_TIME_FORMAT,
FB_ATTR_TIMESTAMP_FORMAT, attributes with PDO::getAttribute.
Added new attributes to specify transaction isolation level and access mode. Five constants relating to this functionality have been added:
Pdo\Firebird::TRANSACTION_ISOLATION_LEVEL,
Pdo\Firebird::READ_COMMITTED,
Pdo\Firebird::REPEATABLE_READ,
Pdo\Firebird::SERIALIZABLE,
Pdo\Firebird::WRITABLE_TRANSACTION
When using persistent connections, there is now a liveliness check in the constructor.
The content that is built changes depending on the value of
FB_API_VER in
ibase.h. A new static method Pdo\Firebird::getApiVersion can be used to obtain this information. This information is also now referenced in
phpinfo.
Five new data types are now available:
INT128,
DEC16,
DEC34,
TIMESTAMP_TZ,
TIME_TZ . These are available starting with Firebird 4.0.
PDO_MYSQL
It is now possible to fetch the value of the
PDO::ATTR_FETCH_TABLE_NAMES attribute with PDO::getAttribute.
PDO_PGSQL
Support retrieving the memory usage of queries for
Pdo\Pgsql::ATTR_RESULT_MEMORY_SIZE.
If the column is of type
FLOAT4OID or
FLOAT8OID the value will now be returned as a
float instead of a
string.
PGSQL
The
conditions parameter of
pg_select is now optional and accepts an empty array.
Phar
The Phar::setAlias, Phar::setDefaultStub methods now have a tentative return type of
true instead of
bool.
POSIX
posix_isatty now sets the error number when the file descriptor/stream argument is invalid.
Reflection
ReflectionGenerator::getFunction may now be called after the generator finished executing.
Sockets
The
backlog parameter of
socket_create_listen now has a default value of
SOMAXCONN. Previously, it was
128.
Sodium
The
sodium_crypto_aead_aes256gcm_* functions are now available on aarch64 CPUs with the ARM cryptographic extensions.
SPL
The SplPriorityQueue::insert, SplPriorityQueue::recoverFromCorruption, SplHeap::insert, SplHeap::recoverFromCorruption methods now have a tentative return type of
true instead of
bool.
SplObjectStorage now implements SeekableIterator.
Standard
The default
'cost' value for the
PASSWORD_BCRYPT hashing algorithm for
password_hash has been increased from
10 to
12.
debug_zval_dump now indicates whether an array is packed.
long2ip now has a return type of
string instead of
string|false.
highlight_string now has a return type of
string|true instead of
string|bool.
print_r now has a return type of
string|true instead of
string|bool.
Rounding with
round
The
mode parameter of the
round function has been widened to
RoundingMode|int, accepting instances of a new
RoundingMode enum.
Four new modes have been added to the
round function: RoundingMode::PositiveInfinity, RoundingMode::NegativeInfinity, RoundingMode::TowardsZero, RoundingMode::AwayFromZero
The internal implementation for rounding to integers has been rewritten to be easier to verify for correctness and to be easier to maintain. Some rounding bugs have been fixed as a result of the rewrite. For example previously rounding
0.49999999999999994 to the nearest integer would have resulted in
1.0 instead of the correct result
0.0. Additional inputs might also be affected and result in different outputs compared to earlier PHP versions.
Fixed a bug caused by "pre-rounding" of the
round function. Previously, using "pre-rounding" to treat a value like
0.285 (actually
0.28499999999999998) as a decimal number and round it to
0.29. However, "pre-rounding" incorrectly rounds certain numbers, so this fix removes "pre-rounding" and changes the way numbers are compared, so that the values are correctly rounded as decimal numbers.
The maximum precision that can be handled by
round has been extended by one digit. For example,
round(4503599627370495.5) returned in
4503599627370495.5, but now returns
4503599627370496.
Other Changes to Extensions
cURL
The minimum libcurl version required is now 7.61.0.
The
CURLOPT_DNS_USE_GLOBAL_CACHE option no longer has any effect, and is silently ignored. This underlying feature was deprecated in libcurl 7.11.1, and removed in libcurl 7.62.0.
GMP
Casting a
GMP object to
bool is now possible instead of emitting a
E_RECOVERABLE_ERROR. The casting behaviour is overloaded such that a
GMP object representing the value
0 is cast to ENTITY.
LibXML
The minimum libxml2 version required is now 2.9.4.
Intl
Cloning an Intl object consistently throws an Error when the clone cannot be performed, either because the object has not been initialized, or because the underlying ICU clone operation failed. Formerly, most of these classes threw an Exception instead, and
Spoofchecker raised a fatal error.
MBString
Unicode data tables have been updated to Unicode 16.0.
MySQLnd
Support for the new VECTOR data type from MySQL 9.
OpenSSL
The minimum OpenSSL version required is now 1.1.1.
PDO_PGSQL
The minimum libpq version required is now 10.0.
PGSQL
The minimum libpq version required is now 10.0.
SPL
Out of bounds accesses in
SplFixedArray now throw exceptions of type OutOfBoundsException instead of RuntimeException. Because OutOfBoundsException is a child class of RuntimeException no behavioural changes are exhibited when attempting to catch those exceptions.
XSL
The typed properties XSLTProcessor::$cloneDocument and XSLTProcessor::$doXInclude are now declared.
Zlib
The minimum zlib version required is now 1.2.11.
Performance
Core
Improved the performance of floating point number parsing and formatting in ZTS builds under highly concurrent loads. This affects the
printf family of functions as well as serialization functions such as
json_encode, or
serialize.
sprintf using only
%s and
%d specifiers will be compiled into the equivalent string interpolation, avoiding the overhead of a function call and repeatedly parsing the format string.
BCMath
Improved performance of number conversions and operations.
DOM
The performance of DOMNode::C14N is greatly improved for the case without an xpath query. This can give a time improvement of easily two order of magnitude for documents with tens of thousands of nodes.
Improved performance and reduce memory consumption of XML serialization.
Reduced memory usage of node classes.
FTP
Improved the performance of FTP uploads up to a factor of 10x for large uploads.
Hash
Added SSE2 and SHA-NI implementations of SHA-256. This improves the performance on supported CPUs by ~1.3x (SSE2), and 3x - 5x (SHA-NI). Credit to Colin Percival / Tarsnap for this optimization.
MBString
mb_strcut is much faster now for UTF-8 and UTF-16 strings.
Looking up mbstring encoding names is much faster now.
The performance of converting SJIS-win to Unicode is greatly improved.
MySQLnd
Improved the performance of MySQLnd quoting.
PCRE
Improved the performance of named capture groups.
Random
Improved the performance of
Random\Randomizer, with a specific focus on the Random\Randomizer::getBytes, and Random\Randomizer::getBytesFromString methods.
SimpleXML
Improved performance and reduce memory consumption of XML serialization.
Standard
The performance of
strspn and
strcspn is greatly improved. They now run in linear time instead of being bounded by quadratic time.
Improved the performance of
strpbrk.
get_browser is much faster now, up to 1.5x - 2.5x for some test cases.
Removed Extensions
These extensions have been moved to PECL and are no longer part of the PHP distribution. New releases for the PECL packages will be published on an ad-hoc basis according to user demand.
IMAP
OCI8
PDO_OCI
PSpell
Windows Support
Core
Building with Visual Studio now requires at least Visual Studio 2019. However, Visual Studio 2022 is recommended.
AVX(2) CPU support is now properly detected for MSVC builds.
Native AVX-512 builds are now supported via the
--enable-native-intrinsics=avx512 configure option.
Migrating from PHP 8.4.x to PHP 8.5.x
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.
ENTITY 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x, 8.2.x. 8.3.x. 8.4.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
New Global Constants
Core
PHP_BUILD_DATE
PHP_BUILD_PROVIDER
cURL
CURLINFO_USED_PROXY
CURLINFO_HTTPAUTH_USED
CURLINFO_PROXYAUTH_USED
CURLINFO_CONN_ID
CURLINFO_QUEUE_TIME_T
CURLOPT_INFILESIZE_LARGE
CURLFOLLOW_ALL
CURLFOLLOW_OBEYCODE
CURLFOLLOW_FIRSTONLY
Filter
FILTER_THROW_ON_FAILURE
Intl
DECIMAL_COMPACT_SHORT
DECIMAL_COMPACT_LONG
OpenSSL
OPENSSL_PKCS1_PSS_PADDING
PKCS7_NOSMIMECAP
PKCS7_CRLFEOL
PKCS7_NOCRL
PKCS7_NO_DUAL_CONTENT
POSIX
POSIX_SC_OPEN_MAX
Sockets
IPPROTO_ICMP
IPPROTO_ICMPV6
TCP_FUNCTION_BLK
(FreeBSD only)
TCP_FUNCTION_ALIAS
(FreeBSD only)
TCP_REUSPORT_LB_NUMA
(FreeBSD only)
TCP_REUSPORT_LB_NUMA_NODOM
(FreeBSD only)
TCP_REUSPORT_LB_NUMA_CURDOM
(FreeBSD only)
TCP_BBR_ALGORITHM
(FreeBSD only)
AF_PACKET
(Linux only)
IP_BINDANY
(FreeBSD/NetBSD/OpenBSD only)
SO_BUSY_POLL
(Linux only)
UDP_SEGMENT
(Linux only)
SHUT_RD
SHUT_WR
SHUT_RDWR
Tokenizer
T_VOID_CAST
T_PIPE
Standard
IMAGETYPE_HEIF
IMAGETYPE_SVG
when libxml is loaded.
Deprecated Features
PHP Core
Changes to user output handler
Trying to produce output (e.g. with
echo) within a user output handler is deprecated. The deprecation warning will bypass the handler producing the output to ensure it is visible; if there are nested output handlers the next one will still be used.
Non-canonical cast names
Non-canonical cast names
(boolean),
(integer),
(double), and
(binary) have been deprecated, use
(bool),
(int),
(float), and
(string) respectively.
Terminating case statements with a semicolon
Terminating case statements with a semicolon instead of a colon has been deprecated.
The backtick operator
The backtick operator as an alias for
shell_exec has been deprecated.
Returning null from __debugInfo()
Returning ENTITY from __debugInfo() has been deprecated. Return an empty array instead.
report_memleaks INI directive
The report_memleaks INI directive has been deprecated.
Constant redeclaration
Constant redeclaration has been deprecated. Note that this already generated a warning and will continue to do so.
Closure binding issues
The following closure binding issues, which already emit an
E_WARNING, are now deprecated: Binding an instance to a static closure., Binding methods to objects that are not instances of the class (or subclass) that the method is defined., Unbinding $this from a method., Unbinding $this from a closure that uses `$this`., Binding a closure to the scope of an internal class., Rebinding the scope of a closure created from a function or method.
__sleep() and __wakeup() magic methods
The __sleep() and __wakeup() magic methods have been soft-deprecated. The __serialize() and __unserialize() magic methods should be used instead, or at the same time if compatibility with PHP 7 is required.
Using null as an array offset
Using ENTITY as an array offset or when calling
array_key_exists is now deprecated. Instead an empty string should be used.
Incrementing non-numeric strings
Incrementing non-numeric strings is now deprecated. Instead the
str_increment function should be used.
register_argc_argv INI directive
Deriving
$_SERVER['argc'] and
$_SERVER['argv'] from the query string for non-CLI SAPIs has been deprecated. Configure
register_argc_argv=0 and switch to either
$_GET or
$_SERVER['QUERY_STRING'] to access the information, after verifying that the usage is safe.
cURL
The
curl_close function has been deprecated, as
CurlHandle objects are freed automatically.
The
curl_share_close function has been deprecated, as
CurlShareHandle objects are freed automatically.
Date
The
DATE_RFC7231 and
DateTimeInterface::RFC7231 constants have been deprecated. This is because the associated timezone is ignored and always uses GMT.
FileInfo
The
finfo_close function has been deprecated. As
finfo objects are freed automatically.
The
context parameter of the
finfo_buffer function has been deprecated as it is ignored.
GD
The
imagedestroy function has been deprecated, as
GdImage objects are freed automatically.
Hash
The
MHASH_* constants have been deprecated.
Intl
The intl.error_level INI setting has been deprecated. Errors should either be checked manually or exceptions should be enabled by using the intl.use_exceptions INI setting.
LDAP
Specific Oracle Instant Client calls and constants have been deprecated. List of affected calls:
ldap_connect with wallet support,
ldap_connect_wallet List of affected constants:
GSLC_SSL_NO_UATH,
GSLC_SSL_ONEWAY_UATH,
GSLC_SSL_TWOWAY_UATH
MySQLi
The
mysqli_execute alias function has been deprecated. Use
mysqli_stmt_execute instead.
OpenSSL
The
key_length parameter for
openssl_pkey_derive has been deprecated. This is because it is either ignored, or truncates the key, which can be a security vulnerability.
PDO
The
"uri:" DSN scheme has been deprecated due to security concerns with DSNs coming from remote URIs.
Driver specific constants in the PDO class have been deprecated. List of affected constants and their replacement:
PDO::DBLIB_ATTR_CONNECTION_TIMEOUT =>
Pdo\Dblib::ATTR_CONNECTION_TIMEOUT,
PDO::DBLIB_ATTR_QUERY_TIMEOUT =>
Pdo\Dblib::ATTR_QUERY_TIMEOUT,
PDO::DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER =>
Pdo\Dblib::ATTR_STRINGIFY_UNIQUEIDENTIFIER,
PDO::DBLIB_ATTR_VERSION =>
Pdo\Dblib::ATTR_VERSION,
PDO::DBLIB_ATTR_TDS_VERSION =>
Pdo\Dblib::ATTR_TDS_VERSION,
PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS =>
Pdo\Dblib::ATTR_SKIP_EMPTY_ROWSETS,
PDO::DBLIB_ATTR_DATETIME_CONVERT =>
Pdo\Dblib::ATTR_DATETIME_CONVERT,
PDO::FB_ATTR_DATE_FORMAT =>
Pdo\Firebird::ATTR_DATE_FORMAT,
PDO::FB_ATTR_TIME_FORMAT =>
Pdo\Firebird::ATTR_TIME_FORMAT,
PDO::FB_ATTR_TIMESTAMP_FORMAT =>
Pdo\Firebird::ATTR_TIMESTAMP_FORMAT,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY =>
Pdo\Mysql::ATTR_USE_BUFFERED_QUERY,
PDO::MYSQL_ATTR_LOCAL_INFILE =>
Pdo\Mysql::ATTR_LOCAL_INFILE,
PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY =>
Pdo\Mysql::ATTR_LOCAL_INFILE_DIRECTORY,
PDO::MYSQL_ATTR_INIT_COMMAND =>
Pdo\Mysql::ATTR_INIT_COMMAND,
PDO::MYSQL_ATTR_MAX_BUFFER_SIZE =>
Pdo\Mysql::ATTR_MAX_BUFFER_SIZE,
PDO::MYSQL_ATTR_READ_DEFAULT_FILE =>
Pdo\Mysql::ATTR_READ_DEFAULT_FILE,
PDO::MYSQL_ATTR_READ_DEFAULT_GROUP =>
Pdo\Mysql::ATTR_READ_DEFAULT_GROUP,
PDO::MYSQL_ATTR_COMPRESS =>
Pdo\Mysql::ATTR_COMPRESS,
PDO::MYSQL_ATTR_DIRECT_QUERY =>
Pdo\Mysql::ATTR_DIRECT_QUERY,
PDO::MYSQL_ATTR_FOUND_ROWS =>
Pdo\Mysql::ATTR_FOUND_ROWS,
PDO::MYSQL_ATTR_IGNORE_SPACE =>
Pdo\Mysql::ATTR_IGNORE_SPACE,
PDO::MYSQL_ATTR_SSL_KEY =>
Pdo\Mysql::ATTR_SSL_KEY,
PDO::MYSQL_ATTR_SSL_CERT =>
Pdo\Mysql::ATTR_SSL_CERT,
PDO::MYSQL_ATTR_SSL_CA =>
Pdo\Mysql::ATTR_SSL_CA,
PDO::MYSQL_ATTR_SSL_CAPATH =>
Pdo\Mysql::ATTR_SSL_CAPATH,
PDO::MYSQL_ATTR_SSL_CIPHER =>
Pdo\Mysql::ATTR_SSL_CIPHER,
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT =>
Pdo\Mysql::ATTR_SSL_VERIFY_SERVER_CERT,
PDO::MYSQL_ATTR_SERVER_PUBLIC_KEY =>
Pdo\Mysql::ATTR_SERVER_PUBLIC_KEY,
PDO::MYSQL_ATTR_MULTI_STATEMENTS =>
Pdo\Mysql::ATTR_MULTI_STATEMENTS,
PDO::ODBC_ATTR_USE_CURSOR_LIBRARY =>
Pdo\Odbc::ATTR_USE_CURSOR_LIBRARY,
PDO::ODBC_ATTR_ASSUME_UTF8 =>
Pdo\Odbc::ATTR_ASSUME_UTF8,
PDO::ODBC_SQL_USE_IF_NEEDED =>
Pdo\Odbc::SQL_USE_IF_NEEDED,
PDO::ODBC_SQL_USE_DRIVER =>
Pdo\Odbc::SQL_USE_DRIVER,
PDO::ODBC_SQL_USE_ODBC =>
Pdo\Odbc::SQL_USE_ODBC,
PDO::PGSQL_ATTR_DISABLE_PREPARES =>
Pdo\Pgsql::ATTR_DISABLE_PREPARES,
PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES =>
Pdo\Sqlite::ATTR_EXTENDED_RESULT_CODES,
PDO::SQLITE_ATTR_OPEN_FLAGS =>
Pdo\Sqlite::ATTR_OPEN_FLAGS,
PDO::SQLITE_ATTR_READONLY_STATEMENT =>
Pdo\Sqlite::ATTR_READONLY_STATEMENT,
PDO::SQLITE_DETERMINISTIC =>
Pdo\Sqlite::DETERMINISTIC,
PDO::SQLITE_OPEN_READONLY =>
Pdo\Sqlite::OPEN_READONLY,
PDO::SQLITE_OPEN_READWRITE =>
Pdo\Sqlite::OPEN_READWRITE,
PDO::SQLITE_OPEN_CREATE =>
Pdo\Sqlite::OPEN_CREATE
Driver specific methods in the PDO class have been deprecated. List of affected methods and their replacement: PDO::pgsqlCopyFromArray => Pdo\Pgsql::copyFromArray, PDO::pgsqlCopyFromFile => Pdo\Pgsql::copyFromFile, PDO::pgsqlCopyToArray => Pdo\Pgsql::copyToArray, PDO::pgsqlCopyToFile => Pdo\Pgsql::copyToFile, PDO::pgsqlGetNotify => Pdo\Pgsql::getNotify, PDO::pgsqlGetPid => Pdo\Pgsql::getPid, PDO::pgsqlLOBCreate => Pdo\Pgsql::lobCreate, PDO::pgsqlLOBOpen => Pdo\Pgsql::lobOpen, PDO::pgsqlLOBUnlink => Pdo\Pgsql::lobUnlink, PDO::sqliteCreateAggregate => Pdo\Sqlite::createAggregate, PDO::sqliteCreateCollation => Pdo\Sqlite::createCollation, PDO::sqliteCreateFunction => Pdo\Sqlite::createFunction
PDO_PGSQL
Constants related to transaction states have been deprecated as this feature is unavailable with PDO:
PDO::PGSQL_TRANSACTION_IDLE,
PDO::PGSQL_TRANSACTION_ACTIVE,
PDO::PGSQL_TRANSACTION_INTRANS,
PDO::PGSQL_TRANSACTION_INERROR,
PDO::PGSQL_TRANSACTION_UNKNOWN
Reflection
The
setAccessible() methods of various Reflection objects have been deprecated, as those no longer have an effect.
Calling ReflectionClass::getConstant for constants that do not exist has been deprecated.
Calling ReflectionProperty::getDefaultValue for properties without default values has been deprecated.
SPL
Unregistering all autoloaders by passing the
spl_autoload_call function as a callback argument to
spl_autoload_unregister has been deprecated. Instead if this is needed, one should iterate over the return value of
spl_autoload_functions and call
spl_autoload_unregister on each value.
The SplObjectStorage::contains, SplObjectStorage::attach, and SplObjectStorage::detach methods have been deprecated in favour of SplObjectStorage::offsetExists, SplObjectStorage::offsetSet, and SplObjectStorage::offsetUnset respectively.
Using
ArrayObject and
ArrayIterator with objects has been deprecated.
Standard
The
socket_set_timeout alias function has been deprecated. Use
stream_set_timeout instead.
Passing ENTITY to
readdir,
rewinddir, and
closedir to use the last opened directory has been deprecated. Provide the last opened directory explicitly instead.
Passing integers outside the interval
[0, 255] to
chr is now deprecated. This is because a byte can only hold a value within this interval.
Passing a string which is not a single byte to
ord is now deprecated, this is indicative of a bug.
The locally predefined variable $http_response_header is deprecated. Instead one should call the
http_get_last_response_headers function.
XML
The
xml_parser_free function has been deprecated, as
XMLParser objects are freed automatically.
Backward Incompatible Changes
PHP Core
"array" and
"callable" alias name
It is no longer possible to use
"array" and
"callable" as class alias names in
class_alias
Loosely comparing uncomparable objects
Loosely comparing uncomparable objects (e.g. enums,
CurlHandle and other internal classes) to booleans was previously inconsistent. If compared to a boolean literal
$object == true, it would behave the same way as
(bool)$object. If compared to a statically unknown value
$object == $true, it would always return ENTITY. This behavior was consolidated to always follow the behavior of
(bool)$object.
Return value of gc_collect_cycles
The return value of
gc_collect_cycles no longer includes strings and resources that were indirectly collected through cycles.
Substitute static keyword in final subclass
It is now allowed to substitute
static with
self or the concrete class name in final subclasses.
Tick handlers
The tick handlers are now deactivated after all shutdown functions, destructors have run and the output handlers have been cleaned up.
Traits binding
Traits are now bound before the parent class. This is a subtle behavioral change, but should more closely match user expectations.
Errors during compilation and class linking
Errors emitted during compilation and class linking are now always delayed and handled after compilation or class linking. Fatal errors emitted during compilation or class linking cause any delayed errors to be handled immediately, without calling user-defined error handlers.
Exceptions thrown by user-defined error handler
Exceptions thrown by user-defined error handlers when handling class linking errors are not promoted to fatal errors anymore and do not prevent linking.
Attribute apply error during compilation
Applying
#[\Attribute] to an abstract class, enum, interface, or trait triggers an error during compilation. Previously, the attribute could be added, but when ReflectionAttribute::newInstance was called an error would be thrown. The error can be delayed from compilation to runtime using the new
#[\DelayedTargetValidation] attribute.
disable_classes INI setting
The disable_classes INI setting has been removed as it causes various engine assumptions to be broken.
Destructuring non-array values
Destructuring non-array values (other than ENTITY) using
[] or
list now emits a warning.
Warnings related to cast
A warning is now emitted when casting floats (or strings that look like floats) to int if they cannot be represented as one. This affects explicit int casts and implicit int casts.
A warning is now emitted when casting NAN to other types.
Bzip2
bzcompress now throws a
ValueError when
block_size is not between 1 and 9.
bzcompress now throws a
ValueError when
work_factor is not between 0 and 250.
DOM
Cloning a
DOMNamedNodeMap,
DOMNodeList,
Dom\NamedNodeMap,
Dom\NodeList,
Dom\HTMLCollection, and
Dom\DtdNamedNodeMap now fails. This never actually resulted in a working object, therefore no impact is expected.
FileInfo
finfo_file and finfo::file now throws a ValueError instead of a TypeError when
filename contains nul bytes. This aligns the type of Error thrown to be consistent with the rest of the language.
Intl
The extension now requires at least ICU 57.1.
IntlDateFormatter::setTimeZone/
datefmt_set_timezone now throws an IntlException on uninitialised classes/clone failures.
All
Locale methods now throw a ValueError when the locale argument contain null bytes.
The behaviour of
Collator::SORT_REGULAR with respect to handling numeric strings is now aligned with the behaviour of
SORT_REGULAR in ext/standard.
LDAP
ldap_get_option and
ldap_set_option now throw a ValueError when passing an invalid option.
MBString
Unicode data tables have been updated to Unicode 17.0
MySQLi
Calling the mysqli constructor on an already-constructed object is now no longer possible and throws an Error.
ODBC
ODBC now assumes that at least ODBC 3.5 functionality is available. The ODBCVER definition and build system flags to control it have been removed.
ODBC no longer has build flags to build against specific drivers (except for DB2) and removes special cases for those drivers. It is strongly recommended to use a driver manager like iODBC or unixODBC on non-Windows.
Opcache
The Opcache extension is now always built into the PHP binary and is always loaded. The INI directives opcache.enable and opcache.enable_cli are still honored.
The
--enable-opcache/
--disable-opcache configure flags have been removed, and the build does not produce
opcache.so or
php_opcache.dll objects anymore.
Using
zend_extension=opcache.so or
zend_extension=php_opcache.dll INI directives will emit a warning.
PCNTL
pcntl_exec now throws ValueError when entries of the
args parameter contain null bytes.
pcntl_exec now throws ValueError when entries or keys of the
env_vars parameter contain null bytes.
PCRE
The extension is compiled without semi-deprecated PCRE2_EXTRA_ALLOW_LOOKAROUND_BSK compile option.
PDO
The constructor arguments set in conjunction with
PDO::FETCH_CLASS now follow the usual CUFA (
call_user_func_array) semantics. This means string keys will act like a named argument. Moreover, automatic wrapping for by-value arguments passed to a by-ref parameter has been removed, and the usual
E_WARNING about this is now emitted. To pass a variable by-ref to a constructor argument use the general array value reference assignment:
$ctor_args = [ENTITY$valByRef]
Attempting to call PDOStatement::setFetchMode during a call to PDOStatement::fetch, PDOStatement::fetchObject, PDOStatement::fetchAll, for example using tricks such as passing the statement object as a constructor argument when fetching into an object, will now throw an Error.
The value of the constants
PDO::FETCH_GROUP,
PDO::FETCH_UNIQUE,
PDO::FETCH_CLASSTYPE,
PDO::FETCH_PROPS_LATE, and
PDO::FETCH_SERIALIZE have changed.
A ValueError is now thrown if
PDO::FETCH_PROPS_LATE is used with a fetch mode different than
PDO::FETCH_CLASS, consistent with other fetch flags.
A ValueError is now thrown if
PDO::FETCH_INTO is used as a fetch mode in PDOStatement::fetchAll, similar to
PDO::FETCH_LAZY.
PDO_FIREBIRD
A ValueError is now thrown when trying to set a cursor name that is too long on a
PDOStatement resulting from the Firebird driver.
PDO_SQLITE
SQLite PDO::quote will now throw an exception or emit a warning, depending on the error mode, if the string contains a null byte.
PDO::sqliteCreateCollation will now throw an exception if the callback has the wrong return type, making it more in line with Pdo\Sqlite::createCollation behavior.
POSIX
posix_kill now throws a ValueError when the process_id argument is lower or greater than what the platform supports (signed integer or long range),
posix_setpgid now throws a ValueError when the process_id or the process_group_id is lower than zero or greater than what the platform supports.
posix_setrlimit now throws a ValueError when the hard_limit or soft_limit arguments are lower than -1 or if soft_limit is greater than hard_limit.
Reflection
ReflectionAttribute::newInstance can now throw errors for internal attributes if the attribute was applied on an invalid target and the error was delayed from compile time to runtime via the #[\DelayedTargetValidation] attribute.
Session
Attempting to write session data where
$_SESSION has a key containing the pipe character (
|) will now emit a warning instead of silently failing.
session_start is stricter in regard to the options argument. It now throws a ValueError if the array is not a hashmap, or a TypeError if the read_and_close value is not a valid type compatible with int.
SimpleXML
Passing an XPath expression that returns something other than a node set to SimpleXMLElement::xpath will now emit a warning and return ENTITY, instead of silently failing and returning an empty array.
SNMP
snmpget,
snmpset,
snmp2_get,
snmp2_set,
snmp3_get,
snmp3_set and SNMP::__construct now throw a ValueError when the hostname is too large, contains any null byte or if the port is given when negative or greater than 65535, timeout and retries values are lower than -1 or too large.
SOAP
SoapClient::__doRequest now accepts a new, optional
uriParserClass parameter accepting string or ENTITY arguments. ENTITY represents the original (
parse_url) based method, while the new backends will be used when passing either
Uri\Rfc3986\Uri or
Uri\WhatWg\Url.
Sockets
socket_create_listen,
socket_bind and
socket_sendto now throw a ValueError if the port is lower than 0 or greater than 65535, and also if any of the hints array entries are indexed numerically.
socket_addrinfo_lookup now throws a TypeError if any of the hints values cannot be cast to int and can throw a ValueError if any of these values overflow.
socket_set_option with
MCAST_LEAVE_GROUP/
MCAST_LEAVE_SOURCE_GROUP options now throw an exception if the value isn't a valid object or array.
socket_set_option with multicast context now throws a ValueError when the created socket is not of
AF_INET/
AF_INET6 family.
SPL
ArrayObject no longer accepts enums, as modifying the $name or $value properties can break engine assumptions.
SplFileObject::fwrite's parameter
length is now nullable. The default value changed from
0 to ENTITY.
Standard
Using a printf-family function with a formatter that did not specify the precision previously incorrectly reset the precision instead of treating it as a precision of 0.
Passing an integer
0 as the
locales argument to
setlocale is no longer supported and now throws a TypeError.
Tidy
tidy::__construct, tidy::parseFile, tidy::parseString now throws a ValueError if the configuration contains an invalid value or attempts to set a read-only internal entry, and a TypeError if a configuration key is not a string.
New Classes and Interfaces
Core
NoDiscard
DelayedTargetValidation
Curl
CurlSharePersistentHandle
Filter
Filter\FilterException
Filter\FilterFailedException
Intl
IntlListFormatter
URI
Uri\UriException
Uri\InvalidUriException
Uri\UriComparisonMode
Uri\Rfc3986\Uri
Uri\WhatWg\InvalidUrlException
Uri\WhatWg\UrlValidationErrorType
Uri\WhatWg\UrlValidationError
Uri\WhatWg\Url
New Features
PHP Core
Pipe Operator
Added the pipe (
|ENTITY) operator.
strlen(...);
print $result . PHP_EOL; // Prints "11"
Closure in constant expressions
Added support for Closures and first class callables in constant expressions. This includes: Attribute parameters., Default values of properties and parameters., Constants and Class Constants.
#[\NoDiscard] attribute
Added the
NoDiscard attribute to indicate that a function's return value is important and should be consumed.
Also, added the
(void) cast to indicate that not using a value is intentional. The
(void) cast has no effect on the program's execution by itself, but it can be used to suppress warnings emitted by
#[\NoDiscard] and possibly also diagnostics emitted by external IDEs or static analysis tools.
= 8.7.0),
CURLINFO_HTTPAUTH_USED, and
CURLINFO_PROXYAUTH_USED (libcurl >= 8.12.0) to the
curl_getinfo function. When
curl_getinfo returns an array, the same information is available as
"used_proxy",
"httpauth_used", and
"proxyauth_used" keys.
CURLINFO_USED_PROXY gets zero set if no proxy was used in the previous transfer or a non-zero value if a proxy was used.
CURLINFO_HTTPAUTH_USED and
CURLINFO_PROXYAUTH_USED get bitmasks indicating the HTTP and proxy authentication methods that were used in the previous request. See
CURLAUTH_* constants for possible values.
Added
CURLOPT_INFILESIZE_LARGE Curl option, which is a safe replacement for
CURLOPT_INFILESIZE. On certain systems,
CURLOPT_INFILESIZE only accepts a 32-bit signed integer as the file size (2.0 GiB) even on 64-bit systems.
CURLOPT_INFILESIZE_LARGE accepts the largest integer value the system can handle.
Added
CURLFOLLOW_OBEYCODE,
CURLFOLLOW_FIRSTONLY and
CURLFOLLOW_ALL values for
CURLOPT_FOLLOWLOCATION
curl_setopt option.
CURLFOLLOW_OBEYCODE to follow more strictly in regard to redirect if they are allowed.
CURLFOLLOW_FIRSTONLY to follow only the first redirect thus if there is any follow up redirect, it won't go any further.
CURLFOLLOW_ALL is equivalent to setting
CURLOPT_FOLLOWLOCATION to true.
Added support for
CURLINFO_CONN_ID (libcurl >= 8.2.0) to the
curl_getinfo function. This constant allows retrieving the unique ID of the connection used by a cURL transfer. It is primarily useful when connection reuse or connection pooling logic is needed in PHP-level applications. When
curl_getinfo returns an array, this value is available as the
"conn_id" key.
Added support for
CURLINFO_QUEUE_TIME_T (libcurl >= 8.6.0) to the
curl_getinfo function. This constant allows retrieving the time (in microseconds) that the request spent in libcurl’s connection queue before it was sent. This value can also be retrieved by passing
CURLINFO_QUEUE_TIME_T to the
curl_getinfo
option parameter.
Added support for
CURLOPT_SSL_SIGNATURE_ALGORITHMS to specify the signature algorithms to use for TLS.
DOM
Added Dom\Element::$outerHTML.
Added $children property to Dom\ParentNode implementations.
EXIF
Added support for
OffsetTime* Exif tags.
Added support for HEIF/HEIC.
Filter
Added new
FILTER_THROW_ON_FAILURE flag which can be passed to the filter functions and will force an exception to be triggered when validation fails. The new flag cannot be combined with
FILTER_NULL_ON_FAILURE; trying to do so will result in a ValueError being thrown.
Intl
Added class constants
NumberFormatter::CURRENCY_ISO,
NumberFormatter::CURRENCY_PLURAL,
NumberFormatter::CASH_CURRENCY, and
NumberFormatter::CURRENCY_STANDARD for various currency-related number formats.
Added Locale::addLikelySubtags and Locale::minimizeSubtags to handle likely tags on a given locale.
Added
IntlListFormatter class to format, order, and punctuate a list of items with a given locale,
IntlListFormatter::TYPE_AND,
IntlListFormatter::TYPE_OR,
IntlListFormatter::TYPE_UNITS operands and
IntlListFormatter::WIDTH_WIDE,
IntlListFormatter::WIDTH_SHORT and
IntlListFormatter::WIDTH_NARROW widths. It is supported from icu 67.
PDO_Sqlite
Added class constant
Pdo\Sqlite::ATTR_BUSY_STATEMENT.
Added class constants
Pdo\Sqlite::ATTR_EXPLAIN_STATEMENT,
Pdo\Sqlite::EXPLAIN_MODE_PREPARED,
Pdo\Sqlite::EXPLAIN_MODE_EXPLAIN,
Pdo\Sqlite::EXPLAIN_MODE_EXPLAIN_QUERY_PLAN.
Added
Pdo\Sqlite::ATTR_TRANSACTION_MODE connection attribute with possible values
Pdo\Sqlite::TRANSACTION_MODE_DEFERRED,
Pdo\Sqlite::TRANSACTION_MODE_IMMEDIATE, and
Pdo\Sqlite::TRANSACTION_MODE_EXCLUSIVE, allowing to configure the transaction mode to use when calling beginTransaction().
Session
session_set_cookie_params,
session_get_cookie_params, and
session_start now support partitioned cookies via the
"partitioned" key.
SOAP
Enumeration cases are now dumped in SoapClient::__getTypes.
Added support for Soap 1.2 Reason Text xml:lang attribute.
The signature of SoapFault::__construct and SoapServer::fault therefore now have an optional
lang parameter. This support solves compatibility with .NET SOAP clients.
Standard
mail now returns the actual sendmail error and detects if the sendmail process was terminated unexpectedly. In such cases, a warning is emitted and the function returns false. Previously, these errors were silently ignored. This change affects only the sendmail transport.
getimagesize now supports HEIF/HEIC images.
getimagesize now supports SVG images when ext-libxml is also loaded. Similarly,
image_type_to_extension and
image_type_to_mime_type now also handle IMAGETYPE_SVG.
The array returned by
getimagesize now has two additional entries:
"width_unit" and
"height_unit" to indicate in which units the dimensions are expressed. These units are px by default. They are not necessarily the same (just to give one example: one may be cm and the other may be px).
setcookie and
setrawcookie now support the
"partitioned" key.
URI
An always enabled uri extension is added that can be used for handling URIs and URLs according to RFC 3986 and WHATWG URL.
XSL
The
namespace argument of XSLTProcessor::getParameter, XSLTProcessor::setParameter and XSLTProcessor::removeParameter now actually works instead of being treated as empty. This only works if the
name argument does not use Clark notation and is not a QName because in those cases the namespace is taken from the namespace href or prefix respectively.
Zlib
flock is now supported on zlib streams. Previously, this always failed to perform any locking action.
New Functions
Core
get_error_handler
get_exception_handler
Closure::getCurrent
Curl
curl_multi_get_handles
curl_share_init_persistent
DOM
Dom\Element::getElementsByClassName
Dom\Element::insertAdjacentHTML
Enchant
enchant_dict_remove_from_session
enchant_dict_remove
Intl
Locale::isRightToLeft
locale_is_right_to_left
grapheme_levenshtein
Opcache
opcache_is_script_cached_in_file_cache
PDO_SQLITE
Pdo\Sqlite::setAuthorizer
PGSQL
pg_close_stmt
Reflection
ReflectionConstant::getFileName
ReflectionConstant::getExtension
ReflectionConstant::getExtensionName
ReflectionConstant::getAttributes
ReflectionProperty::getMangledName
Sqlite
Sqlite3Stmt::busy
Standard
array_first
array_last
Other Changes
Core changes
Core
The high resolution timer (
hrtime) on macOS now uses the recommended
clock_gettime_nsec_np(CLOCK_UPTIME_RAW) API instead of
mach_absolute_time().
CGI/CLI
The
-z or
--zend-extension option has been removed as it was non-functional. Use
-d zend_extension=[path] instead.
PDO_ODBC
The fetch behaviour for larger columns has been changed. Rather than fetching 256 byte blocks, PDO_ODBC will try to fetch a larger block size; currently, this is the page size minus string overhead. Drivers that return SQL_NO_TOTAL in SQLGetData are also better handled as well. This should improve compatibility and performance.
Changes in SAPI Modules
CLI
Trying to set a process title that is too long with
cli_set_process_title will now fail instead of silently truncating the given title.
Added a new
--ini=diff option to print INI settings changed from the builtin default.
FPM
FPM with httpd ProxyPass optionally decodes the full script path. Added fastcgi.script_path_encoded INI setting to prevent this new behavior.
FPM access log limit now respects log_limit value.
Changed Functions
Intl
grapheme_extract properly assigns
next value when skipping over invalid starting bytes. Previously there were cases where it would point to the start of the grapheme boundary instead of the end.
transliterator_get_error_code,
transliterator_get_error_message, TransLiterator::getErrorCode, and TransLiterator::getErrorMessage have dropped ENTITY from the return type union. Returning ENTITY was actually never possible.
The following functions now support a
locale argument:
grapheme_strpos,
grapheme_stripos,
grapheme_strrpos,
grapheme_strripos,
grapheme_substr,
grapheme_strstr and
grapheme_stristr
LDAP
ldap_get_option now accepts a ENTITY connection, like
ldap_set_option, to allow retrieval of global options.
libxml
libxml_set_external_entity_loader now has a formal return type of
true.
OpenSSL
openssl_public_encrypt and
openssl_private_decrypt have a new parameter
digest_algo that allows specifying the hash digest algorithm for OAEP padding.
openssl_sign and
openssl_verify have a new parameter
padding to allow using more secure RSA PSS padding.
openssl_cms_encrypt
cipher_algo parameter can be a string with the cipher name. That allows to use more algorithms including AES GCM cipher algorithms for auth enveloped data.
PCNTL
pcntl_exec now has a formal return type of
false.
pcntl_waitid takes an additional resource_usage argument to gather various platform specific metrics about the child process.
PDO_PGSQL
Pdo\Pgsql::copyFromArray now supports
iterable inputs.
Pdo\Pgsql::setAttribute and Pdo\Pgsql::prepare support setting
PDO::ATTR_PREFETCH to 0 which enters lazy fetch mode. In this mode, statements cannot be run in parallel.
PostgreSQL
pg_copy_from now supports
iterable inputs.
pg_connect checks if the connection_string argument contains any null byte.
pg_close_stmt checks if the statement_name argument contains any null byte.
POSIX
posix_ttyname sets last_error to EBADF when encountering an invalid file descriptor.
posix_isatty raises an
E_WARNING message when encountering an invalid file descriptor.
posix_fpathconf checks invalid file descriptors and sets last_error to EBADF and raises an
E_WARNING message.
Reflection
The output of ReflectionClass::__toString for enums has changed to better indicate that the class is an enum, and that the enum cases are enum cases rather than normal class constants.
The output of ReflectionProperty::__toString for properties with hooks has changed to indicate what hooks the property has, whether those hooks are final, and whether the property is virtual. This also affects the output of ReflectionClass::__toString when a class contains hooked properties.
Sockets
socket_create/
socket_bind can create
AF_PACKET family sockets.
socket_getsockname gets the interface index and its string representation with
AF_PACKET socket.
Zlib
The
use_include_path argument for the
gzfile,
gzopen and
readgzfile functions has been changed from
int to
bool.
gzfile,
gzopen and
readgzfile functions now respect the default stream context.
Other Changes to Extensions
cURL
curl_setopt with
CURLOPT_FOLLOWLOCATION option's value no longer is treated as boolean but integer to handle
CURLFOLLOW_OBEYCODE and
CURLFOLLOW_FIRSTONLY.
Fileinfo
Upgraded file from 5.45 to 5.46.
The return type of
finfo_close has been changed to
true, rather than
bool.
Intl
Intl's internal error mechanism has been modernized so that it indicates more accurately which call site caused what error. Moreover, some ext/date exceptions have been wrapped inside a
IntlException now.
Lexbor
An always enabled lexbor extension is added. It contains the lexbor library that was separated from ext/dom for being reused among other extensions. The new extension is not directly exposed to userland.
PCRE
Upgraded pcre2lib from 10.44 to 10.46.
PDO_Sqlite
Increased minimum release version support from 3.7.7 to 3.7.17.
Readline
The return types of
readline_add_history,
readline_clear_history, and
readline_callback_handler_install have been changed to
true, rather than
bool.
Reflection
ReflectionConstant is no longer final.
Changes to INI File Handling
Core
Added fatal_error_backtraces to control whether fatal errors should include a backtrace.
Added startup-only max_memory_limit INI setting to control the maximum memory_limit that may be configured at startup or runtime. Exceeding this value emits a warning, unless set to -1, and sets memory_limit to the current max_memory_limit instead.
Opcache
Added opcache.file_cache_read_only to support a read-only opcache.file_cache directory, for use with read-only file systems (e.g. read-only Docker containers). Best used with
opcache.validate_timestamps=0,
opcache.enable_file_override=1, and
opcache.file_cache_consistency_checks=0.
[!NOTE]
A cache generated with a different build of PHP, a different file path, or different settings (including which extensions are loaded), may be ignored.
The default value of opcache.jit_hot_loop is now 61 (a prime) to prevent it from being a multiple of loop iteration counts. It is recommended that this parameter is set to a prime number.
Changing opcache.memory_consumption when OPcache SHM is already set up will now correctly report a failure instead of silently doing nothing and showing misleading values in PHPInfo.
OpenSSL
Added openssl.libctx to select the OpenSSL library context type. Either custom libctx for each thread can be used or a single global (default) libctx is used.
Performance
Core
Remove OPcodes for identity comparisons against booleans, particularly for the
match(true) pattern.
Add OPcode specialization for
=== [] and
!== [] comparisons.
Creating exception objects is now much faster.
The parts of the code that used SSE2 have been adapted to use SIMD with ARM NEON as well.
Introduced the TAILCALL VM, enabled by default when compiling with Clang>=19 on x86_64 or aarch64. The TAILCALL VM is as fast as the HYBRID VM used when compiling with GCC. This makes PHP binaries built with Clang>=19 as fast as binaries built with GCC. The performance of the CALL VM, used with other compilers, has also improved considerably.
Intl
Now avoids creating extra string copies when converting strings for use in the collator.
MBString
The parts of the code that used SSE2 have been adapted to use SIMD with ARM NEON as well.
Opcache
Improved performance of fetching TLS variables in JIT'ed code in non-Glibc builds.
Reflection
Improved performance of the following methods: ReflectionProperty::getValue, ReflectionProperty::getRawValue, ReflectionProperty::isInitialized, ReflectionProperty::isInitialized, ReflectionProperty::setValue, ReflectionProperty::setRawValue
SPL
Improved performance of dimension accessors and methods of
SplFixedArray.
Standard
Improved performance of array functions with callbacks (
array_find,
array_filter,
array_map,
usort, ...).
Improved performance of
urlencode and
rawurlencode.
Improved
unpack performance with nameless repetitions by avoiding creating temporary strings and reparsing them.
Improved
pack performance.
Minor improvements in
array_chunk performance.
XML
Improved
XMLReader property access performance.
Improved
XMLWriter performance and reduced memory consumption.
Windows Support
Core
The configuration variables
PHP_VERSION,
PHP_MINOR_VERSION, and
PHP_RELEASE_VERSION are now always numbers. Previously, they have been strings for buildconf builds.
phpize builds now reflect the source tree in the build dir (as it already worked for in-tree builds); some extension builds (especially when using Makefile.frag.w32) may need adjustments.
--enable-sanitizer is now supported for MSVC builds. This enables ASan and debug assertions, and is supported as of MSVC 16.10 and Windows 10.
The
--with-uncritical-warn-choke configuration option for clang builds is no longer supported. Select warnings to suppress via CFLAGS instead.
COM
The extension is now build shared by default; previously it defaulted to a static extension, although the official Windows binaries built a shared extension.
FFI
It is no longer necessary to specify the library when using FFI::cdef and FFI::load. However, this convenience feature should not be used in production.
Streams
If only pipe streams are contained in the
read array, and the
write and
except arrays are empty,
stream_select now behaves similar to POSIX systems, i.e. the function only returns if at least one pipe is ready to be read, or after the timeout expires. Previously,
stream_select returned immediately, reporting all streams as ready to read.
Migrating from PHP 8.5.x to PHP 8.6.x
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.
ENTITY 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x, 8.2.x, 8.3.x, 8.4.x, 8.5.x.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
New Global Constants
Core
ARRAY_FILTER_USE_VALUE
STREAM_CRYPTO_STATUS_NONE
STREAM_CRYPTO_STATUS_WANT_READ
STREAM_CRYPTO_STATUS_WANT_WRITE
cURL
CURLINFO_SIZE_DELIVERED
(libcurl >= 8.20.0)
CURLOPT_SEEKFUNCTION
CURL_SEEKFUNC_OK
CURL_SEEKFUNC_FAIL
CURL_SEEKFUNC_CANTSEEK
CURL_READFUNC_ABORT
MySQLi
MYSQLI_OPT_COMPRESS
OpenSSL
OPENSSL_RSA_PSS_SALTLEN_DIGEST
OPENSSL_RSA_PSS_SALTLEN_AUTO
OPENSSL_RSA_PSS_SALTLEN_MAX
Sockets
TCP_USER_TIMEOUT
(Linux only)
AF_UNSPEC
EAI_BADFLAGS
EAI_NONAME
EAI_AGAIN
EAI_FAIL
EAI_NODATA
EAI_FAMILY
EAI_SOCKTYPE
EAI_SERVICE
EAI_ADDRFAMILY
EAI_SYSTEM
EAI_OVERFLOW
EAI_INPROGRESS
EAI_CANCELED
EAI_NOTCANCELED
EAI_ALLDONE
EAI_INTR
EAI_IDN_ENCODE
SO_DETACH_REUSEPORT_BPF
(Linux only)
Sodium
SODIUM_CRYPTO_IPCRYPT_BYTES
SODIUM_CRYPTO_IPCRYPT_KEYBYTES
SODIUM_CRYPTO_IPCRYPT_ND_KEYBYTES
SODIUM_CRYPTO_IPCRYPT_ND_TWEAKBYTES
SODIUM_CRYPTO_IPCRYPT_ND_INPUTBYTES
SODIUM_CRYPTO_IPCRYPT_ND_OUTPUTBYTES
SODIUM_CRYPTO_IPCRYPT_NDX_KEYBYTES
SODIUM_CRYPTO_IPCRYPT_NDX_TWEAKBYTES
SODIUM_CRYPTO_IPCRYPT_NDX_INPUTBYTES
SODIUM_CRYPTO_IPCRYPT_NDX_OUTPUTBYTES
SODIUM_CRYPTO_IPCRYPT_PFX_KEYBYTES
SODIUM_CRYPTO_IPCRYPT_PFX_BYTES
SODIUM_CRYPTO_KEM_PUBLICKEYBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_SECRETKEYBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_CIPHERTEXTBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_SHAREDSECRETBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_SEEDBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_KEYPAIRBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_MLKEM768_PUBLICKEYBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_MLKEM768_SECRETKEYBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_MLKEM768_CIPHERTEXTBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_MLKEM768_SHAREDSECRETBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_MLKEM768_SEEDBYTES
(libsodium >= 1.0.22)
SODIUM_CRYPTO_KEM_MLKEM768_KEYPAIRBYTES
(libsodium >= 1.0.22)
Deprecated Features
PHP Core
Using "namespace" as a class constant name
Declaring a class constant named
namespace is now deprecated.
namespace is a semi-reserved keyword, and the name is being reserved for possible future syntax such as a
::namespace pseudo-constant analogous to
::class. Methods and static properties named
namespace are not affected. Rename the constant, for example to
NAMESPACE_NAME.
Returning from a finally block
Using the
return statement inside a ENTITY block is now deprecated, and emits a compile-time deprecation notice. Such a
return silently discards an exception thrown by, or overwrites the value returned from, the associated
try or
catch block, so failures vanish without a trace. Move the
return out of the
finally block instead; the same result can always be expressed without it.
is_float,
is_long =>
is_int,
is_integer =>
is_int,
doubleval =>
floatval
strcoll() and SORT_LOCALE_STRING
The
strcoll function is now deprecated. It compares strings according to the
LC_COLLATE setting of the current locale, which is global process state set via
setlocale that any library can change, it is not binary safe unlike every other string comparison function, and some locales do not implement correct collation rules. Use Collator::compare from the intl extension instead, which is accurate and has up-to-date collation rules.
The
SORT_LOCALE_STRING flag of the sort functions is now deprecated for the same reasons, as it sorts using
strcoll. Use one of the following methods of the
Collator class instead: Collator::sort, Collator::asort, Collator::sortWithSortKeys
Bzip2
Passing an object as the parameters of the bzip2.compress and bzip2.decompress stream filters is now deprecated, as only an associative array is documented and supported. Call
get_object_vars on the object first and pass the resulting array.
GMP
The shift (
ENTITYENTITY,
ENTITYENTITY) and exponentiation (
**) operators on
GMP objects now emit a deprecation notice when the right operand is a
float whose conversion to
int loses precision, consistent with the deprecation of implicit lossy float to int conversions elsewhere in the language.
MBString
The mbregex functions have been deprecated, because the underlying Oniguruma library is no longer maintained; its maintenance ended in April 2025. The functions will be removed in PHP 9.0. For most use cases the PCRE functions with the
u modifier are a suitable replacement. The affected functions are:
mb_ereg,
mb_ereg_match,
mb_ereg_replace,
mb_ereg_replace_callback,
mb_ereg_search,
mb_ereg_search_getpos,
mb_ereg_search_getregs,
mb_ereg_search_init,
mb_ereg_search_pos,
mb_ereg_search_regs,
mb_ereg_search_setpos,
mb_eregi,
mb_eregi_replace,
mb_regex_encoding,
mb_regex_set_options,
mb_split
The
MB_ONIGURUMA_VERSION constant and the mbstring.regex_retry_limit and mbstring.regex_stack_limit INI directives are deprecated along with them.
Passing an object as the
vars argument to
mb_convert_variables is now deprecated, as objects are silently interpreted as the array of their visible properties. Call
get_object_vars on the object first, or use
mb_convert_encoding, which converts arrays recursively and returns the result instead of modifying its argument in place.
MySQLi
The
mysqli_get_charset function and the mysqli::get_charset method are now deprecated, without replacement. They expose internal implementation details of the character set that have been meaningless since the switch to mysqlnd; in particular the reported collation does not correspond to the collation defined by the server. To get the name of the current character set, use
mysqli_character_set_name or mysqli::character_set_name.
The
mysqli_stmt_init function and the mysqli::stmt_init method are now deprecated. They create an empty statement object that still has to be prepared before use, and are a source of statement objects left in an inconsistent state. Use
mysqli_prepare or mysqli::prepare instead, which prepare the statement in one step. For the same reason, calling the mysqli_stmt::__construct constructor without the
query parameter is now deprecated; pass the query to the constructor instead.
Reflection
Calling ReflectionProperty::setValue or ReflectionProperty::setRawValue with an object that is not an instance of the class on which the property was declared is now deprecated. Unlike the other
ReflectionProperty methods, which throw for such objects, these methods silently set a property on the unrelated object, which is no better than a normal assignment and conceptually wrong.
Passing an object to ReflectionMethod::invoke or ReflectionMethod::invokeArgs when invoking a static method is now deprecated. Static methods have no
$this, so the object was ignored entirely and never validated. Pass ENTITY instead.
Session
Passing an object that does not implement both the SessionIdInterface::create_sid and SessionUpdateTimestampHandlerInterface::validateId methods to
session_set_save_handler is now deprecated, regardless of which interfaces the object declares. These methods are required for a save handler to behave correctly under session.use_strict_mode, which is enabled by default as of PHP 8.6 and mitigates session fixation.
Accordingly, a deprecation notice is now emitted when a class implements SessionHandlerInterface without defining the SessionIdInterface::create_sid or SessionUpdateTimestampHandlerInterface::validateId methods. In PHP 9.0 these methods will be moved from SessionIdInterface and SessionUpdateTimestampHandlerInterface into SessionHandlerInterface, where they will be required. Implement both methods on custom save handlers now.
SPL
The
spl_classes function is now deprecated. No other extension exposes such a function, and the Reflection extension is always available. Use ReflectionExtension::getClassNames instead.
The
spl_object_hash function is now deprecated. Since PHP 8.1 its return value has been nothing more than a reformatted
spl_object_id, and the name is misleading as the value is not derived from the contents of the object. The string form is also error-prone: two hashes can compare loosely equal because both are numeric strings. Use
spl_object_id instead.
The following
ArrayIterator methods are now deprecated. They only exist because
ArrayIterator historically shared its implementation with
ArrayObject; most of them make little sense on an iterator and prevent optimizing its implementation. The corresponding
ArrayObject methods are not deprecated. ArrayIterator::getFlags, ArrayIterator::setFlags, ArrayIterator::asort, ArrayIterator::ksort, ArrayIterator::uasort, ArrayIterator::uksort, ArrayIterator::natsort, ArrayIterator::natcasesort, ArrayIterator::unserialize, ArrayIterator::serialize
The CSV methods of
SplFileObject are now deprecated. Their historical design inconsistencies, further exposed by named arguments, have made them increasingly difficult to maintain, and CSV handling does not naturally belong in
SplFileObject. Use
fgetcsv and
fputcsv on a stream instead. SplFileObject::fgetcsv, SplFileObject::fputcsv, SplFileObject::setCsvControl, SplFileObject::getCsvControl
Zlib
Passing an object as the parameters of the zlib.deflate and zlib.inflate stream filters is now deprecated, as only an associative array is documented and supported. Call
get_object_vars on the object first and pass the resulting array.
Passing an object as the
options argument to
deflate_init or
inflate_init is now deprecated, as objects are silently interpreted as the array of their visible properties. Call
get_object_vars on the object first and pass the resulting array.
Backward Incompatible Changes
PHP Core
By-reference foreach after array compaction
By-reference foreach loops may now visit previously skipped elements after array compaction. Internal pointers on deleted elements now move to the next surviving element during copy-on-write.
Null coalescing and
empty on magic properties
?? and
empty on a magic property no longer call __get() when __isset() has materialized the property by writing into the property table. The freshly-written value is returned directly.
isset applied directly to the property is unaffected; nested forms such as
isset($o-ENTITYp['k']) follow the same path as
??.
$name = 'from __isset()';
return true;
}
public function __get(string $name): string
{
return 'from __get()';
}
}
$example = new Example();
var_dump($example->foo ?? 'default');
// As of PHP 8.6.0: string(14) "from __isset()"
// Prior to PHP 8.6.0: string(12) "from __get()"
String conversion in
array_intersect
array_intersect with at least two arrays now converts values to strings while scanning its inputs instead of during sort comparisons. This can change the number and order of conversion warnings and __toString() calls, which conversion exception is reached, and the result for stateful __toString() implementations. Argument types are validated before checking for empty arrays or converting values, so an invalid later argument can suppress conversion side effects from earlier arrays. Values are not converted if any input array is empty.
Form feed trimmed by default
Form feed (
\f) is now added to the default trimmed characters of
trim,
rtrim and
ltrim.
1]
// Prior to PHP 8.6.0: [" 1]
COM
It is no longer possible to clone
variant objects, because the cloning behavior was ill-defined.
cURL
The callback registered with
CURLOPT_READFUNCTION now throws a ValueError when returning an integer other than
0,
CURL_READFUNC_ABORT or
CURL_READFUNC_PAUSE.
DOM
Properties previously documented as read-only (e.g. DOMNode::$nodeType, DOMDocument::$xmlEncoding, DOMEntity::$actualEncoding, DOMEntity::$encoding, DOMEntity::$version) are now declared with asymmetric visibility (
public private(set)). Attempts to write to them from outside the class now raise “Cannot modify private(set) property ::$ from global scope” instead of the prior readonly modification error. ReflectionProperty::isWritable also reports these properties accurately.
Array access on
Dom\DtdNamedNodeMap objects now returns ENTITY for negative integer indexes instead of returning the first node, and raises a ValueError when the integer index is greater than
PHP_INT_MAX instead of overflowing to a smaller index.
FTP
ftp_nb_fget,
ftp_nb_fput,
ftp_nb_get and
ftp_nb_put now throw an Error when the connection is already transferring, instead of emitting a warning and returning ENTITY.
ftp_close already throws on the same condition.
GD
imagesetstyle,
imagefilter and
imagecrop filter the types and values of their array arguments and raise a TypeError or ValueError accordingly.
imageaffinematrixget now enforces the documented
arrayfloat type for the
options parameter, including the corresponding weak and strict typing behavior.
GMP
gmp_fact now throws a ValueError if
num does not fit into an unsigned long.
gmp_pow,
gmp_binomial,
gmp_root and
gmp_rootrem now throw a ValueError if their second argument does not fit into an unsigned long.
The shift (
ENTITYENTITY,
ENTITYENTITY) and exponentiation (
**) operators on
GMP objects now throw a ValueError when
GMP right operands are outside the unsigned long range, instead of silently truncating them.
GMP integer string parsing now throws a ValueError for strings containing
NUL bytes, instead of silently truncating them.
The message of the DivisionByZeroError raised by
gmp_powm on modulo by zero now includes the function name and argument index (
modulus).
Intl
Passing a non-stringable object as a time zone to Intl APIs that accept time zone objects or strings now raises a TypeError instead of an Error.
IntlIterator::current now returns ENTITY when called before the iterator is positioned, or after the iterator becomes invalid, instead of exposing an undefined value.
IntlBreakIterator::getLocale now raises a ValueError when the type is neither
Locale::ACTUAL_LOCALE nor
Locale::VALID_LOCALE instead of returning ENTITY.
MessageFormatter::parse and MessageFormatter::parseMessage now return
PHP_INT_MIN as
int, rather than
float, on 64-bit platforms when parsing integer values.
The
type parameter of IntlBreakIterator::getPartsIterator has been changed from
string to
int to match the underlying implementation.
UConverter::transcode now rejects
from_subst and
to_subst option values longer than 127 bytes instead of silently truncating the length before passing it to ICU.
ResourceBundle::get and
resourcebundle_get now report fallback-disabled resource lookups with “without fallback to ” instead of the malformed “without fallback from to ”.
IntlDateFormatter::parse/
datefmt_parse and IntlDateFormatter::localtime/
datefmt_localtime now raise a TypeError when the
offset argument is not of type
int instead of silently converting the value.
Collator::sort,
collator_sort, Collator::asort, and
collator_asort now report UTF-8/UTF-16 conversion failures during comparison through the intl error mechanism and return ENTITY. With intl.use_exceptions enabled, these failures throw an IntlException. Previously, these paths emitted a warning and compared the value as an empty string.
MBString
Unicode data tables have been updated to Unicode 18.0.
PCNTL
pcntl_alarm now raises a ValueError if the
seconds argument is lower than zero or greater than the platform's
UINT_MAX.
pcntl_exec now raises a ValueError if the
args argument is not a list array.
PCRE
preg_grep now returns ENTITY instead of a partial array when a PCRE execution error occurs (e.g. malformed UTF-8 input with the
u modifier). This is consistent with the other
preg_* functions.
PGSQL
When
pg_fetch_object is given a non-empty
constructor_args for a class without a constructor, the ValueError now refers to the
constructor_args argument instead of
class. Errors raised when the requested class is not instantiable (abstract, interface, enum) now surface before the row is fetched.
Phar
Phar::mungServer now raises a ValueError when an invalid argument value is passed instead of being silently ignored.
Phar::addEmptyDir now rejects
"/.phar" paths in addition to
".phar" paths, and raises the same BadMethodCallException for attempts to create the reserved magic
".phar" directory through that form. Non-magic names that merely share the
".phar" prefix are now treated as ordinary directories.
Files are only automatically interpreted as Phar archives when included if
".phar" occurs as an extension in the filename component of their paths. Previously, it could occur in a directory name or as part of an extension such as
".pharma".
Session
Setting session.cookie_path, session.cookie_domain, or session.cache_limiter to a value containing
NUL bytes now emits a warning and leaves the setting unchanged. Previously,
NUL bytes were silently accepted: for
cookie_path and
cookie_domain this caused the SAPI to drop the
Set-Cookie header; for
cache_limiter the value was silently truncated at the
NUL byte.
session_module_name now throws a ValueError if
name is a string containing
NUL bytes.
session_encode now returns an empty string instead of ENTITY for empty sessions. It only returns ENTITY now when the session data could not be encoded. This mainly happens with the default serialization handler if a key contains the pipe (
|) character.
When session.lazy_write is enabled and a session handler implements SessionUpdateTimestampHandlerInterface, sessions that were read as empty and remain empty at write time will now trigger SessionUpdateTimestampHandlerInterface::updateTimestamp instead of SessionHandlerInterface::write. Previously, SessionHandlerInterface::write was always called for empty sessions because
session_encode returned ENTITY, bypassing the lazy_write comparison. Custom session handlers that rely on SessionHandlerInterface::write being called with empty data (e.g. to destroy the session) should implement the same logic in their SessionUpdateTimestampHandlerInterface::updateTimestamp method.
The defaults of three session INI settings have changed to provide secure behavior out of the box: session.use_strict_mode is now
1 (was
0). Strict mode rejects uninitialized session IDs, mitigating session fixation. Custom session handlers that previously relied on accepting externally supplied IDs without a corresponding storage entry must either implement SessionUpdateTimestampHandlerInterface::validateId and SessionIdInterface::create_sid, or explicitly set this to
0., session.cookie_httponly is now
1 (was
0). Session cookies are no longer accessible to JavaScript via
document.cookie. Applications that read the session cookie from JavaScript must explicitly set this to
0., session.cookie_samesite is now
"Lax" (was unset). Session cookies are no longer sent on cross-site requests other than top-level navigations using safe HTTP methods. Applications that depend on session cookies being sent on cross-site POST submissions must explicitly set this to
"None" (and also set session.cookie_secure to
1).
SessionHandler::validateId has been added and delegates to the configured save handler. A subclass that declares SessionHandler::validateId without a return type now emits a deprecation notice for the tentative
bool return type. A subclass that overrides SessionHandler::open without calling
parent::open() keeps its previous behavior and emits a warning when an ID is validated.
Shmop
shmop_open now raises a ValueError when the
key argument is outside the platform's
key_t range instead of passing a truncated key to the operating system.
SimpleXML
SimpleXMLElement::__construct now raises a ValueError when the
data argument contains
NUL bytes, matching
simplexml_load_file. With
dataIsURL set, it previously truncated the path at the first
NUL byte. Without it, the string went to libxml, which with default options rejects a
NUL on current versions but accepts the truncated document on older ones and under
LIBXML_RECOVER.
SOAP
The
"classmap" option of
SoapClient and
SoapServer now rejects arrays containing integer keys. Previously, sparse integer-keyed and mixed-keyed arrays could be accepted.
SoapClient now throws a TypeError for non-array
"classmap" options and a ValueError for arrays containing integer keys, also when the
"exceptions" option is disabled.
WSDL/XML Schema parsing now rejects out-of-range integer values for occurrence constraints and integer restriction facets. Negative
minOccurs and
maxOccurs values are rejected as well.
SOAP encoding errors now report the affected type or failing operation in the error message instead of the generic “Encoding: Violation of encoding rules” message. Code that compares the exact message may need to be updated.
Sockets
socket_set_option with
SO_ATTACH_REUSEPORT_CBPF now requires an
int
value and a
level of
SOL_SOCKET. Any other value type throws a TypeError instead of being coerced, and any other level raises a warning and returns ENTITY.
socket_set_option with
SO_ATTACH_REUSEPORT_CBPF and a
value of
0 now detaches the reuseport filter through
SO_DETACH_REUSEPORT_BPF. It previously used
SO_DETACH_BPF, an alias of
SO_DETACH_FILTER, which left the reuseport program attached.
Sodium
The password-hashing functions
sodium_crypto_pwhash,
sodium_crypto_pwhash_str,
sodium_crypto_pwhash_scryptsalsa208sha256 and
sodium_crypto_pwhash_scryptsalsa208sha256_str now throw a ValueError instead of a SodiumException when an argument is out of range, such as an
opslimit or
memlimit below the documented minimum. SodiumException is still thrown for internal libsodium failures.
SPL
SplObjectStorage::getHash implementations may no longer mutate any
SplObjectStorage instance. Attempting to do so now throws an Error.
SplFileObject::next now advances the stream when no prior SplFileObject::current call has cached a line. A subsequent SplFileObject::current call returns the new line rather than the previous one.
SplFileObject::fgets no longer caches the returned line for subsequent SplFileObject::current calls. SplFileObject::current now re-reads from the current stream position instead of returning the line SplFileObject::fgets just returned.
SplFileObject::next past EOF no longer increments SplFileObject::key without bound. SplFileObject::seek past EOF now produces the same SplFileObject::key value as
SplTempFileObject; the two previously returned different values.
DirectoryIterator::key now returns
intstring, and DirectoryIterator::current returns
stringSplFileInfostatic.
Sysvshm
shm_attach now raises a ValueError when the
key argument is outside the platform's
key_t range instead of passing a truncated key to the operating system.
URI
Uri\WhatWg\Url::__construct now sets
softErrors to an empty array when URL processing throws an exception, instead of preserving its value. URL validation errors remain available in the Uri\WhatWg\InvalidUrlException::$errors property.
Uri\WhatWg\Url::__construct, Uri\WhatWg\Url::parse, the
Uri\WhatWg\Url::with*() methods, and Uri\WhatWg\UrlBuilder::build now report validation errors in the order in which they are detected. This reverses the order of multiple errors compared to PHP 8.5.
Zip
ZipArchive::extractTo now raises a TypeError for the
files argument if one or more of the entries is not a string.
ZipArchive::addGlob and ZipArchive::addPattern now raise a TypeError when the
"remove_all_path" option is not of type
bool, or when the
"comp_method",
"comp_flags", or
"enc_method" options are not of type
int (numeric strings are coerced), instead of emitting a warning.
Serializing or unserializing a
ZipArchive now throws an Exception. A subclass can override __serialize() and __unserialize() to round-trip through ZipArchive::closeString and ZipArchive::openString.
Zlib
deflate_init now raises a TypeError when the value for option
"level",
"memory",
"window", or
"strategy" is not of type
int.
inflate_init now raises a TypeError when the value for option
"window" is not of type
int.
New Classes and Interfaces
Core
SortDirection
StreamError
StreamException
StreamErrorStore
StreamErrorMode
StreamErrorCode
Io\IoException
Io\Poll\Context
Io\Poll\Watcher
Io\Poll\Backend
Io\Poll\Event
Io\Poll\Handle
Io\Poll\PollException
Io\Poll\FailedPollOperationException
Io\Poll\FailedContextInitializationException
Io\Poll\FailedHandleAddException
Io\Poll\FailedWatcherModificationException
Io\Poll\FailedPollWaitException
Io\Poll\BackendUnavailableException
Io\Poll\InactiveWatcherException
Io\Poll\HandleAlreadyWatchedException
Io\Poll\InvalidHandleException
StreamPollHandle
Date
Time\Duration
Time\TimeException
Intl
IntlNumberRangeFormatter
OpenSSL
Openssl\OpensslException
Openssl\Session
Openssl\Psk
SNMP
Snmp\Mib
Snmp\OidOutput
Snmp\Output
Snmp\StringOutput
URI
Uri\Rfc3986\UriBuilder
Uri\WhatWg\UrlBuilder
Uri\WhatWg\UrlPercentEncodingMode
New Features
PHP Core
Default values for readonly properties
Readonly properties may now declare default values.
timeout); // int(30)
Reference assignment on WeakMap
It is now possible to use reference assignment on a
WeakMap without the key needing to be present beforehand.
$this->name, 'symbol' => $this->value];
}
}
var_dump(Suit::Hearts);
ENTITY
enum(Suit::Hearts) (2) {
["suit"]=>
string(6) "Hearts"
["symbol"]=>
string(1) "H"
}
#[\Override] for class constants
The
Override attribute can now be applied to class constants, including enum cases. As with methods and properties, a compile-time error is raised if no matching constant exists in a parent class or implemented interface.
prop = $val.
debug = true;
var_dump(CONFIG->debug); // bool(true)
Endianness modifiers for pack() and unpack()
pack and
unpack now accept the
ENTITY (little-endian) and
ENTITY (big-endian) modifiers after the
s,
S,
l,
L,
q and
Q integer format codes, and after the
f and
d float and double format codes.
', 1)), PHP_EOL; // Prints "00000001"
echo bin2hex(pack('l<', 1)), PHP_EOL; // Prints "01000000"
echo bin2hex(pack('f>', 1.5)), PHP_EOL; // Prints "3fc00000"
var_dump(unpack('s>value', "\xff\xfe")); // ["value" => int(-2)]
cURL
The array returned by
curl_getinfo now includes a new
"size_delivered" key, which indicates the total number of bytes passed to the download write callback. This value can also be obtained by passing
CURLINFO_SIZE_DELIVERED as the
option parameter. Requires libcurl 8.20.0 or later.
Added
CURLOPT_SEEKFUNCTION to register a callback that repositions a streamed request body, so libcurl can rewind and resend it on a redirect, multi-pass authentication, or a retried reused connection instead of failing with
CURLE_SEND_FAIL_REWIND. The callback receives the
CurlHandle, offset and origin, and must return one of
CURL_SEEKFUNC_OK,
CURL_SEEKFUNC_FAIL or
CURL_SEEKFUNC_CANTSEEK.
Date
Added the
Time\Duration class.
FileInfo
finfo_file now works with remote streams.
GMP
Added
gmp_powm_sec for side-channel quiet modular exponentiation. Requires GNU MP 5.0.0 or later; it is not available on official Windows builds using MPIR.
Added
gmp_prevprime to get the largest prime smaller than the given number. The optional
definitely_prime output parameter indicates whether the returned number is definitely prime, as opposed to probably prime. A ValueError is thrown if no such prime exists. This function is only available when PHP is built against GNU MP 6.3.0 or later; it is not available on official Windows builds using MPIR.
Intl
Added the static methods IntlDatePatternGenerator::getSkeleton and IntlDatePatternGenerator::getBaseSkeleton to generate the unique skeleton and base skeleton for a date/time pattern.
Added Locale::getDisplayKeyword and Locale::getDisplayKeywordValue, with the aliases
locale_get_display_keyword and
locale_get_display_keyword_value, respectively.
Added the
IntlNumberRangeFormatter class to format an interval of two numbers with a given skeleton and locale. It is supported as of ICU 63. The collapse behavior is one of:
IntlNumberRangeFormatter::COLLAPSE_AUTO,
IntlNumberRangeFormatter::COLLAPSE_NONE,
IntlNumberRangeFormatter::COLLAPSE_UNIT,
IntlNumberRangeFormatter::COLLAPSE_ALL The identity fallback is one of:
IntlNumberRangeFormatter::IDENTITY_FALLBACK_SINGLE_VALUE,
IntlNumberRangeFormatter::IDENTITY_FALLBACK_APPROXIMATELY_OR_SINGLE_VALUE,
IntlNumberRangeFormatter::IDENTITY_FALLBACK_APPROXIMATELY,
IntlNumberRangeFormatter::IDENTITY_FALLBACK_RANGE
Added SpoofChecker::areBidiConfusable to check whether two strings are confusable for a given text direction, along with the
SpoofChecker::LTR and
SpoofChecker::RTL direction constants. It is supported as of ICU 74.
Added SpoofChecker::getBidiSkeleton to generate a confusable skeleton for a given text direction. It is supported as of ICU 74.
Added SpoofChecker::getSkeleton to generate a confusable skeleton for a given string.
IO
Added a new polling API, consisting of: The
Io\Poll\Context and
Io\Poll\Watcher classes, The Io\Poll\Backend and Io\Poll\Event enums, The Io\Poll\Handle interface, The
StreamPollHandle class to watch streams
JSON
Added extra information about the error location to the error messages returned by
json_last_error_msg and to the message of JsonException.
OpenSSL
Added TLS session resumption support for streams. This allows saving and restoring client sessions across requests, implementing custom server-side session storage, and controlling session cache behavior, using the following new SSL context options:
session_data,
session_new_cb,
session_cache,
session_cache_size,
session_timeout,
session_id_context,
session_get_cb,
session_remove_cb,
num_tickets
Added TLS external PSK support for streams with the new SSL context options
psk_client_cb and
psk_server_cb. This allows setting and receiving pre-shared keys.
Added TLS 1.3 early data (0-RTT) support for streams. Clients send early data with the
early_data SSL context option; servers accept it with
max_early_data and receive it through the
early_data_cb callback. The outcome is reported as
"accepted",
"rejected" or
"not_sent" in the
"early_data" key of the
"crypto" entry of the
stream_get_meta_data array.
PDO_PGSQL
Added
Pdo\Pgsql::ATTR_CHUNK_SIZE, the number of rows a statement fetches per chunk. A value of 1 or more enters the lazy fetch mode of
PDO::ATTR_PREFETCH => 0. Setting
PDO::ATTR_PREFETCH replaces the chunk size. Statements that are prepared with neither it nor
PDO::ATTR_PREFETCH fall back to the value set on the connection. Requires libpq 17 or later.
Phar
Overriding the SplFileInfo::getMTime and SplFileInfo::getPathname methods now influences the result of the Phar::buildFromDirectory and Phar::buildFromIterator family of methods. This makes it possible to override the timestamp and names of files.
SNMP
It is now possible to use
AES192,
AES192C,
AES256, and
AES256C as SNMPv3 security protocols if the underlying library supports them.
It is now possible to reset the MIB tree using the new
snmp_init_mib function.
Additional MIB parsing and output control functionality has been exposed via:
snmp_set_mib_option,
snmp_set_output_option,
snmp_set_string_output_format, SNMP::$numeric_index, SNMP::$numeric_timeticks, SNMP::$extended_index, SNMP::$dont_print_units, SNMP::$escape_quotes, SNMP::$print_hex_text, SNMP::setOidOutputFormat, SNMP::setStringOutputFormat
Streams
Added a new stream errors API, consisting of: The StreamError and StreamException classes, The StreamErrorStore, StreamErrorMode, and StreamErrorCode enums, The
stream_last_errors and
stream_clear_errors functions It is controlled using the
error_mode,
error_store and
error_handler stream context options.
Added the
filter.max_filter_count stream context option for php://filter URLs. When set, opening the stream fails with a warning if the URL would add more filters than the configured value. Negative values disable the check.
Added the socket context option
so_reuseaddr that allows disabling address reuse (
SO_REUSEADDR) and explicitly uses
SO_EXCLUSIVEADDRUSE on Windows.
Added the socket context options
so_keepalive,
tcp_keepidle,
tcp_keepintvl and
tcp_keepcnt that allow setting socket keepalive options.
Added the socket context option
so_linger that sets
SO_LINGER on TCP sockets. A positive value enables lingering for that many seconds, zero or a negative value disables it. Values above 65535 are clamped as the linger time is limited to an unsigned short on some platforms.
Added the socket context options
so_rcvbuf and
so_sndbuf that set the socket receive and send buffer sizes in bytes (
SO_RCVBUF and
SO_SNDBUF) on TCP and UDP sockets. The value must be an integer between 1 and 2147483647, any other value makes the stream creation fail. The operating system may round, cap or otherwise adjust the requested size, and may stop sizing that buffer automatically, so the size read back can differ from the one requested.
Filtered streams can now be cast to file descriptors for use with
stream_select.
Added the
"write_seek_mode" filter parameter for the bz2, iconv, zlib, and convert stream filters. This parameter must be set via an associative array where the key is
"write_seek_mode" and the value is one of the following strings:
"preserve",
"reset",
"strict"
URI
Added Uri\Rfc3986\Uri::getUriType and Uri\WhatWg\Url::isSpecialScheme.
Added Uri\Rfc3986\Uri::getHostType and Uri\WhatWg\Url::getHostType.
Added the
Uri\Rfc3986\UriBuilder and
Uri\WhatWg\UrlBuilder classes.
Added
Uri\WhatWg\url_percent_encode.
New Functions
Core
clamp
returns the given value if in range, else returns the nearest bound.
stream_last_errors
stream_clear_errors
stream_socket_get_crypto_status
GMP
gmp_powm_sec
gmp_prevprime
Intl
grapheme_strrev
IntlDatePatternGenerator::getSkeleton
IntlDatePatternGenerator::getBaseSkeleton
Locale::getDisplayKeyword
locale_get_display_keyword
Locale::getDisplayKeywordValue
locale_get_display_keyword_value
SpoofChecker::areBidiConfusable
SpoofChecker::getBidiSkeleton
SpoofChecker::getSkeleton
MySQLi
mysqli::quote_string
mysqli_quote_string
Reflection
ReflectionAttribute::inNamespace
ReflectionAttribute::getNamespaceName
ReflectionAttribute::getShortName
ReflectionConstant::inNamespace
ReflectionParameter::getDocComment
ReflectionProperty::isReadable
ReflectionProperty::isWritable
SNMP
snmp_init_mib
snmp_set_mib_option
snmp_set_output_option
snmp_set_string_output_format
SNMP::setOidOutputFormat
SNMP::setStringOutputFormat
Sodium
sodium_crypto_ipcrypt_keygen
sodium_crypto_ipcrypt_encrypt
sodium_crypto_ipcrypt_decrypt
sodium_crypto_ipcrypt_nd_keygen
sodium_crypto_ipcrypt_nd_encrypt
sodium_crypto_ipcrypt_nd_decrypt
sodium_crypto_ipcrypt_ndx_keygen
sodium_crypto_ipcrypt_ndx_encrypt
sodium_crypto_ipcrypt_ndx_decrypt
sodium_crypto_ipcrypt_pfx_keygen
sodium_crypto_ipcrypt_pfx_encrypt
sodium_crypto_ipcrypt_pfx_decrypt
sodium_bin2ip
sodium_ip2bin
The following functions expose the X-Wing KEM (hybrid ML-KEM768+X25519, libsodium's recommended KEM). They are available when PHP is built against libsodium 1.0.22 or later.
sodium_crypto_kem_keypair,
sodium_crypto_kem_seed_keypair,
sodium_crypto_kem_secretkey,
sodium_crypto_kem_publickey,
sodium_crypto_kem_enc,
sodium_crypto_kem_dec
The following functions expose the ML-KEM768 (FIPS 203) KEM. They are available when PHP is built against libsodium 1.0.22 or later.
sodium_crypto_kem_mlkem768_keypair,
sodium_crypto_kem_mlkem768_seed_keypair,
sodium_crypto_kem_mlkem768_secretkey,
sodium_crypto_kem_mlkem768_publickey,
sodium_crypto_kem_mlkem768_enc,
sodium_crypto_kem_mlkem768_dec
URI
Uri\Rfc3986\Uri::getUriType
Uri\WhatWg\Url::isSpecialScheme
Uri\Rfc3986\Uri::getHostType
Uri\WhatWg\Url::getHostType
Uri\WhatWg\url_percent_encode
Zip
ZipArchive::openString
ZipArchive::closeString
Other Changes
Core changes
Core
In case of a hard OOM (out of memory) condition, PHP now calls
abort() instead of
exit(1), changing the exit code to 134 and possibly creating a core dump.
The
PHP_OS_FAMILY constant has an
AIX value for when running on AIX or IBM i via PASE.
Changes in SAPI Modules
CLI
The built-in development server now accepts requests using the HTTP
QUERY method instead of returning
501 Not Implemented.
The built-in development server no longer reflects the
Host header from requests.
Changed Functions
Core
header_register_callback now declares
true as its return type. It has not been able to return ENTITY since PHP 8.0.0, when passing an invalid callback started throwing a TypeError instead.
register_tick_function now declares
true as its return type. It has always returned ENTITY on success; an invalid callback throws a TypeError during argument parsing before the function body is reached.
ini_get_all now includes a
"builtin_default_value" element for each directive when
details is ENTITY. It holds the built-in default value of the directive (or ENTITY if it has none), independent of values set in ENTITY, on the command line, or at runtime.
fclose,
file_put_contents and
copy now return ENTITY when flushing or closing the stream fails. Previously such failures were silently ignored.
Date
The following methods now have tentative
static return types: DateTime::createFromInterface, DateTimeImmutable::__set_state, DateTimeImmutable::modify, DateTimeImmutable::add, DateTimeImmutable::sub, DateTimeImmutable::setTimezone, DateTimeImmutable::setTime, DateTimeImmutable::setDate, DateTimeImmutable::setISODate, DateTimeImmutable::setTimestamp, DateTimeImmutable::createFromInterface, DateTimeZone::__set_state, DateInterval::__set_state, DatePeriod::__set_state
Filter
The return type of
filter_var_array has been narrowed from
arrayfalsenull to
arrayfalse. The function always establishes an array before filtering, so ENTITY was never returned.
filter_input_array is unaffected: it still returns ENTITY when the requested superglobal does not exist.
LDAP
The return type of
ldap_free_result has been narrowed from
bool to
true. The function already always returned ENTITY.
MySQLi
The return structure of
mysqli_get_charset no longer contains the undocumented
"comment" element. The value of
"charsetnr" is now set to a constant
0 as this number was an implementation detail that should not have been exposed to the public.
OpenSSL
The output of
openssl_x509_parse now contains a
"criticalExtensions" entry listing all critical certificate extensions.
openssl_sign and
openssl_verify now have an additional optional
salt_length argument that allows controlling the RSA-PSS salt length when
OPENSSL_PKCS1_PSS_PADDING is used. It accepts an explicit length or one of the new
OPENSSL_RSA_PSS_SALTLEN_* constants.
PDO_DBLIB
When using persistent connections, there is now a liveness check in PDO::__construct.
Phar
Phar::mungServer now supports reference values.
Readline
readline_completion_function now declares
true as its return type. It has always returned ENTITY on success; an invalid callback throws a TypeError during argument parsing before the function body is reached.
Reflection
The outputs of ReflectionClassConstant::__toString and ReflectionConstant::__toString now print
bool constant values as
true and
false rather than
1 and an empty string. This also affects other ways of printing class constants, e.g. ReflectionClass::__toString.
Sockets
socket_addrinfo_lookup now has an additional optional
error_code argument that, when not ENTITY, receives the error code on failure (one of the
EAI_* constants).
The return type of
socket_cmsg_space has been narrowed from
intnull to
int. Every failure path has thrown a ValueError since PHP 8.0.0, so ENTITY was never returned.
Zip
The return type of
zip_entry_close has been narrowed from
bool to
true. The function already always returned ENTITY.
Other Changes to Extensions
Fileinfo
Upgraded to file 5.48. Custom compiled magic databases from older file versions must be regenerated.
Hash
The bundled version of xxHash was upgraded to 0.8.2.
MySQLi
Added the new constant
MYSQLI_OPT_COMPRESS.
Opcache
JIT is now supported for ZTS builds on Apple Silicon.
Changes to INI File Handling
Core
The error_include_args INI option has been added to make the display of function arguments consistent in errors; it is off by default. Previously, whether a function showed a parameter in the error was up to each call to the internal error function. Now, all parameters as they were actually passed to the function will be displayed. This uses the same infrastructure as stack traces, so sensitive parameters will not be displayed, and strings will be truncated according to zend.exception_string_param_max_len.
MBString
The mbstring.detect_order INI directive now updates the internal detection order when changed at runtime via
ini_set. Previously, runtime changes using
ini_set did not take effect for
mb_detect_order. Setting the directive to ENTITY or an empty string at runtime now leaves the previously configured detection order unchanged.
MySQLi
mysqli.default_port now checks the validity of the value, which should be between
0 and
65535 inclusive.
Opcache
opcache.jit_debug accepts a new flag:
ZEND_JIT_DEBUG_TRACE_EXIT_INFO_SRC. When used along with
ZEND_JIT_DEBUG_TRACE_EXIT_INFO, the source of exit points is printed in the exit info output, in debug builds.
Performance
Core
printf using only
%s and
%d will be compiled into the equivalent string interpolation, avoiding the overhead of a function call and repeatedly parsing the format string.
Arguments are now passed more efficiently to known constructors (e.g. when using
new self()).
array_map using a first-class callable or partial function application callback will be compiled into the equivalent foreach loop, avoiding the creation of intermediate
Closures, the overhead of calling userland callbacks from internal functions and providing for better insight for the JIT.
The performance of the TAILCALL VM has been improved, and it is now enabled on Windows when compiling with Clang 19 or later on x86_64.
The performance of ZTS builds has been improved.
Added a stateless closure cache.
Deeply recursive code that causes the VM to allocate new stack pages should now be faster.
Improved performance of sorting single-element arrays.
Improved performance of the following functions:
addcslashes, when generating octal escapes,
array_fill_keys,
array_intersect,
array_map, with multiple arrays passed,
array_product and
array_sum, for integer-only arrays,
array_unshift,
array_walk,
intval, for
intval('0b...', 2) and
intval('+0b...', 2),
pathinfo, when requesting a single component,
str_pad,
str_repeat, when the multiplier is
1,
str_split
DOM
Made DOMText::splitText and Dom\Text::splitText faster and consume less memory.
GD
imagebmp,
imagewbmp,
imagegd, and
imagegd2 now buffer output when writing to PHP streams, significantly improving performance when writing images to files.
Improved performance of
imagegrabscreen and
imagegrabwindow on Windows.
Intl
Improved performance of IntlCalendar::getAvailableLocales and IntlDateFormatter::localtime/
datefmt_localtime by pre-allocating their returned arrays.
Improved performance of
transliterator_list_ids and
resourcebundle_locales by pre-allocating their returned arrays.
Optimized callback invocation in IntlChar::enumCharTypes.
JSON
Improved performance of encoding arrays and objects.
Improved performance of indentation generation in
json_encode when using
JSON_PRETTY_PRINT.
MBString
Improved performance of
mb_str_pad.
Phar
Reduced temporary allocations when iterating Phar directories.
URI
Improved performance of Uri\WhatWg\Url::parse when collecting validation errors by pre-allocating the error array.
Reduced allocations when reading IPv6/IPvFuture hosts and paths with
Uri\Rfc3986\Uri.
Improved performance and memory consumption when using normalizing (non-raw) getters on already-normalized URIs with
Uri\Rfc3986\Uri.
Zip
Improved performance of ZipArchive::addGlob and ZipArchive::addPattern by pre-allocating their returned arrays.
Avoid string copies in ZipArchive::addFromString.
Windows Support
Core
The official Windows builds now use Visual Studio 2026 (VS18).
LibXML
The libxml2 library used by the official Windows builds has been upgraded to version 2.15.3. As a result, DOMDocument::$documentURI for documents loaded from a local file now contains a native filesystem path instead of a file URI.
OpenSSL
The OpenSSL library used by the official Windows builds has been upgraded to OpenSSL 4.
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 (
int)
The current PHP "major" version as an integer (e.g., int(5) from version "5.2.7-extra").
PHP_MINOR_VERSION (
int)
The current PHP "minor" version as an integer (e.g., int(2) from version "5.2.7-extra").
PHP_RELEASE_VERSION (
int)
The current PHP "release" version as an integer (e.g., int(7) from version "5.2.7-extra").
PHP_VERSION_ID (
int)
The current PHP version as an integer, useful for version comparisons (e.g., int(50207) from version "5.2.7-extra").
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.
PHP_BUILD_DATE (
string)
The date and time when PHP was built, in
"M d Y H:i:s" format. Available as of PHP 8.5.0.
PHP_BUILD_PROVIDER (
string)
The provider who built PHP. Available as of PHP 8.5.0.
[!NOTE]
This constant may not be available in all builds of PHP. (e.g., not set when building from source without specifying a value during configuration).
ZEND_THREAD_SAFE (
bool)
Indicates whether the current build of PHP is thread safe.
ZEND_DEBUG_BUILD (
bool)
Indicates whether the current build of PHP is a debug build.
PHP_ZTS (
bool) ENTITY
ZEND_THREAD_SAFE
Indicates whether the current build of PHP is thread safe.
PHP_DEBUG (
bool) ENTITY
ZEND_DEBUG_BUILD
Indicates whether the current build of PHP is a debug build.
DEBUG_BACKTRACE_PROVIDE_OBJECT (
int)
Populate the "object" index.
DEBUG_BACKTRACE_IGNORE_ARGS (
int)
Don't include the argument information for functions in the stack trace.
PHP_MAXPATHLEN (
int)
The maximum length of filenames (including path) supported by this build of PHP.
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.
PHP_INT_MAX (
int)
The largest integer supported in this build of PHP. Usually int(2147483647) in 32 bit systems and int(9223372036854775807) in 64 bit systems.
PHP_INT_MIN (
int)
The smallest integer supported in this build of PHP. Usually int(-2147483648) in 32 bit systems and int(-9223372036854775808) in 64 bit systems. Usually, PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (
int)
The size of an integer in bytes in this build of PHP.
PHP_FLOAT_DIG (
int)
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)
The default directory where to look for dynamically loadable extensions (unless overridden by extension_dir). Defaults to
PHP_PREFIX (or
PHP_PREFIX . "\\ext" on Windows).
PHP_PREFIX (
string)
The value
--prefix was set to at configure. On Windows, it is the value
--with-prefix was set to at configure.
PHP_BINDIR (
string)
The value
--bindir was set to at configure. On Windows, it is the value
--with-prefix was set to at configure.
PHP_SBINDIR (
string)
The value
--sbindir was set to at configure. On Windows, it is the value
--with-prefix was set to at configure. Available as of PHP 8.4.0.
PHP_BINARY (
string)
Specifies the PHP binary path during script execution.
PHP_MANDIR (
string)
Specifies where the manpages were installed into.
[!NOTE]
This constant is not present on Windows builds of PHP.
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 (
int)
The maximum number of file descriptors for select system calls. Available as of PHP 7.1.0.
E_ERROR (
int);
E_WARNING (
int);
E_PARSE (
int);
E_NOTICE (
int);
E_CORE_ERROR (
int);
E_CORE_WARNING (
int);
E_COMPILE_ERROR (
int);
E_COMPILE_WARNING (
int);
E_USER_ERROR (
int);
E_USER_WARNING (
int);
E_USER_NOTICE (
int);
E_RECOVERABLE_ERROR (
int);
E_DEPRECATED (
int);
E_USER_DEPRECATED (
int);
E_ALL (
int)
Error reporting constants.
E_STRICT (
int)
Error reporting constants. This constant is unused, and has been deprecated as of PHP 8.4.0.
__COMPILER_HALT_OFFSET__ (
int)
ENTITY (
bool)
See Booleans.
ENTITY (
bool)
See Booleans.
ENTITY (
null)
See Null.
PHP_WINDOWS_EVENT_CTRL_C (
int)
A Windows +CTRL+ +C+ event. Available as of PHP 7.4.0 (Windows only).
PHP_WINDOWS_EVENT_CTRL_BREAK (
int)
A Windows +CTRL+ +BREAK+ event. Available as of PHP 7.4.0 (Windows only).
PHP_CLI_PROCESS_TITLE (
bool)
Indicates whether the setting and getting of the process title is available. Available only under the CLI SAPI.
STDERR (
resource)
An already opened stream to
stderr. Available only under the CLI SAPI.
STDIN (
resource)
An already opened stream to
stdin. Available only under the CLI SAPI.
STDOUT (
resource)
An already opened stream to
stdout. Available only under the CLI SAPI.
See also: Magic constants.
ENTITY
ENTITY ENTITY
Standard Predefined Constants
All constants from core extensions are defined in PHP by default.
List of 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. The following words cannot be used as constants, class names, or function names. They are, however, allowed as property, constant, and method names of classes, interfaces, traits and enums, except that
class may not be used as constant name.
__halt_compiler
abstract
and
array
as
break
callable
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
fn (as of PHP 7.4)
for
foreach
function
global
goto
if
implements
include
include_once
instanceof
insteadof
interface
isset
list
ENTITY (as of PHP 8.0)
namespace
new
or
print
private
protected
public
readonly (as of PHP 8.1.0) *
require
require_once
return
static
switch
throw
trait
try
unset
use
var
while
xor
yield
yield from
PHP Keywords
*
readonly may be used as function name.
__CLASS__
__DIR__
__FILE__
__FUNCTION__
__LINE__
__METHOD__
__PROPERTY__
__NAMESPACE__
__TRAIT__
Compile-time constants
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
A generic empty class created as a result of typecasting to object or various standard functions.
__PHP_Incomplete_Class
Possibly created by
unserialize.
Exception
ErrorException
php_user_filter
Closure
The predefined final class
Closure is used for representing anonymous functions.
Generator
The predefined final class
Generator is used for representing generators.
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.
ENTITY
List of other reserved words
The following words cannot be used to name a class, interface, trait or enum. Prior to PHP 8.0, they are also prohibited from being used in namespaces.
parent
self
int
float
bool
string
true
false
null
void (as of PHP 7.1)
iterable (as of PHP 7.1)
object (as of PHP 7.2)
mixed (as of PHP 8.0)
never (as of PHP 8.1)
array (as of PHP 8.5)
callable (as of PHP 8.5)
Reserved words
The following list of words have had soft reservations placed on them. Whilst they may still be used as class, interface, trait and enum names, usage of them is highly discouraged since they may be used in future versions of PHP.
enum
resource
numeric
Soft reserved words
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 Type Name
Created By
Used By
Destroyed By
Definition
AddressInfo
socket_addrinfo_lookup
socket_addrinfo_bind,
socket_addrinfo_connect,
socket_addrinfo_explain,
None
AddressInfo (sockets extension)
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 handle
curl_multi
curl_multi_init
curl_multi_errno,
curl_multi_exec,
curl_multi_info_read,
curl_multi_remove_handle,
curl_multi_select,
curl_multi_setopt
curl_multi_close
cURL multi handle
curl_share
curl_share_init
curl_share_errno,
curl_share_setopt
curl_share_close
cURL share handle
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
enchant_broker
enchant_broker_init
enchant_broker_describe,
enchant_broker_dict_exists,
enchant_broker_get_dict_path,
enchant_broker_get_error,
enchant_broker_list_dicts,
enchant_broker_set_dict_path,
enchant_broker_set_ordering
enchant_broker_free
Enchant broker (prior to PHP 8.0.0)
enchant_dict
enchant_broker_request_dict
enchant_broker_request_pwl_dict
enchant_dict_add_to_personal,
enchant_dict_add_to_session,
enchant_dict_check,
enchant_dict_describe,
enchant_dict_get_error,
enchant_dict_is_in_session,
enchant_dict_store_replacement,
enchant_dict_suggest
enchant_broker_free_dict
Enchant dictionary (prior to PHP 8.0.0)
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 connection (prior to PHP 8.1.0)
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,
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 (prior to PHP 8.0.0)
gd font
imageloadfont
imagechar,
imagecharup,
imagefontheight
None
Font for GD (prior to PHP 8.1.0)
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 (prior to PHP 8.1.0)
interbase blob
ibase_blob_create,
ibase_blob_import,
ibase_blob_open
ibase_blob_add,
ibase_blob_cancel,
ibase_blob_echo,
ibase_blob_get,
ibase_blob_info
ibase_blob_close
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 (prior to PHP 8.1.0)
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 (prior to PHP 8.1.0)
ldap result entry
ldap result entry (prior to PHP 8.1.0)
mailparse_mail_structure
mailparse_msg_create
mailparse_msg_parse_file
mailparse_msg_extract_part_file
mailparse_msg_extract_part
mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
mailparse_msg_get_part
mailparse_msg_get_structure
mailparse_msg_parse
mailparse_msg_free
mysql link
mysql_connect
mysql_affected_rows,
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_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
OCICollection::append,
OCICollection::assign,
OCICollection::assignElem,
OCICollection::getElem,
OCICollection::max,
OCICollection::size,
OCICollection::trim
OCICollection::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
OCILob::append,
OCILob::close,
OCILob::eof,
OCILob::erase,
OCILob::export,
OCILob::flush,
OCILob::getBuffering,
OCILob::import,
OCILob::load,
OCILob::read,
OCILob::rewind,
OCILob::save,
OCILob::saveFile,
OCILob::seek,
OCILob::setBuffering,
OCILob::size,
OCILob::tell,
OCILob::truncate,
OCILob::write,
OCILob::writeTemporary,
OCILob::writeToFile,
oci_lob_copy,
oci_lob_is_equal
OCILob::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
Link to Birdstep database (prior to PHP 7.3.0)
birdstep result
Birdstep result (prior to PHP 7.3.0)
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
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 (prior to PHP 8.1.0)
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_meta_data,
pg_convert,
pg_insert,
pg_select,
pg_delete,
pg_update
pg_close
Link to PostgreSQL database (prior to PHP 8.1.0)
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_meta_data,
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 (prior to PHP 8.1.0)
pgsql string
process
proc_open
proc_get_status
proc_terminate
proc_close
Process
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 (prior to PHP 8.1.0)
pspell config
pspell_config_create
pspell_new_config
None
pspell configuration (prior to PHP 8.1.0)
shmop
shmop_open
shmop_read,
shmop_write,
shmop_size,
shmop_delete
shmop_close
Shared memory block handle (prior to PHP 8.0.0)
Socket
socket_accept,
socket_addrinfo_bind,
socket_addrinfo_connect,
socket_create,
socket_create_listen,
socket_import_stream,
socket_wsaprotocol_info_import
socket_accept,
socket_bind,
socket_clear_error,
socket_connect,
socket_get_option,
socket_getpeername,
socket_getsockname,
socket_last_error,
socket_listen,
socket_read,
socket_recv,
socket_recvfrom,
socket_recvmsg,
socket_select,
socket_send,
socket_sendmsg,
socket_sendto,
socket_set_block,
socket_set_nonblock,
socket_set_option,
socket_shutdown,
socket_write,
socket_wsaprotocol_info_export,
socket_wsaprotocol_info_release
socket_close
Socket (sockets extension)
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
SSH2 Session
ssh2_connect
ssh2_disconnect
SSH2 Listener
ssh2_forward_listen
``
SSH2 SFTP
ssh2_sftp
``
SSH2 Publickey Subsystem
ssh2_publickey_init
``
sysvmsg queue
msg_get_queue
msg_queue_exists,
msg_receive,
msg_send,
msg_set_queue,
msg_stat_queue
msg_remove_queue
System V Message Queue (prior to PHP 8.0.0)
sysvsem
sem_get
sem_acquire
sem_release
System V Semaphore (prior to PHP 8.0.0)
sysvshm
shm_attach
shm_remove,
shm_put_var,
shm_get_var,
shm_remove_var
shm_detach
System V Shared Memory (prior to PHP 8.0.0)
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 (prior to PHP 8.0.0)
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 (prior to PHP 8.0.0)
zlib.inflate
inflate_init
inflate_add,
inflate_get_read_len,
inflate_get_status
None
incremental inflate context (prior to PHP 8.0.0)
Resource Types
List of Parser Tokens
Various parts of the PHP language are represented internally by tokens. A code snippet that contains an invalid sequence of tokens may lead to errors like
Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10." where token
== is internally represented by
T_IS_EQUAL.
The following table lists all tokens. They are also available as PHP constants.
[!NOTE]
T_* constants values are automatically generated based on PHP's underlying parser infrastructure. This means that the concrete value of a token may change between two PHP versions. 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.
To make use of T_* constants across multiple PHP versions, undefined constants may be defined by the user (using big numbers like
10000) with an appropriate strategy that will work with both PHP versions and T_* values.
Token
Syntax
Reference
T_ABSTRACT (
int)
abstract
???
T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG (
int)
ENTITY
??? (available as of PHP 8.1.0)
T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG (
int)
ENTITY
??? (available as of PHP 8.1.0)
T_AND_EQUAL (
int)
ENTITY=
assignment operators
T_ARRAY (
int)
array()
array, array syntax
T_ARRAY_CAST (
int)
(array)
type-casting
T_AS (
int)
as
ENTITY
T_ATTRIBUTE (
int)
#[
attributes (available as of PHP 8.0.0)
T_BAD_CHARACTER (
int)
anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d) (available as of PHP 7.4.0)
T_BOOLEAN_AND (
int)
ENTITYENTITY
logical operators
T_BOOLEAN_OR (
int)
||
logical operators
T_BOOL_CAST (
int)
(bool) or (boolean)
type-casting
T_BREAK (
int)
break
break
T_CALLABLE (
int)
callable
callable
T_CASE (
int)
case
switch
T_CATCH (
int)
catch
???
T_CLASS (
int)
class
classes and objects
T_CLASS_C (
int)
__CLASS__
magic constants
T_CLONE (
int)
clone
classes and objects
T_CLOSE_TAG (
int)
?ENTITY or %ENTITY
escaping from HTML
T_COALESCE (
int)
??
comparison operators
T_COALESCE_EQUAL (
int)
??=
assignment operators (available as of PHP 7.4.0)
T_COMMENT (
int)
// or #, and /* */
comments
T_CONCAT_EQUAL (
int)
.=
assignment operators
T_CONST (
int)
const
class constants
T_CONSTANT_ENCAPSED_STRING (
int)
"foo" or 'bar'
string syntax
T_CONTINUE (
int)
continue
continue
T_CURLY_OPEN (
int)
{$
advanced variable string interpolation
T_DEC (
int)
--
incrementing/decrementing operators
T_DECLARE (
int)
declare
declare
T_DEFAULT (
int)
default
switch
T_DIR (
int)
__DIR__
magic constants
T_DIV_EQUAL (
int)
/=
assignment operators
T_DNUMBER (
int)
0.12, etc.
floating point numbers
T_DO (
int)
do
do..while
T_DOC_COMMENT (
int)
/** */
PHPDoc style comments
T_DOLLAR_OPEN_CURLY_BRACES (
int)
${
basic variable string interpolation
T_DOUBLE_ARROW (
int)
=ENTITY
array syntax
T_DOUBLE_CAST (
int)
(real), (double) or (float)
type-casting
T_DOUBLE_COLON (
int)
::
see
T_PAAMAYIM_NEKUDOTAYIM below
T_ECHO (
int)
echo
echo
T_ELLIPSIS (
int)
...
function arguments
T_ELSE (
int)
else
else
T_ELSEIF (
int)
elseif
elseif
T_EMPTY (
int)
empty
empty
T_ENCAPSED_AND_WHITESPACE (
int)
" $a"
constant part of string with variables
T_ENDDECLARE (
int)
enddeclare
declare, alternative syntax
T_ENDFOR (
int)
endfor
for, alternative syntax
T_ENDFOREACH (
int)
endforeach
ENTITY, alternative syntax
T_ENDIF (
int)
endif
if, alternative syntax
T_ENDSWITCH (
int)
endswitch
switch, alternative syntax
T_ENDWHILE (
int)
endwhile
while, alternative syntax
T_ENUM (
int)
enum
Enumerations (available as of PHP 8.1.0)
T_END_HEREDOC (
int)
heredoc syntax
T_EVAL (
int)
eval()
eval
T_EXIT (
int)
exit or die
exit,
die
T_EXTENDS (
int)
extends
extends, classes and objects
T_FILE (
int)
__FILE__
magic constants
T_FINAL (
int)
final
???
T_FINALLY (
int)
finally
???
T_FN (
int)
fn
arrow functions (available as of PHP 7.4.0)
T_FOR (
int)
for
for
T_FOREACH (
int)
foreach
ENTITY
T_FUNCTION (
int)
function
functions
T_FUNC_C (
int)
__FUNCTION__
magic constants
T_GLOBAL (
int)
global
variable scope
T_GOTO (
int)
goto
goto
T_HALT_COMPILER (
int)
__halt_compiler()
???
T_IF (
int)
if
if
T_IMPLEMENTS (
int)
implements
???
T_INC (
int)
++
incrementing/decrementing operators
T_INCLUDE (
int)
include
include
T_INCLUDE_ONCE (
int)
include_once
include_once
T_INLINE_HTML (
int)
text outside PHP
T_INSTANCEOF (
int)
instanceof
type operators
T_INSTEADOF (
int)
insteadof
???
T_INTERFACE (
int)
interface
???
T_INT_CAST (
int)
(int) or (integer)
type-casting
T_ISSET (
int)
isset()
isset
T_IS_EQUAL (
int)
==
comparison operators
T_IS_GREATER_OR_EQUAL (
int)
ENTITY=
comparison operators
T_IS_IDENTICAL (
int)
===
comparison operators
T_IS_NOT_EQUAL (
int)
!= or ENTITYENTITY
comparison operators
T_IS_NOT_IDENTICAL (
int)
!==
comparison operators
T_IS_SMALLER_OR_EQUAL (
int)
ENTITY=
comparison operators
T_LINE (
int)
__LINE__
magic constants
T_LIST (
int)
list()
list
T_LNUMBER (
int)
123, 012, 0x1ac, etc.
integers
T_LOGICAL_AND (
int)
and
logical operators
T_LOGICAL_OR (
int)
or
logical operators
T_LOGICAL_XOR (
int)
xor
logical operators
T_MATCH (
int)
match
ENTITY (available as of PHP 8.0.0)
T_METHOD_C (
int)
__METHOD__
magic constants
T_MINUS_EQUAL (
int)
-=
assignment operators
T_MOD_EQUAL (
int)
%=
assignment operators
T_MUL_EQUAL (
int)
*=
assignment operators
T_NAMESPACE (
int)
namespace
namespaces
T_NAME_FULLY_QUALIFIED (
int)
\App\Namespace
namespaces (available as of PHP 8.0.0)
T_NAME_QUALIFIED (
int)
App\Namespace
namespaces (available as of PHP 8.0.0)
T_NAME_RELATIVE (
int)
namespace\Namespace
namespaces (available as of PHP 8.0.0)
T_NEW (
int)
new
classes and objects
T_NS_C (
int)
__NAMESPACE__
namespaces
T_NS_SEPARATOR (
int)
\
namespaces
T_NUM_STRING (
int)
"$a[0]"
numeric array index inside string
T_OBJECT_CAST (
int)
(object)
type-casting
T_OBJECT_OPERATOR (
int)
-ENTITY
classes and objects
T_NULLSAFE_OBJECT_OPERATOR (
int)
?-ENTITY
classes and objects
T_OPEN_TAG (
int)
ENTITY?php, ENTITY? or ENTITY%
escaping from HTML
T_OPEN_TAG_WITH_ECHO (
int)
ENTITY?= or ENTITY%=
escaping from HTML
T_OR_EQUAL (
int)
|=
assignment operators
T_PAAMAYIM_NEKUDOTAYIM (
int)
::
scope resolution. Also defined as
T_DOUBLE_COLON.
T_PIPE
|>
functional operators (available as of PHP 8.5.0)
T_PLUS_EQUAL (
int)
+=
assignment operators
T_POW (
int)
**
arithmetic operators
T_POW_EQUAL (
int)
**=
assignment operators
T_PRINT (
int)
print
print
T_PRIVATE (
int)
private
classes and objects
T_PRIVATE_SET (
int)
private(set)
property hooks (available as of PHP 8.4.0)
T_PROPERTY_C (
int)
__PROPERTY__
magic constants (available as of PHP 8.4.0)
T_PROTECTED (
int)
protected
classes and objects
T_PROTECTED_SET (
int)
protected(set)
property hooks (available as of PHP 8.4.0)
T_PUBLIC (
int)
public
classes and objects
T_PUBLIC_SET (
int)
public(set)
property hooks (available as of PHP 8.4.0)
T_READONLY (
int)
readonly
classes and objects (available as of PHP 8.1.0)
T_REQUIRE (
int)
require
require
T_REQUIRE_ONCE (
int)
require_once
require_once
T_RETURN (
int)
return
returning values
T_SL (
int)
ENTITYENTITY
bitwise operators
T_SL_EQUAL (
int)
ENTITYENTITY=
assignment operators
T_SPACESHIP (
int)
ENTITY=ENTITY
comparison operators
T_SR (
int)
ENTITYENTITY
bitwise operators
T_SR_EQUAL (
int)
ENTITYENTITY=
assignment operators
T_START_HEREDOC (
int)
ENTITYENTITYENTITY
heredoc syntax
T_STATIC (
int)
static
variable scope
T_STRING (
int)
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 (
int)
(string)
type-casting
T_STRING_VARNAME (
int)
"${a
variable variables to interpolate in a string
T_SWITCH (
int)
switch
switch
T_THROW (
int)
throw
???
T_TRAIT (
int)
trait
???
T_TRAIT_C (
int)
__TRAIT__
__TRAIT__
T_TRY (
int)
try
???
T_UNSET (
int)
unset()
unset
T_UNSET_CAST (
int)
(unset)
type-casting
T_USE (
int)
use
namespaces
T_VAR (
int)
var
classes and objects
T_VARIABLE (
int)
$foo
variables
T_VOID_CAST
(void)
void cast (available as of PHP 8.5.0)
T_WHILE (
int)
while
while, do..while
T_WHITESPACE (
int)
\t \r\n
T_XOR_EQUAL (
int)
^=
assignment operators
T_YIELD (
int)
yield
generators
T_YIELD_FROM (
int)
yield from
generators
Tokens
See also
token_name.
List of Supported Socket Transports
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 Socket Functions of 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
ssl://,
tls://,
sslv2:// ENTITY
sslv3://.
[!NOTE]
The
sslv2:// and
sslv3:// transports are obsolete and should not be used. They are documented for backward compatibility only.
[!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
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]
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.
ssl:// will attempt to negotiate a secure SSL/TLS connection depending on the capabilities and preferences of both the client and the remote host. The actual protocols that may be used are determined by the OpenSSL configuration and by any options provided through
stream_context_create, such as
ssl.crypto_method.
The SSLv2 and SSLv3 protocols are obsolete and insecure. Their use is strongly discouraged and they are no longer enabled by default in modern versions of PHP and OpenSSL.
Unix Domain: Unix and UDG
unix:// and
udg://.
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.
[!NOTE]
Unix domain sockets are not supported on Windows.
Userland Naming Guide
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 user symbols.
Global Namespace
Here is an overview of code constructs that go into the global namespace:
functions
classes
interfaces
traits
enumerations
constants (not class constants)
variables defined outside of functions and 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 PHP 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, class names use
PascalCase, and method names use
camelCase.
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, so some existing names are not prefixed.) Examples:
curl_exec
mysqli_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 not to create symbols starting with
__ in PHP, unless the intent is to use documented magical functionality. Examples:
__get()
__construct()
Tips
In order to write future-proof code, it is recommended not to place many variables, functions or classes in the global namespace. This will prevent naming conflicts with third-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.
Keeping track of the namespaces already in use is still necessary, but once a namespace has been chosen, all functions and classes can be added 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 third-party code.
[!NOTE]
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.
Chapters
What is PHP and what can it do?
What is PHP?
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
Nice, but what does that mean? An example:
Example
Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does (in this case, output
Hi, I'm a PHP script!). The PHP code is enclosed in special start and end processing instructions
ENTITY?php and
?ENTITY that allow jumping in and out of “PHP mode.”
What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. A web server can even be configured to process all HTML files with PHP, and then there's no way that users can tell that PHP is being used.
The best part about using PHP is that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid to read the long list of PHP's features. With PHP, almost anyone can get up and running and be writing simple scripts in no time at all.
Although PHP's development is focused on server-side scripting, much more can be done with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial to jump straight to learning about web programming.
What can PHP do?
Anything. PHP is mainly focused on server-side scripting, so it can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.
There are two main areas where PHP scripts are used.
Server-side scripting. This is the most widely used and main target field for PHP. Three things are needed to make this work: the PHP parser (CGI or server module), a web server, and a web browser. All these can run on a local machine in order to just experiment with PHP programming. See the installation instructions section for more information.
Command line scripting. A PHP script can be run without any server or browser; only the PHP parser is needed to use it this way. This type of usage is ideal for scripts regularly executed using
cron (on Unix or macOS) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, macOS, RISC OS, and probably others. PHP also has support for most of the web servers today. This includes Apache, IIS, and many others. And this includes any web server that can utilize the FastCGI PHP binary, like lighttpd and nginx. PHP works as either a module, or as a CGI processor.
So with PHP, developers have the freedom of choosing an operating system and a web server. Furthermore, they also have the choice of using procedural programming or object-oriented programming (OOP), or a mixture of them both.
PHP is not limited to outputting HTML. PHP's abilities include outputting rich file types, such as images or PDF files, encrypting data, and sending emails. It can also easily output any text, such as JSON or XML. PHP can autogenerate these files, and save them in the filesystem, instead of printing them out, forming a server-side cache for dynamic content.
One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple using one of the database specific extensions (e.g., for MySQL), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB.
PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. It can also open raw network sockets and interact using any other protocol.
PHP has useful text processing features, which include 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 by adding SimpleXML, XMLReader and XMLWriter support.
And many other interesting extensions exist, which are categorized both alphabetically and by category. And there are additional PECL extensions that may or may not be documented within the PHP manual itself, like XDebug.
This page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.
A simple tutorial
Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.
PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.
Your first PHP-enabled page
This tutorial assumes PHP is already installed. Installation instructions can be found on the download page.
Create a file named
hello.php with the following content:
Using your terminal, navigate to the directory containing this file and start a development server with the following command:
php -S localhost:8000
Use your browser to access the file with your web server's URL, ending with the
/hello.php file reference. According to the previous command executed, the URL will be
http://localhost:8000/hello.php. If everything is configured correctly, this file will be parsed by PHP and you will see the "Hello World!" output displayed in your browser.
PHP can be embedded within a normal HTML web page. That means inside your HTML document you can write the PHP statements, as demonstrated in the following example:
PHP Test
Hello World
'; ?>
This will result in the following output:
PHP Test
Hello World
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display:
Hello World using the PHP
echo statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
The point of the example is to show the special PHP tag format. In this example we used
ENTITY?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag,
?ENTITY. 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]
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 line feed that follows immediately after a closing
?ENTITY 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
?ENTITY 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]
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]
Word processors such as StarOffice Writer, Microsoft Word and AbiWord are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the
phpinfo function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.
Something Useful
Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is
$_SERVER['HTTP_USER_AGENT'].
[!NOTE]
$_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information.
To display this variable, you can simply do:
A sample output of this script may be:
Mozilla/5.0 (Linux) Firefox/112.0
There are many types of variables available in PHP. In the above example we printed an element from an Array variable. Arrays can be very useful.
$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the
phpinfo function used in the example in the previous section.
You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Firefox you can do this:
A sample output of this script may be:
You are using Firefox.
Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.
The second concept we introduced was the
str_contains function call.
str_contains is a function built into PHP which determines if a given string contains another string. In this case we are looking for
'Firefox' (so-called needle) inside
$_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns true. Otherwise, it returns ENTITY. If it returns ENTITY, the if expression evaluates to ENTITY 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:
str_contains() returned true
You are using Firefox
str_contains() returned false
You are not using Firefox
A sample output of this script may be:
str_contains() returned true
You are using Firefox
Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of
str_contains. In other words, it depends on whether the string
Firefox was found or not.
Dealing with Forms
One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:
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:
Hi .
You are years old.
A sample output of this script may be:
Hi Joe. You are 22 years old.
Apart from the
htmlspecialchars and
(int) parts, it should be obvious what this does.
htmlspecialchars makes sure any characters that are special in HTML are properly encoded so people can't inject HTML tags or JavaScript into your page. For the age field, since we know it is a number, we can just convert it to an
int which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The
$_POST['name'] and
$_POST['age'] variables are automatically set for you by PHP. Earlier we used the
$_SERVER superglobal; above we just introduced the
$_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the
$_GET superglobal instead. You may also use the
$_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data.
What's next?
With your new knowledge you should be able to understand most of the manual.
In particular you may want to explore the following features: Reading and writing files with the filesystem functions, Handling file uploads, Fetching remote pages and files with Curl, Storing and analyzing data in a database with PDO (SQLite can be used without running a database server), Persisting data across requests with Sessions
There's a trove of libraries and frameworks for every occasion on the Packagist repository, all installable via the Composer package manager.
For community help and advice, check out the Help page.
For a variety of podcasts, presentations and other videos, check out the community PeerTube.
Other community resources that will help you include "awesome lists" (curated directories of links) and "developer roadmaps" (lists of related topics).
When you're stuck with no idea where to start, try breaking down your project or problem into smaller parts, allowing you to more easily see what you already know how to do and what you need to learn. The list can be as deep / detailed as you need. For example, building a blog might be broken down into the following parts:
Listing and viewing pages
Reading records (pages) from a database
Creating pages
Handle form submission
Writing records (pages) to a database
Admin login
Reading records (users) from a database
Handling passwords
Persisting data (user login) across requests / pages (sessions)
If there's nothing particular you want to build, you can try searching for coding exercises such as katas, challenges and "code golf". Even when not specifically aimed at PHP, most should be completable and will likely challenge your knowledge and thinking.
Language
Attributes
Attributes overview
PHP attributes provide structured, machine-readable metadata for classes, methods, functions, parameters, properties, and constants. They can be inspected at runtime via the Reflection API, enabling dynamic behavior without modifying code. Attributes provide a declarative way to annotate code with metadata.
Attributes enable the decoupling of a feature's implementation from its usage. While interfaces define structure by enforcing methods, attributes provide metadata across multiple elements, including methods, functions, properties, and constants. Unlike interfaces, which enforce method implementations, attributes annotate code without altering its structure.
Attributes can complement or replace optional interface methods by providing metadata instead of enforced structure. Consider an
ActionHandler interface that represents an operation in an application. Some implementations may require a setup step while others do not. Instead of forcing all classes implementing
ActionHandler to define a
setUp() method, an attribute can indicate setup requirements. This approach increases flexibility, allowing attributes to be applied multiple times when necessary.
Implementing optional methods of an interface with Attributes
fileName)) {
throw new RuntimeException("File does not exist");
}
}
#[SetUp]
public function targetDirectoryExists()
{
if (!file_exists($this->targetDirectory)) {
mkdir($this->targetDirectory);
} elseif (!is_dir($this->targetDirectory)) {
throw new RuntimeException("Target directory $this->targetDirectory is not a directory");
}
}
public function execute()
{
copy($this->fileName, $this->targetDirectory . '/' . basename($this->fileName));
}
}
function executeAction(ActionHandler $actionHandler)
{
$reflection = new ReflectionObject($actionHandler);
foreach ($reflection->getMethods() as $method) {
$attributes = $method->getAttributes(SetUp::class);
if (count($attributes) > 0) {
$methodName = $method->getName();
$actionHandler->$methodName();
}
}
$actionHandler->execute();
}
$copyAction = new CopyFile();
$copyAction->fileName = "/tmp/foo.jpg";
$copyAction->targetDirectory = "/home/user";
executeAction($copyAction);
Attribute syntax
Attribute syntax consists of several key components. An attribute declaration starts with
#[ and ends with
]. Inside, one or more attributes can be listed, separated by commas. The attribute name can be unqualified, qualified, or fully-qualified, as described in Using Namespaces Basics. Arguments to the attribute are optional and enclosed in parentheses
(). Arguments can only be literal values or constant expressions. Both positional and named argument syntax are supported.
Attribute names and their arguments are resolved to a class, and the arguments are passed to its constructor when an instance of the attribute is requested through the Reflection API. Therefore, it is recommended to introduce a class for each attribute.
Attribute Syntax
value = $value;
}
}
// b.php
namespace Another;
use MyExample\MyAttribute;
#[MyAttribute]
#[\MyExample\MyAttribute]
#[MyAttribute(1234)]
#[MyAttribute(value: 1234)]
#[MyAttribute(MyAttribute::VALUE)]
#[MyAttribute(array("key" => "value"))]
#[MyAttribute(100 + 200)]
class Thing
{
}
#[MyAttribute(1234), MyAttribute(5678)]
class AnotherThing
{
}
Reading Attributes with the Reflection API
To access attributes from classes, methods, functions, parameters, properties, and class constants, use the
getAttributes method provided by the Reflection API. This method returns an array of
ReflectionAttribute instances. These instances can be queried for the attribute name, arguments, and can be used to instantiate an instance of the represented attribute.
Separating the reflected attribute representation from its actual instance provides more control over error handling, such as missing attribute classes, mistyped arguments, or missing values. Objects of the attribute class are instantiated only after calling
ReflectionAttribute::newInstance, ensuring that argument validation occurs at that point.
Reading Attributes using Reflection API
value = $value;
}
}
#[MyAttribute(value: 1234)]
class Thing
{
}
function dumpAttributeData($reflection) {
$attributes = $reflection->getAttributes();
foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}
dumpAttributeData(new ReflectionClass(Thing::class));
ENTITY
string(11) "MyAttribute"
array(1) {
["value"]=>
int(1234)
}
object(MyAttribute)#3 (1) {
["value"]=>
int(1234)
}
Instead of iterating over all attributes on the reflection instance, you can retrieve only those of a specific attribute class by passing the attribute class name as an argument.
Reading Specific Attributes using Reflection API
value = $value;
}
}
#[MyAttribute(value: 1234)]
class Thing
{
}
function dumpMyAttributeData($reflection) {
$attributes = $reflection->getAttributes(MyAttribute::class);
foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}
dumpMyAttributeData(new ReflectionClass(Thing::class));
Declaring Attribute Classes
It is recommended to define a separate class for each attribute. In the simplest case, an empty class with the
#[Attribute] declaration is sufficient. The attribute can be imported from the global namespace using a
use statement.
Simple Attribute Class
2. You can use the short echo tag to = 'print this string' ?>.
It's equivalent to .
3. echo 'this code is within short tags, but will only work '.
'if short_open_tag is enabled'; ?>
Short tags (the third line in the example above) are available by default but can be disabled either via the short_open_tag ENTITY configuration file directive, or are disabled by default if PHP is built with the
--disable-short-tags configuration.
[!NOTE]
As short tags can be disabled it is recommended to only use the normal tags (
ENTITY?php ?ENTITY and
ENTITY?= ?ENTITY) to maximise compatibility.
If a file ends with PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
PHP Code Only File
This is going to be ignored by PHP and displayed by the browser.
This will also be ignored by PHP and displayed by the browser.
This works as expected, because when the PHP interpreter hits the ?ENTITY closing tags, it simply starts outputting whatever it finds (except for the immediately following newline - see instruction separation) until it hits another opening tag unless in the middle of a conditional statement in which case the interpreter will determine the outcome of the conditional before making a decision of what to skip over. See the next example.
Using structures with conditions
Advanced escaping using conditions
This will show if the expression is true.
Otherwise this will show.
In this example PHP will skip the blocks where the condition is not met, even though they are outside of the PHP open/close tags; PHP skips them according to the condition since the PHP interpreter will jump over blocks contained within a condition that is not met.
For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through
echo or
print.
[!NOTE]
If PHP is embedded within XML or XHTML the normal PHP
ENTITY?php ?ENTITY must be used to remain compliant with the standards.
Instruction separation
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.
Example showing the closing tag encompassing the trailing newline
No newline
= "But newline now" ?>
ENTITY
Some textNo newline
But newline now
Examples of entering and exiting the PHP parser
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
// ... ?ENTITY or
# ... ?ENTITY WILL be printed: ?ENTITY breaks out of PHP mode and returns to HTML mode, and
// or
# cannot influence that.
One Line Comments
This is an example
The header above will say 'This is an example'.
'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.
Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). Constants are case-sensitive. By convention, constant identifiers are always uppercase.
[!NOTE]
Prior to PHP 8.0.0, constants defined using the
define function may be case-insensitive.
[!NOTE]
As of PHP 8.5.0, redeclaring an already-defined constant is deprecated.
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly:
^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$
It is possible to
define constants with reserved or even invalid names, whose value can only be retrieved with the
constant function. However, doing so is not recommended.
ENTITY
Valid and invalid constant names
greet();
echo __NAMESPACE__, "\n";
ENTITY
App\helper
App\helper
App\Greeter
App\Greets
App\Greets::greet
greet
App
ENTITY
::class,
get_class,
get_called_class,
dirname
context
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.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
ftp
FTP context options
FTP context option listing
ENTITY
Context options for
ftp:// and
ftps:// transports.
ENTITY
overwrite
bool
Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only.
Defaults to ENTITY.
resume_pos
int
File offset at which to begin transfer. Applies to read mode (downloading) only.
Defaults to
0 (Beginning of File).
proxy
string
Proxy FTP request via http proxy server. Applies to file read operations only. Ex:
tcp://squid.example.com:8000.
ENTITY
[!NOTE]
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.
ENTITY
???, ???, ???
http
HTTP context options
HTTP context option listing
ENTITY
Context options for
http:// and
https:// transports.
ENTITY
method
string
GET,
POST, or any other HTTP method supported by the remote server.
Defaults to
GET.
header
array or
string
Additional headers to be sent during request. Values in this option will override other values (such as
User-agent:,
Host:, and
Authentication:), even when following
Location: redirects. Thus it is not recommended to set a
Host: header, if
follow_location is enabled.
String value should be
Key: value pairs delimited by
\r\n, e.g.
"Content-Type: application/json\r\nConnection: close". Array value should be a list of
Key: value pairs, e.g.
["Content-Type: application/json", "Connection: close"].
user_agent
string
Value to send with
User-Agent: header. This value will only be used if user-agent is not specified in the
header context option above.
By default the user_agent ENTITY setting is used.
content
string
Additional data to be sent after the headers. Typically used with POST or PUT requests.
proxy
string
URI specifying address of proxy server (e.g.
tcp://proxy.example.com:5100).
request_fulluri
bool
When set to ENTITY, the entire URI will be used when constructing the request (e.g.
GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it.
Defaults to ENTITY.
follow_location
int
Follow
Location header redirects. Set to
0 to disable.
When this option is not set, redirects are only followed for the
300,
301,
302,
303,
307 and
308 response codes. Setting it to
1 is not equivalent: any response carrying a
Location header is then followed, whatever its response code.
max_redirects
int
The max number of redirects to follow. Value
1 or less means that no redirects are followed.
Defaults to
20.
protocol_version
float
HTTP protocol version.
Defaults to
1.1 as of PHP 8.0.0; prior to that version the default was
1.0.
timeout
float
Read timeout in seconds, specified by a
float (e.g.
10.5).
By default the default_socket_timeout ENTITY setting is used.
ignore_errors
bool
Fetch the content even on failure status codes.
Defaults to ENTITY.
uri_parser_class
string or
null
The class to use for parsing URIs. When ENTITY, the legacy behavior based on
parse_url is used. Accepted values are
Uri\Rfc3986\Uri (RFC 3986 compliant parser) and
Uri\WhatWg\Url (WHATWG URL Standard parser). Custom userland implementations are not supported.
Defaults to ENTITY.
ENTITY
ENTITY
ENTITY
8.5.0
The
uri_parser_class option was added.
ENTITY
Fetch a page and send POST data
'some content',
'var2' => 'doh',
]
);
$opts = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata,
]
];
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
Ignore redirects but fetch headers and content
[
'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);
?>
ENTITY
[!NOTE]
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]
When this stream wrapper follows a redirect, the
wrapper_data returned by
stream_get_meta_data might not necessarily contain the HTTP status line that actually applies to the content data at index
0.
array (
'wrapper_data' =>
array (
0 => 'HTTP/1.0 301 Moved Permanently',
1 => 'Cache-Control: no-cache',
2 => 'Connection: close',
3 => 'Location: http://example.com/foo.jpg',
4 => 'HTTP/1.1 200 OK',
...
The first request returned a
301 (permanent redirect), so the stream wrapper automatically followed the redirect to get a
200 response (index =
4).
ENTITY
???, ???, ???
parameters
Context parameters
Context parameter listing
ENTITY
These
parameters can be set on a
context using the
stream_context_set_params function.
ENTITY
notification
callable
A
callable to be called when an event occurs on a stream.
See stream_notification_callback for more details.
phar
Phar context options
Phar context option listing
ENTITY
Context options for
phar:// wrapper.
ENTITY
compress
int
One of Phar compression constants.
metadata
mixed
Phar metadata. See
Phar::setMetadata.
ENTITY
???, Phar stream wrapper
socket
Socket context options
Socket context option listing
ENTITY
Socket context options are available for all wrappers that work over sockets, like
tcp,
http and
ftp.
ENTITY
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 ENTITY will set
SOL_TCP,NO_DELAY=1 appropriately, thus disabling the TCP Nagle algorithm.
ENTITY
ENTITY
ENTITY
7.1.0
Added
tcp_nodelay.
7.0.1
Added
ipv6_v6only.
ENTITY
Basic
bindto usage example
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);
?>
ssl
SSL context options
SSL context option listing
ENTITY
Context options for
ssl:// and
tls:// transports.
ENTITY
peer_name
string
Peer name to be used. If this value is not set, then the name is guessed based on the hostname used when opening the stream.
verify_peer
bool
Require verification of SSL certificate used.
Defaults to ENTITY.
verify_peer_name
bool
Require verification of peer name.
Defaults to ENTITY.
allow_self_signed
bool
Allow self-signed certificates. Requires
verify_peer.
Defaults to ENTITY
cafile
string
Location of Certificate Authority file on local filesystem which should be used with the
verify_peer context option to authenticate the identity of the remote peer.
capath
string
If
cafile is not specified or if the certificate is not found there, the directory pointed to by
capath is searched for a suitable certificate.
capath must be a correctly hashed certificate directory.
local_cert
string
Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers. The private key also may be contained in a separate file specified by
local_pk.
local_pk
string
Path to local private key file on filesystem in case of separate files for certificate (
local_cert) and private key.
passphrase
string
Passphrase with which your
local_cert file was encoded.
verify_depth
int
Abort if the certificate chain is too deep.
Defaults to no verification.
ciphers
string
Sets the list of available ciphers. The format of the string is described in ciphers(1).
Defaults to
DEFAULT.
capture_peer_cert
bool
If set to ENTITY a
peer_certificate context option will be created containing the peer certificate.
capture_peer_cert_chain
bool
If set to ENTITY a
peer_certificate_chain context option will be created containing the certificate chain.
SNI_enabled
bool
If set to ENTITY server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address.
SNI_server_certs
array
An array of server names and their corresponding certificates to be used for SNI. The keys are the server names and the values are the paths to the certificate files on the local filesystem. The certificate files must be PEM encoded and contain both the certificate and private key.
Available as of PHP 5.6.0.
alpn_protocols
array
An array of application layer protocol names to be used for ALPN (Application-Layer Protocol Negotiation). The values are the protocol names as strings (e.g. "http/1.1", "h2").
Available as of PHP 7.0.0 and OpenSSL 1.0.2.
no_ticket
bool
If set, disable TLS session tickets. This can help to enhance security by providing Perfect Forward Secrecy (PFS).
Available as of PHP 5.3.6.
disable_compression
bool
If set, disable TLS compression. This can help mitigate the CRIME attack vector.
peer_fingerprint
string |
array
Aborts when the remote certificate digest doesn't match the specified hash.
When a
string is used, the length will determine which hashing algorithm is applied, either "md5" (32) or "sha1" (40).
When an
array is used, the keys indicate the hashing algorithm name and each corresponding value is the expected digest.
security_level
int
Sets the security level. If not specified the library default security level is used. The security levels are described in SSL_CTX_get_security_level(3).
Available as of PHP 7.2.0 and OpenSSL 1.1.0.
min_proto_version
int
Sets the minimum protocol version allowed. If not specified the library default minimum protocol version is used. The protocol versions are described in SSL_CTX_set_min_proto_version(3).
Available as of PHP 7.3.0 and OpenSSL 1.1.0.
max_proto_version
int
Sets the maximum protocol version allowed. If not specified the library default maximum protocol version is used. The protocol versions are described in SSL_CTX_set_max_proto_version(3).
Available as of PHP 7.3.0 and OpenSSL 1.1.0.
ENTITY
ENTITY
ENTITY
7.3.0
Added
min_proto_version and
max_proto_version. Requires OpenSSL ENTITY= 1.1.0.
7.2.0
Added
security_level. Requires OpenSSL ENTITY= 1.1.0.
7.0.0
Added
alpn_protocols. Requires OpenSSL ENTITY= 1.0.2.
5.6.0
Added
SNI_server_certs.
5.3.6
Added
no_ticket.
ENTITY
[!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.
ENTITY
zip
Zip context options
Zip context option listing
ENTITY
Zip context options are available for
zip wrappers.
ENTITY
password
Used to specify password used for encrypted archive.
ENTITY
ENTITY
ENTITY
7.2.0, PECL zip 1.14.0
Added
password.
ENTITY
Basic
password usage example
array(
'password' => 'secret',
),
);
// create the context...
$context = stream_context_create($opts);
// ...and use it to fetch the data
echo file_get_contents('zip://test.zip#test.txt', false, $context);
?>
zlib
Zlib context options
Zlib context option listing
ENTITY
Zlib context options are available for
zlib wrappers.
ENTITY
level
Used to specify the compression level (
0 -
9).
ENTITY
ENTITY
ENTITY
7.3.0
level has been added.
Control Structures
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.
ENTITY
The following are also considered language constructs even though they are referenced under functions in the manual.
list,
array,
echo,
eval,
print
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
Alternative syntax for control structures
PHP offers an alternative syntax for some of its control structures; namely,
if,
while,
for,
foreach,
switch, and
declare. 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;,
endswitch;, or
enddeclare;, respectively.
A is equal to 5
ENTITY
A is equal to 5
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:
Foo is 1
ENTITY
Parse error: syntax error, unexpected T_INLINE_HTML " ", expecting "endswitch" or "case" or "default" in script on line 4
Whereas this is valid, as the trailing newline after the
switch statement is considered part of the closing
?ENTITY and hence nothing is output between the
switch and
case:
Foo is 1
ENTITY
Foo is 1
See also while, for, and if for further examples.
break
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.
$value) {
if (0 === ($key % 2)) { // skip members with even key
continue;
}
echo $value . "\n";
}
ENTITY
one
three
five
0) {
$a += 2; // causes a tick event
print $a . "\n"; // causes a tick event
}
ENTITY
tick_handler() called
tick_handler() called
tick_handler() called
3
tick_handler() called
See also
register_tick_function and
unregister_tick_function.
Encoding
A script's encoding can be specified per-script using the
encoding directive.
Declaring an encoding for the script
0);
ENTITY
0
The above loop would run one time exactly, since after the first iteration, when the truth expression is checked, it evaluates to ENTITY (
$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:
$b) {
echo "a is greater than b\n";
} else {
echo "a is NOT greater than b\n";
}
ENTITY
a is NOT greater than b
The
else statement is only executed if the
if expression evaluated to ENTITY, and if there were any
elseif expressions - only if they evaluated to ENTITY as well (see elseif).
[!NOTE]
In case of nested
if-
else statements, an
else is always associated with the nearest
if.
$b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
ENTITY
a is equal to b
There may be several
elseifs within the same
if statement. The first
elseif expression (if any) that evaluates to ENTITY would be executed. In PHP, it's possible to write
else if (in two words) and the behavior would be identical to that of
elseif (in a single word). The syntactic meaning is slightly different (the same behavior as C) but the bottom line is that both would result in exactly the same behavior.
The
elseif statement is only executed if the preceding
if expression and any preceding
elseif expressions evaluated to ENTITY, and the current
elseif expression evaluated to ENTITY.
[!NOTE]
Note that
elseif and
else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define
if/
elseif conditions, the use of
elseif in a single word becomes necessary. PHP will fail with a parse error if
else if is split into two words.
$b):
echo $a." is greater than ".$b;
else if ($a == $b): // Will not compile.
echo "The above line causes a parse error.";
endif;
ENTITY
Parse error: syntax error, unexpected token "if", expecting ":" in script on line 8
$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;
ENTITY
3 is greater than 1
finally
A ENTITY block may also be specified after or instead of ENTITY blocks. Code within the ENTITY block will always be executed after the ENTITY and ENTITY blocks, even if a ENTITY or ENTITY statement is encountered, or if a Throwable error is not caught or is rethrown. It will be executed prior to resuming the normal execution flow. The only exception to this rule is when the script is terminated abruptly, such as by a call to
exit or by a fatal error (for example, when the maximum execution time is exceeded).
Throwable error handling with a ENTITY block
getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (DivisionByZeroError $e) {
echo 'Caught error: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
ENTITY
0.2
First finally.
Caught error: Division by zero
Second finally.
Hello World
When the call stack is unwound after a Throwable error has been thrown, all ENTITY blocks it encounters along the way will be executed. In other words, nested ENTITY blocks are executed even if the Throwable error is not caught by an adjacent ENTITY block.
All ENTITY blocks will be executed
getMessage(),
$e->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getPrevious()->getMessage(),
);
}
ENTITY
string(5) "First"
string(6) "Second"
string(5) "Third"
string(6) "Fourth"
Behaviour of a ENTITY block in a Generator
If, during the traversal of a generator, a Throwable error is thrown, the ENTITY block within the generator will be executed, as it is the previous element of the call stack.
ENTITY block being run when an Exception has been thrown
10) {
break;
}
echo $i . " ";
}
ENTITY
1 2 3 4 5 6 7 8 9 10
10) {
break;
}
echo $i . " ";
$i++;
}
ENTITY
1 2 3 4 5 6 7 8 9 10
$value) {
statement_list
}
The first form traverses the value given by
iterable_expression. On each iteration, the value of the current element is assigned to
$value.
The second form will additionally assign the current element's key to the
$key variable on each iteration.
Note that
foreach does not modify the internal array pointer, which is used by functions such as
current and
key.
By default, an object is traversed over the properties that are visible from the current scope. It is possible to customize object iteration.
Common
foreach usages
1,
"two" => 2,
"three" => 3,
"seventeen" => 17
];
foreach ($array as $key => $value) {
echo "Key: $key => Value: $value\n";
}
echo "\n\nMulti-dimensional key-value arrays:\n";
$grid = [];
$grid[0][0] = "a";
$grid[0][1] = "b";
$grid[1][0] = "y";
$grid[1][1] = "z";
foreach ($grid as $y => $row) {
foreach ($row as $x => $value) {
echo "Value at position x=$x and y=$y: $value\n";
}
}
echo "\n\nDynamic arrays:\n";
foreach (range(1, 5) as $value) {
echo "$value\n";
}
ENTITY
Value only
Current element of $array: 1.
Current element of $array: 2.
Current element of $array: 3.
Current element of $array: 17.
Key and value:
Key: one => Value: 1
Key: two => Value: 2
Key: three => Value: 3
Key: seventeen => Value: 17
Multi-dimensional key-value arrays:
Value at position x=0 and y=0: a
Value at position x=1 and y=0: b
Value at position x=0 and y=1: y
Value at position x=1 and y=1: z
Dynamic arrays:
1
2
3
4
5
[!NOTE]
foreach does not support the ability to suppress error messages using the
@.
Unpacking nested arrays
It is possible to iterate over an array of arrays and unpack the nested array into loop variables by using either array destructuring via
[] or by using the
list language construct as the value.
[!NOTE]
Please note that array destructuring via
[] is only possible as of PHP 7.1.0.
In both of the following examples
$a will be set to the first element of the nested array and
$b will contain the second element:
int(2)
[1]=>
int(4)
[2]=>
int(6)
[3]=>
&int(8)
}
[!WARNING]
A reference to the
$value of the last array element remains even after the
foreach loop. It is recommended to destroy it using
unset. Otherwise, the following behavior will occur:
$value) {
// $arr[3] will be updated with each value from $arr...
echo "{$key} => {$value}\n";
}
// ...until ultimately the second-to-last value is copied onto the last value
var_dump($arr);
ENTITY
array(4) {
[0]=>
int(2)
[1]=>
int(4)
[2]=>
int(6)
[3]=>
&int(8)
}
Another loop:
0 => 2
1 => 4
2 => 6
3 => 6
array(4) {
[0]=>
int(2)
[1]=>
int(4)
[2]=>
int(6)
[3]=>
&int(6)
}
Iterate a constant array's values by reference
is evaluated to its Boolean value. If evaluates to ENTITY, PHP will execute , and if it evaluates to ENTITY - it'll ignore it. More information about what values evaluate to ENTITY 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:
$b)
echo "a is bigger than b\n";
ENTITY
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:
$b) {
echo "a is bigger than b\n";
$b = $a;
}
var_dump($b);
ENTITY
a is bigger than b
int(3)
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.
include_once
The
include_once expression includes and evaluates the specified file during the execution of the script. This behavior is similar to the
include expression, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns ENTITY. 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.
include
The
include expression includes and evaluates the specified file.
The documentation below also applies to
require.
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path,
include will finally check in the calling script's own directory and the current working directory before failing. The
include construct will emit an
E_WARNING if it cannot find a file; this is different behavior from
require, which will emit an
E_ERROR.
Note that both
include and
require raise additional
E_WARNINGs, if the file cannot be accessed, before raising the final
E_WARNING or
E_ERROR, respectively.
If a path is defined — whether absolute (starting with a drive letter or
\ on Windows, or
/ on Unix/Linux systems) or relative to the current directory (starting with
. or
..) — the include_path will be ignored altogether. For example, if a filename begins with
../, the parser will look in the parent directory to find the requested file.
For more information on how PHP handles including files and the include path, see the documentation for include_path.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
Basic
include example
vars.php
test.php
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 is magic constants which are evaluated by the parser before the include occurs.
Including within functions
noreturn.php
testreturns.php
$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, ENTITY is returned and
E_WARNING is issued.
If there are functions defined in the included file, they can be used in the main file regardless of whether 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 returning 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:
Using output buffering to include a PHP file into a string
return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
Basic
match usage
'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
ENTITY
string(19) "This food is a cake"
Example of using
match with comparison operators
"Baby",
$age < 13 => "Child",
$age <= 19 => "Teenager",
$age >= 40 => "Adult",
$age > 19 => "Young adult",
};
var_dump($output);
ENTITY
string(8) "Teenager"
[!NOTE]
The result of a
match expression does not need to be used.
[!NOTE]
When a
match expression is used as a standalone expression, it must be terminated by a semicolon
;.
The
match expression is similar to a
switch statement but has some key differences:
A
match arm compares values strictly (
===) instead of loosely as the switch statement does.
A
match expression returns a value.
match arms do not fall through to later cases the way
switch statements do.
A
match expression must be exhaustive.
Like
switch statements,
match expressions are executed match arm by match arm. In the beginning, no code is executed. The conditional expressions are only evaluated if all previous conditional expressions failed to match the subject expression. Only the return expression corresponding to the matching conditional expression will be evaluated. For example:
'value',
$this->bar() => 'value', // $this->bar() isn't called if foo() === $x
$this->baz => beep(), // beep() isn't called unless $x === $this->baz
// etc.
};
match expression arms may contain multiple expressions separated by a comma. That is a logical OR, and is a shorthand for multiple match arms with the same right-hand side.
5,
// Is equivalent to these three match arms:
$a => 5,
$b => 5,
$c => 5,
};
A special case is the
default pattern. This pattern matches anything that wasn't previously matched. For example:
foo(),
3, 4 => bar(),
default => baz(),
};
[!NOTE]
Multiple default patterns will raise an
E_FATAL_ERROR error.
A
match expression must be exhaustive. If the subject expression is not handled by any match arm, an
UnhandledMatchError is thrown.
Example of an unhandled match expression
foo(),
3, 4 => bar(),
};
} catch (UnhandledMatchError $e) {
var_dump($e);
}
ENTITY
object(UnhandledMatchError)#1 (7) {
["message":protected]=>
string(22) "Unhandled match case 5"
["string":"Error":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(6) "script"
["line":protected]=>
int(5)
["trace":"Error":private]=>
array(0) {
}
["previous":"Error":private]=>
NULL
}
Using match expressions to handle non-identity checks
It is possible to use a
match expression to handle non-identity conditional cases by using
true as the subject expression.
Using a generalized match expression to branch on integer ranges
= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
ENTITY
string(11) "young adult"
Using a generalized match expression to branch on string content
'en',
str_contains($text, 'Bienvenue'), str_contains($text, 'Bonjour') => 'fr',
// ...
};
var_dump($result);
ENTITY
string(2) "fr"
require_once
The
require_once expression is identical to
require except PHP will check if the file has already been included, and if so, not include (require) it again.
See the
include_once documentation for information about the
_once behaviour, and how it differs from its non
_once siblings.
require
require is identical to
include except upon failure it will also produce an
Error exception (
E_COMPILE_ERROR level error prior to PHP 8.0.0) whereas
include will only produce a warning (
E_WARNING level error).
See the
include documentation for how this works.
return
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 ENTITY, 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 ENTITY will be returned. Calling
return with parentheses but with no arguments will result in a parse error.
As of PHP 7.1.0, return statements without an argument in functions which declare a return type trigger
E_COMPILE_ERROR, unless the return type is
void, in which case return statements with an argument trigger that error.
switch
The
switch statement is similar to a series of
if statements on the same expression. In situations where it is necessary to compare the same variable or expression with many different values, and execute a different piece of code depending on which value it equals, the
switch statement is often more convenient and easier to read.
[!NOTE]
Note that unlike some other languages, the continue statement applies to
switch and acts similarly 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 a loose comparison.
In the following example, each code block is equivalent. One uses a series of
if and
elseif statements, and the other a
switch statement. In each case, the output is the same.
switch structure
getMessage();
}
ENTITY
It did not work
It is possible to handle a thrown Throwable by using a try-catch block. See the error handling section for more information.
try...catch
try
A ENTITY block delimits a segment of code which might ENTITY a Throwable error that needs handling. A ENTITY block must have at least one corresponding ENTITY or ENTITY block.
When a Throwable error is thrown in a ENTITY block, PHP will attempt to find the first matching ENTITY block to handle the error. If none can be found, the call stack is unwound until a matching ENTITY block is found or the global scope is reached. An uncaught object is then passed to the exception handler set with
set_exception_handler, if one is set; otherwise, the script terminates with a fatal error.
catch
A ENTITY block defines how to respond to a thrown Throwable error. It specifies one or more subclasses of Throwable (most commonly Exception) it can handle, and optionally a variable to which the exception is assigned.
The first ENTITY block that matches the class of the thrown Throwable object will handle the error. Normal execution resumes after the ENTITY block without entering any other matching ENTITY blocks.
[!NOTE]
It is not recommended to catch Error objects, as they signal a programming error.
Catching an Exception
getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
ENTITY
Caught exception: Error
Hello World
As of PHP 7.1.0, a ENTITY block may specify a union of Throwable subclasses that the block should handle using the pipe (
|) character. This is useful when different exceptions from different class hierarchies are handled in the same way.
Catching a union of classes to handle
testing();
ENTITY
string(11) "MyException"
Multiple ENTITY blocks can be used to handle different classes of Throwable errors in different ways.
Multiple catch blocks
getMessage());
}
}
}
$foo = new Test;
$foo->testing();
ENTITY
string(4) "foo!"
[!CAUTION]
An object thrown inside a ENTITY block will not be caught by an adjacent ENTITY block.
Sequential catch blocks
name;
// prints "Spades"
It is also possible to use the
defined and
constant functions to check for the existence of or read an enum case if the name is obtained dynamically. This is, however, discouraged as using Backed enums should work for most use cases.
Backed enumerations
By default, Enumerated Cases have no scalar equivalent. They are simply singleton objects. However, there are ample cases where an Enumerated Case needs to be able to round-trip to a database or similar datastore, so having a built-in scalar (and thus trivially serializable) equivalent defined intrinsically is useful.
To define a scalar equivalent for an Enumeration, the syntax is as follows:
value;
// Prints "C"
In order to enforce the
value property as read-only, a variable cannot be assigned as a reference to it. That is, the following throws an error:
value;
// Fatal Error: Cannot indirectly modify readonly property Suit::$value
Backed enums implement an internal BackedEnum interface, which exposes two additional methods:
from(int|string): self
will take a scalar and return the corresponding Enum Case. If one is not found, it will throw a
ValueError
. This is mainly useful in cases where the input scalar is trusted and a missing enum value should be considered an application-stopping error.
tryFrom(int|string): ?self
will take a scalar and return the corresponding Enum Case. If one is not found, it will return ENTITY. This is mainly useful in cases where the input scalar is untrusted and the caller wants to implement their own error handling or default-value logic.
The
from() and
tryFrom() methods follow standard weak/strong typing rules. In weak typing mode, passing an integer or string is acceptable and the system will coerce the value accordingly. Passing a float will also work and be coerced. In strict typing mode, passing an integer to
from() on a string-backed enum (or vice versa) will result in a
TypeError, as will a float in all circumstances. All other parameter types will throw a TypeError in both modes.
'S',
];
}
$record = get_stuff_from_database(42);
print $record['suit'] . "\n";
$suit = Suit::tryFrom('A') ?? Suit::Spades;
// Invalid data returns null, so Suit::Spades is used instead.
print $suit->value . "\n";
$suit = Suit::from('X');
// Invalid data throws a ValueError: "X" is not a valid backing scalar value for enum Suit
print $suit->value . "\n";
Manually defining a
from() or
tryFrom() method on a Backed Enum will result in a fatal error.
Enumeration methods
Enums (both Pure Enums and Backed Enums) may contain methods, and may implement interfaces. If an Enum implements an interface, then any type check for that interface will also accept all cases of that Enum.
'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
// Not part of an interface; that's fine.
public function shape(): string
{
return "Rectangle";
}
}
function paint(Colorful $c)
{
print $c->color() . "\n";
}
paint(Suit::Clubs); // Works
print Suit::Diamonds->shape(); // prints "Rectangle"
In this example, all four instances of
Suit have two methods,
color() and
shape(). As far as calling code and type checks are concerned, they behave exactly the same as any other object instance.
On a Backed Enum, the interface declaration goes after the backing type declaration.
'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
Inside a method, the
$this variable is defined and refers to the Case instance.
Methods may be arbitrarily complex, but in practice will usually return a static value or ENTITY on
$this to provide different results for different cases.
Note that in this case it would be a better data modeling practice to also define a
SuitColor Enum Type with values Red and Black and return that instead. However, that would complicate this example.
The above hierarchy is logically similar to the following class structure (although this is not the actual code that runs):
'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
public function shape(): string
{
return "Rectangle";
}
public static function cases(): array
{
// Illegal method, because manually defining a cases() method on an Enum is disallowed.
// See also "Value listing" section.
}
}
Methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed.
Enumeration static methods
Enumerations may also have static methods. The use for static methods on the enumeration itself is primarily for alternative constructors. E.g.:
self::Small,
$cm < 100 => self::Medium,
default => self::Large,
};
}
}
var_dump(Size::fromLength(50));
Static methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed.
Enumeration constants
Enumerations may include constants, which may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed.
An enum constant may refer to an enum case:
'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
$suit = Suit::Spades;
var_dump($suit->color());
var_dump($suit->shape());
Enum values in constant expressions
Because cases are represented as constants on the enum itself, they may be used as static values in most constant expressions: property defaults, static variable defaults, parameter defaults, global and class constant values. They may not be used in other enum case values, but normal constants may refer to an enum case.
However, implicit magic method calls such as
ArrayAccess on enums are not allowed in static or constant definitions as we cannot absolutely guarantee that the resulting value is deterministic or that the method invocation is free of side effects. Function calls, method calls, and property access continue to be invalid operations in constant expressions.
newInstanceWithoutConstructor()
// Error: Cannot instantiate enum Suit
Value listing
Both Pure Enums and Backed Enums implement an internal interface named UnitEnum.
UnitEnum includes a static method
cases().
cases() returns a packed array of all defined Cases in the order of declaration.
Bar
)
Baz Enum:int {
[name] => Beep
[value] => 5
}
*/
Why enums aren't extendable
Classes have contracts on their methods:
true,
};
}
The ENTITY statement in the function
quux can be static analyzed to cover all of the cases in ErrorCode.
But imagine it was allowed to extend enums:
'Pending',
self::Active => 'Active',
self::Suspended => 'Suspended',
self::CanceledByUser => 'Canceled by user',
};
}
}
$status = UserStatus::Suspended;
var_dump($status->label());
In this example, a user's status may be one of, and exclusively,
UserStatus::Pending,
UserStatus::Active,
UserStatus::Suspended, or
UserStatus::CanceledByUser. A function can type a parameter against
UserStatus and then only accept those four values, period.
All four values have a
label() method, which returns a human-readable string. That string is independent of the "machine name" scalar equivalent string, which can be used in, for example, a database field or an HTML select box.
'Pending',
self::Active => 'Active',
self::Suspended => 'Suspended',
self::CanceledByUser => 'Canceled by user',
};
}
}
foreach (UserStatus::cases() as $case) {
printf(
"\n",
htmlentities($case->value),
htmlentities($case->label())
);
}
Error Handling
Errors are a normal part of the development and life cycle of an application. As such, PHP provides multiple ways to report and deal with errors.
PHP has two main mechanisms for reporting errors:
Throwable errors, which are further split into programming errors via the Error class hierarchy and recoverable errors via the Exception class hierarchy. These errors can be thrown with the ENTITY keyword and caught with the ENTITY keyword.
Diagnostic errors, which are classified into different severities.
Throwable errors
A Throwable error is an execution event which disrupts the normal flow of instructions. When a Throwable error is ENTITYn, it will unwind the call stack until it is caught by a ENTITY block or the global scope is reached. All ENTITY blocks it encounters along the way will be executed. An uncaught Throwable error is passed to the exception handler set with
set_exception_handler, if one is set; otherwise, the program is terminated with a fatal error.
To throw a Throwable error from within PHP code, use the ENTITY keyword.
[!TIP]
The Standard PHP Library (SPL) provides various built-in exceptions. It is also possible to create custom exceptions by extending the Exception class.
It is possible to handle a Throwable error within PHP by surrounding the code that may throw an error in a ENTITY block.
[!WARNING]
Throwable objects cannot be cloned. Attempting to clone such an object throws an Error with the following message:
Trying to clone an uncloneable object of class ClassName. This happens even if a subclass declares its own __clone() method. See Exception::__clone and Error::__clone.
Global exception handler
It's possible to add a handler for any uncaught Throwable with
set_exception_handler. This is similar to wrapping the entire code in a ENTITY-ENTITY block, except that execution does not resume afterwards: the script terminates once the handler returns.
Extending exceptions
A user-defined exception can be defined by extending the built-in Exception class.
If a class extends the built-in Exception class and redefines 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 custom output when the object is used as a string.
Extending Exception
code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
try {
throw new CustomException("Something happened", 5);
} catch (CustomException $e) {
echo "Caught custom exception\n", $e;
$e->customFunction();
}
ENTITY
Caught custom exception
CustomException: [5]: Something happened
A custom function for this type of exception
Throwable hierarchy
Throwable
Error
ArithmeticError
DivisionByZeroError
AssertionError
CompileError
ParseError
TypeError
ArgumentCountError
ValueError
UnhandledMatchError
FiberError
Exception
The Exception class has many subclasses, among them the SPL exceptions and those defined by extensions.
Diagnostic errors
Diagnostic errors, also known as traditional errors, are used to signal a number of different conditions, and can be displayed and/or logged as required. By default, PHP will report all diagnostic errors. (Prior to PHP 8.0.0,
E_NOTICE and
E_DEPRECATED diagnostics were not reported by default.)
In contrast to Throwable errors, most diagnostic errors do not disrupt the normal flow of execution. Fatal diagnostics, such as
E_ERROR, terminate the script.
Which diagnostics are reported and which are ignored is controlled by the
error_reporting ENTITY directive, or at runtime by calling
error_reporting. It is strongly recommended that the configuration directive be set, as some errors can occur before execution of your script begins.
[!NOTE]
In a development environment,
error_reporting should always be set to
E_ALL so that issues raised by PHP are noticed and fixed. In production, the level of verbosity can be reduced to
E_ALL ENTITY ~E_NOTICE ENTITY ~E_DEPRECATED, although in many cases
E_ALL is still appropriate, as it may provide early warning of potential issues.
What happens to the diagnostics depends on two further ENTITY directives.
display_errors controls whether the diagnostic is shown as part of the script's output. This should always be disabled in a production environment, as the output 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 diagnostics when the
log_errors directive is enabled. This will log any diagnostic to the file or syslog defined by
error_log. This can be extremely useful in a production environment, as diagnostics are logged when they occur, and reports can then be generated from those logs.
Individual diagnostics can be suppressed using the
@ operator.
[!WARNING]
Prior to PHP 8.0.0, it was possible to suppress critical diagnostics that would terminate the execution of the PHP script.
[!NOTE]
Between PHP versions, diagnostics may be added or removed, have their severity changed, or be elevated to Throwable errors.
User-defined diagnostic handler
If PHP's default diagnostic handling is inadequate, it is possible to override the default diagnostic handler with a custom one which is set using
set_error_handler. Some diagnostics, such as
E_ERROR and
E_PARSE, cannot be handled this way (see
set_error_handler for the full list). The others can be handled in various ways. For example, a custom handler can show an error page to the user and report the error more directly than a log would, such as by sending an email.
Another typical usage is to elevate diagnostic errors to exceptions with ErrorException.
Elevating diagnostic errors to exceptions
Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing
$c = foo() is essentially just like writing
$c = 5, and you're right. Functions are expressions with the value of their return value. Since
foo() returns 5, the value of the expression '
foo()' is 5. Usually functions don't just return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types:
int values, floating point values (
float),
string values and
bool values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.
PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with,
$a = 5. It's easy to see that there are two values involved here, the value of the integer constant
5, and the value of
$a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that
$a = 5, regardless of what it does, is an expression with the value 5. Thus, writing something like
$b = ($a = 5) is like writing
$a = 5; $b = 5; (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write
$b = $a = 5.
Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of
variable++ and
variable--. These are increment and decrement operators. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written
++$variable, evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written
$variable++ evaluates to the original value of
$variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').
A very common type of expressions are comparison expressions. These expressions evaluate to either ENTITY or ENTITY. PHP supports ENTITY (bigger than), ENTITY= (bigger than or equal to), == (equal), != (not equal), ENTITY (smaller than) and ENTITY= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as
if statements.
The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment
$a by 1, you can simply write
$a++ or
++$a. But what if you want to add more than one to it, for instance 3? You could write
$a++ multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write
$a = $a + 3.
$a + 3 evaluates to the value of
$a plus 3, and is assigned back into
$a, which results in incrementing
$a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of
$a can be written
$a += 3. This means exactly "take the value of
$a, add 3 to it, and assign it back into
$a". In addition to being shorter and clearer, this also results in faster execution. The value of
$a += 3, like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of
$a plus 3 (this is the value that's assigned into
$a). Any two-place operator can be used in this operator-assignment mode, for example
$a -= 5 (subtract 5 from the value of
$a),
$b *= 7 (multiply the value of
$b by 7), etc.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:
If the value of the first subexpression is ENTITY (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:
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 ENTITY or ENTITY. The constants ENTITY and ENTITY (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.
Fibers
Fibers overview
Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack, pausing execution within the fiber until the fiber is resumed at a later time.
Fibers pause the entire execution stack, so the direct caller of the function does not need to change how it invokes the function.
Execution may be interrupted anywhere in the call stack using Fiber::suspend (that is, the call to Fiber::suspend may be in a deeply nested function or not even exist at all).
Unlike stack-less
Generators, each
Fiber has its own call stack, allowing them to be paused within deeply nested function calls. A function declaring an interruption point (that is, calling Fiber::suspend) need not change its return type, unlike a function using ENTITY which must return a
Generator instance.
Fibers can be suspended in any function call, including those called from within the PHP VM, such as functions provided to
array_map or methods called by ENTITY on an
Iterator object.
Once suspended, execution of the fiber may be resumed with any value using Fiber::resume or by throwing an exception into the fiber using Fiber::throw. The value is returned (or exception thrown) from Fiber::suspend.
[!NOTE]
Prior to PHP 8.4.0, switching fibers during the execution of an object destructor was not allowed.
Basic usage
start();
echo "Value from fiber suspending: ", $value, PHP_EOL;
$fiber->resume('test');
?>
ENTITY
Value from fiber suspending: fiber
Value used to resume fiber: test
Functions
User-defined functions
A function is defined using the
function keyword, a name, a list of parameters (which might be empty) separated by commas (
,) enclosed in parentheses, followed by the body of the function enclosed in curly braces, such as the following:
Declaring a new function named
foo
brew();
}
echo makecoffee();
echo makecoffee(new FancyCoffeeMaker);
ENTITY
Making coffee.
Crafting a beautiful coffee just for you.
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
Note that any optional parameters should be specified after any required parameters, otherwise they cannot be omitted from calls. Consider the following example:
Incorrect usage of default function parameters
$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);
ENTITY
3 days
Fatal error: Uncaught TypeError: total_intervals(): Argument #2 must be of type DateInterval, null given, called in script on line 15 and defined in script:2
Stack trace:
#0 script(15): total_intervals('d', NULL)
#1 {main}
thrown in script on line 2
Finally, variable arguments can also be passed by reference by prefixing the
... with an ampersand (
ENTITY).
Named Arguments
PHP 8.0.0 introduced named arguments as an extension of the existing positional parameters. Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position. This makes the meaning of the argument self-documenting, makes the arguments order-independent and allows skipping default values arbitrarily.
Named arguments are passed by prefixing the value with the parameter name followed by a colon. Using reserved keywords as parameter names is allowed. The parameter name must be an identifier, specifying dynamically is not allowed.
Named argument syntax
2, 'a' => 1], d: 40)); // 46
var_dump(foo(...[1, 2], b: 20)); // Fatal error. Named parameter $b overwrites previous argument
Some internal functions document an alternative signature, such as
session_set_save_handler, whose parameter names do not exist in the function itself. These names cannot be used as named arguments and result in an error.
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 ENTITY will be returned.
Use of return
Use of
return
$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:
Variable method example with static properties
Variable() reading $variable in this scope.
ENTITY
static property
Method Variable called
Complex callables
string(5) "hello"
[1]=>
string(5) "world"
}
As of PHP 8.0.0, the list of scope-inherited variables may include a trailing comma, which will be ignored.
Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:
Closures and scoping
products[$product] = ($this->products[$product] ?? 0) + $quantity;
}
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
Automatic binding of
$this
testing();
$function();
ENTITY
object(Test)#1 (0) {
}
When declared in the context of a class, the current class is automatically bound to it, making
$this available inside of the function's scope. If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead.
Static anonymous functions
Anonymous functions may be declared statically. This prevents them from having the current class automatically bound to them. Objects may also not be bound to them at runtime.
Attempting to use
$this inside a static anonymous function
__construct()
#2 {main}
thrown in script on line 7
Attempting to bind an object to a static anonymous function
bindTo(new stdClass);
$func();
ENTITY
Warning: Cannot bind an instance to a static closure, this will be an error in PHP 9 in script on line 5
Fatal error: Uncaught Error: Value of type null is not callable in script:6
Stack trace:
#0 {main}
thrown in script on line 6
ENTITY
ENTITY
ENTITY
8.5.0
Closures can now be used in constant expressions (e.g. default property values, attribute parameters, constants).
8.3.0
Closures created from magic methods can accept named parameters.
7.1.0
Anonymous functions may not close over ENTITY,
$this, or any variable with the same name as a parameter.
ENTITY
[!NOTE]
It is possible to use
func_num_args,
func_get_arg, and
func_get_args from within a closure.
Arrow Functions
Arrow functions were introduced in PHP 7.4 as a more concise syntax for anonymous functions.
Both anonymous functions and arrow functions are implemented using the
Closure class.
Arrow functions have the basic form
fn (argument_list) =ENTITY expr.
Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic.
When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value. In the following example, the functions
$fn1 and
$fn2 behave the same way.
Arrow functions capture variables by value automatically
$x + $y;
// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
return $x + $y;
};
var_export($fn1(3));
ENTITY
4
This also works if the arrow functions are nested:
Arrow functions capture variables by value automatically, even when nested
fn($y) => $x * $y + $z;
// Outputs 51
var_export($fn(5)(10));
Similarly to anonymous functions, the arrow function syntax allows arbitrary function signatures, including parameter and return types, default values, variadics, as well as by-reference passing and returning. All of the following are valid examples of arrow functions:
Examples of arrow functions
$x;
static fn($x): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;
Arrow functions use by-value variable binding. This is roughly equivalent to performing a
use($x) for every variable
$x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope. Anonymous functions can be used instead for by-ref bindings.
Values from the outer scope cannot be modified by arrow functions
$x++; // Has no effect
$fn();
var_export($x); // Outputs 1
ENTITY
ENTITY
ENTITY
7.4.0
Arrow functions became available.
ENTITY
[!NOTE]
It is possible to use
func_num_args,
func_get_arg, and
func_get_args from within an arrow function.
First class callable syntax
The first class callable syntax is introduced as of PHP 8.1.0, as a way of creating anonymous functions from callable. It supersedes existing callable syntax using strings and arrays. The advantage of this syntax is that it is accessible to static analysis, and uses the scope at the point where the callable is acquired.
CallableExpr(...) syntax is used to create a
Closure object from callable.
CallableExpr accepts any expression that can be directly called in the PHP grammar:
Simple first class callable syntax
method(...);
$f4 = $obj->$methodStr(...);
$f5 = Foo::staticmethod(...);
$f6 = $classStr::$staticmethodStr(...);
// traditional callable using string, array
$f7 = 'strlen'(...);
$f8 = [$obj, 'method'](...);
$f9 = [Foo::class, 'staticmethod'](...);
[!NOTE]
The
... is part of the syntax, and not an omission.
CallableExpr(...) has the same semantics as Closure::fromCallable. That is, unlike callable using strings and arrays,
CallableExpr(...) respects the scope at the point where it is created:
Scope comparison of
CallableExpr(...) and traditional callable
getPrivateMethod();
$privateMethod();
// Fatal error: Call to private method Foo::privateMethod() from global scope
// This is because call is performed outside from Foo and visibility will be checked from this point.
privateMethod(...); // identical to Closure::fromCallable([$this, 'privateMethod']);
}
private function privateMethod() {
echo __METHOD__, "\n";
}
}
$foo1 = new Foo1;
$privateMethod = $foo1->getPrivateMethod();
$privateMethod(); // Foo1::privateMethod
[!NOTE]
Object creation by this syntax (e.g
new Foo(...)) is not supported, because
new Foo() syntax is not considered a call.
[!NOTE]
The first-class callable syntax cannot be combined with the nullsafe operator. Both of the following result in a compile-time error:
method(...);
$obj?->prop->method(...);
ENTITY
ENTITY
ENTITY
8.5.0
First-class callables can now be used in constant expressions (e.g. default property values, attribute parameters, constants).
Generators
Generators overview
Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the
Iterator interface.
A generator offers a convenient way to provide data to ENTITY loops without having to build an array in memory ahead of time, which may cause the program to exceed a memory limit or require a considerable amount of processing time to generate. Instead, a generator function can be used, which is the same as a normal function, except that instead of returning once, a generator can ENTITY as many times as it needs to in order to provide the values to be iterated over. Like with iterators, random data access is not possible.
A simple example of this is to reimplement the
range function as a generator. The standard
range function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling
range(0, 1000000) will result in well over 10 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.
Implementing
range as a generator
= 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 ";
}
ENTITY
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 ENTITYs as many values as it needs to. Any function containing ENTITY 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 ENTITY loop), PHP will call the object's iteration methods each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.
Once there are no more values to be yielded, then the generator can simply return, and the calling code continues just as if an array has run out of values.
[!NOTE]
A generator can return values, which can be retrieved using Generator::getReturn.
yield keyword
The heart of a generator function is the
yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
A simple example of yielding values
$fields;
}
}
foreach (input_parser($input) as $id => $fields) {
echo "$id:\n";
echo " $fields[0]\n";
echo " $fields[1]\n";
}
ENTITY
1:
PHP
Likes dollar signs
2:
Python
Likes whitespace
3:
Ruby
Likes blocks
Yielding null values
Yield can be called without an argument to yield a ENTITY value with an automatic key.
Yielding ENTITYs
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.
Yielding values by reference
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).'... ';
}
ENTITY
2... 1... 0...
Generator delegation via
yield from
Generator delegation allows you to yield values from another generator,
Traversable object, or
array by using the
yield from keyword. The outer generator will then yield all values from the inner generator, object, or array until that is no longer valid, after which execution will continue in the outer generator.
If a generator is used with
yield from, the
yield from expression will also return any value returned by the inner generator.
[!CAUTION]
yield from does not reset the keys. It preserves the keys returned by the
Traversable object, or
array. Thus some values may share a common key with another
yield or
yield from, which, upon insertion into an array, will overwrite former values with that key.
A common case where this matters is
iterator_to_array returning a keyed array by default, leading to possibly unexpected results.
iterator_to_array has a second parameter
preserve_keys which can be set to ENTITY to collect all the values while ignoring the keys returned by the
Generator.
yield from with
iterator_to_array
int(1)
[1]=>
int(4)
[2]=>
int(3)
}
Basic use of
yield from
getReturn();
ENTITY
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:
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.
ENTITY
Object Iteration
Namespaces
Namespaces overview
What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file
foo.txt can exist in both directory
/home/greg and in
/home/other, but two copies of
foo.txt cannot co-exist in the same directory. In addition, to access the
foo.txt file outside of the
/home/greg directory, we must prepend the directory name to the file name using the directory separator to get
/home/greg/foo.txt. This same principle extends to namespaces in the programming world.
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:
Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
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:
Namespace syntax example
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";
?>
ENTITY
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
Abstract method example
prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>
ENTITY
Mr. Pacman
Mrs. Pacwoman
Abstract property example
$value;
}
// This expands the visibility from protected to public, which is fine
public string $both;
}
?>
An abstract property on an abstract class may provide implementations for any hook, but must have either
get or
set declared but not defined (as in the example above).
Abstract property with hooks example
foo = $value;
}
}
}
?>
Anonymous classes
Anonymous classes are useful when simple, one-off objects need to be created.
setLogger(new Logger());
// Using an anonymous class
$util->setLogger(new class {
public function log($msg)
{
echo $msg;
}
});
They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:
num = $num;
}
use SomeTrait;
});
ENTITY
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:
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();
ENTITY
6
All objects created by the same anonymous class declaration are instances of that very class.
prefix . ' ' . $msg;
}
});
Autoloading Classes
Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
The
spl_autoload_register function registers any number of autoloaders, enabling classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.
Any class-like construct may be autoloaded the same way. That includes classes, interfaces, traits, and enumerations.
[!CAUTION]
Prior to PHP 8.0.0, it was possible to use
__autoload to autoload classes and interfaces. However, it is a less flexible alternative to
spl_autoload_register and
__autoload is deprecated as of PHP 7.2.0, and removed as of PHP 8.0.0.
[!NOTE]
spl_autoload_register may be called multiple times in order to register multiple autoloaders. Throwing an exception from an autoload function, however, will interrupt that process and not allow further autoload functions to run. For that reason, throwing exceptions from an autoload function is strongly discouraged.
Autoload example
This example attempts to load the classes
MyClass1 and
MyClass2 from the files
MyClass1.php and
MyClass2.php respectively.
Autoload other example
This example attempts to load the interface
ITest.
Using Composer's autoloader
ENTITY generates a
vendor/autoload.php which is set up to automatically load packages that are being managed by Composer. By including this file, those packages can be used without any additional work.
", $uuid->toString(), "\n";
?>
ENTITY
unserialize, unserialize_callback_func, unserialize_max_depth,
spl_autoload_register,
spl_autoload,
__autoload
The Basics
class
Basic class definitions begin with the keyword
class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.
The class name can be any valid label, provided it is not a PHP reserved word. As of PHP 8.4.0, using a single underscore
_ as a class name is deprecated. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus:
^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
Simple Class definition
var;
}
}
?>
The pseudo-variable
$this is available when a method is called from within an object context.
$this is the value of the calling object.
[!WARNING]
Calling a non-static method statically throws an
Error. Prior to PHP 8.0.0, this would generate a deprecation notice, and
$this would be undefined.
Some examples of the
$this pseudo-variable
foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
ENTITY
$this is defined (A)
Deprecated: Non-static method A::foo() should not be called statically in %s on line 27
$this is not defined.
Deprecated: Non-static method A::foo() should not be called statically in %s on line 20
$this is not defined.
Deprecated: Non-static method B::bar() should not be called statically in %s on line 32
Deprecated: Non-static method A::foo() should not be called statically in %s on line 20
$this is not defined.
ENTITY
$this is defined (A)
Fatal error: Uncaught Error: Non-static method A::foo() cannot be called statically in %s :27
Stack trace:
#0 {main}
thrown in %s on line 27
Readonly classes
As of PHP 8.2.0, a class can be marked with the readonly modifier. Marking a class as readonly will add the readonly modifier to every declared property, and prevent the creation of dynamic properties. Moreover, it is impossible to add support for them by using the
AllowDynamicProperties attribute. Attempting to do so will trigger a compile-time error.
As neither untyped nor static properties can be marked with the
readonly modifier, readonly classes cannot declare them either:
A readonly class can be extended if, and only if, the child class is also a readonly class.
new
To create an instance of a class, the
new keyword must be used. An object will always be created unless the object has a constructor defined that throws an Exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
If a variable containing a
string with the name of a class is used with
new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.
[!NOTE]
If there are no arguments to be passed to the class's constructor, parentheses after the class name may be omitted.
Creating an instance
As of PHP 8.0.0, using
new with arbitrary expressions is supported. This allows more complex instantiation if the expression produces a
string. The expressions must be wrapped in parentheses.
Creating an instance using an arbitrary expression
In the given example we show multiple examples of valid arbitrary expressions that produce a class name. This shows a call to a function, string concatenation, and the
::class constant.
ENTITY
object(ClassA)#1 (0) {
}
object(ClassB)#1 (0) {
}
object(ClassC)#1 (0) {
}
object(ClassD)#1 (0) {
}
In the class context, it is possible to create a new object by
new self and
new parent.
When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.
Object Assignment
var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
ENTITY
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
It's possible to create instances of an object in a couple of ways:
Creating new objects
ENTITY
bool(true)
bool(true)
bool(true)
It is possible to access a member of a newly created object in a single expression:
Access member of newly created object
format('Y'), PHP_EOL;
// surrounding parentheses are optional as of PHP 8.4.0
echo new DateTime()->format('Y'), PHP_EOL;
?>
ENTITY
2025
2025
[!NOTE]
Prior to PHP 7.1, the arguments are not evaluated if there is no constructor function defined.
Properties and methods
Class properties and methods live in separate "namespaces", so it is possible to have a property and a method with the same name. Referring to both a property and a method has the same notation, and whether a property will be accessed or a method will be called, solely depends on the context, i.e. whether the usage is a variable access or a function call.
Property access vs. method call
bar, PHP_EOL, $obj->bar(), PHP_EOL;
ENTITY
property
method
That means that calling an anonymous function which has been assigned to a property is not directly possible. Instead the property has to be assigned to a variable first, for instance. It is possible to call such a property directly by enclosing it in parentheses.
Calling an anonymous function stored in a property
bar = function() {
return 42;
};
}
}
$obj = new Foo();
echo ($obj->bar)(), PHP_EOL;
ENTITY
42
extends
A class can inherit the constants, methods, and properties of another class by using the keyword
extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.
The inherited constants, methods, and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method or constant as final, they may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.
[!NOTE]
As of PHP 8.1.0, constants may be declared as final.
Simple Class Inheritance
displayVar();
?>
ENTITY
Extending class
Parent class
Signature compatibility rules
When overriding a method, its signature must be compatible with the parent method. Otherwise, a fatal error is emitted, or, prior to PHP 8.0.0, an
E_WARNING level error is generated. A signature is compatible if it respects the variance rules, makes a mandatory parameter optional, adds only optional new parameters and doesn't restrict but only relaxes the visibility. This is known as the Liskov Substitution Principle, or LSP for short. The constructor, and
private methods are exempt from these signature compatibility rules, and thus won't emit a fatal error in case of a signature mismatch.
Compatible child methods
foo();
$extended2 = new Extend2();
$extended2->foo(1);
ENTITY
Valid
Valid
The following examples demonstrate that a child method which removes a parameter, or makes an optional parameter mandatory, is not compatible with the parent method.
Fatal error when a child method removes a parameter
test(foo: "foo", bar: "bar"); // ERROR!
ENTITY
Fatal error: Uncaught Error: Unknown named parameter $foo in /in/XaaeN:14
Stack trace:
#0 {main}
thrown in /in/XaaeN on line 14
::class
The
class keyword is also used for class name resolution. To obtain the fully qualified name of a class
ClassName use
ClassName::class. This is particularly useful with namespaced classes.
Class name resolution
ENTITY
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.
Missing class name resolution
ENTITY
Does\Not\Exist
As of PHP 8.0.0,
::class may also be used on objects. This resolution happens at runtime, not compile time. Its effect is the same as calling
get_class on the object.
Object name resolution
ENTITY
NS\ClassName
Nullsafe methods and properties
As of PHP 8.0.0, properties and methods may also be accessed with the "nullsafe" operator instead:
?->. The nullsafe operator works the same as property or method access as above, except that if the object being dereferenced is ENTITY then ENTITY will be returned rather than an exception thrown. If the dereference is part of a chain, the rest of the chain is skipped.
The effect is similar to wrapping each access in an
is_null check first, but more compact.
Nullsafe Operator
getUser(5)?->name;
// Is equivalent to the following code block:
if (is_null($repository)) {
$result = null;
} else {
$user = $repository->getUser(5);
if (is_null($user)) {
$result = null;
} else {
$result = $user->name;
}
}
?>
[!NOTE]
The nullsafe operator is best used when null is considered a valid and expected possible value for a property or method return. For indicating an error, a thrown exception is preferable.
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.
ENTITY
ENTITY
8.5.0
Changed: A method that returns
static may now be overridden in a final class to declare
self or the class's own type as its return type, as these are equivalent to
static in a class that cannot be extended further.
8.5.0
Changed: Traits are now bound to a class before its parent class.
8.4.0
Added: Support for Property Hooks.
8.4.0
Added: Support for Lazy Objects.
8.1.0
Added: Support for the final modifier for class constants. Also, interface constants become overridable by default.
8.0.0
Added: Support for the nullsafe operator ?-ENTITY to access properties and methods on objects that may be null.
7.4.0
Changed: It is now possible to throw an 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-ENTITY 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 ENTITY.
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 ENTITY will now have the same behaviour as iterating over by-reference ENTITYs.
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 provision. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.
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 ENTITY context (e.g. in
printf with
%s modifier) but not in other type contexts (e.g. with
%d modifier). As of PHP 5.2.0, converting ENTITYs without a __toString method to ENTITY 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.
Object Cloning
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.
An object copy is created by using the
clone keyword (which calls the object's __clone() method if possible).
$copy_of_object = clone $object;
When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.
void
__clone
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 to be changed.
Cloning an object
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);
?>
ENTITY
Original Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 1
)
[object2] => SubObject Object
(
[instance] => 2
)
)
Cloned Object:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
)
[object2] => SubObject Object
(
[instance] => 2
)
)
It is possible to access a member of a freshly cloned object in a single expression:
Access member of freshly cloned object
format('Y');
?>
ENTITY
2016
Cloning with property overrides
As of PHP 8.5.0,
clone is also available as a function, whose second parameter
withProperties takes an array mapping property names to the values the copy receives. Only the listed properties are overridden, every other property keeps the value it was copied with.
The overrides are applied after __clone() has run, and they honour the visibility of all properties. Readonly properties can be updated on the copy even if they were already set on the original object, which makes the function suited to methods returning a modified copy.
Cloning an object with property overrides
$x]);
}
}
$p = new Point(1, 2);
$q = $p->withX(10);
echo $q->x, ' ', $q->y;
?>
ENTITY
10 2
Class Constants
It is possible to define constants on a per-class basis. The default visibility of class constants is
public.
[!NOTE]
Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final.
It's also possible for interfaces to have constants. Look at the interface documentation for examples.
It's possible to reference the class using a variable. The variable's value can not be a keyword (e.g.
self,
parent and
static).
Note that class constants are allocated once per class, and not for each class instance.
As of PHP 8.3.0, class constants can have a scalar type such as
bool,
int,
float,
string, or even
array. When using
array, the contents can only be other scalar types.
Defining and using a constant
showConstant();
echo $class::CONSTANT."\n";
?>
The special
::class constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:
Namespaced ::class example
Class constant expression example
Class constant visibility modifiers, as of PHP 7.1.0
ENTITY
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.
Class constant visibility variance check, as of PHP 8.3.0
ENTITY
Fatal error: Access level to MyClass::VALUE must be public (as in interface MyInterface) …
[!NOTE]
As of PHP 8.3.0 visibility variance is checked more strictly. Prior to this version, the visibility of a class constant could be different from the visibility of the constant in the implemented interface.
Fetch class constant syntax, as of PHP 8.3.0
[!NOTE]
As of PHP 8.3.0, class constants can be fetched dynamically using a variable.
Assigning types to class constants, as of PHP 8.3.0
ENTITY
bool(true)
int(1)
float(1.01)
string(3) "one"
array(4) {
[0]=>
bool(true)
[1]=>
int(1)
[2]=>
float(1.01)
[3]=>
string(3) "one"
}
Constructors and Destructors
Constructor
void
__construct
mixed
values
""
PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
[!NOTE]
Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to
parent::__construct within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
Constructors in inheritance
Unlike other methods, __construct() is exempt from the usual signature compatibility rules when being extended.
Constructors are ordinary methods which are called during the instantiation of their corresponding object. As such, they may define an arbitrary number of arguments, which may be required, may have a type, and may have a default value. Constructor arguments are called by placing the arguments in parentheses after the class name.
Using constructor arguments
x = $x;
$this->y = $y;
}
}
// Pass both parameters.
$p1 = new Point(4, 5);
// Pass only the required parameter. $y will take its default value of 0.
$p2 = new Point(4);
// With named parameters (as of PHP 8.0):
$p3 = new Point(y: 5, x: 4);
?>
If a class has no constructor, or the constructor has no required arguments, the parentheses may be omitted.
Old-style constructors
Prior to PHP 8.0.0, classes in the global namespace will interpret a method named the same as the class as an old-style constructor. That syntax is deprecated, and will result in an
E_DEPRECATED error but still call that function as a constructor. If both __construct() and a same-name method are defined, __construct() will be called.
In namespaced classes, or any class as of PHP 8.0.0, a method named the same as the class never has any special meaning.
Always use __construct() in new code.
Constructor Promotion
As of PHP 8.0.0, constructor parameters may also be promoted to correspond to an object property. It is very common for constructor parameters to be assigned to a property in the constructor but otherwise not operated upon. Constructor promotion provides a short-hand for that use case. The example above could be rewritten as the following.
Using constructor property promotion
Static creation methods
PHP only supports a single constructor per class. In some cases, however, it may be desirable to allow an object to be constructed in different ways with different inputs. The recommended way to do so is by using static methods as constructor wrappers.
Using static creation methods
1005Elephpant";
class Product {
private ?int $id;
private ?string $name;
private function __construct(?int $id = null, ?string $name = null) {
$this->id = $id;
$this->name = $name;
}
public static function fromBasicData(int $id, string $name): static {
$new = new static($id, $name);
return $new;
}
public static function fromJson(string $json): static {
$data = json_decode($json, true);
return new static($data['id'], $data['name']);
}
public static function fromXml(string $xml): static {
$data = simplexml_load_string($xml);
$new = new static();
$new->id = (int) $data->id;
$new->name = $data->name;
return $new;
}
}
$p1 = Product::fromBasicData(5, 'Widget');
$p2 = Product::fromJson($some_json_string);
$p3 = Product::fromXml($some_xml_string);
var_dump($p1, $p2, $p3);
The constructor may be made private or protected to prevent it from being called externally. If so, only a static method will be able to instantiate the class. Because they are in the same class definition they have access to private methods, even if not of the same object instance. The private constructor is optional and may or may not make sense depending on the use case.
The three public static methods then demonstrate different ways of instantiating the object.
fromBasicData()
takes the exact parameters that are needed, then creates the object by calling the constructor and returning the result.
fromJson()
accepts a JSON string and does some pre-processing on it itself to convert it into the format desired by the constructor. It then returns the new object.
fromXml()
accepts an XML string, preprocesses it, and then creates a bare object. The constructor is still called, but as all of the parameters are optional the method skips them. It then assigns values to the object properties directly before returning the result.
In all three cases, the
static keyword is translated into the name of the class the code is in. In this case,
Product.
Destructor
void
__destruct
PHP possesses a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
Destructor Example
Final class example
Final property example as of PHP 8.4.0
Final constants example as of PHP 8.1.0
[!NOTE]
As of PHP 8.0.0, private methods may not be declared final except for the constructor.
[!NOTE]
A property that is declared
private(set) is implicitly
final.
Object Inheritance
Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.
For example, when extending a class, the subclass inherits all of the public and protected methods, properties and constants from the parent class. Unless a class overrides those methods, they will retain their original functionality.
This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.
Private methods of a parent class are not accessible to a child class. As a result, child classes may reimplement a private method themselves without regard for normal inheritance rules. Prior to PHP 8.0.0, however,
final and
static restrictions were applied to private methods. As of PHP 8.0.0, the only private method restriction that is enforced is
private final constructors, as that is a common way to "disable" the constructor when using static factory methods instead.
The visibility of methods, properties and constants can be relaxed, e.g. a
protected method can be marked as
public, but they cannot be restricted, e.g. marking a
public property as
private. One exception is constructors, whose visibility can be restricted, e.g. a
public constructor can be marked as
private in a child class.
[!NOTE]
Unless autoloading is used, the classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.
[!NOTE]
It is not allowed to override a read-write property with a readonly property or vice versa.
readonly
public readonly int $prop;
}
?>
Inheritance Example
printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP(); // Output: 'PHP is great.'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP(); // Output: 'PHP is great.'
?>
Return Type Compatibility with Internal Classes
Prior to PHP 8.1, most internal classes or methods didn't declare their return types, and any return type was allowed when extending them.
As of PHP 8.1.0, most internal methods started to "tentatively" declare their return type, in that case the return type of methods should be compatible with the parent being extended; otherwise, a deprecation notice is emitted. Note that lack of an explicit return declaration is also considered a signature mismatch, and thus results in the deprecation notice.
If the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a
ReturnTypeWillChange attribute can be added to silence the deprecation notice.
The overriding method does not declare any return type
The overriding method declares a wrong return type
The overriding method declares a wrong return type without a deprecation notice
Object Interfaces
Object interfaces allow you to create code which specifies which methods and properties a class must implement, without having to define how these methods or properties are implemented. Interfaces share a namespace with classes, traits, and enumerations, so they may not use the same name.
Interfaces are defined in the same way as a class, but with the
interface keyword replacing the
class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.
In practice, interfaces serve two complementary purposes:
To allow developers to create objects of different classes that may be used interchangeably because they implement the same interface or interfaces. A common example is multiple database access services, multiple payment gateways, or different caching strategies. Different implementations may be swapped out without requiring any changes to the code that uses them.
To allow a function or method to accept and operate on a parameter that conforms to an interface, while not caring what else the object may do or how it is implemented. These interfaces are often named like
Iterable
,
Cacheable
,
Renderable
, and so on to describe the significance of the behavior.
Interfaces may define magic methods to require implementing classes to implement those methods.
[!NOTE]
Although they are supported, including constructors in interfaces is strongly discouraged. Doing so significantly reduces the flexibility of the object implementing the interface. Additionally, constructors are not enforced by inheritance rules, which can cause inconsistent and unexpected behavior.
implements
To implement an interface, the
implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
[!WARNING]
A class that implements an interface may use a different name for its parameters than the interface. However, as of PHP 8.0 the language supports named arguments, which means callers may rely on the parameter name in the interface. For that reason, it is strongly recommended that developers use the same parameter names as the interface being implemented.
[!NOTE]
Interfaces can be extended like classes using the extends operator.
[!NOTE]
The class implementing the interface must declare all methods in the interface with a compatible signature. A class can implement multiple interfaces which declare a method with the same name. In this case, the implementation must follow the signature compatibility rules for all the interfaces. So covariance and contravariance can be applied.
Constants
It's possible for interfaces to have constants. Interface constants work exactly like class constants. Prior to PHP 8.1.0, they cannot be overridden by a class/interface that inherits them.
Properties
As of PHP 8.4.0, interfaces may also declare properties. If they do, the declaration must specify if the property is to be readable, writeable, or both. The interface declaration applies only to public read and write access.
A class may satisfy an interface property in multiple ways. It may define a public property. It may define a public virtual property that implements only the corresponding hook. Or a read property may be satisfied by a
readonly property. However, an interface property that is settable may not be
readonly.
Interface properties example
strtoupper($this->writeable); }
// The interface only requires the property be settable,
// but also including get operations is entirely valid.
// This example creates a virtual property, which is fine.
public string $writeable {
get => $this->written;
set {
$this->written = $value;
}
}
// This property requires both read and write be possible,
// so we need to either implement both, or allow it to have
// the default behavior.
public string $both {
get => $this->all;
set {
$this->all = strtoupper($value);
}
}
}
?>
ENTITY
Interface example
vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (Template::getHtml)
class BadTemplate implements Template
{
private $vars = [];
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
Extendable Interfaces
Variance compatibility with multiple interfaces
Multiple interface inheritance
Interfaces with constants
Interfaces with abstract classes
Extending and implementing simultaneously
An interface, together with type declarations, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type declarations.
Object Iteration
PHP provides a way for objects to be defined so it is possible to iterate through a list of items with, for example, a ENTITY statement. By default, all visible properties will be used for the iteration.
Simple Object Iteration
$value) {
print "$key => $value\n";
}
}
}
$class = new MyClass();
foreach($class as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$class->iterateVisible();
?>
ENTITY
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 ENTITY iterated through all of the visible properties that could be accessed.
ENTITY
Generators, Iterator, IteratorAggregate, SPL Iterators
Late Static Bindings
PHP implements a feature called late static bindings which can be used to reference the called class in the 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:
self:: usage
ENTITY
A
Late Static Bindings' usage
Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow referencing
B from
test() in the previous example. It was decided not to introduce a new keyword but rather use
static that was already reserved.
static:: simple usage
ENTITY
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.
static:: usage in a non-static context
foo();
static::foo();
}
}
class B extends A
{
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
class C extends A
{
private function foo()
{
/* Original method is replaced; the scope of the new one is C */
}
}
$b = new B();
$b->test();
$c = new C();
try {
$c->test();
} catch (Error $e) {
echo $e->getMessage();
}
?>
ENTITY
Success!
Success!
Success!
Call to private method C::foo() from scope A
[!NOTE]
Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like
parent:: or
self:: will forward the calling information.
Forwarding and non-forwarding calls
ENTITY
A
C
C
Lazy Objects
A lazy object is an object whose initialization is deferred until its state is observed or modified. Some use-case examples include dependency injection components that provide lazy services fully initialized only if needed, ORMs providing lazy entities that hydrate themselves from the database only when accessed, or a JSON parser that delays parsing until elements are accessed.
Two lazy object strategies are supported: Ghost Objects and Virtual Proxies, hereafter referred to as ENTITYlazy ghostsENTITY and ENTITYlazy proxiesENTITY. In both strategies, the lazy object is attached to an initializer or factory that is called automatically when its state is observed or modified for the first time. From an abstraction point of view, lazy ghost objects are indistinguishable from non-lazy ones: they can be used without knowing they are lazy, allowing them to be passed to and used by code that is unaware of laziness. Lazy proxies are similarly transparent, but care must be taken when their identity is used, as the proxy and its real instance have different identities.
[!NOTE]
Lazy objects were introduced in PHP 8.4.
Creating Lazy Objects
It is possible to create a lazy instance of any user defined class or the
stdClass class (other internal classes are not supported), or to reset an instance of these classes to make it lazy. The entry points for creating a lazy object are the ReflectionClass::newLazyGhost and ReflectionClass::newLazyProxy methods.
Both methods accept a function that is called when the object requires initialization. The function's expected behavior varies depending on the strategy in use, as described in the reference documentation for each method.
Creating a Lazy Ghost
newLazyGhost(function (Example $object) {
// Initialize object in-place
$object->__construct(1);
});
var_dump($lazyObject);
var_dump(get_class($lazyObject));
// Triggers initialization
var_dump($lazyObject->prop);
?>
ENTITY
lazy ghost object(Example)#3 (0) {
["prop"]=>
uninitialized(int)
}
string(7) "Example"
Example::__construct
int(1)
Creating a Lazy Proxy
newLazyProxy(function (Example $object) {
// Create and return the real instance
return new Example(1);
});
var_dump($lazyObject);
var_dump(get_class($lazyObject));
// Triggers initialization
var_dump($lazyObject->prop);
?>
ENTITY
lazy proxy object(Example)#3 (0) {
["prop"]=>
uninitialized(int)
}
string(7) "Example"
Example::__construct
int(1)
Any access to properties of a lazy object triggers its initialization (including via
ReflectionProperty). However, certain properties might be known in advance and should not trigger initialization when accessed:
Initializing Properties Eagerly
newLazyGhost(function ($post) {
$data = fetch_from_store($post->id);
$post->__construct($data['id'], $data['title'], $data['content']);
});
// Without this line, the following call to ReflectionProperty::setValue() would
// trigger initialization.
$reflector->getProperty('id')->skipLazyInitialization($post);
$reflector->getProperty('id')->setValue($post, 123);
// Alternatively, one can use this directly:
$reflector->getProperty('id')->setRawValueWithoutLazyInitialization($post, 123);
// The id property can be accessed without triggering initialization
var_dump($post->id);
?>
The ReflectionProperty::skipLazyInitialization and ReflectionProperty::setRawValueWithoutLazyInitialization methods offer ways to bypass lazy-initialization when accessing a property.
About Lazy Object Strategies
Lazy ghosts are objects that initialize in-place and, once initialized, are indistinguishable from an object that was never lazy. This strategy is suitable when we control both the instantiation and initialization of the object, making it unsuitable if either of these is managed by another party.
Lazy proxies, once initialized, act as proxies to a real instance: any operation on an initialized lazy proxy is forwarded to the real instance. The creation of the real instance can be delegated to another party, making this strategy useful in cases where lazy ghosts are unsuitable. Although lazy proxies are nearly as transparent as lazy ghosts, caution is needed when their identity is used, as the proxy and its real instance have distinct identities.
Lifecycle of Lazy Objects
Objects can be made lazy at instantiation time using ReflectionClass::newLazyGhost or ReflectionClass::newLazyProxy, or after instantiation by using ReflectionClass::resetAsLazyGhost or ReflectionClass::resetAsLazyProxy. Following this, a lazy object can become initialized through one of the following operations:
Interacting with the object in a way that triggers automatic initialization. See
Initialization triggers
.
Marking all its properties as non-lazy using
ReflectionProperty::skipLazyInitialization
or
ReflectionProperty::setRawValueWithoutLazyInitialization
.
Calling explicitly
ReflectionClass::initializeLazyObject
or
ReflectionClass::markLazyObjectAsInitialized
.
As lazy objects become initialized when all their properties are marked non-lazy, the above methods will not mark an object as lazy if no properties could be marked as lazy.
Initialization Triggers
Lazy objects are designed to be fully transparent to their consumers, so normal operations that observe or modify the object's state will automatically trigger initialization before the operation is performed. This includes, but is not limited to, the following operations:
Reading or writing a property.
Testing if a property is set or unsetting it.
Accessing or modifying a property via
ReflectionProperty::getValue
,
ReflectionProperty::getRawValue
,
ReflectionProperty::setValue
, or
ReflectionProperty::setRawValue
.
Listing properties with
ReflectionObject::getProperties
,
ReflectionObject::getProperty
,
get_object_vars
.
Iterating over properties of an object that does not implement
Iterator
or
IteratorAggregate
using
foreach
.
Serializing the object with
serialize
,
json_encode
, etc.
Cloning
the object.
Method calls that do not access the object state will not trigger initialization. Similarly, interactions with the object that invoke magic methods or hook functions will not trigger initialization if these methods or functions do not access the object's state.
Non-Triggering Operations
The following specific methods or low-level operations allow access or modification of lazy objects without triggering initialization:
Marking properties as non-lazy with
ReflectionProperty::skipLazyInitialization
or
ReflectionProperty::setRawValueWithoutLazyInitialization
.
Retrieving the internal representation of properties using
get_mangled_object_vars
or by
casting the object to an array
.
Using
serialize
when
ReflectionClass::SKIP_INITIALIZATION_ON_SERIALIZE
is set, unless
__serialize()
or
__sleep()
trigger initialization.
Calling
ReflectionObject::__toString
.
Using
var_dump
or
debug_zval_dump
, unless
__debugInfo()
triggers initialization.
Initialization Sequence
This section outlines the sequence of operations performed when initialization is triggered, based on the strategy in use.
Ghost Objects
The object is marked as non-lazy.
Properties not initialized with
ReflectionProperty::skipLazyInitialization
or
ReflectionProperty::setRawValueWithoutLazyInitialization
are set to their default values, if any. At this stage, the object resembles one created with
ReflectionClass::newInstanceWithoutConstructor
, except for already initialized properties.
The initializer function is then called with the object as its first parameter. The function is expected, but not required, to initialize the object state, and must return ENTITY or no value. The object is no longer lazy at this point, so the function can access its properties directly.
After initialization, the object is indistinguishable from an object that was never lazy.
Proxy Objects
The object is marked as non-lazy.
Unlike ghost objects, the properties of the object are not modified at this stage.
The factory function is called with the object as its first parameter and must return a non-lazy instance of a compatible class (see
ReflectionClass::newLazyProxy
).
The returned instance is referred to as the
real instance
and is attached to the proxy.
The proxy's property values are discarded as though
unset
was called.
After initialization, accessing any property on the proxy will yield the same result as accessing the corresponding property on the real instance; all property accesses on the proxy are forwarded to the real instance, including declared, dynamic, non-existing, or properties marked with ReflectionProperty::skipLazyInitialization or ReflectionProperty::setRawValueWithoutLazyInitialization.
The proxy object itself is not replaced or substituted for the real instance.
While the factory receives the proxy as its first parameter, it is not expected to modify it (modifications are allowed but will be lost during the final initialization step). However, the proxy can be used for decisions based on the values of initialized properties, the class, the object itself, or its identity. For instance, the initializer might use an initialized property's value when creating the real instance.
Common Behavior
The scope and
$this context of the initializer or factory function remains unchanged, and usual visibility constraints apply.
After successful initialization, the initializer or factory function is no longer referenced by the object and may be released if it has no other references.
If the initializer throws an exception, the object state is reverted to its pre-initialization state and the object is marked as lazy again. In other words, all effects on the object itself are reverted. Other side effects, such as effects on other objects, are not reverted. This prevents exposing a partially initialized instance in case of failure.
Cloning
Cloning a lazy object triggers its initialization before the clone is created, resulting in an initialized object.
For proxy objects, both the proxy and its real instance are cloned, and the clone of the proxy is returned. The
__clone method is called on the real instance, not on the proxy. The cloned proxy and real instance are linked as they are during initialization, so accesses to the proxy clone are forwarded to the real instance clone.
This behavior ensures that the clone and the original object maintain separate states. Changes to the original object or its initializer's state after cloning do not affect the clone. Cloning both the proxy and its real instance, rather than returning a clone of the real instance alone, ensures that the clone operation consistently returns an object of the same class.
Destructors
For lazy ghosts, the destructor is only called if the object has been initialized. For proxies, the destructor is only called on the real instance, if one exists.
The ReflectionClass::resetAsLazyGhost and ReflectionClass::resetAsLazyProxy methods may invoke the destructor of the object being reset.
Magic Methods
Magic methods are special methods which override PHP's default action when certain actions are performed on an object.
[!CAUTION]
All method names starting with
__ are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.
The following method names are considered magical: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __serialize(), __unserialize(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __debugInfo().
[!WARNING]
All magic methods, with the exception of __construct(), __destruct(), and __clone(), must be declared as
public, otherwise an
E_WARNING is emitted. Prior to PHP 8.0.0, no diagnostic was emitted for the magic methods __sleep(), __wakeup(), __serialize(), __unserialize(), and __set_state().
[!WARNING]
If type declarations are used in the definition of a magic method, they must be identical to the signature described in this document. Otherwise, a fatal error is emitted. Prior to PHP 8.0.0, no diagnostic was emitted. However, __construct() and __destruct() must not declare a return type; otherwise a fatal error is emitted.
__serialize() and __unserialize()
public
array
__serialize
public
void
__unserialize
array
data
serialize checks if the class has a function with the magic name __serialize(). If so, that function is executed prior to any serialization. It must construct and return an associative array of key/value pairs that represent the serialized form of the object. If no array is returned a
TypeError will be thrown.
[!NOTE]
If both __serialize() and __sleep() are defined in the same object, only __serialize() will be called. __sleep() will be ignored. If the object implements the Serializable interface, the interface's
serialize() method will be ignored and __serialize() used instead.
The intended use of __serialize() is to define a serialization-friendly arbitrary representation of the object. Elements of the array may correspond to properties of the object but that is not required.
Conversely,
unserialize checks for the presence of a function with the magic name __unserialize(). If present, this function will be passed the restored array that was returned from __serialize(). It may then restore the properties of the object from that array as appropriate.
[!NOTE]
If both __unserialize() and __wakeup() are defined in the same object, only __unserialize() will be called. __wakeup() will be ignored.
[!NOTE]
This feature is available as of PHP 7.4.0.
Serialize and unserialize
dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
$this->link = new PDO($this->dsn, $this->username, $this->password);
}
public function __serialize(): array
{
return [
'dsn' => $this->dsn,
'user' => $this->username,
'pass' => $this->password,
];
}
public function __unserialize(array $data): void
{
$this->dsn = $data['dsn'];
$this->username = $data['user'];
$this->password = $data['pass'];
$this->connect();
}
}?>
__sleep() and __wakeup()
[!WARNING]
This serialization mechanism is soft-deprecated as of PHP 8.5.0. It is maintained for backward compatibility. However, new and existing code should be migrated to use the __serialize() and __unserialize() magic methods instead.
public
array
__sleep
public
void
__wakeup
serialize checks if the class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then ENTITY is serialized and
E_NOTICE is issued.
[!NOTE]
It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an
E_NOTICE level error. Use __serialize() instead.
[!NOTE]
As of PHP 8.0.0, returning a value which is not an array from __sleep() generates a warning. Previously, it generated a notice.
The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if a very large object doesn't need to be saved completely.
Conversely,
unserialize checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Sleep and wakeup
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
string
__toString
The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what
echo $obj; will print.
[!WARNING]
As of PHP 8.0.0, the return value follows standard PHP type semantics, meaning it will be coerced into a
string if possible and if strict typing is disabled.
A Stringable object will not be accepted by a
string type declaration if strict typing is enabled. If such behaviour is wanted the type declaration must accept Stringable and
string via a union type.
As of PHP 8.0.0, any class that contains a __toString() method will also implicitly implement the Stringable interface, and will thus pass type checks for that interface. Explicitly implementing the interface anyway is recommended.
In PHP 7.4, the returned value must be a
string, otherwise an
Error is thrown.
Prior to PHP 7.4.0, the returned value must be a
string, otherwise a fatal
E_RECOVERABLE_ERROR is emitted.
[!WARNING]
It was not possible to throw an exception from within a __toString() method prior to PHP 7.4.0. Doing so will result in a fatal error.
Simple example
foo = $foo;
}
public function __toString()
{
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
ENTITY
Hello
__invoke()
mixed
__invoke
values
The __invoke() method is called when a script tries to call an object as a function.
Using __invoke()
ENTITY
int(5)
bool(true)
Using __invoke()
key = $key;
}
public function __invoke(array $a, array $b): int
{
return $a[$this->key] <=> $b[$this->key];
}
}
$customers = [
['id' => 1, 'first_name' => 'John', 'last_name' => 'Do'],
['id' => 3, 'first_name' => 'Alice', 'last_name' => 'Gustav'],
['id' => 2, 'first_name' => 'Bob', 'last_name' => 'Filipe']
];
// sort customers by first name
usort($customers, new Sort('first_name'));
print_r($customers);
// sort customers by last name
usort($customers, new Sort('last_name'));
print_r($customers);
?>
ENTITY
Array
(
[0] => Array
(
[id] => 3
[first_name] => Alice
[last_name] => Gustav
)
[1] => Array
(
[id] => 2
[first_name] => Bob
[last_name] => Filipe
)
[2] => Array
(
[id] => 1
[first_name] => John
[last_name] => Do
)
)
Array
(
[0] => Array
(
[id] => 1
[first_name] => John
[last_name] => Do
)
[1] => Array
(
[id] => 2
[first_name] => Bob
[last_name] => Filipe
)
[2] => Array
(
[id] => 3
[first_name] => Alice
[last_name] => Gustav
)
)
__set_state()
static
object
__set_state
array
properties
This static method is called for classes exported by
var_export.
The only parameter of this method is an array containing exported properties in the form
['property' => value, ...].
Using __set_state()
var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
$b = var_export($a, true);
var_dump($b);
eval('$c = ' . $b . ';');
var_dump($c);
?>
ENTITY
string(60) "A::__set_state(array(
'var1' => 5,
'var2' => 'foo',
))"
object(A)#2 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
[!NOTE]
When exporting an object,
var_export does not check whether __set_state() is implemented by the object's class, so re-importing objects will result in an
Error exception, if __set_state() is not implemented. Particularly, this affects some internal classes.
It is the responsibility of the programmer to verify that only objects whose class implements __set_state will be re-imported.
__debugInfo()
array
__debugInfo
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.
As of PHP 8.5.0, returning ENTITY from __debugInfo() is deprecated. Return an empty
array instead.
Using __debugInfo()
prop = $val;
}
public function __debugInfo() {
return [
'propSquared' => $this->prop ** 2,
];
}
}
var_dump(new C(42));
?>
ENTITY
object(C)#1 (1) {
["propSquared"]=>
int(1764)
}
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 of object comparison
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);
?>
ENTITY
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 their own rules for comparing their objects (
==).
Overloading
Overloading in PHP provides means to dynamically “create” properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.
The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms “inaccessible properties” and “inaccessible methods” to refer to this combination of declaration and visibility.
All overloading methods must be defined as
public.
[!NOTE]
None of the arguments of these magic methods can be passed by reference.
[!NOTE]
PHP's interpretation of “overloading” is different than most object-oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.
Property overloading
public
void
__set
string
name
mixed
value
public
mixed
__get
string
name
public
bool
__isset
string
name
public
void
__unset
string
name
__set() is run when writing data to inaccessible (protected or private) or non-existing properties.
__get() is utilized for reading data from inaccessible (protected or private) or non-existing properties.
__isset() is triggered by calling
isset or
empty on inaccessible (protected or private) or non-existing properties.
__unset() is invoked when
unset is used on inaccessible (protected or private) or non-existing properties.
The
$name argument is the name of the property being interacted with. The __set() method's
$value argument specifies the value the
$name'ed property should be set to.
Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. A warning is issued if one of the magic overloading methods is declared
static.
[!NOTE]
The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignments together like this:
$a = $obj->b = 8;
[!NOTE]
PHP will not call an overloaded method from within the same overloaded method. That means, for example, writing
return $this->foo inside of __get() will return ENTITY and raise an
E_WARNING if there is no
foo property defined, rather than calling __get() a second time. However, overload methods may invoke other overload methods implicitly (such as __set() triggering __get()).
Overloading properties via the __get(), __set(), __isset() and __unset() methods
data[$name] = $value;
}
public function __get($name)
{
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
public function __isset($name)
{
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
public function __unset($name)
{
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}
/** Not a magic method, just here for example. */
public function getHidden()
{
return $this->hidden;
}
}
$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n\n";
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";
echo $obj->declared . "\n\n";
echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>
ENTITY
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 script on line 71 in script on line 27
Method overloading
public
mixed
__call
string
name
array
arguments
public static
mixed
__callStatic
string
name
array
arguments
__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.
Overloading methods via the __call() and __callStatic() methods
runTest('in object context');
MethodTest::runTest('in static context');
?>
ENTITY
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
Scope Resolution Operator (::)
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to a constant, static property, or static method of a class or one of its parents. Moreover, static properties or methods can be overridden via late static binding.
When referencing these items from outside the class definition, use the name of the class.
It's possible to reference the class using a variable. The variable's value can not be a keyword (e.g.
self,
parent and
static).
Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!
:: from outside the class definition
Three special keywords
self,
parent and
static are used to access properties or methods from inside the class definition.
:: from inside the class definition
When an extending class overrides the parent's definition of a method, PHP will not call the parent's method. It's up to the extended class whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.
Calling a parent's method
myFunc();
?>
See also some examples of static call trickery.
Properties
Class member variables are called properties. They may be referred to using other terms such as fields, but for the purposes of this reference properties will be used. They are defined by using at least one modifier (such as ???, ???, or, as of PHP 8.1.0, readonly), optionally (except for
readonly properties), as of PHP 7.4, followed by a type declaration, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value.
[!NOTE]
An obsolete way of declaring class properties is by using the
var keyword instead of a modifier.
[!NOTE]
A property declared without a ??? modifier will be declared as
public.
Within class methods non-static properties may be accessed by using
-ENTITY (Object Operator):
$this-ENTITYproperty (where
property is the name of the property). Static properties are accessed by using the
:: (Double Colon):
self::$property. See ??? for more information on the difference between static and non-static properties.
The pseudo-variable
$this is available inside any class method when that method is called from within an object context.
$this is the value of the calling object.
Property declarations
[!NOTE]
There are various functions to handle classes and objects. See the Class/Object Functions reference.
Type declarations
As of PHP 7.4.0, property definitions can include ???, with the exception of
callable.
Example of typed properties
id = $id;
$this->name = $name;
}
}
$user = new User(1234, null);
var_dump($user->id);
var_dump($user->name);
?>
ENTITY
int(1234)
NULL
Typed properties must be initialized before accessing, otherwise an
Error is thrown.
Accessing properties
numberOfSides = $numberOfSides;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getNumberOfSides(): int
{
return $this->numberOfSides;
}
public function getName(): string
{
return $this->name;
}
}
$triangle = new Shape();
$triangle->setName("triangle");
$triangle->setNumberOfSides(3);
var_dump($triangle->getName());
var_dump($triangle->getNumberOfSides());
$circle = new Shape();
$circle->setName("circle");
var_dump($circle->getName());
var_dump($circle->getNumberOfSides());
?>
ENTITY
string(8) "triangle"
int(3)
string(6) "circle"
Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization
Readonly properties
As of PHP 8.1.0, a property can be declared with the
readonly modifier, which prevents modification of the property after initialization. Prior to PHP 8.4.0 a
readonly property is implicitly private-set, and may only be written to from the same class. As of PHP 8.4.0,
readonly properties are implicitly
protected(set), so may be set from child classes. That may be overridden explicitly if desired.
Example of readonly properties
prop = $prop;
}
}
$test = new Test("foobar");
// Legal read.
var_dump($test->prop); // string(6) "foobar"
// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>
[!NOTE]
The readonly modifier can only be applied to typed properties. A readonly property without type constraints can be created using the ??? type.
[!NOTE]
Readonly static properties are not supported.
A readonly property can only be initialized once, and only from the scope where it has been declared. Any other assignment or modification of the property will result in an
Error exception.
Illegal initialization of readonly properties
prop = "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>
[!NOTE]
Readonly properties can only be initialized by a direct assignment. An uninitialized readonly property cannot be initialized by reference, not even from the scope where it has been declared: passing it to a function parameter that expects to be passed by reference, or assigning it by reference, results in an Error exception.
matches);
// Error: Cannot indirectly modify readonly property Test::$matches
}
}
new Test('abc 42');
?>
[!NOTE]
Specifying an explicit default value on readonly properties is not allowed, because a readonly property with a default value is essentially the same as a constant, and thus not particularly useful.
[!NOTE]
Readonly properties cannot be
unset once they are initialized. However, it is possible to unset a readonly property prior to initialization, from the scope where the property has been declared.
Modifications are not necessarily plain assignments, all of the following will also result in an
Error exception:
i += 1;
$test->i++;
++$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
unset($test->ary[0]);
$ref =& $test->i;
$test->i =& $ref;
byRef($test->i);
foreach ($test as &$prop);
?>
However, readonly properties do not preclude interior mutability. Objects (or resources) stored in readonly properties may still be modified internally:
obj->foo = 1;
// Illegal reassignment.
$test->obj = new stdClass;
?>
As of PHP 8.3.0, readonly properties can be reinitialized when cloning an object using the __clone() method.
Readonly properties and cloning
prop = null;
}
public function setProp(string $prop): void {
$this->prop = $prop;
}
}
$test1 = new Test1;
$test1->setProp('foobar');
$test2 = clone $test1;
var_dump($test2->prop); // NULL
?>
[!NOTE]
As of PHP 8.4.0, indirect modification of a readonly property within __clone(), such as acquiring a reference to it (
$ref = ENTITY$this->prop), is no longer allowed. This was already forbidden during readonly initialization.
Dynamic properties
If trying to assign to a non-existent property on an ENTITY, PHP will automatically create a corresponding property. This dynamically created property will only be available on this class instance.
Dynamic properties are supported by stdClass and its subclasses. Other classes may enable similar behavior with AllowDynamicProperties or property overloading.
[!WARNING]
Creating a dynamic property is deprecated as of PHP 8.2.0, unless the class is marked with the
#[\AllowDynamicProperties] attribute. It is recommended to declare the property instead. To handle arbitrary property names, the class should implement the magic methods __get() and __set(). Marking the class with the attribute remains an option, but is generally considered a last resort.
Property Hooks
Property hooks, also known as "property accessors" in some other languages, are a way to intercept and override the read and write behavior of a property. This functionality serves two purposes:
It allows for properties to be used directly, without get- and set- methods, while leaving the option open to add additional behavior in the future. That renders most boilerplate get/set methods unnecessary, even without using hooks.
It allows for properties that describe an object without needing to store a value directly.
There are two hooks available on non-static properties:
get and
set. They allow overriding the read and write behavior of a property, respectively. Hooks are available for both typed and untyped properties.
A property may be "backed" or "virtual". A backed property is one that actually stores a value. Any property that has no hooks is backed. A virtual property is one that has hooks and those hooks do not interact with the property itself. In this case, the hooks are effectively the same as methods, and the object does not use any space to store a value for that property.
Property hooks are incompatible with
readonly properties. If there is a need to restrict access to a
get or
set operation in addition to altering its behavior, use asymmetric property visibility.
[!NOTE]
Property hooks were introduced in PHP 8.4.
Basic Hook Syntax
The general syntax for declaring a hook is as follows.
Property hooks (full version)
modified) {
return $this->foo . ' (modified)';
}
return $this->foo;
}
set(string $value) {
$this->foo = strtolower($value);
$this->modified = true;
}
}
}
$example = new Example();
$example->foo = 'changed';
print $example->foo;
?>
The
$foo property ends in
{}, rather than a semicolon. That indicates the presence of hooks. Both a
get and
set hook are defined, although it is allowed to define only one or the other. Both hooks have a body, denoted by
{}, that may contain arbitrary code.
The
set hook additionally allows specifying the type and name of an incoming value, using the same syntax as a method. The type must be either the same as the type of the property, or contravariant (wider) to it. For instance, a property of type
string could have a
set hook that accepts
stringStringable, but not one that only accepts
array.
At least one of the hooks references
$this->foo, the property itself. That means the property will be "backed". When calling
$example->foo = 'changed', the provided string will be first cast to lowercase, then saved to the backing value. When reading from the property, the previously saved value may conditionally be appended with additional text.
There are a number of shorthand syntax variants as well to handle common cases.
If the
get hook is a single expression, then the
{} may be omitted and replaced with an arrow expression.
Property get expression
This example is equivalent to the previous.
$this->foo . ($this->modified ? ' (modified)' : '');
set(string $value) {
$this->foo = strtolower($value);
$this->modified = true;
}
}
}
?>
If the
set hook's parameter type is the same as the property type (which is typical), it may be omitted. In that case, the value to set is automatically given the name
$value.
Property set defaults
This example is equivalent to the previous.
$this->foo . ($this->modified ? ' (modified)' : '');
set {
$this->foo = strtolower($value);
$this->modified = true;
}
}
}
?>
If the
set hook is only setting a modified version of the passed in value, then it may also be simplified to an arrow expression. The value the expression evaluates to will be set on the backing value.
Property set expression
$this->foo . ($this->modified ? ' (modified)' : '');
set => strtolower($value);
}
}
?>
This example is not quite equivalent to the previous, as it does not also modify
$this->modified. If multiple statements are needed in the set hook body, use the braces version.
A property may implement zero, one, or both hooks as the situation requires. All shorthand versions are mutually-independent. That is, using a short-get with a long-set, a short-set with an explicit type, and so on is all valid.
On a backed property, omitting a
get or
set hook means the default read or write behavior will be used.
[!NOTE]
Hooks can be defined when using constructor property promotion. However, when doing so, values provided to the constructor must match the type associated with the property, regardless of what the
set hook might allow.
Consider the following:
created = $value;
}
},
) {
}
}
Internally, the engine decomposes this to the following:
created = $value;
}
}
public function __construct(
DateTimeInterface $created,
) {
$this->created = $created;
}
}
Any attempts to set the property outside the constructor will allow either
string or DateTimeInterface values, but the constructor will only allow DateTimeInterface. This is because the defined type for the property (DateTimeInterface) is used as the parameter type within the constructor signature, regardless of what the
set hook allows.
If this kind of behavior is needed from the constructor, constructor property promotion cannot be used.
Virtual properties
Virtual properties are properties that have no backing value. A property is virtual if neither its
get nor
set hook references the property itself using exact syntax. That is, a property named
$foo whose hook contains
$this->foo will be backed. But the following is not a backed property, and will error:
Invalid virtual property
$temp; // Doesn't refer to $this->foo, so it doesn't count.
}
}
}
?>
For virtual properties, if a hook is omitted then that operation does not exist and trying to use it will produce an error. Virtual properties take up no memory space in an object. Virtual properties are suited for "derived" properties, such as those that are the combination of two other properties.
Virtual property
$this->h * $this->w;
}
public function __construct(public int $h, public int $w) {}
}
$s = new Rectangle(4, 5);
print $s->area; // prints 20
$s->area = 30; // Error, as there is no set operation defined.
?>
Defining both a
get and
set hook on a virtual property is also allowed.
Scoping
All hooks operate in the scope of the object being modified. That means they have access to all public, private, or protected methods of the object, as well as any public, private, or protected properties, including properties that may have their own property hooks. Accessing another property from within a hook does not bypass the hooks defined on that property.
The most notable implication of this is that non-trivial hooks may sub-call to an arbitrarily complex method if they wish.
Calling a method from a hook
$this->sanitizePhone($value);
}
private function sanitizePhone(string $value): string {
$value = ltrim($value, '+');
$value = ltrim($value, '1');
if (!preg_match('/\d\d\d\-\d\d\d\-\d\d\d\d/', $value)) {
throw new \InvalidArgumentException();
}
return $value;
}
}
?>
References
Because the presence of hooks intercepts the read and write process for properties, they cause issues when acquiring a reference to a property or with indirect modification, such as
$this->arrayProp['key'] = 'value';. That is because any attempted modification of the value by reference would bypass a set hook, if one is defined.
In the rare case that getting a reference to a property that has hooks defined is necessary, the
get hook may be prefixed with
ENTITY to cause it to return by reference. Defining both
get and
ENTITYget on the same property is a syntax error.
Defining both
ENTITYget and
set hooks on a backed property is not allowed. As noted above, writing to the value returned by reference would bypass the
set hook. On virtual properties, there is no necessary common value shared between the two hooks, so defining both is allowed.
Writing to an index of an array property also involves an implicit reference. For that reason, writing to a backed array property with hooks defined is allowed if and only if it defines only a
ENTITYget hook. On a virtual property, writing to the array returned from either
get or
ENTITYget is legal, but whether that has any impact on the object depends on the hook implementation.
Overwriting the entire array property is fine, and behaves the same as any other property. Only working with elements of the array requires special care.
Inheritance
Final hooks
Hooks may also be declared final, in which case they may not be overridden.
Final hooks
strtolower($value);
}
}
class Manager extends User
{
public string $username {
// This is allowed
get => strtoupper($this->username);
// But this is NOT allowed, because set is final in the parent.
set => strtoupper($value);
}
}
?>
A property may also be declared final. A final property may not be redeclared by a child class in any way, which precludes altering hooks or widening its access.
Declaring hooks final on a property that is declared final is redundant, and will be silently ignored. This is the same behavior as final methods.
A child class may define or redefine individual hooks on a property by redefining the property and just the hooks it wishes to override. A child class may also add hooks to a property that had none. This is essentially the same as if the hooks were methods.
Hook inheritance
x = $value;
}
}
}
?>
Each hook overrides parent implementations independently of each other. If a child class adds hooks, any default value set on the property is removed, and must be redeclared. That is consistent with how inheritance works on hook-less properties.
Accessing parent hooks
A hook in a child class may access the parent class's property using the
parent::$prop keyword, followed by the desired hook. For example,
parent::$propName::get(). It may be read as "access the
prop defined on the parent class, and then run its get operation" (or set operation, as appropriate).
If not accessed this way, the parent class's hook is ignored. This behavior is consistent with how all methods work. This also offers a way to access the parent class's storage, if any. If there is no hook on the parent property, its default get/set behavior will be used. Hooks may not access any other hook except their own parent on their own property.
The example above could be rewritten as follows, which would allow for the
Point class to add its own
set hook in the future without issues (in the previous example, a hook added to the parent class would be ignored in the child).
Parent hook access (set)
An example of overriding only a get hook could be:
Parent hook access (get)
$this->uppercase
? strtoupper(parent::$val::get())
: strtolower(parent::$val::get());
}
}
?>
Serialization
PHP has a number of different ways in which an object may be serialized, either for public consumption or for debugging purposes. The behavior of hooks varies depending on the use case. In some cases, the raw backing value of a property will be used, bypassing any hooks. In others, the property will be read or written "through" the hook, just like any other normal read/write action.
var_dump
: Use raw value
serialize
: Use raw value
unserialize
: Use raw value
__serialize()
/
__unserialize()
: Custom logic, uses get/set hook
Array casting: Use raw value
var_export
: Use get hook
json_encode
: Use get hook
JsonSerializable
: Custom logic, uses get hook
get_object_vars
: Use get hook
get_mangled_object_vars
: Use raw value
Objects and references
One of the key-points of PHP OOP that is often mentioned is that "objects are passed by reference by default". This is not completely true. This section rectifies that general thought using some examples.
A PHP reference is an alias, which allows two different variables to write to the same value. In PHP, an object variable doesn't contain the object itself as value. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
References and Objects
$b->foo = 2;
echo $a->foo."\n";
$c = new A;
$d = &$c; // $c and $d are references
// ($c,$d) =
$d->foo = 2;
echo $c->foo."\n";
$e = new A;
function foo($obj) {
// ($obj) = ($e) =
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
ENTITY
2
2
2
Serializing objects - objects in sessions
serialize returns a string containing a byte-stream representation of any value that can be stored in PHP.
unserialize can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class.
In order to be able to
unserialize an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserialize an object of class A in another file, 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.
one;
}
}
// page1.php:
include "A.php";
$a = new A;
$s = serialize($a);
// store $s somewhere where page2.php can find it.
file_put_contents('store', $s);
// page2.php:
// this is needed for the unserialize to work properly.
include "A.php";
$s = file_get_contents('store');
$a = unserialize($s);
// now use the function show_one() of the $a object.
$a->show_one();
?>
It is strongly recommended that if an application serializes objects, for use later in the application, the application includes the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of
__PHP_Incomplete_Class_Name, which has no methods and would render the object useless.
So if in the example above
$a became part of a session by adding a new key to the
$_SESSION superglobal array, you should include the file
A.php on all of your pages, not only
page1.php and
page2.php.
Beyond the above advice, note that you can also hook into the serialization and unserialization events on an object using the __sleep() and __wakeup() methods. Using __sleep() also allows you to only serialize a subset of the object's properties.
Static Keyword
[!TIP]
This page describes the use of the
static keyword to define static methods and properties.
static can also be used to define static variables, define static anonymous functions and for late static bindings. Please refer to those pages for information on those meanings of
static.
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object.
Static methods
Because static methods are callable without an instance of the object created, the pseudo-variable
$this is not available inside methods declared as static.
[!WARNING]
Calling non-static methods statically throws an
Error.
Prior to PHP 8.0.0, calling non-static methods statically was deprecated, and generated an
E_DEPRECATED warning.
Static method example
Static properties
Static properties are accessed using the Scope Resolution Operator (
::) and cannot be accessed through the object operator (
-ENTITY).
It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g.
self,
parent and
static).
Static property example
staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n";
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
ENTITY
foo
foo
Notice: Accessing static property Foo::$my_static as non static in /in/V0Rvv on line 23
Warning: Undefined property: Foo::$my_static in /in/V0Rvv on line 23
foo
foo
foo
foo
Traits
PHP implements a way to reuse code called Traits.
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.
Trait example
sayHello();
echo ' ';
$this->sayWorld();
echo "!\n";
}
}
$myHelloWorld = new MyHelloWorld();
$myHelloWorld->sayHelloWorld();
?>
ENTITY
Hello World!
Precedence
An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.
[!NOTE]
As of PHP 8.5.0, traits are bound to a class before its parent class; previously they were bound after. This more closely reflects the copy and paste semantics of traits. In particular, when a trait and the parent class both declare a property or constant of the same name, the trait's definition now takes precedence over the inherited one, whereas earlier versions raised a fatal error about an incompatible composition. Method resolution is unaffected. See the migration guide for details.
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.
sayHello();
?>
ENTITY
Hello World!
Alternate Precedence Order Example
sayHello();
?>
ENTITY
Hello Universe!
Multiple Traits
Multiple Traits can be inserted into a class by listing them in the
use statement, separated by commas.
Multiple Traits Usage
sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>
ENTITY
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.
Conflict Resolution
In this example, Talker uses the traits A and B. Since A and B have conflicting methods, it specifies that it uses 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.
Changing Method Visibility
Using the
as syntax, one can also adjust the visibility of the method in the exhibiting class.
Changing Method Visibility
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.
Traits Composed from Traits
sayHello();
$o->sayWorld();
?>
ENTITY
Hello World!
Abstract Trait Members
Traits support the use of abstract methods in order to impose requirements upon the exhibiting class. Public, protected, and private methods are supported. Prior to PHP 8.0.0, only public and protected abstract methods were supported.
[!CAUTION]
As of PHP 8.0.0, the signature of a concrete method must follow the signature compatibility rules. Previously, its signature might be different.
Express Requirements by Abstract Methods
getWorld();
}
abstract public function getWorld();
}
class MyHelloWorld {
private $world;
use Hello;
public function getWorld() {
return $this->world;
}
public function setWorld($val) {
$this->world = $val;
}
}
?>
Static Trait Members
Traits can define static variables, static methods and static properties.
[!NOTE]
As of PHP 8.1.0, calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.
Static Variables
inc();
$p = new C2();
$p->inc();
?>
ENTITY
1
1
Static Methods
ENTITY
Doing something
Static Properties
[!CAUTION]
Prior to PHP 8.3.0, static properties defined in a trait were shared across all classes in the same inheritance hierarchy which used that trait. As of PHP 8.3.0, if a child class uses a trait with a static property, it will be considered distinct from the one defined in the parent class.
ENTITY
2
1
Properties
Traits can also define properties.
Defining Properties
x;
?>
If a trait defines a property then a class can not define a property with the same name unless it is compatible (same visibility and type, readonly modifier, and initial value), otherwise a fatal error is issued.
Conflict Resolution
ENTITY
Traits can, as of PHP 8.2.0, also define constants.
Defining Constants
ENTITY
1
If a trait defines a constant then a class can not define a constant with the same name unless it is compatible (same visibility, initial value, and finality), otherwise a fatal error is issued.
Conflict Resolution
Final methods
As of PHP 8.3.0, the final modifier can be applied using the
as operator to methods imported from traits. This can be used to prevent child classes from overriding the method. However, the class that uses the trait can still override the method.
Defining a method coming from a trait as
final
ENTITY
Fatal error: Cannot override final method FinalExampleA::method() in ...
Covariance and Contravariance
In PHP 7.2.0, partial contravariance was introduced by removing type restrictions on parameters in a child method. As of PHP 7.4.0, full covariance and contravariance support was added.
Covariance allows a child's method to return a more specific type than the return type of its parent's method. Contravariance allows a parameter type to be less specific in a child method, than that of its parent.
A type declaration is considered more specific in the following case:
A type is removed from a union type
A type is added to an intersection type
A class type is changed to a child class type
iterable is changed to
array or
Traversable
A type declaration is considered less specific if the opposite is true.
Covariance
To illustrate how covariance works, a simple abstract parent class,
Animal is created.
Animal will be extended by child classes,
Cat, and
Dog.
name = $name;
}
abstract public function speak();
}
class Dog extends Animal
{
public function speak()
{
echo $this->name . " barks";
}
}
class Cat extends Animal
{
public function speak()
{
echo $this->name . " meows";
}
}
Note that there aren't any methods which return values in this example. A few factories will be added which return a new object of class type
Animal,
Cat, or
Dog.
adopt("Ricky");
$kitty->speak();
echo "\n";
$doggy = (new DogShelter)->adopt("Mavrick");
$doggy->speak();
ENTITY
Ricky meows
Mavrick barks
[!NOTE]
As of PHP 8.5.0, when a parent method declares
static as its return type, an overriding method in a final class may declare
self or the class's own type as its return type instead, since these are equivalent to
static in a class that cannot be extended further. See the migration guide for details.
Contravariance
Continuing with the previous example with the classes
Animal,
Cat, and
Dog, a class called
Food and
AnimalFood will be included, and a method
eat(AnimalFood $food) is added to the
Animal abstract class.
name = $name;
}
public function eat(AnimalFood $food)
{
echo $this->name . " eats " . get_class($food);
}
}
In order to see the behavior of contravariance, the
eat method is overridden in the
Dog class to allow any
Food type object. The
Cat class remains unchanged.
name . " eats " . get_class($food);
}
}
The next example will show the behavior of contravariance.
adopt("Ricky");
$catFood = new AnimalFood();
$kitty->eat($catFood);
echo "\n";
$doggy = (new DogShelter)->adopt("Mavrick");
$banana = new Food();
$doggy->eat($banana);
ENTITY
Ricky eats AnimalFood
Mavrick eats Food
But what happens if
$kitty tries to eat the
$banana?
$kitty->eat($banana);
ENTITY
Fatal error: Uncaught TypeError: Argument 1 passed to Animal::eat() must be an instance of AnimalFood, instance of Food given
Property variance
By default, properties are neither covariant nor contravariant, hence invariant. That is, their type may not change in a child class at all. The reason for that is "get" operations must be covariant, and "set" operations must be contravariant. The only way for a property to satisfy both requirements is to be invariant.
As of PHP 8.4.0, with the addition of abstract properties (on an interface or abstract class) and virtual properties, it is possible to declare a property that has only a get or set operation. As a result, abstract properties or virtual properties that have only a "get" operation required may be covariant. Similarly, an abstract property or virtual property that has only a "set" operation required may be contravariant.
Once a property has both a get and set operation, however, it is no longer covariant or contravariant for further extension. That is, it is now invariant.
Property type variance
Visibility
The visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by prefixing the declaration with the keywords
public,
protected or
private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inheriting and parent classes. Members declared as private may only be accessed by the class that defines the member.
Property Visibility
Class properties may be defined as public, private, or protected. Properties declared without any explicit visibility keyword are defined as public.
Property declaration
public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected properties, but not private
public $public = 'Public2';
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public2, Protected2, Undefined
?>
Asymmetric Property Visibility
As of PHP 8.4, object properties may also have their visibility set asymmetrically, with a different scope for reading (
get) and writing (
set). Specifically, the
set visibility may be specified separately, provided it is not more permissive than the default visibility.
Asymmetric Property visibility
author = $author; // OK
$this->pubYear = $year; // Fatal Error
}
}
$b = new Book('How to PHP', 'Peter H. Peterson', 2024);
echo $b->title; // Works
echo $b->author; // Works
echo $b->pubYear; // Fatal Error
$b->title = 'How not to PHP'; // Fatal Error
$b->author = 'Pedro H. Peterson'; // Fatal Error
$b->pubYear = 2023; // Fatal Error
?>
As of PHP 8.5,
set visibility may also be applied to static properties of classes.
Asymmetric Static Property Visibility
doAThing(); // Works
echo Manager::$calls; // Works
Manager::$calls = 5; // Fatal error
?>
ENTITY
1
Fatal error: Uncaught Error: Cannot modify private(set) property Manager::$calls from global scope in /some/file.php
There are a few caveats regarding asymmetric visibility:
Only typed properties may have a separate
set visibility.
The
set visibility must be the same as
get or more restrictive. That is,
public protected(set) and
protected protected(set) are allowed, but
protected public(set) will cause a syntax error.
If a property is
public, then the main visibility may be omitted. That is,
public private(set) and
private(set) will have the same result.
A property with
private(set) visibility is automatically
final, and may not be redeclared in a child class.
Obtaining a reference to a property follows
set visibility, not
get. That is because a reference may be used to modify the property value.
Similarly, trying to write to an array property involves both a
get and
set operation internally, and therefore will follow the
set visibility, as that is always the more restrictive.
[!NOTE]
Spaces are not allowed in the set-visibility declaration.
private(set) is correct.
private( set ) is not correct and will result in a parse error.
When a class extends another, the child class may redefine any property that is not
final. When doing so, it may widen either the main visibility or the
set visibility, provided that the new visibility is the same or wider than the parent class. However, be aware that if a
private property is overridden, it does not actually change the parent's property but creates a new property with a different internal name.
Asymmetric Property inheritance
Method Visibility
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
Method Declaration
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.
Constant Declaration as of PHP 7.1.0
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.
Accessing private members of the same object type
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'));
?>
ENTITY
string(5) "hello"
Accessed the private method.
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.
There is a PECL extension that allows for overloading of some operators for objects. For more information, see the Operator Overloading for Objects section.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
Arithmetic Operators
Remember basic arithmetic from school? These work just like those.
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.
Arithmetic Operators
The division operator
/ returns a
float value unless the two operands are
int (or numeric strings which are type juggled to
int) and the numerator is a multiple of the divisor, in which case an integer value will be returned. For integer division, see
intdiv.
Operands of modulo are converted to
int before processing. For floating-point modulo, see
fmod.
The result of the modulo operator
% has the same sign as the dividend — that is, the result of
$a % $b will have the same sign as
$a. For example:
The Modulo Operator
ENTITY
int(2)
int(2)
int(-2)
int(-2)
ENTITY
Math functions
Array Operators
Example
Name
Result
$a + $b
Union
Union of
$a and
$b.
$a == $b
Equality
ENTITY if
$a and
$b have the same key/value pairs.
$a === $b
Identity
ENTITY if
$a and
$b have the same key/value pairs in the same order and of the same types.
$a != $b
Inequality
ENTITY if
$a is not equal to
$b.
$a ENTITYENTITY $b
Inequality
ENTITY if
$a is not equal to
$b.
$a !== $b
Non-identity
ENTITY if
$a is not identical to
$b.
Array Operators
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.
Array Append Operator
"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);
?>
ENTITY
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.
Comparing arrays
"banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
ENTITY
Array type, Array 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:
Nested Assignments
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:
Combined Assignments
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 = ENTITY$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.
Assigning by reference
The new operator returns a reference automatically, as such assigning the result of new by reference is an error.
new Operator By-Reference
ENTITY
Parse error: syntax error, unexpected token ";", expecting "("
More information on references and their potential uses can be found in the References Explained section of the manual.
Arithmetic Assignment Operators
Example
Equivalent
Operation
$a += $b
$a = $a + $b
Addition
$a -= $b
$a = $a - $b
Subtraction
$a *= $b
$a = $a * $b
Multiplication
$a /= $b
$a = $a / $b
Division
$a %= $b
$a = $a % $b
Modulus
$a **= $b
$a = $a ** $b
Exponentiation
Bitwise Assignment Operators
Example
Equivalent
Operation
$a ENTITY= $b
$a = $a ENTITY $b
Bitwise And
$a |= $b
$a = $a | $b
Bitwise Or
$a ^= $b
$a = $a ^ $b
Bitwise Xor
$a ENTITYENTITY= $b
$a = $a ENTITYENTITY $b
Left Shift
$a ENTITYENTITY= $b
$a = $a ENTITYENTITY $b
Right Shift
Other Assignment Operators
Example
Equivalent
Operation
$a .= $b
$a = $a . $b
String Concatenation
$a ??= $b
$a = $a ?? $b
Null Coalesce
ENTITY
arithmetic operators, bitwise operators, null coalescing operator
Bitwise Operators
Bitwise operators allow evaluation and manipulation of specific bits within an integer.
Example
Name
Result
$a ENTITY $b
And
Bits that are set in both
$a and
$b are set.
`$a
$b`
Or (inclusive or)
$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 ENTITYENTITY $b
Shift left
Shift the bits of
$a
$b steps to the left (each step means "multiply by two")
$a ENTITYENTITY $b
Shift right
Shift the bits of
$a
$b steps to the right (each step means "divide by two")
Bitwise Operators
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 ENTITY $b == true evaluates the equivalency then the bitwise and; while
($a ENTITY $b) == true evaluates the bitwise and then the equivalency.
If both operands for the
ENTITY,
| 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
ENTITYENTITY and
ENTITYENTITY 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 ENTITY ~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 (ENTITY) 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
Bitwise AND, OR and XOR operations on integers
ENTITY
--------- --------- -- ---------
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)
Bitwise XOR operations on strings
Bit shifting on integers
> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');
$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);
$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');
$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');
echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";
$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');
$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');
$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');
echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";
$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');
$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);
$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');
$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');
echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";
$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');
$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);
$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');
/*
* Ignore this bottom section,
* it is just formatting to make output clearer.
*/
function p($res, $val, $op, $places, $note = '') {
$format = '%0' . (PHP_INT_SIZE * 8) . "b\n";
printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);
echo " Decimal:\n";
printf(" val=%d\n", $val);
printf(" res=%d\n", $res);
echo " Binary:\n";
printf(' val=' . $format, $val);
printf(' res=' . $format, $res);
if ($note) {
echo " NOTE: $note\n";
}
echo "\n\n";
}
?>
ENTITY
--- 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
ENTITY
--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
Decimal:
val=4
res=2
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000010
NOTE: copy of sign bit shifted into left side
Expression: 1 = 4 >> 2
Decimal:
val=4
res=1
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000001
Expression: 0 = 4 >> 3
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out right side
Expression: 0 = 4 >> 4
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: same result as above; can not shift beyond 0
--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
Decimal:
val=-4
res=-2
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111110
NOTE: copy of sign bit shifted into left side
Expression: -1 = -4 >> 2
Decimal:
val=-4
res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111111
NOTE: bits shift out right side
Expression: -1 = -4 >> 3
Decimal:
val=-4
res=-1
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111111
NOTE: same result as above; can not shift beyond -1
--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
Decimal:
val=4
res=8
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000001000
NOTE: zeros fill in right side
Expression: 4611686018427387904 = 4 << 60
Decimal:
val=4
res=4611686018427387904
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0100000000000000000000000000000000000000000000000000000000000000
Expression: -9223372036854775808 = 4 << 61
Decimal:
val=4
res=-9223372036854775808
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=1000000000000000000000000000000000000000000000000000000000000000
NOTE: sign bits get shifted out
Expression: 0 = 4 << 62
Decimal:
val=4
res=0
Binary:
val=0000000000000000000000000000000000000000000000000000000000000100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out left side
--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
Decimal:
val=-4
res=-8
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1111111111111111111111111111111111111111111111111111111111111000
NOTE: zeros fill in right side
Expression: -9223372036854775808 = -4 << 61
Decimal:
val=-4
res=-9223372036854775808
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=1000000000000000000000000000000000000000000000000000000000000000
Expression: 0 = -4 << 62
Decimal:
val=-4
res=0
Binary:
val=1111111111111111111111111111111111111111111111111111111111111100
res=0000000000000000000000000000000000000000000000000000000000000000
NOTE: bits shift out left side, including sign bit
[!WARNING]
Use functions from the gmp extension for bitwise manipulation on numbers beyond
PHP_INT_MAX.
ENTITY
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.
Example
Name
Result
$a == $b
Equal
ENTITY if
$a is equal to
$b after type juggling.
$a === $b
Identical
ENTITY if
$a is equal to
$b, and they are of the same type.
$a != $b
Not equal
ENTITY if
$a is not equal to
$b after type juggling.
$a ENTITYENTITY $b
Not equal
ENTITY if
$a is not equal to
$b after type juggling.
$a !== $b
Not identical
ENTITY if
$a is not equal to
$b, or they are not of the same type.
$a ENTITY $b
Less than
ENTITY if
$a is strictly less than
$b.
$a ENTITY $b
Greater than
ENTITY if
$a is strictly greater than
$b.
$a ENTITY= $b
Less than or equal to
ENTITY if
$a is less than or equal to
$b.
$a ENTITY= $b
Greater than or equal to
ENTITY if
$a is greater than or equal to
$b.
$a ENTITY=ENTITY $b
Spaceship
An
int less than, equal to, or greater than zero when
$a is less than, equal to, or greater than
$b, respectively.
Comparison Operators
If both operands are numeric strings, or one operand is a number and the other one is a numeric string, then the comparison is done numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is
=== or
!== as this involves comparing the type as well as the value.
[!WARNING]
Prior to PHP 8.0.0, if a
string is compared to a number or a numeric string then the
string was converted to a number before performing the comparison. This can lead to surprising results as can be seen with the following example:
ENTITY
bool(true)
bool(true)
bool(true)
bool(true)
0
ENTITY
bool(false)
bool(true)
bool(true)
bool(true)
a
Comparison Operators
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).
Type of Operand 1
Type of Operand 2
Result
null or
string
string
Convert ENTITY to "", numerical or lexical comparison
bool or
null
anything
Convert both sides to
bool, ENTITY ENTITY ENTITY
object
object
Built-in classes can define its own comparison, different classes are incomparable, same class see Object Comparison
string,
resource,
int or
float
string,
resource,
int or
float
Translate strings and resources to numbers, usual math
array
array
Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are incomparable, otherwise - compare value by value (see following example)
object
anything
object is always greater
array
anything
array is always greater
Comparison with Various Types {#language.operators.comparison.types}
Boolean/null comparison
Transcription of standard array comparison
count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return 1;
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>
[!WARNING]
Because of the way
floats are represented internally, you should not test two
floats for equality.
See the documentation for
float for more information.
[!NOTE]
Be aware that PHP's type juggling is not always obvious when comparing values of different types, particularly comparing ENTITYs to ENTITYs or ENTITYs to ENTITYs. It is therefore generally advisable to use
=== and
!== comparisons rather than
== and
!= in most cases.
[!NOTE]
Encountering recursion during comparison, for example when comparing an array or object that contains a reference to itself, throws an Error as of PHP 8.4.0; previously, it resulted in a fatal error.
Incomparable Values
While identity comparison (
=== and
!==) can be applied to arbitrary values, the other comparison operators should only be applied to comparable values. The result of comparing incomparable values is undefined, and should not be relied upon.
[!NOTE]
As of PHP 8.5.0, loosely comparing an
object that is not comparable (such as an enum,
CurlHandle, or another internal class) against a
bool using
== or
!= consistently evaluates as if the object were cast to
bool, that is
(bool) $object. Because such an object always casts to ENTITY, it is equal to ENTITY and not equal to ENTITY. Prior to PHP 8.5.0, this only applied when comparing against a boolean literal (
$object == true); comparing against a boolean value held in a variable always returned ENTITY. See the migration guide for details.
ENTITY
strcasecmp,
strcmp, Array operators, Types
Ternary Operator
Another conditional operator is the "?:" (or ternary) operator.
Assigning a default value
The expression
(expr1) ? (expr2) : (expr3) evaluates to if evaluates to ENTITY, and if evaluates to ENTITY.
It is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3 evaluates to the result of if evaluates to ENTITY, and otherwise. is only evaluated once in this case.
[!NOTE]
Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement
return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.
[!NOTE]
It is recommended to avoid "stacking" ternary expressions. PHP's behaviour when using more than one unparenthesized ternary operator within a single expression is non-obvious compared to other languages. Indeed prior to PHP 8.0.0, ternary expressions were evaluated left-associative, instead of right-associative like most other programming languages. Relying on left-associativity is deprecated as of PHP 7.4.0. As of PHP 8.0.0, the ternary operator is non-associative.
Non-obvious Ternary Behaviour
[!NOTE]
Chaining of short-ternaries (
?:), however, is stable and behaves reasonably. It will evaluate to the first argument that evaluates to a non-falsy value. Note that undefined values will still raise a warning.
Short-ternary chaining
Null Coalescing Operator
Another useful shorthand operator is the "??" (or null coalescing) operator.
Assigning a default value
The expression
(expr1) ?? (expr2) evaluates to if is ENTITY, and otherwise.
In particular, this operator does not emit a notice or warning if the left-hand side value does not exist, just like
isset. This is especially useful on array keys.
[!NOTE]
Please note that the null coalescing operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement
return $foo ?? $bar; in a return-by-reference function will therefore not work and a warning is issued.
[!NOTE]
The null coalescing operator has low precedence. That means if mixing it with other operators (such as string concatenation or arithmetic operators) parentheses will likely be required.
[!NOTE]
Please note that the null coalescing operator allows for simple nesting:
Nesting null coalescing operator
Error Control Operators
PHP supports one error control operator: the at sign (
@). When prepended to an expression in PHP, any diagnostic error that might be generated by that expression will be suppressed.
If a custom error handler function is set with
set_error_handler, it will still be called even though the diagnostic has been suppressed.
[!WARNING]
Prior to PHP 8.0.0, the
error_reporting called inside the custom error handler always returned
0 if the error was suppressed by the
@ operator. As of PHP 8.0.0, it returns the value of this (bitwise) expression:
E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR | E_PARSE.
Any error message generated by the expression is available in the
"message" element of the array returned by
error_get_last. The result of that function will change on each error, so it needs to be checked early.
Intentional file error
Suppressing Expressions
[!NOTE]
The
@-operator works only on expressions. A simple rule of thumb is: if one can take the value of something, then one can prepend the
@ operator to it. For instance, it can be prepended to variables, functions calls, certain language construct calls (e.g.
include), and so forth. It cannot be prepended to function or class definitions, or conditional structures such as
if and ENTITY, and so forth.
[!WARNING]
Prior to PHP 8.0.0, it was possible for the
@ operator to disable critical errors that will terminate script execution. For example, prepending
@ to a call of a function which did not exist, by being unavailable or mistyped, would cause the script to terminate with no indication as to why.
ENTITY
error_reporting, Error Handling and Logging functions
Execution Operators
PHP supports one execution operator: backticks (
``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to
shell_exec.
Backtick Operator
$output";
?>
[!NOTE]
The backtick operator is disabled when
shell_exec is disabled.
[!NOTE]
Unlike some other languages, backticks have no special meaning within double-quoted strings.
ENTITY
ENTITY
ENTITY
8.5.0
The backtick operator as an alias for
shell_exec has been deprecated.
ENTITY
Program Execution functions,
popen,
proc_open, Using PHP from the commandline
Functional Operators
PHP 8.5 and later supports one operator that works directly on callables. The
|ENTITY operator, or “pipe,” accepts a single-parameter callable on the right and passes the left-side value to it, evaluating to the callable's result. The callable on the right may be any valid PHP callable: a
Closure, a first-class callable, an object that implements __invoke(), etc.
That means the following two lines are logically equivalent.
Using
|ENTITY
strlen(...);
echo $result, PHP_EOL;
$result = strlen("Hello World");
echo $result, PHP_EOL;
?>
ENTITY
11
11
For a single call that is not especially useful. It becomes useful when multiple calls are chained together. That is, the following two code fragments are logically equivalent:
Chaining |ENTITY calls
htmlentities(...)
|> str_split(...)
|> (fn($x) => array_map(strtoupper(...), $x))
|> (fn($x) => array_filter($x, fn($v) => $v != 'O'))
;
print_r($result);
$temp = "PHP Rocks";
$temp = htmlentities($temp);
$temp = str_split($temp);
$temp = array_map(strtoupper(...), $temp);
$temp = array_filter($temp, fn($v) => $v != 'O');
$result = $temp;
print_r($result);
?>
ENTITY
Array
(
[0] => P
[1] => H
[2] => P
[3] =>
[4] => R
[6] => C
[7] => K
[8] => S
)
Array
(
[0] => P
[1] => H
[2] => P
[3] =>
[4] => R
[6] => C
[7] => K
[8] => S
)
The left-hand side of the pipe may be any value or expression. The right-hand side may be any valid PHP callable that takes a single parameter, or any expression that evaluates to such a callable. Functions with more than one required parameter are not allowed and will fail as if the function were called normally with insufficient arguments. Functions that take a variable by reference are not allowed. If the right-hand side does not evaluate to a valid callable it will throw an Error.
[!NOTE]
Be aware that, to avoid syntax ambiguity, arrow functions MUST be wrapped in parentheses when used with a pipe operator, as in the examples above. Failing to do so will result in a fatal error.
ENTITY
Closure
Incrementing/Decrementing Operators
PHP supports pre- and post-increment and decrement operators. Those unary operators allow to increment or decrement the value by one.
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.
Increment/decrement Operators
Examples of Increment/Decrement
ENTITY
Post-increment:
int(5)
int(6)
Pre-increment:
int(6)
int(6)
Post-decrement:
int(5)
int(4)
Pre-decrement:
int(4)
int(4)
[!WARNING]
The increment and decrement operators have no effect on values of type
bool. A
E_WARNING is emitted as of PHP 8.3.0, because this will implicitly cast the value to
int in the future.
The decrement operator has no effect on values of type
null. A
E_WARNING is emitted as of PHP 8.3.0, because this will implicitly cast the value to
int in the future.
The decrement operator has no effect on non- numeric string, except the empty string, which becomes
-1. A
E_DEPRECATED is emitted as of PHP 8.3.0, because a
TypeError will be thrown in the future.
[!NOTE]
Internal objects that support overloading addition and/or subtraction can also be incremented and/or decremented. One such internal object is
GMP.
PERL string increment feature
[!WARNING]
This feature is soft-deprecated as of PHP 8.3.0. The
str_increment function should be used instead. As of PHP 8.5.0, incrementing non-numeric strings emits a deprecation warning.
It is possible to increment a non- numeric string in PHP. The string must be an alphanumerical ASCII string. Which increments letters up to the next letter, when reaching the letter
Z the increment is carried to the value on the left. For example,
$a = 'Z'; $a++; turns
$a into
'AA'.
As of PHP 8.3.0, incrementing empty or non-alphanumeric strings emits
E_DEPRECATED. As of PHP 8.5.0, this applies to all non-numeric strings.
PERL string increment example
ENTITY
== Alphabetic strings ==
X
Y
Z
AA
AB
AC
== Alphanumeric strings ==
A9
B0
B1
B2
B3
B4
A09
A10
A11
A12
A13
A14
[!WARNING]
If the alphanumerical string can be interpreted as a numeric string it will be cast to an
int or
float. This is particularly an issue with strings that look like a floating point numbers written in exponential notation. The
str_increment function does not suffer from these implicit type cast.
Alphanumerical string converted to float
ENTITY
string(3) "5e0"
float(6)
This is because the value
"5e0" is interpreted as a
float and cast to the value
5.0 before being incremented.
Logical Operators
Example
Name
Result
$a and $b
And
ENTITY if both
$a and
$b are ENTITY.
$a or $b
Or
ENTITY if either
$a or
$b is ENTITY.
$a xor $b
Xor
ENTITY if either
$a or
$b is ENTITY, but not both.
! $a
Not
ENTITY if
$a is not ENTITY.
$a ENTITYENTITY $b
And
ENTITY if both
$a and
$b are ENTITY.
$a || $b
Or
ENTITY if either
$a or
$b is ENTITY.
Logical Operators
The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)
Logical operators illustrated
ENTITY
bool(true)
bool(false)
bool(false)
bool(true)
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 ENTITY 2 ENTITY 1 is illegal in PHP. The expression
1 ENTITY= 1 == 1 on the other hand is legal, because the
== operator has a lower precedence than the
ENTITY= operator.
Associativity is only meaningful for binary (and ternary) operators. Unary operators are either prefix or postfix so this notion is not applicable. For example
!!$a can only be grouped as
!(!$a).
Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.
The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping.
Associativity
Operators
Additional Information
(n/a)
clone
new
clone and new
right
**
arithmetic
(n/a)
+
-
++
--
~
(int)
(float)
(string)
(array)
(object)
(bool)
@
arithmetic (unary
+ and
-), increment/decrement, bitwise, type castingENTITY error control
left
instanceof
type
(n/a)
!
logical
left
*
/
%
arithmetic
left
+
-
.
arithmetic (binary
+ and
-), arrayENTITY string (
. prior to PHP 8.0.0)
left
ENTITYENTITY
ENTITYENTITY
bitwise
left
.
string (as of PHP 8.0.0)
left
`
ENTITY`
non-associative
ENTITY
ENTITY=
ENTITY
ENTITY=
comparison
non-associative
==
!=
===
!==
ENTITYENTITY
ENTITY=ENTITY
comparison
left
ENTITY
bitwiseENTITY references
left
^
bitwise
left
`
`
left
ENTITYENTITY
logical
left
`
right
??
null coalescing
non-associative
? :
ternary (left-associative prior to PHP 8.0.0)
right
=
+=
-=
*=
**=
/=
.=
%=
ENTITY= `
=
^=
ENTITYENTITY=
ENTITYENTITY=
??=`
(n/a)
yield from
yield from
(n/a)
=ENTITY
yield with keys
(n/a)
yield
yield
(n/a)
print
print
left
and
logical
left
xor
logical
left
or
logical
(n/a)
include
include_once
require
require_once
include,
include_once,
requireENTITY
require_once
(n/a)
fn (...) =ENTITY
fn arrow disambiguity
(n/a)
throw
throw
Operator Precedence
[!NOTE]
The unary operators sharing the row with the cast operators (
~,
@, and unary
+/
-) bind more tightly than
instanceof, whereas
! binds less tightly. Consequently
(int) $x instanceof Foo is grouped as
((int) $x) instanceof Foo, while
!$x instanceof Foo is grouped as
!($x instanceof Foo).
Associativity
$a = 5, $b = 5
var_dump($a, $b);
?>
The ternary operator specifically requires the use of parenthesis to disambiguate precedence.
Explicit Precedence
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.
Undefined order of evaluation
+,
- and
. precedence
ENTITY
-1, or so I hope
-1, or so I hope
Fatal error: Uncaught TypeError: Unsupported operand types: string - int
Prior to PHP 8,
+,
- and
. had the same precedence
ENTITY
-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.
This is possible because the left-hand side of an assignment must be a variable, so the assignment is grouped with that variable rather than with the surrounding higher-precedence prefix operator. The same applies to the other prefix operators that take an expression operand, such as
clone, the cast operators,
@ and
~: for instance
clone $a = $b is grouped as
clone ($a = $b), not
(clone $a) = $b.
ENTITY
ENTITY
ENTITY
8.0.0
String concatenation (
.) now has a lower precedence than arithmetic addition/subtraction (
+ and
-) and bitwise shift left/right (
ENTITYENTITY and
ENTITYENTITY); previously it had the same precedence as
+ and
- and a higher precedence than
ENTITYENTITY and
ENTITYENTITY.
8.0.0
The ternary operator (
? :) is non-associative now; previously it was left-associative.
7.4.0
Relying on the precedence of string concatenation (
.) relative to arithmetic addition/subtraction (
+ or
-) or bitwise shift left/right (
ENTITYENTITY or
ENTITYENTITY), i.e. using them together in an unparenthesized expression, is deprecated.
7.4.0
Relying on left-associativity of the ternary operator (
? :), i.e. nesting multiple unparenthesized ternary operators, is deprecated.
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.
String Concatenating
ENTITY
String type, String functions
Type Operators
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:
Using
instanceof with classes
ENTITY
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:
Using
instanceof with inherited classes
ENTITY
bool(true)
bool(true)
To check if an object is not an instanceof a class, the logical
not operator can be used.
Using
instanceof to check if object is not an instanceof a class
ENTITY
bool(true)
Lastly,
instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:
Using
instanceof with interfaces
ENTITY
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:
Using
instanceof with other variables
ENTITY
bool(true)
bool(true)
bool(false)
instanceof does not throw any error if the variable being tested is not an object, it simply returns ENTITY. Constants, however, were not allowed prior to PHP 7.3.0.
Using
instanceof to test other variables
ENTITY
bool(false)
bool(false)
bool(false)
PHP Fatal error: instanceof expects an object instance, constant given
As of PHP 7.3.0, constants are allowed on the left-hand-side of the
instanceof operator.
Using
instanceof to test constants
ENTITY
bool(false)
As of PHP 8.0.0,
instanceof can now be used with arbitrary expressions. The expression must be wrapped in parentheses and produce a
string.
Using
instanceof with an arbitrary expression
ENTITY
bool(true)
bool(true)
bool(false)
bool(true)
The
instanceof operator has a functional variant with the
is_a function.
ENTITY
get_class,
is_a
construct
AllowDynamicProperties::__construct
Construct a new AllowDynamicProperties attribute instance
ENTITY
public
AllowDynamicProperties::__construct
Constructs a new
AllowDynamicProperties instance.
ENTITY ENTITY
argumentcounterror
ENTITY
ArgumentCountError is thrown when too few arguments are passed to a user-defined function or method.
This error is also thrown when too many arguments are passed to a non-variadic built-in function.
ENTITY
ArgumentCountError
extends
TypeError
ENTITY
ENTITY
arithmeticerror
ENTITY
ArithmeticError is thrown when an error occurs while performing mathematical operations. These errors include attempting to perform a bitshift by a negative amount, and any call to
intdiv that would result in a value outside the possible bounds of an
int.
ENTITY
ArithmeticError
extends
Error
ENTITY
ENTITY
arrayaccess
ENTITY
Interface to provide access to objects as arrays.
ENTITY
ArrayAccess
ENTITY
ENTITY
Basic usage
1,
"two" => 2,
"three" => 3,
];
public function offsetSet($offset, $value): void {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset): bool {
return isset($this->container[$offset]);
}
public function offsetUnset($offset): void {
unset($this->container[$offset]);
}
public function offsetGet($offset): mixed {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new Obj;
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
ENTITY
bool(true)
int(2)
bool(false)
string(7) "A value"
Obj Object
(
[container] => Array
(
[one] => 1
[three] => 3
[two] => A value
[0] => Append 1
[1] => Append 2
[2] => Append 3
)
)
ENTITY ENTITY ENTITY ENTITY
offsetexists
ArrayAccess::offsetExists
Whether an offset exists
ENTITY
public
bool
ArrayAccess::offsetExists
mixed
offset
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 ENTITY.
ENTITY
offset
An offset to check for.
ENTITY
ENTITY
[!NOTE]
The return value will be casted to
bool if non-boolean was returned.
ENTITY
ArrayAccess::offsetExists example
ENTITY
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)
offsetget
ArrayAccess::offsetGet
Offset to retrieve
ENTITY
public
mixed
ArrayAccess::offsetGet
mixed
offset
Returns the value at specified offset.
This method is executed when checking if offset is
empty.
ENTITY
offset
The offset to retrieve.
ENTITY
Can return all value types.
ENTITY
[!NOTE]
It's possible for implementations of this method to return by reference. This makes indirect modifications to the overloaded array dimensions of
ArrayAccess objects possible.
A direct modification is one that replaces completely the value of the array dimension, as in
$obj[6] = 7. An indirect modification, on the other hand, only changes part of the dimension, or attempts to assign the dimension by reference to another variable, as in
$obj[6][7] = 7 or
$var =ENTITY $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.
ENTITY
ArrayAccess::offsetExists
offsetset
ArrayAccess::offsetSet
Assign a value to the specified offset
ENTITY
public
void
ArrayAccess::offsetSet
mixed
offset
mixed
value
Assigns a value to the specified offset.
ENTITY
offset
The offset to assign the value to.
value
The value to set.
ENTITY
ENTITY
ENTITY
[!NOTE]
The
offset parameter will be set to ENTITY if another value is not available, like in the following example.
ENTITY
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.
offsetunset
ArrayAccess::offsetUnset
Unset an offset
ENTITY
public
void
ArrayAccess::offsetUnset
mixed
offset
Unsets an offset.
[!NOTE]
This method will not be called when type-casting to (unset)
ENTITY
offset
The offset to unset.
ENTITY
ENTITY
assertionerror
ENTITY
AssertionError is thrown when an assertion made via
assert fails.
ENTITY
AssertionError
extends
Error
ENTITY
ENTITY
construct
Attribute::__construct
Construct a new Attribute instance
ENTITY
public
Attribute::__construct
int
flags
Attribute::TARGET_ALL
Constructs a new
Attribute instance.
ENTITY
flags
Predefined Attributes
PHP provides some predefined attributes that can be used.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
allowdynamicproperties
ENTITY
This attribute is used to mark classes that allow dynamic properties.
[!NOTE]
Although attributes themselves are not inherited, the effect of the
AllowDynamicProperties attribute is inherited. Child classes of a class marked with this attribute will also allow dynamic properties, even if they do not explicitly declare the attribute.
[!NOTE]
This attribute was introduced in PHP 8.2.0 as the explicit way to allow dynamic properties. Creating a dynamic property on a class that does not use this attribute, and that does not implement __get() or __set(), is deprecated.
ENTITY
#[\Attribute(\Attribute::TARGET_CLASS)]
final
AllowDynamicProperties
ENTITY
ENTITY
AllowDynamicProperties with a dynamic property
To enable dynamic properties, add
#[\AllowDynamicProperties].
myDynamicProp = 1234;
?>
AllowDynamicProperties with non-existing property
As of PHP 8.2.0, the declaration is required unless the class uses this attribute. Creating an undeclared property on such a class emits a deprecation notice.
myUnknownProperty = 1234;
?>
ENTITY
Deprecated: Creation of dynamic property InvalidExample::$myUnknownProperty is deprecated in file on line 5
AllowDynamicProperties with non-existing property in inherited class
nonExistingProp = true;
$o2->nonExistingProp = true;
?>
ENTITY
Deprecated: Creation of dynamic property DefaultBehaviour::$nonExistingProp is deprecated in file on line 12
ENTITY
Attributes overview
ENTITY
attribute
ENTITY
Attributes offer the ability to add structured, machine-readable metadata information on declarations in code: Classes, methods, functions, parameters, properties and class constants can be the target of an attribute. The metadata defined by attributes can then be inspected at runtime using the Reflection APIs. Attributes could therefore be thought of as a configuration language embedded directly into code.
ENTITY
#[\Attribute(\Attribute::TARGET_CLASS)]
final
Attribute
ENTITY
const
int
Attribute::TARGET_CLASS
const
int
Attribute::TARGET_FUNCTION
const
int
Attribute::TARGET_METHOD
const
int
Attribute::TARGET_PROPERTY
const
int
Attribute::TARGET_CLASS_CONSTANT
const
int
Attribute::TARGET_PARAMETER
const
int
Attribute::TARGET_CONSTANT
const
int
Attribute::TARGET_ALL
const
int
Attribute::IS_REPEATABLE
ENTITY
public
int
flags
ENTITY
ENTITY
Attribute::TARGET_CLASS
Attribute::TARGET_FUNCTION
Attribute::TARGET_METHOD
Attribute::TARGET_PROPERTY
Attribute::TARGET_CLASS_CONSTANT
Attribute::TARGET_PARAMETER
Attribute::TARGET_CONSTANT
Attribute::TARGET_ALL
Attribute::IS_REPEATABLE
ENTITY
flags
ENTITY
ENTITY
ENTITY
8.5.0
Added
Attribute::TARGET_CONSTANT. Applying
#[\Attribute] to an abstract class, enum, interface, or trait now triggers a compile-time error (previously it was only reported at runtime when ReflectionAttribute::newInstance was called).
ENTITY
Attributes overview
ENTITY
delayedtargetvalidation
ENTITY
This attribute delays target validation errors for internal attributes from compile time to when the attribute is instantiated via the Reflection API.
When applied to a declaration, any invalid usage of internal attributes on the same target will not trigger a compile time error. Instead, the validation is deferred and performed when the attribute is instantiated via ReflectionAttribute::newInstance().
This is primarily intended for forward compatibility, allowing code to use attributes that may gain additional valid targets in future PHP versions without breaking on older versions.
ENTITY
#[\Attribute(\Attribute::TARGET_ALL)]
final
DelayedTargetValidation
ENTITY
Delaying validation of an invalid target
getAttributes() as $attribute) {
$attribute->newInstance(); // May throw if invalid
}
When any attribute applied to the same target (other than DelayedTargetValidation itself) is instantiated via reflection using ReflectionAttribute::newInstance(), target validation is performed and an exception may be thrown if the attribute is used on an unsupported target.
ENTITY
This attribute only affects target validation of internal attributes.
It does not suppress functional validation performed by those attributes. For example,
Override will still emit an error if a method does not actually override a parent method.
ENTITY
Attributes overview
Override
deprecated
ENTITY
This attribute is used to mark functionality as deprecated. Using deprecated functionality will cause an
E_USER_DEPRECATED error to be emitted.
As of PHP 8.5.0, this attribute can also be applied to traits and to compile-time constants declared outside of a class.
ENTITY
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION | \Attribute::TARGET_CLASS_CONSTANT | \Attribute::TARGET_CONSTANT | \Attribute::TARGET_CLASS)]
final
Deprecated
ENTITY
public
readonly
string
null
message
public
readonly
string
null
since
ENTITY
ENTITY
message
An optional message explaining the reason for the deprecation and possible replacement functionality. Will be included in the emitted deprecation message.
since
An optional string indicating since when the functionality is deprecated. The contents are not validated by PHP and may contain a version number, a date or any other value that is considered appropriate. Will be included in the emitted deprecation message.
Functionality that is part of PHP will use Major.Minor as the
since value, for example
'8.4'.
ENTITY
ENTITY
Deprecated: Function unsafe_function() is deprecated since 1.5, use safe_replacement() instead in example.php on line 9
This is unsafe
ENTITY
ENTITY
ENTITY
8.5.0
Deprecated can now be applied to traits and to compile-time constants declared outside of a class, the latter through the new
Attribute::TARGET_CONSTANT target.
ENTITY
Attributes overview
ReflectionFunctionAbstract::isDeprecated
ReflectionClassConstant::isDeprecated
E_USER_DEPRECATED
ENTITY
construct
Deprecated::__construct
Construct a new Deprecated attribute instance
ENTITY
public
Deprecated::__construct
string
null
message
ENTITY
string
null
since
ENTITY
Constructs a new
Deprecated instance.
ENTITY
message
The value of the message property.
since
The value of the since property.
nodiscard
ENTITY
This attribute can be used to indicate that the return value of a function or a method should not be discarded. If the return value is not used in any way, a warning will be emitted.
This is useful for functions where not checking the return value is likely to be a bug.
To intentionally discard the return value of such a function, use (void) cast to suppress the warning.
[!NOTE]
Since attributes are designed to be backwards compatible,
#[\NoDiscard] can be added to functions and methods even when PHP 8.4 or below are supported, it just won't do anything. On PHP 8.5 and above a warning will be emitted if the result is unused. To suppress the warning without using
(void), which is not supported before PHP 8.5, consider using a variable like
$_.
[!NOTE]
#[\NoDiscard] applies to the specific function or method declaration it is written on, and the warning is emitted based on the declaration that is actually called. As a result, adding
#[\NoDiscard] to an interface method or an abstract method does not emit a warning, because the method that is invoked is the implementing or overriding method. Likewise, a method that overrides a
#[\NoDiscard] method does not emit the warning unless it is itself marked with the attribute. In contrast, a method imported from a trait keeps the attribute, because the trait method is copied into the using class as if declared there.
ENTITY
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
final
NoDiscard
ENTITY
public
readonly
string
null
message
ENTITY
ENTITY
message
An optional message explaining why the return value should not be discarded.
ENTITY
Basic usage
$items
* @return array
*/
#[\NoDiscard("as processing might fail for individual items")]
function bulk_process(array $items): array {
$results = [];
foreach ($items as $key => $item) {
if (\random_int(0, 9999) < 9999) {
// Pretend to do something useful with $item,
// which will succeed in 99.99% of cases.
echo "Processing {$item}", PHP_EOL;
$error = null;
} else {
$error = new \Exception("Failed to process {$item}.");
}
$results[$key] = $error;
}
return $results;
}
bulk_process($items);
?>
ENTITY
Warning: The return value of function bulk_process() should either be used or intentionally ignored by casting it as (void), as processing might fail for individual items
Intentionally discarding the return value
ENTITY
Attributes overview
ENTITY
construct
NoDiscard::__construct
Construct a new NoDiscard attribute instance
ENTITY
public
NoDiscard::__construct
string
null
message
ENTITY
Constructs a new
NoDiscard instance.
ENTITY
message
The value of the message property.
override
ENTITY
This attribute is used to indicate that a method or a property is intended to override a method or a property of a parent class or that it implements a method or a property defined in an interface.
If no method or property with the same name exists in a parent class or in an implemented interface a compile-time error will be emitted.
The attribute cannot be used on the __construct() method, which is exempt from signature checks.
ENTITY
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_PROPERTY)]
final
Override
ENTITY
ENTITY
ENTITY
ENTITY
8.5.0
Override can be applied to properties.
ENTITY
Usage with methods
ENTITY
Fatal error: Extended::boo() has #[\Override] attribute, but no matching parent method exists
Usage with properties
ENTITY
Fatal error: Extended::$boo has #[\Override] attribute, but no matching parent property exists
ENTITY
Attributes overview
ENTITY
construct
Override::__construct
Construct a new Override attribute instance
ENTITY
public
Override::__construct
Constructs a new
Override instance.
ENTITY ENTITY
returntypewillchange
ENTITY
As of PHP 8.1.0, a tentative phase of transitioning to return type declarations for internal class methods began.
Most non-final internal methods now require overriding methods to declare a compatible return type. Otherwise, a deprecation notice is emitted during inheritance validation warning that the signature violates covariance rules.
In a future PHP version, method signature checking will become strict, and mismatches will cause a fatal error.
In case the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, or the overriding method declares an incompatible return type, a
#[\ReturnTypeWillChange] attribute can be added to silence the deprecation notice.
[!WARNING]
When overriding methods defined in user-defined classes, return types are checked strictly. A fatal error is emitted on mismatch, even if the overriding method is marked with the attribute.
The
ReturnTypeWillChange attribute suppresses deprecation warnings only during the tentative return type phase. After strict type checking is enforced, the attribute will stop working and a mismatch in the overriding method signature of an internal class will cause a fatal error.
ENTITY
#[\Attribute(\Attribute::TARGET_METHOD)]
final
ReturnTypeWillChange
ENTITY
ENTITY
Attributes overview
ENTITY
sensitiveparameter
ENTITY
This attribute is used to mark a parameter that is sensitive and should have its value redacted if present in a stack trace.
ENTITY
#[\Attribute(\Attribute::TARGET_PARAMETER)]
final
SensitiveParameter
ENTITY
ENTITY
ENTITY
Exception: Error! in example.php:7
Stack trace:
#0 example.php(19): defaultBehavior('password', 'normal')
#1 {main}
Exception: Error! in example.php:15
Stack trace:
#0 example.php(25): sensitiveParametersWithAttribute(Object(SensitiveParameterValue), 'normal')
#1 {main}
ENTITY
Attributes overview,
SensitiveParameterValue
ENTITY
backedenum
ENTITY
The
BackedEnum interface is automatically applied to backed enumerations by the engine. It may not be implemented by user-defined classes. Enumerations may not override its methods, as default implementations are provided by the engine. It is available only for type checks.
ENTITY
BackedEnum
extends
UnitEnum
ENTITY
ENTITY
ENTITY ENTITY
from
BackedEnum::from
Maps a scalar to an enum instance
ENTITY
public
static
static
BackedEnum::from
int
string
value
The from method translates a
string or
int into the corresponding Enum case, if any. If there is no matching case defined, it will throw a ValueError.
ENTITY
value
The scalar value to map to an enum case.
ENTITY
A case instance of this enumeration.
ENTITY
Basic usage
The following example illustrates how enum cases are returned.
ENTITY
enum(Suit::Hearts)
Fatal error: Uncaught ValueError: "B" is not a valid backing value for enum "Suit" in /file.php:15
ENTITY
UnitEnum::cases, BackedEnum::tryFrom
tryfrom
BackedEnum::tryFrom
Maps a scalar to an enum instance or null
ENTITY
public
static
static
null
BackedEnum::tryFrom
int
string
value
The tryFrom method translates a
string or
int into the corresponding Enum case, if any. If there is no matching case defined, it will return null.
ENTITY
value
The scalar value to map to an enum case.
ENTITY
A case instance of this enumeration, or
null if not found.
ENTITY
Basic usage
The following example illustrates how enum cases are returned.
ENTITY
enum(Suit::Hearts)
enum(Suit::Spades)
ENTITY
UnitEnum::cases, BackedEnum::from
closedgeneratorexception
ENTITY
A ClosedGeneratorException is thrown when trying to retrieve a value from a closed
Generator.
ENTITY
ClosedGeneratorException
extends
Exception
ENTITY
ENTITY
closure
ENTITY
Class used to represent anonymous functions.
Anonymous functions yield objects of this type. This class has methods that allow further control of the anonymous function after it has been created.
Besides the methods listed here, this class also has an
__invoke method. This is for consistency with other classes that implement calling magic, as this method is not used for calling the function.
ENTITY
final
Closure
ENTITY
ENTITY
ENTITY
ENTITY
8.4.0
The output of Closure::__debugInfo now includes the name, line, and file of the closure.
ENTITY
[!NOTE]
Closure objects cannot be serialized as closures may contain bound variables and a specific execution context. Attempting to serialize a closure will throw an Exception.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
bind
Closure::bind
Duplicates a closure with a specific bound object and class scope
ENTITY
public
static
Closure
null
Closure::bind
Closure
closure
object
null
newThis
object
string
null
newScope
"static"
This method is a static version of Closure::bindTo. See the documentation of that method for more information.
ENTITY
closure
The anonymous functions to bind.
newThis
The object to which the given anonymous function should be bound, or ENTITY for the closure to be unbound.
newScope
The class scope to which the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object. It is not allowed to pass (an object of) an internal class as this parameter.
ENTITY
Returns a new
Closure object, or ENTITY on failure.
ENTITY
ENTITY
ENTITY
8.5.0
Binding an instance to a static closure, or binding a method from an incompatible class hierarchy, is now deprecated (these cases already emitted an
E_WARNING).
ENTITY
Closure::bind example
ifoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";
?>
ENTITY
1
2
ENTITY
Anonymous functions
Closure::bindTo
bindto
Closure::bindTo
Duplicates the closure with a new bound object and class scope
ENTITY
public
Closure
null
Closure::bindTo
object
null
newThis
object
string
null
newScope
"static"
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 ENTITY), but this method can nevertheless be used to change their class scope.
This method will ensure that for a non-static closure, having a bound instance will imply being scoped and vice-versa. To this end, non-static closures that are given a scope but a ENTITY 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.
ENTITY
newThis
The object to which the given anonymous function should be bound, or ENTITY for the closure to be unbound.
newScope
The class scope to which the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object. It is not allowed to pass (an object of) an internal class as this parameter.
ENTITY
Returns the newly created
Closure object or ENTITY on failure.
ENTITY
ENTITY
ENTITY
8.5.0
Binding an instance to a static closure, or binding a method from an incompatible class hierarchy, is now deprecated (these cases already emitted an
E_WARNING).
ENTITY
Closure::bindTo example
val = $val;
}
public function getClosure()
{
// Returns closure bound to this object and scope
return function() {
return $this->val;
};
}
}
$ob1 = new A(1);
$ob2 = new A(2);
$cl = $ob1->getClosure();
echo $cl(), "\n";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";
?>
ENTITY
1
2
ENTITY
Anonymous functions
Closure::bind
call
Closure::call
Binds and calls the closure
ENTITY
public
mixed
Closure::call
object
newThis
mixed
args
Temporarily binds the closure to
newThis, and calls it with any given parameters.
ENTITY
newThis
The
object to bind the closure to for the duration of the call.
args
Zero or more parameters, which will be given as parameters to the closure.
ENTITY
Returns the return value of the closure.
ENTITY
Closure::call example
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);
?>
ENTITY
int(7)
int(8)
construct
Closure::__construct
Constructor that disallows instantiation
ENTITY
private
Closure::__construct
This method exists only to disallow instantiation of the
Closure class. Objects of this class are created in the fashion described on the anonymous functions page.
ENTITY ENTITY
ENTITY
Anonymous functions
fromcallable
Closure::fromCallable
Converts a callable into a closure
ENTITY
public
static
Closure
Closure::fromCallable
callable
callback
Create and return a new anonymous function from given
callback using the current scope. This method checks if the
callback is callable in the current scope and throws a TypeError if it is not.
[!NOTE]
As of PHP 8.1.0, First class callable syntax has the same semantics as this method.
ENTITY
callback
The callable to convert.
ENTITY
Returns the newly created
Closure or throws a TypeError if the
callback is not callable in the current scope.
ENTITY
Anonymous functions
First class callable syntax
getcurrent
Closure::getCurrent
Returns the currently executing closure
ENTITY
public
static
Closure
Closure::getCurrent
Returns the currently executing closure. This method is primarily useful for implementing recursive closures without needing to capture a reference to the closure variable using the
use keyword.
This method must be called from within a closure; calling it outside of a closure context will result in
Error: Current function is not a closure.
ENTITY ENTITY
ENTITY
Returns the currently executing
Closure instance.
ENTITY
Throws an Error if called outside of a closure context.
ENTITY
Closure::getCurrent example
Using Closure::getCurrent to implement a recursive Fibonacci function:
Comparison with traditional approach
Prior to PHP 8.5, implementing recursive closures required capturing a reference to the closure variable using the
use keyword:
The Closure::getCurrent approach eliminates the need to declare the variable with a reference in the
use clause, making the code cleaner and less error-prone.
compileerror
ENTITY
CompileError is thrown for some compilation errors, which formerly issued a fatal error.
ENTITY
CompileError
extends
Error
ENTITY
ENTITY
countable
ENTITY
Classes implementing
Countable can be used with the
count function.
ENTITY
Countable
ENTITY
ENTITY
count
Countable::count
Count elements of an object
ENTITY
public
int
Countable::count
This method is executed when the
value for
count is an object implementing
Countable.
ENTITY ENTITY
ENTITY
The custom count as an
int.
ENTITY
Countable::count example
count;
}
}
$counter = new Counter;
for ($i = 0; $i < 10; ++$i) {
echo "I have been count()ed " . count($counter) . " times\n";
}
?>
ENTITY
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
divisionbyzeroerror
ENTITY
DivisionByZeroError is thrown when an attempt is made to divide a number by zero.
ENTITY
DivisionByZeroError
extends
ArithmeticError
ENTITY
ENTITY
error
ENTITY
Error is the base class for errors that indicate programming mistakes. Such errors generally require a correction to the program rather than being handled during normal operation.
ENTITY
Error
implements
Throwable
ENTITY
protected
string
message
""
private
string
string
""
protected
int
code
protected
string
file
""
protected
int
line
private
array
trace
[]
private
Throwable
null
previous
null
ENTITY
ENTITY
message
The error message
code
The error code
file
The filename where the error happened
line
The line where the error happened
previous
The previously thrown exception
string
The string representation of the stack trace
trace
The stack trace as an array
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
clone
Error::__clone
Clone the error
ENTITY
private
void
Error::__clone
Errors do not support cloning; this method exists only to prevent it.
[!WARNING]
Errors cannot be cloned, whether they are instances of Error or of a subclass. Attempting to clone an error throws an Error, which may be caught.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
Attempting to clone an error throws an Error with the following message:
Trying to clone an uncloneable object of class ClassName.
ENTITY
ENTITY
ENTITY
8.1.0
Error::__clone is no longer final.
construct
Error::__construct
Construct the error object
ENTITY
public
Error::__construct
string
message
""
int
code
0
Throwable
null
previous
ENTITY
Constructs the Error.
ENTITY
message
The error message.
code
The error code.
previous
The previous throwable used for the exception chaining.
ENTITY
[!NOTE]
The
message is NOT binary safe.
getcode
Error::getCode
Gets the error code
ENTITY
final
public
int
Error::getCode
Returns the error code.
ENTITY ENTITY
ENTITY
Returns the error code as
int
ENTITY
Error::getCode example
getCode();
}
?>
ENTITY
The Error code is: 30
ENTITY
Throwable::getCode
getfile
Error::getFile
Gets the file in which the error occurred
ENTITY
final
public
string
Error::getFile
Get the name of the file the error occurred.
ENTITY ENTITY
ENTITY
Returns the filename in which the error occurred.
ENTITY
Error::getFile example
getFile();
}
?>
ENTITY
/home/bjori/tmp/ex.php
ENTITY
Throwable::getFile
getline
Error::getLine
Gets the line in which the error occurred
ENTITY
final
public
int
Error::getLine
Get line number where the error occurred.
ENTITY ENTITY
ENTITY
Returns the line number where the error occurred.
ENTITY
Error::getLine example
getLine();
}
?>
ENTITY
The error was created on line: 3
ENTITY
Throwable::getLine
getmessage
Error::getMessage
Gets the error message
ENTITY
final
public
string
Error::getMessage
Returns the error message.
ENTITY ENTITY
ENTITY
Returns the error message as a string.
ENTITY
Error::getMessage example
getMessage();
}
?>
ENTITY
Some error message
ENTITY
Throwable::getMessage
getprevious
Error::getPrevious
Returns previous Throwable
ENTITY
final
public
Throwable
null
Error::getPrevious
Returns previous Throwable (the third parameter of Error::__construct).
ENTITY ENTITY
ENTITY
Returns the previous
Throwable if available or ENTITY otherwise.
ENTITY
Error::getPrevious example
Looping over, and printing out, error trace.
getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
} while($e = $e->getPrevious());
}
?>
ENTITY
/home/bjori/ex.php:8 Something happened (911) [MyCustomError]
/home/bjori/ex.php:6 You are doing it wrong! (112) [TypeError]
ENTITY
Throwable::getPrevious
gettrace
Error::getTrace
Gets the stack trace
ENTITY
final
public
array
Error::getTrace
Returns the stack trace.
ENTITY ENTITY
ENTITY
Returns the stack trace as an
array.
ENTITY
Error::getTrace example
getTrace());
}
?>
ENTITY
array(1) {
[0]=>
array(4) {
["file"]=>
string(22) "/home/bjori/tmp/ex.php"
["line"]=>
int(7)
["function"]=>
string(4) "test"
["args"]=>
array(0) {
}
}
}
ENTITY
Throwable::getTrace
gettraceasstring
Error::getTraceAsString
Gets the stack trace as a string
ENTITY
final
public
string
Error::getTraceAsString
Returns the stack trace as a string.
ENTITY ENTITY
ENTITY
Returns the stack trace as a string.
ENTITY
Error::getTraceAsString example
getTraceAsString();
}
?>
ENTITY
#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}
ENTITY
Throwable::getTraceAsString
tostring
Error::__toString
String representation of the error
ENTITY
public
string
Error::__toString
Returns the
string representation of the error.
ENTITY ENTITY
ENTITY
Returns the
string representation of the error.
ENTITY
Error::__toString example
ENTITY
Error: Some error message in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}
ENTITY
Throwable::__toString
errorexception
ENTITY
An Error Exception.
ENTITY
ErrorException
extends
Exception
ENTITY
protected
int
severity
E_ERROR
ENTITY
ENTITY
ENTITY
ENTITY
severity
The severity of the exception
ENTITY
Use
set_error_handler to change error messages into ErrorException
ENTITY
Fatal error: Uncaught ErrorException: unserialize(): Error at offset 0 of 11 bytes in test.php:16
Stack trace:
#0 [internal function]: {closure}(2, 'unserialize(): ...', 'test.php', 16)
#1 test.php(16): unserialize('broken data')
#2 {main}
thrown in test.php on line 16
ENTITY ENTITY
construct
ErrorException::__construct
Constructs the exception
ENTITY
public
ErrorException::__construct
string
message
""
int
code
0
int
severity
E_ERROR
string
null
filename
ENTITY
int
null
line
ENTITY
Throwable
null
previous
ENTITY
Constructs the Exception.
ENTITY
message
The Exception message to throw.
code
The Exception code.
severity
The severity level of the exception.
[!NOTE]
While the severity can be any
int value, it is intended that the error constants be used.
filename
The filename where the exception is thrown.
line
The line number where the exception is thrown.
previous
The previous exception used for the exception chaining.
ENTITY
ENTITY
ENTITY
8.0.0
filename and
line are nullable now. Previously, their defaults were
__FILE__ and
__LINE__, respectively.
getseverity
ErrorException::getSeverity
Gets the exception severity
ENTITY
final
public
int
ErrorException::getSeverity
Returns the severity of the exception.
ENTITY ENTITY
ENTITY
Returns the severity level of the exception.
ENTITY
ErrorException::getSeverity example
getSeverity();
var_dump($e->getSeverity() === E_USER_ERROR);
}
?>
ENTITY
This exception severity is: 256
bool(true)
exception
ENTITY
Exception is the base class for exceptions that can be handled during normal operation.
ENTITY
Exception
implements
Throwable
ENTITY
protected
string
message
""
private
string
string
""
protected
int
code
protected
string
file
""
protected
int
line
private
array
trace
[]
private
Throwable
null
previous
null
ENTITY
ENTITY
message
The exception message
code
The exception code
file
The filename where the exception was created
line
The line where the exception was created
previous
The previously thrown exception
string
The string representation of the stack trace
trace
The stack trace as an array
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
clone
Exception::__clone
Clone the exception
ENTITY
private
void
Exception::__clone
Exceptions do not support cloning; this method exists only to prevent it.
[!WARNING]
Exceptions cannot be cloned, whether they are instances of Exception or of a subclass. Attempting to clone an exception throws an Error, which may be caught.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
Attempting to clone an exception throws an Error with the following message:
Trying to clone an uncloneable object of class ClassName.
ENTITY
ENTITY
ENTITY
8.1.0
Exception::__clone is no longer declared final, because declaring a private method final emits a warning as of PHP 8.0.0. Exceptions remain uncloneable.
construct
Exception::__construct
Construct the exception
ENTITY
public
Exception::__construct
string
message
""
int
code
0
Throwable
null
previous
ENTITY
Constructs the Exception.
ENTITY
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.
ENTITY
[!NOTE]
The
message is NOT binary safe.
getcode
Exception::getCode
Gets the Exception code
ENTITY
final
public
int
Exception::getCode
Returns the Exception code.
ENTITY ENTITY
ENTITY
Returns the exception code as
int in
Exception but possibly as other type in
Exception descendants (for example as
string in
PDOException).
ENTITY
Exception::getCode example
getCode();
}
?>
ENTITY
The exception code is: 30
ENTITY
Throwable::getCode
getfile
Exception::getFile
Gets the file in which the exception was created
ENTITY
final
public
string
Exception::getFile
Get the name of the file in which the exception was created.
ENTITY ENTITY
ENTITY
Returns the filename in which the exception was created.
ENTITY
Exception::getFile example
getFile();
}
?>
ENTITY
/home/bjori/tmp/ex.php
ENTITY
Throwable::getFile
getline
Exception::getLine
Gets the line in which the exception was created
ENTITY
final
public
int
Exception::getLine
Get line number where the exception was created.
ENTITY ENTITY
ENTITY
Returns the line number where the exception was created.
ENTITY
Exception::getLine example
getLine();
}
?>
ENTITY
The exception was created on line: 3
ENTITY
Throwable::getLine
getmessage
Exception::getMessage
Gets the Exception message
ENTITY
final
public
string
Exception::getMessage
Returns the Exception message.
ENTITY ENTITY
ENTITY
Returns the Exception message as a string.
ENTITY
Exception::getMessage example
getMessage();
}
?>
ENTITY
Some error message
ENTITY
Throwable::getMessage
getprevious
Exception::getPrevious
Returns previous Throwable
ENTITY
final
public
Throwable
null
Exception::getPrevious
Returns previous
Throwable (which had been passed as the third parameter of Exception::__construct).
ENTITY ENTITY
ENTITY
Returns the previous
Throwable if available or ENTITY otherwise.
ENTITY
Exception::getPrevious example
Looping over, and printing out, exception trace.
getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
} while($e = $e->getPrevious());
}
?>
ENTITY
/home/bjori/ex.php:8 Something happened (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]
ENTITY
Throwable::getPrevious
gettrace
Exception::getTrace
Gets the stack trace
ENTITY
final
public
array
Exception::getTrace
Returns the Exception stack trace.
ENTITY ENTITY
ENTITY
Returns the Exception stack trace as an
array.
ENTITY
Exception::getTrace example
getTrace());
}
?>
ENTITY
array(1) {
[0]=>
array(4) {
["file"]=>
string(22) "/home/bjori/tmp/ex.php"
["line"]=>
int(7)
["function"]=>
string(4) "test"
["args"]=>
array(0) {
}
}
}
ENTITY
Throwable::getTrace
gettraceasstring
Exception::getTraceAsString
Gets the stack trace as a string
ENTITY
final
public
string
Exception::getTraceAsString
Returns the Exception stack trace as a string.
ENTITY ENTITY
ENTITY
Returns the Exception stack trace as a string.
ENTITY
Exception::getTraceAsString example
getTraceAsString();
}
?>
ENTITY
#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}
ENTITY
Throwable::getTraceAsString
tostring
Exception::__toString
String representation of the exception
ENTITY
public
string
Exception::__toString
Returns the
string representation of the exception.
ENTITY ENTITY
ENTITY
Returns the
string representation of the exception.
ENTITY
Exception::__toString example
ENTITY
exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}
ENTITY
Throwable::__toString
Predefined Exceptions
See also the SPL Exceptions.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
fiber
ENTITY
Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack, pausing execution within the fiber until the fiber is resumed at a later time.
ENTITY
final
Fiber
ENTITY
ENTITY
Fibers overview
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
construct
Fiber::__construct
Creates a new Fiber instance
ENTITY
public
Fiber::__construct
callable
callback
ENTITY
callback
The
callable to invoke when starting the fiber. Arguments given to Fiber::start will be provided as arguments to the given callable.
getcurrent
Fiber::getCurrent
Gets the currently executing Fiber instance
ENTITY
public
static
Fiber
null
Fiber::getCurrent
ENTITY ENTITY
ENTITY
Returns the currently executing
Fiber instance or ENTITY if this method is called from outside a fiber.
getreturn
Fiber::getReturn
Gets the value returned by the Fiber
ENTITY
public
mixed
Fiber::getReturn
ENTITY ENTITY
ENTITY
Returns the value returned by the
callable provided to Fiber::__construct. If the fiber has not returned a value, either because it has not been started, has not terminated, or threw an exception, a FiberError will be thrown.
isrunning
Fiber::isRunning
Determines if the fiber is running
ENTITY
public
bool
Fiber::isRunning
ENTITY ENTITY
ENTITY
Returns ENTITY only if the fiber is running. A fiber is considered running after a call to Fiber::start, Fiber::resume, or Fiber::throw that has not yet returned. Returns ENTITY if the fiber is not running.
isstarted
Fiber::isStarted
Determines if the fiber has started
ENTITY
public
bool
Fiber::isStarted
ENTITY ENTITY
ENTITY
Returns ENTITY only after the fiber has been started; otherwise ENTITY is returned.
issuspended
Fiber::isSuspended
Determines if the fiber is suspended
ENTITY
public
bool
Fiber::isSuspended
ENTITY ENTITY
ENTITY
Returns ENTITY if the fiber is currently suspended; otherwise ENTITY is returned.
isterminated
Fiber::isTerminated
Determines if the fiber has terminated
ENTITY
public
bool
Fiber::isTerminated
ENTITY ENTITY
ENTITY
Returns ENTITY only after the fiber has terminated, either by returning or throwing an exception; otherwise ENTITY is returned.
resume
Fiber::resume
Resumes execution of the fiber with a value
ENTITY
public
mixed
Fiber::resume
mixed
value
ENTITY
Resumes the fiber using the given value as the result of the current Fiber::suspend call.
If the fiber is not suspended when this method is called, a FiberError will be thrown.
ENTITY
value
The value to resume the fiber. This value will be the return value of the current Fiber::suspend call.
ENTITY
The value provided to the next call to Fiber::suspend or ENTITY if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method.
start
Fiber::start
Start execution of the fiber
ENTITY
public
mixed
Fiber::start
mixed
args
A variadic list of arguments to provide to the callable used when constructing the fiber.
If the fiber has already been started when this method is called, a FiberError will be thrown.
ENTITY
args
The arguments to use when invoking the callable given to the fiber constructor.
ENTITY
The value provided to the first call to Fiber::suspend or ENTITY if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method.
suspend
Fiber::suspend
Suspends execution of the current fiber
ENTITY
public
static
mixed
Fiber::suspend
mixed
value
ENTITY
Suspends execution of the current fiber. The value provided to this method will be returned from the call to Fiber::start, Fiber::resume, or Fiber::throw that switched execution into the current fiber.
When the fiber is resumed, this method returns the value provided to Fiber::resume. If the fiber is resumed using Fiber::throw, the exception given to that method will be thrown from the call to this method.
If this method is called from outside a fiber, a FiberError will be thrown.
ENTITY
value
The value to return from the call to Fiber::start, Fiber::resume, or Fiber::throw that switched execution into the current fiber.
ENTITY
The value provided to Fiber::resume.
throw
Fiber::throw
Resumes execution of the fiber with an exception
ENTITY
public
mixed
Fiber::throw
Throwable
exception
Resumes the fiber by throwing the given exception from the current Fiber::suspend call.
If the fiber is not suspended when this method is called, a FiberError will be thrown.
ENTITY
exception
The exception to throw into the fiber from the current Fiber::suspend call.
ENTITY
The value provided to the next call to Fiber::suspend or ENTITY if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method.
ENTITY
getMessage();
}
});
$fiber->start();
// Resumes execution of the fiber with
// passing the Exception to throw at the interruption point
$fiber->throw(new Exception('Message of an exception thrown at the current interrupt point'));
?>
ENTITY
Message of an exception thrown at the current interrupt point
fibererror
ENTITY
FiberError is thrown when an invalid operation is performed on a
Fiber.
ENTITY
final
FiberError
extends
Error
ENTITY
ENTITY
ENTITY
ENTITY
construct
FiberError::__construct
Constructor to disallow direct instantiation
ENTITY
public
FiberError::__construct
ENTITY ENTITY
ENTITY
Throws an Error exception when called.
generator
ENTITY
Generator objects are returned from generators.
[!CAUTION]
Generator objects cannot be instantiated via new.
ENTITY
final
Generator
implements
Iterator
ENTITY
ENTITY
See also object iteration.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
current
Generator::current
Get the yielded value
ENTITY
public
mixed
Generator::current
ENTITY ENTITY
ENTITY
Returns the yielded value.
getreturn
Generator::getReturn
Get the return value of a generator
ENTITY
public
mixed
Generator::getReturn
ENTITY ENTITY
ENTITY
Returns the generator's return value once it has finished executing.
ENTITY
Generator::getReturn example
getReturn(), PHP_EOL;
ENTITY
1
2
3
key
Generator::key
Get the yielded key
ENTITY
public
mixed
Generator::key
Gets the key of the yielded value.
ENTITY ENTITY
ENTITY
Returns the yielded key.
ENTITY
Generator::key example
'value';
}
$gen = Gen();
echo "{$gen->key()} => {$gen->current()}";
ENTITY
key => value
next
Generator::next
Resume execution of the generator
ENTITY
public
void
Generator::next
Calling Generator::next has the same effect as calling Generator::send with ENTITY as argument.
ENTITY ENTITY
ENTITY
ENTITY
rewind
Generator::rewind
Execute the generator up to and including the first yield
ENTITY
public
void
Generator::rewind
Executes the generator up to and including the first ENTITY. If the generator is already at the first ENTITY, no action will be taken. If the generator has ever advanced beyond a ENTITY expression, this method will throw an
Exception.
[!NOTE]
This is the first method called when starting a ENTITY loop. It will not be executed after ENTITY loops.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
Generator::rewind example
rewind(); // I'm a generator!
// Nothing happens here; the generator is already rewound
$generator->rewind(); // No output (NULL)
// This rewinds the generator to the first yield expression,
// if it's not already there, and iterates over the generator
foreach ($generator as $value) {
// After yielding the first value, the generator remains at
// the first yield expression until it resumes execution and advances to the next yield
echo $value, PHP_EOL; // 1
break;
}
// Resume and rewind again. No error occurs because the generator has not advanced beyond the first yield
$generator->rewind();
echo $generator->current(), PHP_EOL; // 1
// No error occurs, the generator is still at the first yield
$generator->rewind();
// This advances the generator to the second yield expression
$generator->next();
try {
// This will throw an Exception,
// because the generator has already advanced to the second yield
$generator->rewind(); // Fatal error: Uncaught Exception: Cannot rewind a generator that was already run
} catch (Exception $e) {
echo $e->getMessage();
}
?>
ENTITY
I'm a generator!
1
1
Cannot rewind a generator that was already run
send
Generator::send
Send a value to the generator
ENTITY
public
mixed
Generator::send
mixed
value
Sends the given value to the generator as the result of the current ENTITY expression and resumes execution of the generator.
If the generator is not at a ENTITY expression when this method is called, it will first be let to advance to the first ENTITY 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).
ENTITY
value
Value to send into the generator. This value will be the return value of the ENTITY expression the generator is currently at.
ENTITY
Returns the yielded value.
ENTITY
Using Generator::send to inject values
send('Hello world!');
$printer->send('Bye world!');
?>
ENTITY
I'm printer!
Hello world!
Bye world!
throw
Generator::throw
Throw an exception into the generator
ENTITY
public
mixed
Generator::throw
Throwable
exception
Throws an exception into the generator and resumes execution of the generator. The behavior will be the same as if the current ENTITY 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.
ENTITY
exception
Exception to throw into the generator.
ENTITY
Returns the yielded value.
ENTITY
Throwing an exception into a generator
getMessage()}\n";
}
echo "Bar\n";
}
$gen = gen();
$gen->rewind();
$gen->throw(new Exception('Test'));
?>
ENTITY
Foo
Exception: Test
Bar
valid
Generator::valid
Check if the iterator has been closed
ENTITY
public
bool
Generator::valid
ENTITY ENTITY
ENTITY
Returns ENTITY if the iterator has been closed. Otherwise returns ENTITY.
wakeup
Generator::__wakeup
Serialize callback
ENTITY
public
void
Generator::__wakeup
Throws an exception as generators can't be serialized.
ENTITY ENTITY
ENTITY
ENTITY
Predefined Interfaces and Classes
See also the SPL Interfaces and reserved classes.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
internaliterator
ENTITY
Class to ease implementing IteratorAggregate for internal classes.
ENTITY
final
InternalIterator
implements
Iterator
ENTITY
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
construct
InternalIterator::__construct
Private constructor to disallow direct instantiation
ENTITY
private
InternalIterator::__construct
ENTITY ENTITY
current
InternalIterator::current
Return the current element
ENTITY
public
mixed
InternalIterator::current
Returns the current element.
ENTITY ENTITY
ENTITY
Returns the current element.
key
InternalIterator::key
Return the key of the current element
ENTITY
public
mixed
InternalIterator::key
Returns the key of the current element.
ENTITY ENTITY
ENTITY
Returns the key of the current element.
next
InternalIterator::next
Move forward to next element
ENTITY
public
void
InternalIterator::next
Moves the current position to the next element.
ENTITY ENTITY
ENTITY
ENTITY
rewind
InternalIterator::rewind
Rewind the Iterator to the first element
ENTITY
public
void
InternalIterator::rewind
Rewinds back to the first element of the Iterator.
ENTITY ENTITY
ENTITY
ENTITY
valid
InternalIterator::valid
Check if current position is valid
ENTITY
public
bool
InternalIterator::valid
Checks if current position is valid.
ENTITY ENTITY
ENTITY
Returns whether the current position is valid.
iterator
ENTITY
Interface for external iterators or objects that can be iterated themselves internally.
ENTITY
Iterator
extends
Traversable
ENTITY
Predefined iterators
PHP already provides a number of iterators for many day-to-day tasks. See SPL iterators for a list.
ENTITY
Basic usage
This example demonstrates in which order methods are called when using ENTITY with an iterator.
position = 0;
}
public function rewind(): void {
var_dump(__METHOD__);
$this->position = 0;
}
#[\ReturnTypeWillChange]
public function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
#[\ReturnTypeWillChange]
public function key() {
var_dump(__METHOD__);
return $this->position;
}
public function next(): void {
var_dump(__METHOD__);
++$this->position;
}
public function valid(): bool {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
ENTITY
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"
ENTITY
See also object iteration.
ENTITY ENTITY ENTITY ENTITY ENTITY
current
Iterator::current
Return the current element
ENTITY
public
mixed
Iterator::current
Returns the current element.
ENTITY ENTITY
ENTITY
Can return any type.
key
Iterator::key
Return the key of the current element
ENTITY
public
mixed
Iterator::key
Returns the key of the current element.
ENTITY ENTITY
ENTITY
Returns
scalar on success, or ENTITY on failure.
ENTITY
Issues
E_NOTICE on failure.
next
Iterator::next
Move forward to next element
ENTITY
public
void
Iterator::next
Moves the current position to the next element.
[!NOTE]
This method is called after each ENTITY loop.
ENTITY ENTITY
ENTITY
Any returned value is ignored.
rewind
Iterator::rewind
Rewind the Iterator to the first element
ENTITY
public
void
Iterator::rewind
Rewinds back to the first element of the Iterator.
[!NOTE]
This is the first method called when starting a ENTITY loop. It will not be executed after ENTITY loops.
As ENTITY always calls this method before starting iteration, manually advancing the iterator position (for example via SplFileObject::seek) will be reset.
To iterate without rewinding the iterator, wrap it in a
NoRewindIterator.
ENTITY ENTITY
ENTITY
Any returned value is ignored.
valid
Iterator::valid
Checks if current position is valid
ENTITY
public
bool
Iterator::valid
This method is called after Iterator::rewind and Iterator::next to check if the current position is valid.
ENTITY ENTITY
ENTITY
The return value will be casted to
bool and then evaluated. ENTITY
iteratoraggregate
ENTITY
Interface to create an external Iterator.
ENTITY
IteratorAggregate
extends
Traversable
ENTITY
ENTITY
Basic usage
"item one",
"key two" => "item two",
"key three" => "item three"
]);
}
}
$obj = new myData();
foreach ($obj as $key => $value) {
var_dump($key, $value);
echo "\n";
}
ENTITY
string(7) "key one"
string(8) "item one"
string(7) "key two"
string(8) "item two"
string(9) "key three"
string(10) "item three"
ENTITY
getiterator
IteratorAggregate::getIterator
Retrieve an external iterator or traversable
ENTITY
public
Traversable
IteratorAggregate::getIterator
Returns an external iterator or traversable.
ENTITY ENTITY
ENTITY
An instance of an object implementing
Iterator or
Traversable
ENTITY
Throws an
Exception on failure.
parseerror
ENTITY
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.
ENTITY
ParseError
extends
CompileError
ENTITY
ENTITY
php-incomplete-class
ENTITY
Created by
unserialize when trying to unserialize an undefined class or a class that is not listed in the
allowed_classes of
unserialize's
options array.
Prior to PHP 7.2.0, using
is_object on the
__PHP_Incomplete_Class class would return ENTITY. As of PHP 7.2.0, ENTITY will be returned.
ENTITY
#[\AllowDynamicProperties]
final
__PHP_Incomplete_Class
This class has no default properties or methods. When created by
unserialize, in addition to all unserialized properties and values the object will have a
__PHP_Incomplete_Class_Name property which will contain the name of the unserialized class.
ENTITY
ENTITY
ENTITY
8.0.0
This class is now
final.
ENTITY
Created by
unserialize
false]);
var_dump($disallowed);
// unserializes all objects into __PHP_Incomplete_Class objects except those of MyClass2 and MyClass3
$disallowed2 = unserialize($foo, ["allowed_classes" => ["MyClass2", "MyClass3"]]);
var_dump($disallowed2);
// unserializes undefined class into __PHP_Incomplete_Class object
$undefinedClass = unserialize('O:16:"MyUndefinedClass":0:{}');
var_dump($undefinedClass);
ENTITY
object(__PHP_Incomplete_Class)#2 (2) {
["__PHP_Incomplete_Class_Name"]=>
string(7) "MyClass"
["property"]=>
string(7) "myValue"
}
object(__PHP_Incomplete_Class)#3 (2) {
["__PHP_Incomplete_Class_Name"]=>
string(7) "MyClass"
["property"]=>
string(7) "myValue"
}
object(__PHP_Incomplete_Class)#4 (1) {
["__PHP_Incomplete_Class_Name"]=>
string(16) "MyUndefinedClass"
}
requestparsebodyexception
ENTITY
A RequestParseBodyException is thrown in
request_parse_body when the request body is invalid, according to the
Content-Type header.
ENTITY
RequestParseBodyException
extends
Exception
ENTITY
ENTITY
construct
ReturnTypeWillChange::__construct
Construct a new ReturnTypeWillChange attribute instance
ENTITY
public
ReturnTypeWillChange::__construct
Constructs a new
ReturnTypeWillChange instance.
ENTITY ENTITY
construct
SensitiveParameter::__construct
Construct a new SensitiveParameter attribute instance
ENTITY
public
SensitiveParameter::__construct
Constructs a new
SensitiveParameter instance.
ENTITY ENTITY
sensitiveparametervalue
ENTITY
The
SensitiveParameterValue class allows wrapping sensitive values to protect them against accidental exposure.
Values of parameters having the
SensitiveParameter attribute will automatically be wrapped inside of a
SensitiveParameterValue object within stack traces.
ENTITY
final
SensitiveParameterValue
ENTITY
private
readonly
mixed
value
ENTITY
ENTITY
value
The sensitive value to be protected against accidental exposure.
ENTITY ENTITY ENTITY
construct
SensitiveParameterValue::__construct
Constructs a new SensitiveParameterValue object
ENTITY
public
SensitiveParameterValue::__construct
mixed
value
Construct a
SensitiveParameterValue holding a sensitive value.
ENTITY
value
An arbitrary value that should be stored inside the
SensitiveParameterValue object.
debuginfo
SensitiveParameterValue::__debugInfo
Protects the sensitive value against accidental exposure
ENTITY
public
array
SensitiveParameterValue::__debugInfo
Returns an empty ENTITY to protect the sensitive value against accidental exposure when using
var_dump.
ENTITY ENTITY
ENTITY
An empty ENTITY.
ENTITY
Passing a
SensitiveParameterValue object to
var_dump
ENTITY
object(SensitiveParameterValue)#1 (0) {
}
getvalue
SensitiveParameterValue::getValue
Returns the sensitive value
ENTITY
public
mixed
SensitiveParameterValue::getValue
Get the sensitive value.
ENTITY ENTITY
ENTITY
The sensitive value.
ENTITY
SensitiveParameterValue::getValue example
getValue(), "\n";
?>
ENTITY
The protected value is: secret
serializable
ENTITY
Interface for customized serializing.
Classes that implement this interface no longer support __sleep() and __wakeup(). The serialize method 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. The constructor can be called from within the unserialize method if desired.
[!WARNING]
As of PHP 8.1.0, a class which implements Serializable without also implementing __serialize() and __unserialize() will generate a deprecation warning.
New code should use the __serialize() and __unserialize() magic methods instead, available as of PHP 7.4.0. When a class declares both them and this interface,
serialize always uses __serialize() and never reaches Serializable::serialize. Unserializing is decided by the format of the data instead: a payload written by PHP 7.4.0 or later is read by __unserialize(), one written before it is still read by Serializable::unserialize. Implementing Serializable therefore remains of use for reading such older payloads, and for satisfying a Serializable type declaration; declaring all four methods covers every case, and avoids the deprecation notice.
[!NOTE]
The magic methods have no interface of their own, so a class which declares them without implementing Serializable is not an instance of it.
method_exists is the way to detect them.
ENTITY
Serializable
ENTITY
ENTITY
Supporting PHP 7.1.0 through 7.3.0
The magic methods carry the serialized form, and the interface methods delegate to them, so that a single representation serves both.
label = $label;
}
public function __serialize(): array
{
return ['label' => $this->label];
}
public function __unserialize(array $data): void
{
$this->label = $data['label'];
}
// Never called as of PHP 7.4.0
public function serialize()
{
return serialize($this->__serialize());
}
// Still called as of PHP 7.4.0, for data written before it
public function unserialize($data)
{
$this->__unserialize(unserialize($data));
}
}
var_dump(serialize(new Task('deploy')));
?>
ENTITY
string(40) "O:4:"Task":1:{s:5:"label";s:6:"deploy";}"
Prior to PHP 7.4.0, the same code serializes through the interface instead, and outputs
string(47) "C:4:"Task":31:{a:1:{s:5:"label";s:6:"deploy";}}".
ENTITY ENTITY
serialize
Serializable::serialize
String representation of object
ENTITY
public
string
null
Serializable::serialize
Should return the string representation of the object.
ENTITY ENTITY
ENTITY
Returns the string representation of the object or ENTITY
ENTITY
Throws
Exception when returning other types than strings and ENTITY.
ENTITY
__sleep(), __serialize()
unserialize
Serializable::unserialize
Constructs the object
ENTITY
public
void
Serializable::unserialize
string
data
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.
ENTITY
data
The string representation of the object.
ENTITY
The return value from this method is ignored.
ENTITY
__wakeup(), __unserialize()
stdclass
ENTITY
A generic empty class with dynamic properties.
Objects of this class can be instantiated with the new operator or created by typecasting to object. Several PHP functions also create instances of this class, e.g.
json_decode,
mysqli_fetch_object or PDOStatement::fetchObject.
Despite not implementing __get()/__set() magic methods, this class allows dynamic properties and does not require the
#[\AllowDynamicProperties] attribute.
This is not a base class as PHP does not have a concept of a universal base class. However, it is possible to create a custom class that extends
stdClass and as a result inherits the functionality of dynamic properties.
ENTITY
#[\AllowDynamicProperties]
stdClass
This class has no methods or default properties.
ENTITY
Created as a result of typecasting to object
'bar');
var_dump($obj);
ENTITY
object(stdClass)#1 (1) {
["foo"]=>
string(3) "bar"
}
Created as a result of
json_decode
string(3) "bar"
}
Declaring dynamic properties
foo = 42;
$obj->{1} = 42;
var_dump($obj);
ENTITY
object(stdClass)#1 (2) {
["foo"]=>
int(42)
["1"]=>
int(42)
}
stringable
ENTITY
The Stringable interface denotes a class as having a __toString() method. Unlike most interfaces, Stringable is implicitly present on any class that has the magic __toString() method defined, although it can and should be declared explicitly.
Its primary value is to allow functions to type check against the union type
string|Stringable to accept either a string primitive or an object that can be cast to a string.
ENTITY
Stringable
ENTITY
Stringable Examples
Basic Stringable Usage
This uses constructor property promotion.
oct1.$this->oct2.$this->oct3.$this->oct4";
}
}
function showStuff(string|Stringable $value) {
// For a Stringable, this will implicitly call __toString().
print $value;
}
$ip = new IPv4Address('123', '234', '42', '9');
showStuff($ip);
?>
ENTITY
123.234.42.9
ENTITY
tostring
Stringable::__toString
Gets a string representation of the object
ENTITY
public
string
Stringable::__toString
ENTITY ENTITY
ENTITY
Returns the ENTITY representation of the object.
ENTITY
__toString()
throwable
ENTITY
Throwable is the base interface for any object that can be thrown via a ENTITY statement, including Error and Exception.
[!NOTE]
PHP classes cannot implement the Throwable interface directly, and must instead extend Exception.
ENTITY
Throwable
extends
Stringable
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.0.0
Throwable implements Stringable now.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
getcode
Throwable::getCode
Gets the exception code
ENTITY
public
int
Throwable::getCode
Returns the error code associated with the thrown object.
ENTITY ENTITY
ENTITY
Returns the exception code as
int in
Exception but possibly as other type in
Exception descendants (for example as
string in
PDOException).
ENTITY
Exception::getCode
getfile
Throwable::getFile
Gets the file in which the object was created
ENTITY
public
string
Throwable::getFile
Get the name of the file in which the thrown object was created.
ENTITY ENTITY
ENTITY
Returns the filename in which the thrown object was created.
ENTITY
Exception::getFile
getline
Throwable::getLine
Gets the line on which the object was instantiated
ENTITY
public
int
Throwable::getLine
Returns the line number where the thrown object was instantiated.
ENTITY ENTITY
ENTITY
Returns the line number where the thrown object was instantiated.
ENTITY
Exception::getLine
getmessage
Throwable::getMessage
Gets the message
ENTITY
public
string
Throwable::getMessage
Returns the message associated with the thrown object.
ENTITY ENTITY
ENTITY
Returns the message associated with the thrown object.
ENTITY
Exception::getMessage
getprevious
Throwable::getPrevious
Returns the previous Throwable
ENTITY
public
Throwable
null
Throwable::getPrevious
Returns any previous Throwable (for example, one provided as the third parameter to Exception::__construct).
ENTITY ENTITY
ENTITY
Returns the previous
Throwable if available, or ENTITY otherwise.
ENTITY
Exception::getPrevious
gettrace
Throwable::getTrace
Gets the stack trace
ENTITY
public
array
Throwable::getTrace
Returns the stack trace as an
array.
ENTITY ENTITY
ENTITY
Returns the stack trace as an
array in the same format as
debug_backtrace.
ENTITY
Exception::getTrace
gettraceasstring
Throwable::getTraceAsString
Gets the stack trace as a string
ENTITY
public
string
Throwable::getTraceAsString
ENTITY ENTITY
ENTITY
Returns the stack trace as a string.
ENTITY
Exception::getTraceAsString
tostring
Throwable::__toString
Gets a string representation of the thrown object
ENTITY
public
string
Throwable::__toString
ENTITY ENTITY
ENTITY
Returns the
string representation of the thrown object.
ENTITY
Exception::__toString
traversable
ENTITY
Interface to detect if a class is traversable using ENTITY.
Abstract base interface that cannot be implemented alone. Instead, it must be implemented by either IteratorAggregate or Iterator.
ENTITY
Traversable
This interface has no methods; its only purpose is to be the base interface for all traversable classes.
ENTITY
ENTITY
ENTITY
8.0.0
The Traversable interface can now be implemented by abstract classes. Extending classes must implement Iterator or IteratorAggregate.
ENTITY
[!NOTE]
Internal (built-in) classes that implement this interface can be used in a ENTITY construct and do not need to implement IteratorAggregate or Iterator.
[!NOTE]
Prior to PHP 8.0.0, this internal engine interface couldn't be directly implemented in PHP scripts — not even by abstract classes. Either IteratorAggregate or Iterator must be used instead.
typeerror
ENTITY
A TypeError may be thrown when: The value being set for a class property does not match the property's corresponding declared type., The argument type being passed to a function does not match its corresponding declared parameter type., A value being returned from a function does not match the declared function return type.
ENTITY
TypeError
extends
Error
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
7.1.0
In strict mode, passing an incorrect number of arguments to a built-in PHP function no longer results in a generic TypeError. Instead, a more specific ArgumentCountError, which extends TypeError, is thrown.
unhandledmatcherror
ENTITY
An
UnhandledMatchError is thrown when the subject passed to a ENTITY expression is not handled by any arm of the ENTITY expression.
ENTITY
UnhandledMatchError
extends
Error
ENTITY
ENTITY
unitenum
ENTITY
The
UnitEnum interface is automatically applied to all enumerations by the engine. It may not be implemented by user-defined classes. Enumerations may not override its methods, as default implementations are provided by the engine. It is available only for type checks.
ENTITY
UnitEnum
ENTITY
ENTITY
cases
UnitEnum::cases
Generates a list of cases on an enum
ENTITY
public
static
array
UnitEnum::cases
This method will return a packed array of all cases in an enumeration, in order of declaration.
ENTITY ENTITY
ENTITY
An array of all defined cases of this enumeration, in order of declaration.
ENTITY
Basic usage
The following example illustrates how enum cases are returned.
enum(Suit::Hearts)
[1]=>
enum(Suit::Diamonds)
[2]=>
enum(Suit::Clubs)
[3]=>
enum(Suit::Spades)
}
valueerror
ENTITY
A
ValueError is thrown when the type of an argument is correct but its value is incorrect. For example, passing a negative integer when the function expects a positive one, or passing an empty string/array when the function expects it to not be empty.
ENTITY
ValueError
extends
Error
ENTITY
ENTITY
variables
PHP provides predefined variables that represent external variables, built-in environment variables, and other information about the execution environment, such as the number and values of the arguments passed to the script in the CLI environment.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
argc
$argc
The number of arguments passed to script
ENTITY
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.
ENTITY
$argc example
When executing the example with: php script.php arg1 arg2 arg3
ENTITY
int(4)
ENTITY
[!NOTE]
This is also available as
$_SERVER['argc'].
ENTITY
getopt,
$argv
argv
$argv
Array of arguments passed to script
ENTITY
Contains an
array of all the arguments passed to the script when running from the command line.
[!NOTE]
The first argument
$argv[0] is always the name that was used to run the script.
[!NOTE]
This variable is not available when register_argc_argv is disabled.
[!WARNING]
To test if a script is being run from the command line,
php_sapi_name should be used instead of checking whether
$argv or
$_SERVER['argv'] is set.
ENTITY
$argv example
When executing the example with: php script.php arg1 arg2 arg3
ENTITY
array(4) {
[0]=>
string(10) "script.php"
[1]=>
string(4) "arg1"
[2]=>
string(4) "arg2"
[3]=>
string(4) "arg3"
}
ENTITY
[!NOTE]
This is also available as
$_SERVER['argv'].
ENTITY
getopt,
$argc
cookie
$_COOKIE
HTTP Cookies
ENTITY
An associative
array of variables passed to the current script via HTTP Cookies.
ENTITY
$_COOKIE example
Assuming the "name" cookie has been set earlier
ENTITY
Hello Hannes!
ENTITY ENTITY
ENTITY
setcookie, Handling external variables, The filter extension
env
$_ENV
Environment variables
ENTITY
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.
ENTITY
$_ENV example
Assuming "bjori" executes this script
ENTITY
My username is bjori!
ENTITY ENTITY
ENTITY
getenv, The filter extension
files
$_FILES
HTTP File Upload variables
ENTITY
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.
ENTITY ENTITY
ENTITY
move_uploaded_file, Handling File Uploads
get
$_GET
Query string variables
ENTITY
An associative array of variables passed to the current script via the URL parameters (also known as the query string). Note that this array is populated whenever a query string is present, regardless of the HTTP request method.
ENTITY
$_GET example
Assuming the user entered
http://example.com/?name=Hannes.
ENTITY
Hello Hannes!
ENTITY ENTITY
[!NOTE]
The values in
$_GET are automatically passed through
urldecode.
ENTITY
Handling external variables, The filter extension
globals
$GLOBALS
References all variables available in global scope
ENTITY
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.
ENTITY
$GLOBALS example
ENTITY
$foo in global scope: Example content
$foo in current scope: local variable
[!WARNING]
As of PHP 8.1.0, write access to the entire
$GLOBALS array is no longer supported:
writing entire
$GLOBALS will result in error.
ENTITY ENTITY
[!NOTE]
Unlike all of the other superglobals,
$GLOBALS has essentially always been available in PHP.
[!NOTE]
As of PHP 8.1.0,
$GLOBALS is now a read-only copy of the global symbol table. That is, global variables cannot be modified via its copy. Previously,
$GLOBALS array is excluded from the usual by-value behavior of PHP arrays and global variables can be modified via its copy.
$value) {
$GLOBALS[$key] = $value;
}
?>
httpresponseheader
$http_response_header
HTTP response headers
ENTITY
Use
http_get_last_response_headers instead.
ENTITY
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.
ENTITY
$http_response_header example
ENTITY
array(9) {
[0]=>
string(15) "HTTP/1.1 200 OK"
[1]=>
string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
[2]=>
string(29) "Server: Apache/2.2.3 (CentOS)"
[3]=>
string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
[4]=>
string(27) "ETag: "280100-1b6-80bfd280""
[5]=>
string(20) "Accept-Ranges: bytes"
[6]=>
string(19) "Content-Length: 438"
[7]=>
string(17) "Connection: close"
[8]=>
string(38) "Content-Type: text/html; charset=UTF-8"
}
Warning: Undefined variable $http_response_header
NULL
ENTITY
http_get_last_response_headers
http_clear_last_response_headers
phperrormsg
$php_errormsg
The previous error message
ENTITY
Use
error_get_last instead.
ENTITY
$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 ENTITY.
ENTITY
ENTITY
ENTITY
8.0.0
Directive track_errors which caused
$php_errormsg to be available has been removed.
7.2.0
Directive track_errors which caused
$php_errormsg to be available has been deprecated.
ENTITY
$php_errormsg example
ENTITY
Wrong parameter count for strpos()
ENTITY
error_get_last
post
$_POST
Form data from HTTP POST requests
ENTITY
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.
ENTITY
$_POST example
Assuming the user sent a POST request with
name=Hannes in the body.
ENTITY
Hello Hannes!
ENTITY ENTITY
[!NOTE]
To read POST data sent with other content types (e.g.
application/json or
application/xml)
php://input must be used. Unlike
$_POST, which only works with
application/x-www-form-urlencoded and
multipart/form-data,
php://input provides direct access to the raw data from the body of the request.
ENTITY
Handling external variables, The filter extension
request
$_REQUEST
HTTP Request variables
ENTITY
An associative
array that by default contains the contents of
$_GET,
$_POSTENTITY
$_COOKIE.
ENTITY ENTITY
[!NOTE]
When running on the command line , this will not include the argv and argc entries; these are present in the
$_SERVER
array.
[!NOTE]
The variables in
$_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP request_order, and variables_order configuration directives.
ENTITY
Handling external variables
The filter extension
server
$_SERVER
Server and execution environment information
ENTITY
$_SERVER is an ENTITY containing information such as headers, paths, and script locations. The entries in this array are created by the web server, therefore there is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. However, most of these variables are accounted for in the CGI/1.1 specification, and are likely to be defined.
[!NOTE]
When running PHP on the command line most of these entries will not be available or have any meaning.
In addition to the elements listed below, PHP will create additional elements with values from request headers. These entries will be named
HTTP_ followed by the header name, capitalized and with underscores instead of hyphens. For example, the
Accept-Language header would be available as
$_SERVER['HTTP_ACCEPT_LANGUAGE'].
ENTITY
'
PHP_SELF'
The filename of the currently executing script, relative to the document root. For instance,
$_SERVER['PHP_SELF'] in a script at the address
http://example.com/foo/bar.php would be
/foo/bar.php. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
If PHP is running as a command-line processor this variable contains the script name.
'argv'
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'
GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; e.g.
'CGI/1.1'.
'
SERVER_ADDR'
The IP address of the server under which the current script is executing.
'
SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
[!NOTE]
Under Apache 2,
UseCanonicalName = On and
ServerName must be set. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.
'
SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'
SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; e.g.
'HTTP/1.0';
'
REQUEST_METHOD'
Which request method was used to access the page; e.g.
'GET',
'HEAD',
'POST',
'PUT'.
[!NOTE]
PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was
HEAD.
'
REQUEST_TIME'
The timestamp when PHP started processing the request.
'
REQUEST_TIME_FLOAT'
The timestamp when PHP started processing the request, with microsecond precision.
'
QUERY_STRING'
The query string, if any, via which the page was accessed.
'
DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'
HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.
'
REMOTE_ADDR'
The IP address from which the user is viewing the current page.
'
REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based on the
REMOTE_ADDR of the user.
[!NOTE]
The web server must be configured to create this variable. For example in Apache
HostnameLookups On must be set inside ENTITY for it to exist. See also
gethostbyaddr.
'
REMOTE_PORT'
The port being used on the user's machine to communicate with the web server.
'
REMOTE_USER'
The authenticated user.
'
REDIRECT_REMOTE_USER'
The authenticated user if the request is internally redirected.
'
SCRIPT_FILENAME'
The absolute pathname of the currently executing script.
[!NOTE]
If a script is executed with the CLI, as a relative path, such as
file.php or
../file.php,
$_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
'
SERVER_ADMIN'
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
'
SERVER_PORT'
The port on the server machine being used by the web server for communication. For default setups, this will be
'80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
[!NOTE]
Under Apache 2,
UseCanonicalName = On, as well as
UseCanonicalPhysicalPort = On must be set in order to get the physical (real) port, otherwise, this value can be spoofed, and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.
'
SERVER_SIGNATURE'
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
'
PATH_TRANSLATED'
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.
[!NOTE]
Apache 2 users may use
AcceptPathInfo = On inside
httpd.conf to define
PATH_INFO.
'
SCRIPT_NAME'
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'
REQUEST_URI'
The URI which was given in order to access this page; for instance, '
/index.html'.
'
PHP_AUTH_DIGEST'
When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'
PHP_AUTH_USER'
When doing HTTP authentication this variable is set to the username provided by the user.
'
PHP_AUTH_PW'
When doing HTTP authentication this variable is set to the password provided by the user.
'
AUTH_TYPE'
When doing HTTP authentication this variable is set to the authentication type.
'
PATH_INFO'
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URI
http://www.example.com/php/path_info.php/some/stuff?foo=bar, then
$_SERVER['PATH_INFO'] would contain
/some/stuff.
'
ORIG_PATH_INFO'
Original version of '
PATH_INFO' before processed by PHP.
ENTITY
$_SERVER example
ENTITY
www.example.com
ENTITY ENTITY
ENTITY
The filter extension
session
$_SESSION
Session variables
ENTITY
An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.
ENTITY ENTITY
ENTITY
session_start
superglobals
Superglobals
Built-in variables that are always available in all scopes
ENTITY
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
ENTITY
[!NOTE]
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]
Superglobals cannot be used as variable variables inside functions or class methods.
ENTITY
variable scope, The variables_order directive, The filter extension
weakmap
ENTITY
A
WeakMap is a map (or dictionary) that accepts objects as keys. However, unlike the otherwise similar
SplObjectStorage, an object in a key of a
WeakMap does not contribute toward the object's reference count. That is, if at any point the only remaining reference to an object is the key of a
WeakMap, the object will be garbage collected and removed from the
WeakMap. Its primary use case is for building caches of data derived from an object that do not need to live longer than the object.
WeakMap implements ArrayAccess, Traversable (via IteratorAggregate), and Countable, so in most cases it can be used in the same fashion as an associative array.
ENTITY
final
WeakMap
implements
ArrayAccess
Countable
IteratorAggregate
ENTITY
ENTITY
WeakMap usage example
get());
unset($obj);
var_dump($weakref->get());
?>
ENTITY
object(stdClass)#1 (0) {
}
NULL
ENTITY
ENTITY
ENTITY
8.4.0
The output of WeakReference::__debugInfo now includes the referenced object, or ENTITY if the reference is no longer valid.
ENTITY ENTITY ENTITY
construct
WeakReference::__construct
Constructor that disallows instantiation
ENTITY
public
WeakReference::__construct
This method exists only to disallow instantiation of the
WeakReference class. Weak references are to be instantiated with the factory method WeakReference::create.
ENTITY ENTITY
ENTITY
WeakReference::create
create
WeakReference::create
Create a new weak reference
ENTITY
public
static
WeakReference
WeakReference::create
object
object
Creates a new
WeakReference.
ENTITY
object
The object to be weakly referenced.
ENTITY
Returns a new
WeakReference, or the existing instance if there was already a
WeakReference to the same object.
get
WeakReference::get
Get a weakly referenced Object
ENTITY
public
object
null
WeakReference::get
Gets a weakly referenced object. If the object has already been destroyed, ENTITY is returned.
ENTITY ENTITY
ENTITY
Returns the referenced ENTITY, or ENTITY if the object has been destroyed.
References Explained
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:
d);
var_dump(property_exists($c, 'd')); // bool(true)
The same syntax can be used with functions that return references:
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
ENTITY in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for
$myValue.
[!NOTE]
If you try to return a reference from a function with the syntax:
return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else.
To use the returned reference, you must use reference assignment:
foo
)
[!NOTE]
If the assignment is done without the
ENTITY symbol, e.g.
$collection = collector();, the
$collection variable will receive a copy of the value, not the reference returned by the function.
To pass the returned reference to another function expecting a reference you can use this syntax:
ENTITY
bool
string
int(16)
[!NOTE]
Prior to PHP 8.0.0, where the
get_debug_type is not available, the
gettype function can be used instead. However, it doesn't use the canonical type names.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
Arrays
For a list of all array functions, see the array functions chapter in the documentation.
An
array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As
array values can be other
arrays, trees and multidimensional
arrays are also possible.
Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.
Syntax
Specifying with
array
An
array can be created using the
array language construct. It takes any number of comma-separated
key =ENTITY value pairs as arguments.
array(
key
=ENTITY
value
,
key2
=ENTITY
value2
,
key3
=ENTITY
value3
, ... )
The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e.
array(1, 2) is preferred over
array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.
[!NOTE]
A short array syntax exists which replaces
array() with
[].
A simple array
"bar",
"bar" => "foo",
);
// Using the short array syntax
$array2 = [
"foo" => "bar",
"bar" => "foo",
];
var_dump($array1, $array2);
?>
The can either be an
int or a
string. The can be of any type.
Additionally the following casts will occur:
Strings containing valid decimal
ints, unless the number is preceded by a
+ sign, will be cast to the
int type. E.g. the key
"8" will actually be stored under
8. On the other hand
"08" will not be cast, as it isn't a valid decimal integer.
Floats are also cast to
ints, which means that the fractional part will be truncated. E.g. the key
8.7 will actually be stored under
8.
Bools are cast to
ints, too, i.e. the key ENTITY will actually be stored under
1 and the key ENTITY under
0.
Null will be cast to the empty string, i.e. the key ENTITY 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.
Type Casting and Overwriting example
"a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
ENTITY
array(1) {
[1]=>
string(1) "d"
}
As all the keys in the above example are cast to
1, the value will be overwritten on every new element and the last assigned value
"d" is the only one left over.
PHP arrays can contain
int and
string keys at the same time as PHP does not distinguish between indexed and associative arrays.
Mixed
int and
string keys
"bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
ENTITY
array(4) {
["foo"]=>
string(3) "bar"
["bar"]=>
string(3) "foo"
[100]=>
int(-100)
[-100]=>
int(100)
}
The is optional. If it is not specified, PHP will use the increment of the largest previously used
int key.
Indexed arrays without key
ENTITY
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:
Keys not on all elements
"c",
"d",
);
var_dump($array);
?>
ENTITY
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.
Complex Type Casting and Overwriting example
This example includes all variations of type casting of keys and overwriting of elements.
'a',
'1' => 'b', // the value "a" will be overwritten by "b"
1.5 => 'c', // the value "b" will be overwritten by "c"
-1 => 'd',
'01' => 'e', // as this is not an integer string it will NOT override the key for 1
'1.5' => 'f', // as this is not an integer string it will NOT override the key for 1
true => 'g', // the value "c" will be overwritten by "g"
false => 'h',
'' => 'i',
null => 'j', // the value "i" will be overwritten by "j"
'k', // value "k" is assigned the key 2. This is because the largest integer key before that was 1
2 => 'l', // the value "k" will be overwritten by "l"
);
var_dump($array);
?>
ENTITY
array(7) {
[1]=>
string(1) "g"
[-1]=>
string(1) "d"
["01"]=>
string(1) "e"
["1.5"]=>
string(1) "f"
[0]=>
string(1) "h"
[""]=>
string(1) "j"
[2]=>
string(1) "l"
}
Negative index example
When assigning a negative integer key
n, PHP will take care to assign the next key to
n+1.
ENTITY
array(2) {
[-5]=>
int(1)
[-4]=>
int(2)
}
[!WARNING]
Prior to PHP 8.3.0, assigning a negative integer key
n would assign the next key to
0, the previous example would therefore output:
array(2) {
[-5]=>
int(1)
[0]=>
int(2)
}
Accessing array elements with square bracket syntax
Array elements can be accessed using the
array[key] syntax.
Accessing array elements
"bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
ENTITY
string(3) "bar"
int(24)
string(3) "foo"
[!NOTE]
Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g.
$array[42] and
$array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
Array dereferencing
[!NOTE]
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an
E_WARNING-level error message (
E_NOTICE-level prior to PHP 8.0.0) will be issued, and the result will be ENTITY.
[!NOTE]
Array dereferencing a scalar value which is not a
string yields ENTITY. Prior to PHP 7.4.0, that did not issue an error message. As of PHP 7.4.0, this issues
E_NOTICE; as of PHP 8.0.0, this issues
E_WARNING.
Creating/modifying with square bracket syntax
An existing
array can be modified by explicitly setting values in it.
This is done by assigning values to the
array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets (
[]).
$arr[
key
] =
value
; $arr[] =
value
; //
key
may be an
int
or
string
//
value
may be any value of any type
If
$arr doesn't exist yet or is set to ENTITY or ENTITY, 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 place and
[] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.
[!NOTE]
As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.
[!NOTE]
As of PHP 8.1.0, creating a new array from ENTITY value is deprecated. Creating a new array from ENTITY and undefined values is still allowed.
To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the
unset function on it.
Using Square Brackets with Arrays
1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
var_dump($arr);
unset($arr); // This deletes the whole array
var_dump($arr);
?>
[!NOTE]
If no key is specified, the key will be the maximum existing integer index +
1. If the array has no positive integer indices, the key will be
0. As of PHP 8.3.0, it can also be a negative integer.
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:
$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);
?>
ENTITY
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
)
Array
(
[5] => 6
)
Array
(
[0] => 6
[1] => 7
)
Array destructuring
Arrays can be destructured using the
[] (as of PHP 7.1.0) or
list language constructs. These constructs can be used to destructure an array into distinct variables.
Array Destructuring
Array destructuring can be used in ENTITY to destructure a multi-dimensional array while iterating over it.
Array Destructuring in Foreach
Array elements will be ignored if the variable is not provided. Array destructuring always starts at index
0.
Ignoring Elements
As of PHP 7.1.0, associative arrays can be destructured too. This also allows for easier selection of the right element in numerically indexed arrays as the index can be explicitly specified.
Destructuring Associative Arrays
1, 'bar' => 2, 'baz' => 3];
// Assign the element at index 'baz' to the variable $three
['baz' => $three] = $source_array;
echo $three, PHP_EOL; // prints 3
$source_array = ['foo', 'bar', 'baz'];
// Assign the element at index 2 to the variable $baz
[2 => $baz] = $source_array;
echo $baz, PHP_EOL; // prints "baz"
?>
Array destructuring can be used for easy swapping of two variables.
Swapping Two Variable
[!NOTE]
The spread operator (
...) is not supported in assignments.
[!NOTE]
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an
E_WARNING-level error message (
E_NOTICE-level prior to PHP 8.0.0) will be issued, and the result will be ENTITY.
[!NOTE]
Destructuring a scalar value assigns ENTITY to all variables.
Useful functions
There are quite a few useful functions for working with arrays. See the array functions section.
[!NOTE]
The
unset function allows removing keys from an
array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the
array can be reindexed using the
array_values function.
Unsetting Intermediate Elements
'one', 2 => 'two', 3 => 'three');
/* will produce an array that would have been defined as
$a = array(1 => 'one', 3 => 'three');
and NOT
$a = array(1 => 'one', 2 =>'three');
*/
unset($a[2]);
var_dump($a);
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
var_dump($b);
?>
The ENTITY 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:
This is wrong, but it works. The reason is that this code has an undefined constant (
bar) rather than a
string (
'bar' - notice the quotes). It works because PHP automatically converts a bare string (an unquoted
string which does not correspond to any known symbol) into a
string which contains the bare
string. For instance, if there is no defined constant named
bar, then PHP will substitute in the
string
'bar' and use that.
[!WARNING]
The fallback to treat an undefined constant as bare string issues an error of level
E_NOTICE. This has been deprecated as of PHP 7.2.0, and issues an error of level
E_WARNING. As of PHP 8.0.0, it has been removed and throws an
Error exception.
This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.
Key Quoting
ENTITY
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:
More Examples
'apple', 'veggie' => 'carrot');
// Correct
echo $arr['fruit'], PHP_EOL; // apple
echo $arr['veggie'], PHP_EOL; // carrot
// Incorrect. This does not work and throws a PHP Error because
// of an undefined constant named fruit
//
// Error: Undefined constant "fruit"
try {
echo $arr[fruit];
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), PHP_EOL;
}
// This defines a constant to demonstrate what's going on. The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
echo $arr['fruit'], PHP_EOL; // apple
echo $arr[fruit], PHP_EOL; // carrot
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no error occurs here
echo "Hello $arr[fruit]", PHP_EOL; // Hello apple
// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
echo "Hello {$arr[fruit]}", PHP_EOL; // Hello carrot
echo "Hello {$arr['fruit']}", PHP_EOL; // Hello apple
// Concatenation is another option
echo "Hello " . $arr['fruit'], PHP_EOL; // Hello apple
?>
As stated in the syntax section, what's inside the square brackets ('
[' and '
]') must be an expression. This means that code like this works:
This is an example of using a function return value as the array index. PHP also knows about constants:
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:
because
E_ERROR equals
1, etc.
So why is it bad then?
At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words
empty and
default this way, since they are reserved keywords.
[!NOTE]
To reiterate, inside a double-quoted
string, it's valid to not surround array indexes with quotes so
"$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.
Converting to array
For any of the types
int,
float,
string,
bool and
resource, converting a value to an
array results in an array with a single element with index zero and the value of the scalar which was converted. In other words,
(array) $scalarValue is exactly the same as
array($scalarValue).
If an
object is converted to an
array, the result is an
array whose elements are the
object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are inaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have
NUL bytes on either side. Uninitialized typed properties are silently discarded.
Converting to an Array
{1} = null;
}
}
var_export((array) new A());
?>
ENTITY
array (
'' . "\0" . 'A' . "\0" . 'B' => NULL,
'' . "\0" . '*' . "\0" . 'C' => NULL,
'D' => NULL,
1 => NULL,
)
These
NUL can result in some unexpected behaviour:
Casting an Object to an Array
ENTITY
array(3) {
["BA"]=>
NULL
["AA"]=>
NULL
["AA"]=>
NULL
}
ENTITY
array(3) {
["AA"]=>
NULL
["BA"]=>
NULL
["AA"]=>
NULL
}
The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.
Converting ENTITY to an
array results in an empty
array.
Comparing
It is possible to compare arrays with the
array_diff function and with array operators.
Array unpacking
An array prefixed by
... will be expanded in place during array definition. Only arrays and objects which implement Traversable can be expanded. Array unpacking with
... is available as of PHP 7.4.0. This is also called the spread operator.
It's possible to expand multiple times, and add normal elements before or after the
... operator:
Simple array unpacking
'd']; // ['a', 'b', 'c' => 'd']
var_dump($arr1, $arr2, $arr3, $arr4, $arr5, $arr6);
?>
Unpacking an array with the
... operator follows the semantics of the
array_merge function. That is, later string keys overwrite earlier ones and integer keys are renumbered:
Array unpacking with duplicate key
1];
$arr2 = ["a" => 2];
$arr3 = ["a" => 0, ...$arr1, ...$arr2];
var_dump($arr3); // ["a" => 2]
// integer key
$arr4 = [1, 2, 3];
$arr5 = [4, 5, 6];
$arr6 = [...$arr4, ...$arr5];
var_dump($arr6); // [1, 2, 3, 4, 5, 6]
// Which is [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6]
// where the original integer keys have not been retained.
?>
[!NOTE]
Keys that are neither integers nor strings throw a
TypeError. Such keys can only be generated by a Traversable object.
[!NOTE]
Prior to PHP 8.1, unpacking an array which has a string key is not supported:
4];
$arr3 = [...$arr1, ...$arr2];
// Fatal error: Uncaught Error: Cannot unpack array with string keys in example.php:5
$arr4 = [1, 2, 3];
$arr5 = [4, 5];
$arr6 = [...$arr4, ...$arr5]; // works. [1, 2, 3, 4, 5]
?>
Examples
The array type in PHP is very versatile. Here are some examples:
Array Versatility
'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
$b = array('a', 'b', 'c');
var_dump($a, $b);
// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
var_dump($a, $b);
?>
Using array()
4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
var_dump($map);
// strictly numerical keys
// this is the same as array(0 => 7, 1 => 8, ...)
$array = array( 7,
8,
0,
156,
-10
);
var_dump($array);
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
var_dump($switching);
// empty array
$empty = array();
var_dump($empty);
?>
Collection
ENTITY
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.
Changing element in the loop
ENTITY
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
This example creates a one-based array.
One-based index
'January', 'February', 'March');
print_r($firstquarter);
?>
ENTITY
Array
(
[1] => January
[2] => February
[3] => March
)
Filling an array
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.
Sorting an array
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.
Recursive and multi-dimensional arrays
array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
var_dump($fruits);
// Some examples to address values in the array above
echo $fruits["holes"][5]; // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]); // remove "first"
// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
var_dump($juices);
?>
Array assignment always involves value copying. Use the reference operator to copy an
array by reference.
Array Copying
Booleans
The
bool type only has two values, and is used to express a truth value. It can be either ENTITY or ENTITY.
Syntax
To specify a
bool literal, use the constants ENTITY or ENTITY. Both are case-insensitive.
Typically, the result of an operator which returns a
bool value is passed on to a control structure.
\n";
}
// ...because this can be used with exactly the same meaning:
if ($show_separators) {
echo "\n";
}
?>
Converting to boolean
To explicitly convert a value to
bool, use the
(bool) cast. Generally this is not necessary because when a value is used in a logical context it will be automatically interpreted as a value of type
bool. For more information see the Type Juggling page.
When converting to
bool, the following values are considered ENTITY:
the boolean ENTITY itself
the integer
0 (zero)
the floats
0.0 and
-0.0 (zero)
the empty string
"", and the string
"0"
an array with zero elements
the unit type NULL (including unset variables)
Internal objects that overload their casting behaviour to bool. For example,
GMP objects representing the value
0.
Every other value is considered ENTITY (including resource and
NAN).
[!WARNING]
-1 is considered ENTITY, like any other non-zero (whether negative or positive) number!
Casting to Boolean
Callables
A callable is a reference to a function or method that is passed to another function as an argument. They are represented with the
callable type declaration.
Some functions accept callback functions as a parameter, e.g.
array_map,
usort, or
preg_replace_callback.
Creation of callables
A callable is a type that represents something that can be invoked. Callables can be passed as arguments to functions or methods which expect a callback parameter or they can be invoked directly. The
callable type cannot be used as a type declaration for class properties. Instead, use a
Closure type declaration.
Callables can be created in several different ways:
Closure object
ENTITY containing the name of a function or a method
ENTITY containing a class name or an
object in index 0 and the method name in index 1
ENTITY implementing the __invoke() magic method
A
Closure object can be created using anonymous function syntax, arrow function syntax, first-class callable syntax, or the Closure::fromCallable method.
[!NOTE]
The first-class callable syntax is only available as of PHP 8.1.0.
Callback example using a
Closure
$a * 2;
// Using Closure::fromCallable
$double4 = Closure::fromCallable('double_function');
// Use the closure as a callback here to
// double the size of each element in our range
$new_numbers = array_map($double1, range(1, 5));
print implode(' ', $new_numbers) . PHP_EOL;
$new_numbers = array_map($double2, range(1, 5));
print implode(' ', $new_numbers) . PHP_EOL;
$new_numbers = array_map($double3, range(1, 5));
print implode(' ', $new_numbers) . PHP_EOL;
$new_numbers = array_map($double4, range(1, 5));
print implode(' ', $new_numbers);
?>
ENTITY
2 4 6 8 10
2 4 6 8 10
2 4 6 8 10
2 4 6 8 10
A callable can also be a string containing the name of a function or a static method. Any built-in or user-defined function can be used, except language constructs such as:
array,
echo,
empty,
eval,
isset,
list,
print or
unset.
Static class methods can be used without instantiating an
object of that class by either creating an array with the class name at index 0 and the method name at index 1, or by using the special syntax with the scope resolution operator
::, as in
'ClassName::methodName'.
A method of an instantiated
object can be a callable when provided as an array with the
object at index 0 and the method name at index 1.
The main difference between a
Closure object and the
callable type is that a
Closure object is scope-independent and can always be invoked, whereas a callable type may be scope-dependent and may not be directly invoked.
Closure is the preferred way to create callables. As of PHP 8.5.0,
Closure is a proper subtype of
callable.
[!NOTE]
While
Closure objects are bound to the scope where they are created, callables referencing class methods as strings or arrays are resolved in the scope where they are called. To create a callable from a private or protected method, which can then be invoked from outside the class scope, use Closure::fromCallable or the first-class callable syntax.
PHP allows the creation of callables which can be used as a callback argument but cannot be called directly. These are context-dependent callables which reference a class method in the inheritance hierarchy of a class, e.g.
'parent::method' or
["static", "method"].
[!NOTE]
As of PHP 8.2.0, context-dependent callables are deprecated. Remove the context dependency by replacing
'parent::method' with
parent::class . '::method' or use the first-class callable syntax.
Calling various types of callables with
call_user_func
ENTITY
hello world!
Hello World!
Hello World!
Hello World!
Hello World!
Deprecated: Callables of the form ["B", "parent::who"] are deprecated in script on line 44
A
Hello PHP!
ENTITY
Type declarations
Type declarations can be added to function arguments, return values, as of PHP 7.4.0, class properties, and as of PHP 8.3.0, class constants. They ensure that the value is of the specified type at call time, otherwise a
TypeError is thrown.
Every single type that PHP supports, with the exception of
resource, can be used within a user-land type declaration. This page contains a changelog of availability of the different types and documentation about usage of them in type declarations.
[!NOTE]
When a class implements an interface method or reimplements a method which has already been defined by a parent class, it has to be compatible with the aforementioned definition. A method is compatible if it follows the variance rules.
ENTITY
ENTITY
ENTITY
8.3.0
Support for class, interface, trait, and enum constant typing has been added.
8.2.0
Support for DNF types has been added.
8.2.0
Support for the literal type
true has been added.
8.2.0
The types
null and
false can now be used standalone.
8.1.0
Support for intersection types has been added.
8.1.0
Returning by reference from a
void function is now deprecated.
8.1.0
Support for the return only type
never has been added.
8.0.0
Support for
mixed has been added.
8.0.0
Support for the return only type
static has been added.
8.0.0
Support for union types has been added.
7.4.0
Support for class properties typing has been added.
7.2.0
Support for
object has been added.
7.1.0
Support for
iterable has been added.
7.1.0
Support for
void has been added.
7.1.0
Support for nullable types has been added.
Atomic Types Usage Notes
Atomic types have straightforward behaviour with some minor caveats which are described in this section.
Scalar types
[!WARNING]
Name aliases for scalar types (
bool,
int,
float,
string) are not supported. Instead, they are treated as class or interface names. For example, using
boolean as a type declaration will require the value to be an ENTITY the class or interface
boolean, rather than of type
bool:
ENTITY
Warning: "boolean" will be interpreted as a class name. Did you mean "bool"? Write "\boolean" to suppress this warning in /in/9YrUX on line 2
Fatal error: Uncaught TypeError: test(): Argument #1 ($param) must be of type boolean, bool given, called in - on line 3 and defined in -:2
Stack trace:
#0 -(3): test(true)
#1 {main}
thrown in - on line 2
void
[!NOTE]
Returning by reference from a
void function is deprecated as of PHP 8.1.0, because such a function is contradictory. Previously, it already emitted the following
E_NOTICE when called:
Only variable references should be returned by reference.
Callable types
This type cannot be used as a class property type declaration.
[!NOTE]
It is not possible to specify the signature of the function.
Type declarations on pass-by-reference Parameters
If a pass-by-reference parameter has a type declaration, the type of the variable is only checked on function entry, at the beginning of the call, but not when the function returns. This means that a function can change the type of the variable passed by reference.
Typed pass-by-reference Parameters
ENTITY
int(1)
Fatal error: Uncaught TypeError: array_baz(): Argument #1 ($param) must be of type array, int given, called in - on line 9 and defined in -:2
Stack trace:
#0 -(9): array_baz(1)
#1 {main}
thrown in - on line 2
Composite Types Usage Notes
Composite type declarations are subject to a couple of restrictions and will perform a redundancy check at compile time to prevent simple bugs.
[!CAUTION]
Prior to PHP 8.2.0, and the introduction of DNF types, it was not possible to combine intersection types with union types.
Union types
[!WARNING]
It is not possible to combine the two singleton types
false and
true together in a union type. Use
bool instead.
[!CAUTION]
Prior to PHP 8.2.0, as
false and
null could not be used as standalone types, a union type comprised of only these types was not permitted. This comprises the following types:
false,
false|null, and
?false.
Nullable type syntactic sugar
A single base type declaration can be marked nullable by prefixing the type with a question mark (
?). Thus
?T and
T|null are identical.
[!NOTE]
This syntax is supported as of PHP 7.1.0, and predates generalized union types support.
[!NOTE]
It is also possible to achieve nullable arguments by making ENTITY the default value. This is not recommended because if the default value is changed in a child class a type compatibility violation will be raised as the
null type will need to be added to the type declaration. This behavior is also deprecated since PHP 8.4.
Old way to make arguments nullable
ENTITY
object(C)#1 (0) {
}
NULL
Duplicate and redundant types
To catch simple bugs in composite type declarations, redundant types that can be detected without performing class loading will result in a compile-time error. This includes:
Each name-resolved type may only occur once. Types such as
int|string|INT or
CountableENTITYTraversableENTITYCOUNTABLE result in an error.
Using
mixed or
never results in an error.
For union types:
If
bool is used,
false or
true cannot be used additionally.
If
object is used, class types cannot be used additionally.
If
iterable is used,
array and
Traversable cannot be used additionally.
For intersection types:
Using a type which is not a class-type results in an error.
Using either
self,
parent, or
static results in an error.
For DNF types:
If a more generic type is used, the more restrictive one is redundant.
Using two identical intersection types.
[!NOTE]
This does not guarantee that the type is “minimal”, because doing so would require loading all used class types.
For example, if
A and
B are class aliases, then
A|B remains a legal union type, even though it could be reduced to either
A or
B. Similarly, if class
B extends A {}, then
A|B is also a legal union type, even though it could be reduced to just
A.
ENTITY
Basic class type declaration
ENTITY
C
D
Fatal error: Uncaught TypeError: f(): Argument #1 ($c) must be of type C, E given, called in /in/gLonb on line 14 and defined in /in/gLonb:8
Stack trace:
#0 -(14): f(Object(E))
#1 {main}
thrown in - on line 8
Basic interface type declaration
ENTITY
C
Fatal error: Uncaught TypeError: f(): Argument #1 ($i) must be of type I, E given, called in - on line 13 and defined in -:8
Stack trace:
#0 -(13): f(Object(E))
#1 {main}
thrown in - on line 8
Basic return type declaration
ENTITY
float(3)
Returning an object
ENTITY
object(C)#1 (0) {
}
Nullable argument type declaration
ENTITY
object(C)#1 (0) {
}
NULL
Nullable return type declaration
Class property type declaration
id = $id;
$this->username = $username;
}
}
?>
Strict typing
By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an
int for a parameter that expects a
string will get a variable of type
string.
It is possible to enable strict mode on a per-file basis. In strict mode, only a value corresponding exactly to the type declaration will be accepted, otherwise a
TypeError will be thrown. The only exception to this rule is that an
int value will pass a
float type declaration.
[!WARNING]
Function calls from within internal functions will not be affected by the
strict_types declaration.
To enable strict mode, the ENTITY statement is used with the
strict_types declaration:
[!NOTE]
Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (coercive typing) will be respected, and the value will be coerced.
[!NOTE]
Strict typing is only defined for scalar type declarations.
Strict typing for arguments values
ENTITY
int(3)
Fatal error: Uncaught TypeError: sum(): Argument #1 ($a) must be of type int, float given, called in - on line 9 and defined in -:4
Stack trace:
#0 -(9): sum(1.5, 2.5)
#1 {main}
thrown in - on line 4
Coercive typing for argument values
ENTITY
int(3)
int(3)
Strict typing for return values
ENTITY
int(3)
Fatal error: Uncaught TypeError: sum(): Return value must be of type int, float returned in -:5
Stack trace:
#0 -(9): sum(1, 2.5)
#1 {main}
thrown in - on line 5
Enumerations
Basic Enumerations
Enumerations are a restricting layer on top of classes and class constants, intended to provide a way to define a closed set of possible values for a type.
For a full discussion, see the Enumerations chapter.
Casting
If an
enum is converted to an
object, it is not modified. If an
enum is converted to an
array, an array with a single
name key (for Pure enums) or an array with both
name and
value keys (for Backed enums) is created. All other cast types will result in an error.
Floating-point numbers
Floating-point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:
Formally as of PHP 7.4.0 (previously, underscores have not been allowed):
LNUM [0-9]+(_[0-9]+)*
DNUM ({LNUM}?"."{LNUM}) | ({LNUM}"."{LNUM}?)
EXPONENT_DNUM (({LNUM} | {DNUM}) [eE][+-]? {LNUM})
The size of a float is platform-dependent, although a maximum of approximately 1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).
[!WARNING]
Floating-point 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-point number results to the last digit, and do not compare floating-point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.
For a "simple" explanation, see the floating point guide that's also titled "Why don’t my numbers add up?"
Converting to float
From strings
If the string is numeric or leading numeric then it will resolve to the corresponding float value, otherwise it is converted to zero (
0).
From other types
For values of other types, the conversion is performed by converting the value to
int first and then to
float. See Converting to integer for more information.
[!NOTE]
As certain types have undefined behavior when converting to
int, this is also the case when converting to
float.
Comparing floats
As noted in the warning above, testing floating-point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating-point values that work around these limitations.
To test floating-point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.
$a and
$b are equal to 5 digits of precision.
Comparing Floats
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 ENTITY, will have a result of ENTITY.
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.
Integers
An
int is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}.
ENTITY
Floating-point numbers, Arbitrary precision / BCMath, Arbitrary length integer / GMP
Syntax
Ints can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation. The negation operator can be used to denote a negative
int.
To use octal notation, precede the number with a
0 (zero). As of PHP 8.1.0, octal notation can also be preceded with
0o or
0O. To use hexadecimal notation, precede the number with
0x. To use binary notation, precede the number with
0b.
As of PHP 7.4.0, integer literals may contain underscores (
_) between digits, for better readability of literals. These underscores are removed by PHP's scanner.
Integer literals
Formally, the structure for
int literals is as of PHP 8.1.0 (previously, the
0o or
0O octal prefixes were not allowed, and prior to PHP 7.4.0 the underscores were not allowed):
decimal : [1-9][0-9]*(_[0-9]+)*
| 0
hexadecimal : 0[xX][0-9a-fA-F]+(_[0-9a-fA-F]+)*
octal : 0[oO]?[0-7]+(_[0-7]+)*
binary : 0[bB][01]+(_[01]+)*
integer : decimal
| hexadecimal
| octal
| binary
The size of an
int is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned
ints.
int size can be determined using the constant
PHP_INT_SIZE, maximum value using the constant
PHP_INT_MAX, and minimum value using the constant
PHP_INT_MIN.
Integer overflow
If PHP encounters a number beyond the bounds of the
int type, it will be interpreted as a
float instead. Also, an operation which results in a number beyond the bounds of the
int type will return a
float instead.
Integer overflow
Integer division
There is no
int division operator in PHP. To achieve this, use the
intdiv function.
1/2 yields the
float
0.5. The value can be cast to an
int to round it towards zero, or the
round function provides finer control over rounding.
Divisions
Converting to integer
To explicitly convert a value to
int, use the
(int) cast. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an
int argument. A value can also be converted to
int with the
intval function.
If a
resource is converted to an
int, then the result will be the unique resource number assigned to the
resource by PHP at runtime.
See also Type Juggling.
From booleans
ENTITY will yield
0 (zero), and ENTITY will yield
1 (one).
From floating point numbers
When converting from
float to
int, the number will be rounded towards zero. As of PHP 8.1.0, a deprecation notice is emitted when implicitly converting a non-integral ENTITY to an ENTITY which loses precision.
Casting from Float
If the float is beyond the boundaries of
int (usually
+/- 2.15e+9 = 2^31 on 32-bit platforms and
+/- 9.22e+18 = 2^63 on 64-bit platforms), the result is undefined, since the
float doesn't have enough precision to give an exact
int result. As of PHP 8.5.0, an
E_WARNING is emitted when a
float that is not representable as an
int is cast to one. Prior to PHP 8.5.0, no diagnostic at all was issued.
[!NOTE]
NaN,
Inf and
-Inf will always be zero when cast to
int. As of PHP 8.5.0, casting them to
int emits an
E_WARNING, as does casting
NAN to any other type.
[!WARNING]
Never cast an unknown fraction to
int, as this can sometimes lead to unexpected results.
See also the warning about float precision.
From strings
If the string is numeric or leading numeric then it will resolve to the corresponding integer value, otherwise it is converted to zero (
0).
From
NULL
ENTITY is always converted to zero (
0).
From other types
[!CAUTION]
The behaviour of converting to
int is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.
Iterables
Iterable is a built-in compile-time type alias for
array|Traversable. From its introduction in PHP 7.1.0 and prior to PHP 8.2.0,
iterable was a built-in pseudo-type that acted as the aforementioned type alias and could be used as a type declaration. An iterable type can be used in ENTITY and with
yield from within a generator.
[!NOTE]
Functions declaring iterable as a return type may also be generators.
Iterable generator return type example
Mixed
The
mixed type accepts every value. It is equivalent to the union type
object|resource|array|string|float|int|bool|null. Available as of PHP 8.0.0.
mixed is, in type theory parlance, the top type, meaning every other type is a subtype of it.
Never
never is a return-only type indicating the function does not terminate. This means that it either calls
exit, throws an exception, or is an infinite loop. Therefore, it cannot be part of a union type declaration. Available as of PHP 8.1.0.
A
return statement in a
never function is a compile-time error, even if the
return would not be reached during execution. If control flow reaches the end of a
never function without exiting, throwing an exception, or entering an infinite loop, a TypeError is thrown.
never is, in type theory parlance, the bottom type, meaning it is the subtype of every other type and can replace any other return type during inheritance.
NULL
The
null type is PHP's unit type, i.e. it has only one value: ENTITY.
Undefined and
unset variables resolve to the value ENTITY.
Syntax
There is only one value of type
null, and that is the case-insensitive constant ENTITY.
Casting to ENTITY
ENTITY
Casting a variable to
null using
(unset) $var will not remove the variable or unset its value. It will only return a ENTITY value.
ENTITY
is_null,
unset
Numeric strings
A PHP
string is considered numeric if it can be interpreted as an
int or a
float.
Formally as of PHP 8.0.0:
WHITESPACES \s*
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM (({LNUM} | {DNUM}) [eE][+-]? {LNUM})
INT_NUM_STRING {WHITESPACES} [+-]? {LNUM} {WHITESPACES}
FLOAT_NUM_STRING {WHITESPACES} [+-]? ({DNUM} | {EXPONENT_DNUM}) {WHITESPACES}
NUM_STRING ({INT_NUM_STRING} | {FLOAT_NUM_STRING})
PHP also has a concept of leading numeric strings. This is simply a string which starts like a numeric string followed by any characters.
[!NOTE]
Any string that contains the letter
E (case insensitive) bounded by numbers will be seen as a number expressed in scientific notation. This can produce unexpected results.
Scientific Notation Comparisons
Strings used in numeric contexts
When a
string needs to be evaluated as a number (e.g. arithmetic operations,
int type declaration, etc.) the following steps are taken to determine the outcome:
If the
string is numeric, resolve to an
int if the
string is an integer numeric string and fits into the limits of the
int type limits (as defined by
PHP_INT_MIN and
PHP_INT_MAX), otherwise resolve to a
float.
If the context allows leading numeric strings and the
string is one, resolve to an
int if the leading part of the
string is an integer numeric string and fits into the limits of the
int type limits (as defined by
PHP_INT_MIN and
PHP_INT_MAX), otherwise resolve to a
float. Additionally an error of level
E_WARNING is raised.
If the
string is not numeric, throw a
TypeError.
Behavior prior to PHP 8.0.0
Prior to PHP 8.0.0, a
string was considered numeric if it only had leading whitespaces. If it had trailing whitespaces then the string was considered to be leading numeric.
Prior to PHP 8.0.0, when a string was used in a numeric context it would perform the same steps as above with the following differences:
The usage of a leading numeric string would raise an
E_NOTICE instead of an
E_WARNING.
If the string was not numeric, an
E_WARNING was raised and the value
0 would be returned.
Prior to PHP 7.1.0, neither
E_NOTICE nor
E_WARNING was raised.
Objects
Object Initialization
To create a new
object, use the
new statement to instantiate a class:
Object Construction
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 ENTITY, the new instance will be empty. An
array converts to an
object with properties named by keys and with their corresponding values. Prior to PHP 7.2.0, numeric keys would have been inaccessible unless iterated.
Casting to an Object
'foo');
var_dump(isset($obj->{'1'})); // outputs 'bool(true)'
// Deprecated as of PHP 8.1
var_dump(key($obj)); // outputs 'string(1) "1"'
?>
For any other value, a member variable named
scalar will contain the value.
(object) cast
scalar; // outputs 'ciao'
?>
Relative class types
These type declarations can only be used within classes.
self
The value must be an ENTITY the same class as the one in which the type declaration is used.
parent
The value must be an ENTITY a parent of the class in which the type declaration is used.
static
static is a return-only type which requires that the value returned must be an ENTITY the same class as the one the method is called in. Available as of PHP 8.0.0.
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 the 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.
Singleton types
Singleton types are those which allow only one value. PHP has support for two singleton types:
false as of PHP 8.0.0 and
true as of PHP 8.2.0.
[!WARNING]
Prior to PHP 8.2.0, the
false type could only be used as part of a union type.
[!NOTE]
It is not possible to define custom singleton types. Consider using enumerations instead.
Strings
A
string is a series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.
[!NOTE]
On 32-bit builds, a
string can be up to 2GB (2147483647 bytes) in length.
Syntax
A
string literal can be specified in four different ways:
single quoted
double quoted
heredoc syntax
nowdoc syntax
Single quoted
The simplest way to specify a
string is to enclose it in single quotes (the character
').
To specify a literal single quote, escape it with a backslash (
\). To specify a literal backslash, double it (
\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as
\r or
\n, will be output literally as specified rather than having any special meaning.
[!NOTE]
Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted
strings.
Syntax Variants
Double quoted
If the
string is enclosed in double-quotes (
"), PHP will interpret the following escape sequences for special characters:
Sequence
Meaning
\n
linefeed (LF or 0x0A (10) in ASCII)
\r
carriage return (CR or 0x0D (13) in ASCII)
\t
horizontal tab (HT or 0x09 (9) in ASCII)
\v
vertical tab (VT or 0x0B (11) in ASCII)
\e
escape (ESC or 0x1B (27) in ASCII)
\f
form feed (FF or 0x0C (12) in ASCII)
\\
backslash
\$
dollar sign
\"
double-quote
\[0-7]{1,3}
Octal: the sequence of characters matching the regular expression
[0-7]{1,3} is a character in octal notation (e.g.
"\101" === "A"), which silently overflows to fit in a byte (e.g.
"\400" === "\000")
\x[0-9A-Fa-f]{1,2}
Hexadecimal: the sequence of characters matching the regular expression
[0-9A-Fa-f]{1,2} is a character in hexadecimal notation (e.g.
"\x41" === "A")
\u{[0-9A-Fa-f]+}
Unicode: the sequence of characters matching the regular expression
[0-9A-Fa-f]+ is a Unicode codepoint, which will be output to the string as that codepoint's UTF-8 representation. The braces are required in the sequence. E.g.
"\u{41}" === "A"
Escaped characters
As in single quoted
strings, escaping any other character will result in the backslash being printed too.
The most important feature of double-quoted
strings is the fact that variable names will be expanded. See string interpolation for details.
Heredoc
A third way to delimit
strings is the heredoc syntax:
ENTITYENTITYENTITY. After this operator, an identifier is provided, then a newline. The
string itself follows, and then the same identifier again to close the quotation.
The closing identifier may be indented with spaces or tabs. Whitespace equal to the closing identifier's indentation is then removed from the beginning of every line in the heredoc string. Prior to PHP 7.3.0, the closing identifier must begin in the first column of the line.
Also, the closing identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Basic Heredoc example as of PHP 7.3.0
string(11) "a
b
c"
[1] =>
string(5) "d e f"
}
[!WARNING]
If the closing identifier is found at the start of a line, then regardless of whether it is a part of another word, it is considered as the closing identifier and causes a ParseError.
Closing identifier in body of the string tends to cause ParseError
Valid example, even prior to PHP 7.3.0
Heredocs containing variables can not be used for initializing class properties.
Heredoc text behaves just like a double-quoted
string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with
strings.
Heredoc string quoting example
foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
ENTITY
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:
Heredoc in arguments example
It's possible to initialize static variables and class properties/constants using the Heredoc syntax:
Using Heredoc to initialize static values
The opening Heredoc identifier may optionally be enclosed in double quotes:
Using double quotes in Heredoc
Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no string interpolation is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML
ENTITY![CDATA[ ]]ENTITY construct, in that it declares a block of text which is not for parsing.
A nowdoc is identified with the same
ENTITYENTITYENTITY sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g.
ENTITYENTITYENTITY'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.
Nowdoc string quoting example
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;
?>
ENTITY
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
Static data example
String interpolation
When a
string is specified in double quotes or with heredoc, variables can be substituted within it.
There are two types of syntax: a basic one and an advanced one. The basic syntax is the most common and convenient. It provides a way to embed a variable, an
array value, or an
object property in a
string with a minimum of effort.
Basic syntax
If a dollar sign (
$) is encountered, the characters that follow it which can be used in a variable name will be interpreted as such and substituted.
String Interpolation
ENTITY
He drank some apple juice.
Formally, the structure for the basic variable substitution syntax is as follows:
string-variable::
variable-name (offset-or-property)?
| ${ expression }
offset-or-property::
offset-in-string
| property-in-string
offset-in-string::
[ name ]
| [ variable-name ]
| [ integer-literal ]
property-in-string::
-> name
variable-name::
$ name
name::
[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*
[!WARNING]
The
${ expression } syntax is deprecated as of PHP 8.2.0, as it can be interpreted as variable variables:
ENTITY
Deprecated: Using ${var} in strings is deprecated, use {$var} instead in file on line 6
Deprecated: Using ${expr} (variable variables) in strings is deprecated, use {${expr}} instead in file on line 9
string(3) "foo"
string(3) "bar"
ENTITY
string(3) "foo"
string(3) "bar"
The advanced string interpolation syntax should be used instead.
[!NOTE]
If it is not possible to form a valid name the dollar sign remains verbatim in the string:
ENTITY
No interpolation $ has happened
No interpolation $
has happened
No interpolation $2 has happened
Interpolating the value of the first dimension of an array or property
"purple");
echo "He drank some $juices[0] juice.";
echo PHP_EOL;
echo "He drank some $juices[1] juice.";
echo PHP_EOL;
echo "He drank some $juices[string_key] juice.";
echo PHP_EOL;
class A {
public $s = "string";
}
$o = new A();
echo "Object value: $o->s.";
?>
ENTITY
He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
Object value: string.
[!NOTE]
The array key must be unquoted, and it is therefore not possible to refer to a constant as a key with the basic syntax. Use the advanced syntax instead.
As of PHP 7.1.0, negative numeric indices are supported too.
Negative numeric indices
ENTITY
The character at index -2 is n.
Changing the character at index -3 to o gives strong.
For anything more complex, the advanced syntax must be used.
Advanced (curly) syntax
The advanced syntax permits the interpolation of variables with arbitrary accessors.
Any scalar variable, array element or object property (static or not) with a
string representation can be included via this syntax. The expression is written the same way as it would appear outside the
string, and then wrapped in
{ and
}. Since
{ can not be escaped, this syntax will only be recognised when the
$ immediately follows the
{. Use
{\$ to get a literal
{$. Some examples to make it clear:
Curly Syntax
'Indexed value',
'const-key' => 'Key with minus sign',
'foo' => ['foo1', 'foo2', 'foo3']
];
// Won't work, outputs: This is { fantastic}
echo "This is { $great}" . PHP_EOL;
// Works, outputs: This is fantastic
echo "This is {$great}" . PHP_EOL;
// To show curly braces in the output:
echo "This is {{$great}}" . PHP_EOL;
class Square {
public $width;
public function __construct(int $width) { $this->width = $width; }
}
$square = new Square(5);
// Works
echo "This square is {$square->width}00 centimeters wide." . PHP_EOL;
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}" . PHP_EOL;
// Works
echo "This works: {$arr[3][2]}" . PHP_EOL;
echo "This works: {$arr[DATA_KEY]}" . PHP_EOL;
// When using multidimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][2]}" . PHP_EOL;
echo "This works: {$obj->values[3]->name}" . PHP_EOL;
echo "This works: {$obj->$staticProp}" . PHP_EOL;
// Won't work, outputs: C:\directory\{fantastic}.txt
echo "C:\directory\{$great}.txt" . PHP_EOL;
// Works, outputs: C:\directory\fantastic.txt
echo "C:\\directory\\{$great}.txt" . PHP_EOL;
?>
[!NOTE]
As this syntax allows arbitrary expressions, it is possible to use variable variables within the advanced syntax.
String access and modification by character
Characters within
strings may be accessed and modified by specifying the zero-based offset of the desired character after the
string using square
array brackets, as in
$str[42]. Think of a
string as an
array of characters for this purpose. The functions
substr and
substr_replace can be used when you want to extract or replace more than 1 character.
[!NOTE]
As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted
E_NOTICE for reading (yielding an empty string) and
E_WARNING for writing (leaving the string untouched).
[!NOTE]
Prior to PHP 8.0.0,
strings could also be accessed using braces, as in
$str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
[!WARNING]
Writing to an out-of-range offset pads the string with spaces. Non-integer types are converted to an integer. An 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.
Some string examples
String offsets must be either integers or integer-like strings. As of PHP 8.0.0, any other string throws a TypeError, except for a string starting with an integer followed by other characters, which emits
E_WARNING and is interpreted as that leading integer. Prior to PHP 8.0.0, no TypeError was thrown: an illegal offset emitted
E_WARNING instead.
Example of Illegal String Offsets
getMessage(), PHP_EOL;
}
echo PHP_EOL;
}
?>
ENTITY
bool(true)
string(1) "b"
bool(false)
Cannot access offset of type string on string
bool(false)
Cannot access offset of type string on string
bool(false)
Warning: Illegal string offset "1x" in example.php on line 10
string(1) "b"
ENTITY
bool(true)
string(1) "b"
bool(false)
Warning: Illegal string offset '1.0' in example.php on line 10
string(1) "b"
bool(false)
Warning: Illegal string offset 'x' in example.php on line 10
string(1) "a"
bool(false)
Notice: A non well formed numeric value encountered in example.php on line 10
string(1) "b"
[!NOTE]
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using
[] or
{} silently returns ENTITY.
[!NOTE]
Characters within string literals can be accessed using
[] or
{}.
[!NOTE]
Accessing characters within string literals using the
{} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.
Useful functions and operators
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.
There are a number of useful functions for
string manipulation.
See the string functions section for general functions, and the Perl-compatible regular expression functions for advanced find ENTITY replace functionality.
There are also functions for URL strings, and functions to encrypt/decrypt strings (Sodium and Hash).
Finally, see also the character type functions.
Converting to string
A value can be converted to a
string using the
(string) cast or the
strval function.
String conversion is automatically done in the scope of an expression where a
string is needed. This happens when using the
echo or
print functions, or when a variable is compared to a
string. The sections on Types and Type Juggling will make the following clearer. See also the
settype function.
A
bool ENTITY value is converted to the
string
"1".
bool ENTITY is converted to
"" (the empty string). This allows conversion back and forth between
bool and
string values.
An
int or
float is converted to a
string representing the number textually (including the exponent part for
floats). Floating-point numbers can be converted using exponential notation (
4.1E+6).
[!NOTE]
As of PHP 8.0.0, the decimal point character is always a period ("
."). Prior to PHP 8.0.0, the decimal point character is defined in the script's locale (category LC_NUMERIC). See the
setlocale function.
Arrays are always converted to the
string
"Array"; because of this,
echo and
print can not by themselves show the contents of an
array. To view a single element, use a construction such as
echo $arr['foo']. See below for tips on viewing the entire contents.
In order to convert
objects to
string, the magic method __toString must be used.
Resources are always converted to
strings with the structure
"Resource id #1", where
1 is the resource number assigned to the
resource by PHP at runtime. While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed (ie a Web request or CLI process) and won't be reused. To get a
resource's type, use the
get_resource_type function.
ENTITY is always converted to an empty string.
As stated above, directly converting an
array,
object, or
resource to a
string does not provide any useful information about the value beyond its type. See the functions
print_r and
var_dump for more effective means of inspecting the contents of these types.
Most PHP values can also be converted to
strings for permanent storage. This method is called serialization, and is performed by the
serialize function.
Details of the String Type
The
string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value
0 (“NUL bytes”) are allowed anywhere in the string. However, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.
This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.
Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string
"á" equivalent to
"\xE1" (ISO-8859-1),
"\xC3\xA1" (UTF-8, C form),
"\x61\xCC\x81" (UTF-8, D form) or any other possible representation? The answer is that the 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 the case of, for instance,
substr,
strpos,
strlen or
strcmp. Another way to think of these functions is that they operate on memory buffers, i.e., they work with bytes and byte offsets.
Other functions receive the encoding of the string as a parameter or assume a default when it's not provided. This is the case of
htmlentities and the majority of the functions in the mbstring extension.
Others use the current locale (see
setlocale), but operate byte-by-byte.
Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the
u modifier is used).
Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.
Type Juggling
PHP does not require explicit type definition in variable declaration. In this case, the type of a variable is determined by the value it stores. That is to say, if a
string is assigned to variable
$var, then
$var is of type
string. If afterwards an
int value is assigned to
$var, it will be of type
int.
PHP may attempt to convert the type of a value to another automatically in certain contexts. The different contexts which exist are:
Numeric
String
Logical
Integral and string
Comparative
Function
[!NOTE]
When a value needs to be interpreted as a different type, the value itself does not change types.
To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the
settype function.
Numeric contexts
This is the context when using an arithmetical operator.
In this context, if either operand is a
float (or not interpretable as an
int), both operands are interpreted as
floats, and the result will be a
float. Otherwise, the operands will be interpreted as
ints, and the result will also be an
int. As of PHP 8.0.0, if one of the operands cannot be interpreted, a TypeError is thrown.
String contexts
This is the context when using
echo,
print, string interpolation, or the string concatenation operator.
In this context, the value will be interpreted as
string. If the value cannot be interpreted, a TypeError is thrown. Prior to PHP 7.4.0, an
E_RECOVERABLE_ERROR was raised.
Logical contexts
This is the context when using conditional statements, the ternary operator, or a logical operator.
In this context, the value will be interpreted as
bool.
Integral and string contexts
This is the context when using bitwise operators.
In this context, if all operands are of type
string, the result will also be a
string. Otherwise, the operands will be interpreted as
ints, and the result will also be an
int. As of PHP 8.0.0, if one of the operands cannot be interpreted, a TypeError is thrown.
Comparative contexts
This is the context when using a comparison operator.
The type conversions which occur in this context are explained in the Comparison with Various Types table.
Function contexts
This is the context when a value is passed to a typed parameter, property, or returned from a function which declares a return type.
In this context, the value must be a value of the type. Two exceptions exist. The first one is: if the value is of type
int and the declared type is
float, then the integer is converted to a floating point number. The second one is: if the declared type is a scalar type, the value is convertible to a scalar type, and the coercive typing mode is active (the default), the value may be converted to an accepted scalar value. See below for a description of this behaviour.
[!WARNING]
Internal functions automatically coerce ENTITY to scalar types. This behaviour is DEPRECATED as of PHP 8.1.0.
Coercive typing with simple type declarations
bool type declaration: value is interpreted as
bool.
int type declaration: value is interpreted as
int if the conversion is well-defined. For example, the string is numeric.
float type declaration: value is interpreted as
float if the conversion is well-defined. For example, the string is numeric.
string type declaration: value is interpreted as
string.
Coercive typing with union types
When
strict_types is not enabled, scalar type declarations are subject to limited implicit type coercions. If the exact type of the value is not part of the union, then the target type is chosen in the following order of preference:
int
float
string
bool
If the type exists in the union and the value can be coerced to the type under PHP's existing type-checking semantics, then the type is chosen. Otherwise, the next type is tried.
[!CAUTION]
As an exception, if the value is a string and both int and float are part of the union, the preferred type is determined by the existing numeric string semantics. For example, for
"42"
int is chosen, while for
"42.0"
float is chosen.
[!NOTE]
Types that are not part of the above preference list are not eligible targets for implicit coercion. In particular, no implicit coercions to the
null,
false, and
true types occur.
Example of types being coerced into a type part of the union
42 // exact type
"42" --> "42" // exact type
new ObjectWithToString --> "Result of __toString()"
// object never compatible with int, fall back to string
42.0 --> 42 // float compatible with int
42.1 --> 42 // float compatible with int
1e100 --> "1.0E+100" // float too large for int type, fall back to string
INF --> "INF" // float too large for int type, fall back to string
true --> 1 // bool compatible with int
[] --> TypeError // array not compatible with int or string
// int|float|bool
"45" --> 45 // int numeric string
"45.0" --> 45.0 // float numeric string
"45X" --> true // not numeric string, fall back to bool
"" --> false // not numeric string, fall back to bool
"X" --> true // not numeric string, fall back to bool
[] --> TypeError // array not compatible with int, float or bool
?>
Type Casting
Type casting converts the value to a chosen type by writing the type within parentheses before the value to convert.
Type Casting
The casts allowed are:
(int)
- cast to
int
(bool)
- cast to
bool
(float)
- cast to
float
(string)
- cast to
string
(array)
- cast to
array
(object)
- cast to
object
(unset)
- cast to
NULL
The
(void) cast is also available as of PHP 8.5.0, but it is not a value conversion. It is used as a statement to explicitly discard the result of an expression.
[!WARNING]
(integer) is an alias of the
(int) cast.
(boolean) is an alias of the
(bool) cast.
(binary) is an alias of the
(string) cast.
(double) and
(real) are aliases of the
(float) cast. These casts do not use the canonical type name and are deprecated as of PHP 8.5.0.
[!WARNING]
The
(real) cast alias has been deprecated as of PHP 7.4.0 and removed as of PHP 8.0.0.
[!WARNING]
The
(unset) cast has been deprecated as of PHP 7.2.0. Note that the
(unset) cast is the same as assigning the value
NULL to the variable or call. The
(unset) cast is removed as of PHP 8.0.0.
[!CAUTION]
The
(binary) cast and
b prefix exist for forward support. Currently
(binary) and
(string) are identical, however this may change and should not be relied upon.
[!NOTE]
Whitespaces are ignored within the parentheses of a cast. Therefore, the following two casts are equivalent:
Casting literal
strings and variables to binary
strings:
Instead of casting a variable to a
string, it is also possible to enclose the variable in double quotes.
Different Casting Mechanisms
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, Discarding a value with
(void), The type comparison tables
[!NOTE]
Because PHP supports indexing into
strings via offsets using the same syntax as
array indexing, the following example holds true for all PHP versions:
Using Array Offset with a String
See the section titled String access by character for more information.
Type System
PHP uses a nominal type system with a strong behavioral subtyping relation. The subtyping relation is checked at compile time whereas the verification of types is dynamically checked at run time.
PHP's type system supports various atomic types that can be composed together to create more complex types. Some of these types can be written as type declarations.
Atomic types
Some atomic types are built-in types which are tightly integrated with the language and cannot be reproduced with user-defined types.
The list of base types is:
Built-in types
Scalar types:
bool type
int type
float type
string type
array type
object type
resource type
never type
void type
Relative class types:
self,
parent, and
static
Singleton types
false
true
Unit types
null
User-defined types (generally referred to as class-types)
Interfaces
Classes
Enumerations
callable type
Scalar types
A value is considered scalar if it is of type
int,
float,
string or
bool.
User-defined types
It is possible to define custom types with interfaces, classes and enumerations. These are considered as user-defined types, or class-types. For example, a class called
Elephant can be defined, then objects of type
Elephant can be instantiated, and a function can request a parameter of type
Elephant.
Composite types
It is possible to combine multiple atomic types into composite types. PHP allows types to be combined in the following ways:
Intersection of class-types (interfaces and class names).
Union of types.
Intersection types
An intersection type accepts values which satisfy multiple class-type declarations, rather than a single one. Individual types which form the intersection type are joined by the
ENTITY symbol. Therefore, an intersection type comprised of the types
T,
U, and
V will be written as
TENTITYUENTITYV.
Union types
A union type accepts values of multiple different types, rather than a single one. Individual types which form the union type are joined by the
| symbol. Therefore, a union type comprised of the types
T,
U, and
V will be written as
T|U|V. If one of the types is an intersection type, it needs to be bracketed with parentheses for it to be written in DNF:
T|(XENTITYY).
Type aliases
PHP supports two type aliases:
mixed and
iterable which correspond to the union type of
object|resource|array|string|float|int|bool|null and
Traversable|array respectively.
[!NOTE]
PHP does not support user-defined type aliases.
Void
void is a return-only type declaration indicating the function does not return a value, but the function may still terminate. Therefore, it cannot be part of a union type declaration. Available as of PHP 7.1.0.
A
return statement with an expression in a
void function is a compile-time error, even if the
return would not be reached during execution. This includes
return null;; use a bare
return; to exit the function early. The
null mentioned below is only the implicit value of the call.
[!NOTE]
Even if a function has a return type of
void, it will still return a value. This value is always ENTITY.
Discarding a value with
(void)
The
(void) syntax may be used to explicitly discard the result of an expression. This is useful to indicate that ignoring a return value is intentional, especially when calling a function or method marked with the
NoDiscard attribute.
Unlike other casts,
(void) does not convert the value to another type and does not produce a value. It is a statement and cannot be used as part of an expression.
Discarding a return value
Variables
Basics
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
A valid variable name starts with a letter (
A-Z,
a-z, or the bytes from 128 through 255) or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus:
^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$
[!NOTE]
Variable names are compared as bytes, not as characters. PHP does not interpret or validate the encoding of the bytes from 128 through 255, and two names refer to the same variable only when their bytes are identical.
One consequence is that names written in UTF-8 work, because every byte of a UTF-8 multi-byte sequence falls inside the accepted range. The same holds for any encoding whose non-ASCII bytes all fall in that range, and for byte sequences that are not valid text in any encoding. Encodings that use bytes below 128 within a multi-byte sequence, such as Shift-JIS or UTF-16, do not.
Another is that two names which display identically may be distinct.
ä encoded as U+00E4 and as
a followed by the combining diaeresis U+0308 are different variables, as are a name with and without a trailing U+00A0 NO-BREAK SPACE.
[!NOTE]
$this is a special variable that can't be assigned. Prior to PHP 7.1.0, indirect assignment (e.g. by using variable variables) was possible.
ENTITY
Valid variable names
property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdClass;
// Assign the object to the static variable
$obj = $new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
ENTITY
Static object: NULL
Static object: NULL
Static object: NULL
Static object: object(stdClass)#3 (1) {
["property"]=>
int(1)
}
This example demonstrates that when assigning a reference to a static variable, it is not remembered when the
ENTITYget_instance_ref() function is called a second time.
Variable variables
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
$bar, then the local scope will be examined for
$bar and its value will be used as the name of the property of
$foo. This is also true if
$bar is an array access.
Curly braces may also be used to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of multiple parts, or when the property name contains characters that are not otherwise valid (e.g. from
json_decode or SimpleXML).
Variable property example
$bar . "\n";
echo $foo->{$baz[1]} . "\n";
$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "\n";
$arr = 'arr';
echo $foo->{$arr[1]} . "\n";
echo $foo->{$arr}[1] . "\n";
ENTITY
I am bar.
I am bar.
I am bar.
I am r.
I am B.
[!WARNING]
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable
$this is also a special variable that cannot be referenced dynamically.
Variables From External Sources
HTML Forms (GET and POST)
When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are few ways to access this information, for example:
A simple HTML form
There are only two ways to access data from HTML forms. Currently available methods are listed below:
Accessing data from a simple POST HTML form
';
echo htmlspecialchars(print_r($_POST, true));
echo '';
}
?>
[!NOTE]
If an external variable name begins with a valid array syntax, trailing characters are silently ignored. For example,
ENTITYinput name="foo[bar]baz"ENTITY 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:
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables,
sub_x and
sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.
HTTP Cookies
PHP transparently supports HTTP cookies as defined by RFC 6265. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. It is possible to set cookies using the
setcookie function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the
header function. Cookie data is then available in the appropriate cookie data arrays, such as
$_COOKIE as well as in
$_REQUEST. See the
setcookie manual page for more details and examples.
[!NOTE]
As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the names of incoming cookies are no longer url-decoded for security reasons.
If multiple values should be assigned to a single cookie variable, they can be assigned as an array. For example:
Fetch the media type
expect
expect://
Process Interaction Streams
ENTITY
Streams opened via the
expect:// wrapper provide access to process's stdin, stdout and stderr via PTY.
[!NOTE]
In order to use the
expect:// wrapper, the Expect extension available from ENTITY must be installed.
expect:// (PECL)
ENTITY
expect://command
ENTITY
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
Wrapper Summary {role="stream_wrapper"}
file
file://
Accessing local filesystem
ENTITY
file:// is the default wrapper used with PHP and represents the local filesystem. When a relative path is specified (a path which does not begin with
/,
\,
\\, or a Windows drive letter) the path provided will be applied against the current working directory. In many cases this is the directory in which the script resides unless it has been changed. Using the CLI SAPI, this defaults to the directory from which the script was called.
With some functions, such as
fopen and
file_get_contents,
include_path may be optionally searched for relative paths as well.
ENTITY
/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
ENTITY
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
Wrapper Summary {role="stream_wrapper"}
ftp
ftp://
ftps://
Accessing FTP(s) URLs
ENTITY
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 ENTITY, then this value will be sent as the anonymous FTP password.
ENTITY
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
ENTITY
Attribute
Supported
Restricted by allow_url_fopen
Yes
Allows Reading
Yes
Allows Writing
Yes (new files/existing files with
overwrite)
Allows Appending
Yes
Allows Simultaneous Reading and Writing
No
Supports
stat
filesize,
filemtime,
filetype,
file_exists,
is_file, and
is_dir elements only.
Supports
unlink
Yes
Supports
rename
Yes
Supports
mkdir
Yes
Supports
rmdir
Yes
Wrapper Summary {role="stream_wrapper"}
ENTITY
[!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]
Files may be appended via the
ftp:// URL wrapper.
ENTITY
glob
glob://
Find pathnames matching pattern
ENTITY
The
glob: stream wrapper.
ENTITY
glob://
ENTITY
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
Wrapper Summary {role="stream_wrapper"}
ENTITY
Basic usage
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
http
http://
https://
Accessing HTTP(s) URLs
ENTITY
Allows read-only access to files/resources via HTTP. By default, a HTTP 1.0 GET is used. A
Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your ENTITY 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 ???.
ENTITY
http://example.com
http://example.com/file.php?var1=val1ENTITYvar2=val2
http://user:password@example.com
https://example.com
https://example.com/file.php?var1=val1ENTITYvar2=val2
https://user:password@example.com
ENTITY
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
Wrapper Summary {role="stream_wrapper"}
ENTITY
Detecting which URL we ended up on after redirects
ENTITY
[!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.
ENTITY
$http_response_header
stream_get_meta_data
phar
phar://
PHP Archive
ENTITY
The
phar:// stream wrapper. See Phar stream wrapper for a detailed description.
ENTITY
phar://
ENTITY
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
Wrapper Summary {role="stream_wrapper"}
ENTITY
php
php://
Accessing various I/O streams
ENTITY
PHP provides a number of miscellaneous I/O streams that allow access to PHP's own input and output streams, the standard input, output and error file descriptors, in-memory and disk-backed temporary file streams, and filters that can manipulate other file resources as they are read from and written to.
php://stdin, php://stdout and php://stderr
php://stdin,
php://stdout and
php://stderr allow direct access to the corresponding input or output stream of the PHP process. The stream references a duplicate file descriptor, so if you open
php://stdin and later close it, you close only your copy of the descriptor-the actual stream referenced by
STDIN is unaffected. It is recommended that you simply use the constants
STDIN,
STDOUT and
STDERR instead of manually opening streams using these wrappers.
php://stdin is read-only, whereas
php://stdout and
php://stderr are write-only.
php://input
php://input is a read-only stream that allows you to read raw data from the request body. It can be opened and read as many times as needed.
php://input is not available in POST requests with
enctype="multipart/form-data" if enable_post_data_reading option is enabled.
php://output
php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as
print and
echo.
php://fd
php://fd allows direct access to the given file descriptor. For example,
php://fd/3 refers to file descriptor 3.
php://memory and php://temp
php://memory and
php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. One difference between the two is that
php://memory will always store its data in memory, whereas
php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the
sys_get_temp_dir function.
The memory limit of
php://temp can be controlled by appending
/maxmemory:NN, where
NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.
[!CAUTION]
Some PHP extensions may require a standard IO stream, and may attempt to cast a given stream to a standard IO stream. This cast can fail for memory streams as it requires the C
fopencookie function to be available. This C function is not available on Windows.
php://filter
php://filter is a kind of meta-wrapper designed to permit the application of filters to a stream at the time of opening. This is useful with all-in-one file functions such as
readfile,
file, and
file_get_contents where there is otherwise no opportunity to apply a filter to the stream prior the contents being read.
The
php://filter target takes the following parameters as part of its path. Multiple filter chains can be specified on one path. Please refer to the examples for specifics on using these parameters.
Name
Description
resource=ENTITYstream to be filteredENTITY
This parameter is required. It specifies the stream that you would like to filter.
read=ENTITYfilter list to apply to read chainENTITY
This parameter is optional. One or more filter names can be provided here, separated by the pipe character (`
write=ENTITYfilter list to apply to write chainENTITY
This parameter is optional. One or more filter names can be provided here, separated by the pipe character (`
ENTITYfilter list to apply to both chainsENTITY
Any filter lists which are not prefixed by
read= or
write= will be applied to both the read and write chains as appropriate.
php://filter parameters {role="stream_wrapper"}
ENTITY
Attribute
Supported
Restricted by allow_url_fopen
No
Restricted by allow_url_include
php://input,
php://stdin,
php://memory and
php://temp only.
Allows Reading
php://stdin,
php://input,
php://fd,
php://memory and
php://temp only.
Allows Writing
php://stdout,
php://stderr,
php://output,
php://fd,
php://memory and
php://temp only.
Allows Appending
php://stdout,
php://stderr,
php://output,
php://fd,
php://memory and
php://temp only. (Equivalent to writing)
Allows Simultaneous Reading and Writing
php://fd,
php://memory and
php://temp only.
Supports
stat
No. However,
php://memory and
php://temp support
fstat.
Supports
unlink
No
Supports
rename
No
Supports
mkdir
No
Supports
rmdir
No
Supports
stream_select
php://stdin,
php://stdout,
php://stderr,
php://fd and
php://temp only.
Wrapper Summary (for
php://filter, refer to the summary of the wrapper being filtered) {role="stream_wrapper"}
ENTITY
php://temp/maxmemory
This optional parameter allows setting the memory limit before
php://temp starts using a temporary file.
php://filter/resource=ENTITYstream to be filteredENTITY
This parameter must be located at the end of your
php://filter specification and should point to the stream which you want filtered.
php://filter/read=ENTITYfilter list to apply to read chainENTITY
This parameter takes one or more filternames separated by the pipe character
|.
php://filter/write=ENTITYfilter list to apply to write chainENTITY
This parameter takes one or more filternames separated by the pipe character
|.
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.
rar
rar://
RAR
ENTITY
The wrapper takes the url encoded path to the RAR archive (relative or absolute), an optional asterisk (
*), an optional number sign (
#) and an optional url encoded entry name, as stored in the archive. Specifying an entry name requires the number sign; a leading forward slash in the entry name is optional.
This wrapper can open both files and directories. When opening directories, the asterisk sign forces the directory entries names to be returned unencoded. If it's not specified, they will be returned url encoded – the reason for this is to allow the wrapper to be correctly used with built-in functionality like the
RecursiveDirectoryIterator in the presence of file names that seem like url encoded data.
If the pound sign and the entry name part are not included, the root of the archive will be displayed. This differs from regular directories in that the resulting stream will not contain information such as the modification time, as the root directory is not stored in an individual entry in the archive. The usage of the wrapper with
RecursiveDirectoryIterator requires the number sign to be included in the URL when accessing the root, so that the URLs of the children may be constructed correctly.
[!NOTE]
In order to use the
rar:// wrapper, the rar extension available from ENTITY must be installed.
rar:// Available since PECL rar 3.0.0
ENTITY
rar://ENTITYurl encoded archive nameENTITY[*][#[ENTITYurl encoded entry nameENTITY]]
ENTITY
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
Wrapper Summary {role="stream_wrapper"}
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.
Context options {role="stream_wrapper"}
ENTITY
Traversing a RAR archive
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";
}
?>
ENTITY
|-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
Opening an encrypted file (header encryption)
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));
?>
ENTITY
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
)
ssh2
ssh2://
Secure Shell 2
ENTITY
ssh2.shell://
ssh2.exec://
ssh2.tunnel://
ssh2.sftp://
ssh2.scp:// (PECL)
[!NOTE]
In order to use the
ssh2.*:// wrappers, the SSH2 extension available from ENTITY must be installed.
In addition to accepting traditional URI login details, the ssh2 wrappers will also reuse open connections by passing the connection resource in the host portion of the URL.
ENTITY
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
ENTITY
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
Wrapper Summary {role="stream_wrapper"}
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
Context options {role="stream_wrapper"}
ENTITY
Opening a stream from an active connection
This
$session variable must be kept available!
In order to use the
ssh2.*://$session wrappers, the
$session resource variable must be kept. The code below will not have the desired effect:
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).
Reference
book
ENTITY
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.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
configure
ENTITY
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.
[!NOTE]
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.
constants
ENTITY ENTITY
Descriptions and uses for these constants are described within the
curl_setopt,
curl_multi_setopt and
curl_getinfo documentation.
CURLALTSVC_H1 (
int)
Available as of PHP 8.2.0 and cURL 7.64.1.
CURLALTSVC_H2 (
int)
Available as of PHP 8.2.0 and cURL 7.64.1.
CURLALTSVC_H3 (
int)
Available as of PHP 8.2.0 and cURL 7.64.1.
CURLALTSVC_READONLYFILE (
int)
Available as of PHP 8.2.0 and cURL 7.64.1.
CURLAUTH_ANY (
int)
CURLAUTH_ANYSAFE (
int)
CURLAUTH_AWS_SIGV4 (
int)
Available as of PHP 8.2.0 and cURL 7.75.0.
CURLAUTH_BASIC (
int)
CURLAUTH_BEARER (
int)
Available as of PHP 7.3.0 and cURL 7.61.0.
CURLAUTH_DIGEST (
int)
CURLAUTH_DIGEST_IE (
int)
Use HTTP Digest authentication with an IE flavor. Available as of cURL 7.19.3.
CURLAUTH_GSSAPI (
int)
Available as of PHP 7.3.0 and cURL 7.54.1
CURLAUTH_GSSNEGOTIATE (
int)
CURLAUTH_NEGOTIATE (
int)
Available as of PHP 7.0.7 and cURL 7.38.0.
CURLAUTH_NONE (
int)
Available as of cURL 7.10.6.
CURLAUTH_NTLM (
int)
CURLAUTH_NTLM_WB (
int)
Available as of PHP 7.0.7 and cURL 7.22.0
CURLAUTH_ONLY (
int)
This is a meta symbol. OR this value together with a single specific auth value to force libcurl to probe for unrestricted auth and if not, only that single auth algorithm is acceptable. Available as of cURL 7.21.3.
CURLFOLLOW_ALL (
int)
Value for
CURLOPT_FOLLOWLOCATION that enables following redirects and keeps a custom request method set with
CURLOPT_CUSTOMREQUEST in use for all requests, even after redirects. Available as of PHP 8.5.0 and cURL 8.13.0.
CURLFOLLOW_OBEYCODE (
int)
Value for
CURLOPT_FOLLOWLOCATION that enables following redirects while obeying the HTTP response code: a custom request method set with
CURLOPT_CUSTOMREQUEST is kept, except that it is changed to
GET on the redirect status codes that require it (such as 301, 302 and 303). Available as of PHP 8.5.0 and cURL 8.13.0.
CURLFOLLOW_FIRSTONLY (
int)
Value for
CURLOPT_FOLLOWLOCATION that enables following redirects but uses a custom request method set with
CURLOPT_CUSTOMREQUEST for the first request only; subsequent requests follow the method dictated by the redirect response code. Available as of PHP 8.5.0 and cURL 8.13.0.
CURLFTPAUTH_DEFAULT (
int)
CURLFTPAUTH_SSL (
int)
CURLFTPAUTH_TLS (
int)
CURLFTPMETHOD_DEFAULT (
int)
Available as of PHP 8.2.0 and cURL 7.15.3.
CURLFTPMETHOD_MULTICWD (
int)
Do a single
CWD operation for each path part in the given URL. Available as of cURL 7.15.3.
CURLFTPMETHOD_NOCWD (
int)
libcurl makes no
CWD at all. libcurl does
SIZE,
RETR,
STOR etc. and gives a full path to the server for all these commands. Available as of cURL 7.15.3.
CURLFTPMETHOD_SINGLECWD (
int)
libcurl does one
CWD with the full target directory and then operates on the file like in the multicwd case. Available as of cURL 7.15.3.
CURLFTPSSL_ALL (
int)
CURLFTPSSL_CCC_ACTIVE (
int)
Initiate the shutdown and wait for a reply. Available as of cURL 7.16.2.
CURLFTPSSL_CCC_NONE (
int)
Do not attempt to use CCC (Clear Command Channel). Available as of cURL 7.16.2.
CURLFTPSSL_CCC_PASSIVE (
int)
Do not initiate the shutdown, but wait for the server to do it. Do not send a reply. Available as of cURL 7.16.1.
CURLFTPSSL_CONTROL (
int)
CURLFTPSSL_NONE (
int)
CURLFTPSSL_TRY (
int)
CURLFTP_CREATE_DIR (
int)
Available as of PHP 7.0.7 and cURL 7.19.3
CURLFTP_CREATE_DIR_NONE (
int)
Available as of PHP 7.0.7 and cURL 7.19.3
CURLFTP_CREATE_DIR_RETRY (
int)
Available as of PHP 7.0.7 and cURL 7.19.3
CURLGSSAPI_DELEGATION_FLAG (
int)
Allow unconditional GSSAPI credential delegation. Available as of cURL 7.22.0.
CURLGSSAPI_DELEGATION_POLICY_FLAG (
int)
Delegate only if the
OK-AS-DELEGATE flag is set in the service ticket if this feature is supported by the GSS-API implementation and the definition of
GSS_C_DELEG_POLICY_FLAG was available at compile-time. Available as of cURL 7.22.0.
CURLHEADER_SEPARATE (
int)
Available as of PHP 7.0.7 and cURL 7.37.0.
CURLHEADER_UNIFIED (
int)
Available as of PHP 7.0.7 and cURL 7.37.0.
CURLHSTS_ENABLE (
int)
Available as of PHP 8.2.0 and cURL 7.74.0
CURLHSTS_READONLYFILE (
int)
Available as of PHP 8.2.0 and cURL 7.74.0
CURLKHMATCH_LAST (
int)
Available as of PHP 8.3.0 and cURL 7.19.6
CURLKHMATCH_MISMATCH (
int)
Available as of PHP 8.3.0 and cURL 7.19.6
CURLKHMATCH_MISSING (
int)
Available as of PHP 8.3.0 and cURL 7.19.6
CURLKHMATCH_OK (
int)
Available as of PHP 8.3.0 and cURL 7.19.6
CURLMIMEOPT_FORMESCAPE (
int)
Available as of PHP 8.3.0 and cURL 7.81.0
CURLMSG_DONE (
int)
CURLPIPE_HTTP1 (
int)
Available as of cURL 7.43.0.
CURLPIPE_MULTIPLEX (
int)
Available as of cURL 7.43.0.
CURLPIPE_NOTHING (
int)
Available as of cURL 7.43.0.
CURLPROXY_HTTP (
int)
Available as of cURL 7.10.
CURLPROXY_HTTPS (
int)
Available as of PHP 7.3.0 and cURL 7.52.0
CURLPROXY_HTTP_1_0 (
int)
Available as of PHP 7.0.7 and cURL 7.19.3
CURLPROXY_SOCKS4 (
int)
Available as of cURL 7.10.
CURLPROXY_SOCKS4A (
int)
Available as of cURL 7.18.0.
CURLPROXY_SOCKS5 (
int)
Available as of cURL 7.10.
CURLPROXY_SOCKS5_HOSTNAME (
int)
Available as of cURL 7.18.0.
CURLPX_BAD_ADDRESS_TYPE (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_BAD_VERSION (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_CLOSED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_GSSAPI (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_GSSAPI_PERMSG (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_GSSAPI_PROTECTION (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_IDENTD (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_IDENTD_DIFFER (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_LONG_HOSTNAME (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_LONG_PASSWD (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_LONG_USER (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_NO_AUTH (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_OK (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_RECV_ADDRESS (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_RECV_AUTH (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_RECV_CONNECT (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_RECV_REQACK (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_COMMAND_NOT_SUPPORTED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_CONNECTION_REFUSED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_GENERAL_SERVER_FAILURE (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_HOST_UNREACHABLE (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_NETWORK_UNREACHABLE (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_NOT_ALLOWED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_TTL_EXPIRED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REPLY_UNASSIGNED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_REQUEST_FAILED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_RESOLVE_HOST (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_SEND_AUTH (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_SEND_CONNECT (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_SEND_REQUEST (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_UNKNOWN_FAIL (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_UNKNOWN_MODE (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLPX_USER_REJECTED (
int)
Available as of PHP 8.2.0 and cURL 7.73.0
CURLSSH_AUTH_AGENT (
int)
Available as of PHP 7.0.7 and cURL 7.28.0
CURLSSH_AUTH_ANY (
int)
CURLSSH_AUTH_DEFAULT (
int)
CURLSSH_AUTH_GSSAPI (
int)
Available as of PHP 7.3.0 and cURL 7.58.0
CURLSSH_AUTH_HOST (
int)
CURLSSH_AUTH_KEYBOARD (
int)
CURLSSH_AUTH_NONE (
int)
CURLSSH_AUTH_PASSWORD (
int)
CURLSSH_AUTH_PUBLICKEY (
int)
CURLSSLOPT_ALLOW_BEAST (
int)
Available as of cURL 7.25.0
CURLSSLOPT_AUTO_CLIENT_CERT (
int)
Available as of PHP 8.2.0 and cURL 7.77.0
CURLSSLOPT_NATIVE_CA (
int)
Available as of PHP 8.2.0 and cURL 7.71.0
CURLSSLOPT_NO_PARTIALCHAIN (
int)
Available as of PHP 8.2.0 and cURL 7.68.0
CURLSSLOPT_NO_REVOKE (
int)
Available as of PHP 7.0.7 and cURL 7.44.0
CURLSSLOPT_REVOKE_BEST_EFFORT (
int)
Available as of PHP 8.2.0 and cURL 7.70.0
CURLUSESSL_ALL (
int)
Require SSL for all communication or fail with
CURLE_USE_SSL_FAILED. Available as of cURL 7.17.0.
CURLUSESSL_CONTROL (
int)
Require SSL for the control connection or fail with
CURLE_USE_SSL_FAILED. Available as of cURL 7.17.0.
CURLUSESSL_NONE (
int)
Do not attempt to use SSL. Available as of cURL 7.17.0.
CURLUSESSL_TRY (
int)
Try using SSL, proceed as normal otherwise. Note that server may close the connection if the negotiation does not succeed. Available as of cURL 7.17.0.
CURLVERSION_NOW (
int)
CURLWS_RAW_MODE (
int)
Available as of PHP 8.3.0 and cURL 7.86.0
CURL_FNMATCHFUNC_FAIL (
int)
Returned by the wildcard match callback function if an error occurred. Available as of cURL 7.21.0.
CURL_FNMATCHFUNC_MATCH (
int)
Returned by the wildcard match callback function if pattern matches the string. Available as of cURL 7.21.0.
CURL_FNMATCHFUNC_NOMATCH (
int)
Returned by the wildcard match callback function if pattern does not match the string. Available as of cURL 7.21.0.
CURL_HTTP_VERSION_1_0 (
int)
CURL_HTTP_VERSION_1_1 (
int)
CURL_HTTP_VERSION_2 (
int)
Available as of PHP 7.0.7 and cURL 7.43.0
CURL_HTTP_VERSION_2TLS (
int)
Available as of PHP 7.0.7 and cURL 7.47.0
CURL_HTTP_VERSION_2_0 (
int)
Available as of cURL 7.33.0
CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (
int)
Available as of PHP 7.0.7 and cURL 7.49.0
CURL_HTTP_VERSION_3 (
int)
Available as of PHP 8.4.0 and cURL 7.66.0.
CURL_HTTP_VERSION_3ONLY (
int)
Available as of PHP 8.4.0 and cURL 7.88.0.
CURL_HTTP_VERSION_NONE (
int)
CURL_IPRESOLVE_V4 (
int)
Use only IPv4 addresses when establishing a connection or choosing one from the connection pool. Available as of cURL 7.10.8.
CURL_IPRESOLVE_V6 (
int)
Use only IPv6 addresses when establishing a connection or choosing one from the connection pool. Available as of cURL 7.10.8.
CURL_IPRESOLVE_WHATEVER (
int)
Use addresses of all IP versions allowed by the system. Available as of cURL 7.10.8.
CURL_MAX_READ_SIZE (
int)
Available as of PHP 7.3.0 and cURL 7.53.0
CURL_NETRC_IGNORED (
int)
CURL_NETRC_OPTIONAL (
int)
CURL_NETRC_REQUIRED (
int)
CURL_PUSH_DENY (
int)
Available as of PHP 7.1.0 and cURL 7.44.0
CURL_PUSH_OK (
int)
Available as of PHP 7.1.0 and cURL 7.44.0
CURL_READFUNC_PAUSE (
int)
Available as of cURL 7.18.0.
CURL_REDIR_POST_301 (
int)
Available as of PHP 7.0.7 and cURL 7.18.2
CURL_REDIR_POST_302 (
int)
Available as of PHP 7.0.7 and cURL 7.18.2
CURL_REDIR_POST_303 (
int)
Available as of PHP 7.0.7 and cURL 7.25.1
CURL_REDIR_POST_ALL (
int)
Available as of PHP 7.0.7 and cURL 7.18.2
CURL_RTSPREQ_ANNOUNCE (
int)
When sent by a client, this method changes the description of the session.
ANNOUNCE acts like an HTTP PUT or POST just like
CURL_RTSPREQ_SET_PARAMETER. Available as of cURL 7.20.0.
CURL_RTSPREQ_DESCRIBE (
int)
Used to get the low level description of a stream. The application should note what formats it understands in the
Accept: header. Unless set manually, libcurl automatically adds in
Accept: application/sdp. Time-condition headers are added to DESCRIBE requests if the
CURLOPT_TIMECONDITION option is used. Available as of cURL 7.20.0.
CURL_RTSPREQ_GET_PARAMETER (
int)
Retrieve a parameter from the server. By default, libcurl adds a
Content-Type: text/parameters header on all non-empty requests unless a custom one is set.
GET_PARAMETER acts just like an HTTP PUT or POST. Applications wishing to send a heartbeat message should use an empty
GET_PARAMETER request. Available as of cURL 7.20.0.
CURL_RTSPREQ_OPTIONS (
int)
Used to retrieve the available methods of the server. Available as of cURL 7.20.0.
CURL_RTSPREQ_PAUSE (
int)
Send a
PAUSE command to the server. Use the
CURLOPT_RANGE option with a single value to indicate when the stream should be halted (e.g. npt=25). Available as of cURL 7.20.0.
CURL_RTSPREQ_PLAY (
int)
Send a
PLAY command to the server. Use the
CURLOPT_RANGE option to modify the playback time (e.g. npt=10-15). Available as of cURL 7.20.0.
CURL_RTSPREQ_RECEIVE (
int)
Set the RTSP request type to this value to receive interleaved RTP data. Available as of cURL 7.20.0.
CURL_RTSPREQ_RECORD (
int)
Used to tell the server to record a session. Use the
CURLOPT_RANGE option to modify the record time. Available as of cURL 7.20.0.
CURL_RTSPREQ_SETUP (
int)
Used to initialize the transport layer for the session. Available as of cURL 7.20.0.
CURL_RTSPREQ_SET_PARAMETER (
int)
Set a parameter on the server. Available as of cURL 7.20.0.
CURL_RTSPREQ_TEARDOWN (
int)
Terminates an RTSP session. Simply closing a connection does not terminate the RTSP session since it is valid to control an RTSP session over different connections. Available as of cURL 7.20.0.
CURL_SSLVERSION_DEFAULT (
int)
CURL_SSLVERSION_MAX_DEFAULT (
int)
Available as of PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_NONE (
int)
Available as of PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_0 (
int)
Available as of PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_1 (
int)
Available as of PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_2 (
int)
Available as of PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_3 (
int)
Available as of PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_SSLv2 (
int)
CURL_SSLVERSION_SSLv3 (
int)
CURL_SSLVERSION_TLSv1 (
int)
CURL_SSLVERSION_TLSv1_0 (
int)
CURL_SSLVERSION_TLSv1_1 (
int)
CURL_SSLVERSION_TLSv1_2 (
int)
CURL_SSLVERSION_TLSv1_3 (
int)
Available as of PHP 7.3.0 and cURL 7.52.0
CURL_TIMECOND_IFMODSINCE (
int)
CURL_TIMECOND_IFUNMODSINCE (
int)
CURL_TIMECOND_LASTMOD (
int)
CURL_TIMECOND_NONE (
int)
CURL_TLSAUTH_SRP (
int)
Available as of cURL 7.21.4.
CURL_VERSION_ALTSVC (
int)
Available as of PHP 7.3.6 and cURL 7.64.1
CURL_VERSION_ASYNCHDNS (
int)
Asynchronous DNS resolves. Available as of PHP 7.3.0 and cURL 7.10.7
CURL_VERSION_BROTLI (
int)
Available as of PHP 7.3.0 and cURL 7.57.0
CURL_VERSION_CONV (
int)
Character conversions supported. Available as of PHP 7.3.0 and cURL 7.15.4
CURL_VERSION_CURLDEBUG (
int)
Debug memory tracking supported. Available as of PHP 7.3.6 and cURL 7.19.6
CURL_VERSION_DEBUG (
int)
Built with debug capabilities. Available as of PHP 7.3.0 and cURL 7.10.6
CURL_VERSION_GSASL (
int)
Available as of PHP 8.2.0 and cURL 7.76.0
CURL_VERSION_GSSAPI (
int)
Built against a GSS-API library. Available as of PHP 7.3.0 and cURL 7.38.0
CURL_VERSION_GSSNEGOTIATE (
int)
Negotiate auth is supported. Available as of PHP 7.3.0 and cURL 7.10.6 (deprecated as of cURL 7.38.0)
CURL_VERSION_HSTS (
int)
Available as of PHP 8.2.0 and cURL 7.74.0
CURL_VERSION_HTTP2 (
int)
HTTP2 support built-in. Available as of cURL 7.33.0
CURL_VERSION_HTTP3 (
int)
Available as of PHP 8.2.0 and cURL 7.66.0
CURL_VERSION_HTTPS_PROXY (
int)
Available as of PHP 7.3.0 and cURL 7.52.0
CURL_VERSION_IDN (
int)
Internationalized Domain Names are supported. Available as of PHP 7.3.0 and cURL 7.12.0
CURL_VERSION_IPV6 (
int)
IPv6-enabled.
CURL_VERSION_KERBEROS4 (
int)
Kerberos V4 auth is supported.
CURL_VERSION_KERBEROS5 (
int)
Kerberos V5 auth is supported. Available as of PHP 7.0.7 and cURL 7.40.0
CURL_VERSION_LARGEFILE (
int)
Supports files larger than 2GB. Available as of cURL 7.33.0
CURL_VERSION_LIBZ (
int)
libz features are present.
CURL_VERSION_MULTI_SSL (
int)
Available as of PHP 7.3.0 and cURL 7.56.0
CURL_VERSION_NTLM (
int)
NTLM auth is supported. Available as of PHP 7.3.0 and cURL 7.10.6
CURL_VERSION_NTLM_WB (
int)
NTLM delegation to winbind helper is supported. Available as of PHP 7.3.0 and cURL 7.22.0
CURL_VERSION_PSL (
int)
Mozilla's Public Suffix List, used for cookie domain verification. Available as of PHP 7.3.6 and cURL 7.47.0
CURL_VERSION_SPNEGO (
int)
SPNEGO auth is supported. Available as of PHP 7.3.0 and cURL 7.10.8
CURL_VERSION_SSL (
int)
SSL options are present.
CURL_VERSION_SSPI (
int)
Built against Windows SSPI. Available as of PHP 7.3.0 and cURL 7.13.2
CURL_VERSION_TLSAUTH_SRP (
int)
TLS-SRP auth is supported. Available as of PHP 7.3.0 and cURL 7.21.4
CURL_VERSION_UNICODE (
int)
Available as of PHP 8.2.0 and cURL 7.72.0
CURL_VERSION_UNIX_SOCKETS (
int)
Unix domain sockets support. Available as of PHP 7.0.7 and cURL 7.40.0
CURL_VERSION_ZSTD (
int)
Available as of PHP 8.2.0 and cURL 7.72.0
CURL_WRITEFUNC_PAUSE (
int)
Available as of cURL 7.18.0.
CURL_PREREQFUNC_OK (
int)
Available as of PHP 8.4.0 and cURL 7.80.0.
CURL_PREREQFUNC_ABORT (
int)
Available as of PHP 8.4.0 and cURL 7.80.0.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
constants_curl_error
CURLE_ABORTED_BY_CALLBACK (
int)
Aborted by callback. A callback returned "abort" to libcurl.
CURLE_BAD_CALLING_ORDER (
int)
CURLE_BAD_CONTENT_ENCODING (
int)
Unrecognized transfer encoding.
CURLE_BAD_DOWNLOAD_RESUME (
int)
The download could not be resumed because the specified offset was out of the file boundary.
CURLE_BAD_FUNCTION_ARGUMENT (
int)
A function was called with a bad parameter.
CURLE_BAD_PASSWORD_ENTERED (
int)
CURLE_COULDNT_CONNECT (
int)
Failed to connect to host or proxy.
CURLE_COULDNT_RESOLVE_HOST (
int)
Could not resolve host. The given remote host was not resolved.
CURLE_COULDNT_RESOLVE_PROXY (
int)
Could not resolve proxy. The given proxy host could not be resolved.
CURLE_FAILED_INIT (
int)
Early initialization code failed. This is likely to be an internal error or problem, or a resource problem where something fundamental could not get done at init time.
CURLE_FILESIZE_EXCEEDED (
int)
Maximum file size exceeded.
CURLE_FILE_COULDNT_READ_FILE (
int)
A file given with FILE:// could not be opened. Most likely because the file path does not identify an existing file or due to the lack of appropriate file permissions.
CURLE_FTP_ACCESS_DENIED (
int)
CURLE_FTP_BAD_DOWNLOAD_RESUME (
int)
CURLE_FTP_CANT_GET_HOST (
int)
An internal failure to lookup the host used for the new connection.
CURLE_FTP_CANT_RECONNECT (
int)
CURLE_FTP_COULDNT_GET_SIZE (
int)
CURLE_FTP_COULDNT_RETR_FILE (
int)
This was either a unexpected reply to a 'RETR' command or a zero byte transfer complete.
CURLE_FTP_COULDNT_SET_ASCII (
int)
CURLE_FTP_COULDNT_SET_BINARY (
int)
CURLE_FTP_COULDNT_STOR_FILE (
int)
CURLE_FTP_COULDNT_USE_REST (
int)
The FTP REST command returned error. This should never happen if the server is sane.
CURLE_FTP_PARTIAL_FILE (
int)
CURLE_FTP_PORT_FAILED (
int)
The FTP PORT command returned error. This mostly happens when a good enough address has not been specified for libcurl to use. See
CURLOPT_FTPPORT.
CURLE_FTP_QUOTE_ERROR (
int)
CURLE_FTP_SSL_FAILED (
int)
CURLE_FTP_USER_PASSWORD_INCORRECT (
int)
CURLE_FTP_WEIRD_227_FORMAT (
int)
FTP servers return a 227-line as a response to a PASV command. If libcurl fails to parse that line, this return code is passed back.
CURLE_FTP_WEIRD_PASS_REPLY (
int)
After having sent the FTP password to the server, libcurl expects a proper reply. This error code indicates that an unexpected code was returned.
CURLE_FTP_WEIRD_PASV_REPLY (
int)
libcurl failed to get a sensible result back from the server as a response to either a PASV or a EPSV command. The server is flawed.
CURLE_FTP_WEIRD_SERVER_REPLY (
int)
The server sent data libcurl could not parse. This error code is known as
CURLE_WEIRD_SERVER_REPLY as of cURL 7.51.0.
CURLE_FTP_WEIRD_USER_REPLY (
int)
CURLE_FTP_WRITE_ERROR (
int)
CURLE_FUNCTION_NOT_FOUND (
int)
Function not found. A required zlib function was not found.
CURLE_GOT_NOTHING (
int)
Nothing was returned from the server, and under the circumstances, getting nothing is considered an error.
CURLE_HTTP_NOT_FOUND (
int)
CURLE_HTTP_PORT_FAILED (
int)
CURLE_HTTP_POST_ERROR (
int)
This is an odd error that mainly occurs due to internal confusion.
CURLE_HTTP_RANGE_ERROR (
int)
CURLE_HTTP_RETURNED_ERROR (
int)
This is returned if
CURLOPT_FAILONERROR is set ENTITY and the HTTP server returns an error code that is greater than or equal to 400.
CURLE_LDAP_CANNOT_BIND (
int)
LDAP cannot bind. LDAP bind operation failed.
CURLE_LDAP_INVALID_URL (
int)
CURLE_LDAP_SEARCH_FAILED (
int)
LDAP search failed.
CURLE_LIBRARY_NOT_FOUND (
int)
CURLE_MALFORMAT_USER (
int)
CURLE_OBSOLETE (
int)
CURLE_OK (
int)
All fine. Proceed as usual.
CURLE_OPERATION_TIMEDOUT (
int)
Operation timeout. The specified time-out period was reached according to the conditions.
CURLE_OPERATION_TIMEOUTED (
int)
CURLE_OUT_OF_MEMORY (
int)
A memory allocation request failed.
CURLE_PARTIAL_FILE (
int)
A file transfer was shorter or larger than expected. This happens when the server first reports an expected transfer size, and then delivers data that does not match the previously given size.
CURLE_PROXY (
int)
Proxy handshake error.
CURLINFO_PROXY_ERROR provides extra details on the specific problem. Available as of PHP 8.2.0 and cURL 7.73.0
CURLE_READ_ERROR (
int)
There was a problem reading a local file or an error returned by the read callback.
CURLE_RECV_ERROR (
int)
Failure with receiving network data.
CURLE_SEND_ERROR (
int)
Failed sending network data.
CURLE_SHARE_IN_USE (
int)
CURLE_SSH (
int)
An unspecified error occurred during the SSH session. Available as of cURL 7.16.1.
CURLE_SSL_CACERT (
int)
CURLE_SSL_CACERT_BADFILE (
int)
Problem with reading the SSL CA cert.
CURLE_SSL_CERTPROBLEM (
int)
Problem with the local client certificate.
CURLE_SSL_CIPHER (
int)
Could not use specified cipher.
CURLE_SSL_CONNECT_ERROR (
int)
A problem occurred somewhere in the SSL/TLS handshake. Reading the message in the error buffer provides more details on the problem. Could be certificates (file formats, paths, permissions), passwords, and others.
CURLE_SSL_ENGINE_NOTFOUND (
int)
The specified crypto engine was not found.
CURLE_SSL_ENGINE_SETFAILED (
int)
Failed setting the selected SSL crypto engine as default.
CURLE_SSL_PEER_CERTIFICATE (
int)
CURLE_SSL_PINNEDPUBKEYNOTMATCH (
int)
Failed to match the pinned key specified with
CURLOPT_PINNEDPUBLICKEY.
CURLE_TELNET_OPTION_SYNTAX (
int)
CURLE_TOO_MANY_REDIRECTS (
int)
Too many redirects. When following redirects, libcurl hit the maximum amount. The limit can be set with
CURLOPT_MAXREDIRS.
CURLE_UNKNOWN_TELNET_OPTION (
int)
CURLE_UNSUPPORTED_PROTOCOL (
int)
The URL passed to libcurl used a protocol that libcurl does not support. The issue might be a compile-time option that was not used, a misspelled protocol string or just a protocol libcurl has no code for.
CURLE_URL_MALFORMAT (
int)
The URL was not properly formatted.
CURLE_URL_MALFORMAT_USER (
int)
CURLE_WEIRD_SERVER_REPLY (
int)
The server sent data libcurl could not parse. This error code was known as
CURLE_FTP_WEIRD_SERVER_REPLY before cURL 7.51.0. Available as of PHP 7.3.0 and cURL 7.51.0
CURLE_WRITE_ERROR (
int)
An error occurred when writing received data to a local file, or an error was returned to libcurl from a write callback.
constants_curl_getinfo
CURLINFO_APPCONNECT_TIME (
int)
Time in seconds it took from the start until the SSL/SSH connect/handshake to the remote host was completed
CURLINFO_APPCONNECT_TIME_T (
int)
Time, in microseconds, it took from the start until the SSL/SSH connect/handshake to the remote host was completed. Available as of PHP 7.3.0 and cURL 7.61.0
CURLINFO_CAINFO (
int)
Default built-in CA certificate path. Available as of PHP 8.3.0 and cURL 7.84.0
CURLINFO_CAPATH (
int)
Default built-in CA path string. Available as of PHP 8.3.0 and cURL 7.84.0
CURLINFO_CERTINFO (
int)
TLS certificate chain
CURLINFO_CONDITION_UNMET (
int)
Info on unmet time conditional
CURLINFO_CONN_ID (
int)
The ID of the last connection used by the transfer. The connection ID is unique among all connections using the same connection cache and is useful to tell connection reuse apart. Available as of PHP 8.5.0 and cURL 8.2.0.
CURLINFO_CONNECT_TIME (
int)
Time in seconds it took to establish the connection
CURLINFO_CONNECT_TIME_T (
int)
Total time taken, in microseconds, from the start until the connection to the remote host (or proxy) was completed. Available as of PHP 7.3.0 and cURL 7.61.0
CURLINFO_CONTENT_LENGTH_DOWNLOAD (
int)
Content length of download, read from Content-Length: field. Deprecated since cURL 7.55.0. Use
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T instead.
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T (
int)
The content-length of the download. This is the value read from the Content-Length: field. -1 if the size isn't known. Available as of PHP 7.3.0 and cURL 7.55.0
CURLINFO_CONTENT_LENGTH_UPLOAD (
int)
Specified size of upload. Deprecated since cURL 7.55.0. Use
CURLINFO_CONTENT_LENGTH_UPLOAD_T instead.
CURLINFO_CONTENT_LENGTH_UPLOAD_T (
int)
The specified size of the upload. -1 if the size isn't known. Available as of PHP 7.3.0 and cURL 7.55.0
CURLINFO_CONTENT_TYPE (
int)
Content-Type of the requested document. NULL indicates server did not send valid
Content-Type header
CURLINFO_COOKIELIST (
int)
All known cookies
CURLINFO_EFFECTIVE_METHOD (
int)
Get the last used HTTP method.
CURLINFO_EFFECTIVE_URL (
int)
Last effective URL
CURLINFO_FILETIME (
int)
Remote time of the retrieved document, with the
CURLOPT_FILETIME enabled; if -1 is returned the time of the document is unknown
CURLINFO_FILETIME_T (
int)
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. Available as of PHP 7.3.0 and cURL 7.59.0
CURLINFO_FTP_ENTRY_PATH (
int)
Entry path in FTP server
CURLINFO_HEADER_OUT (
int)
The request string sent. For this to work, add the
CURLINFO_HEADER_OUT option to the handle by calling
curl_setopt
CURLINFO_HEADER_SIZE (
int)
Total size of all headers received
CURLINFO_HTTPAUTH_AVAIL (
int)
Bitmask indicating the authentication method(s) available according to the previous response
CURLINFO_HTTPAUTH_USED (
int)
Bitmask indicating the HTTP authentication method(s) actually used in the previous request. Available as of PHP 8.5.0 and cURL 8.12.0.
CURLINFO_HTTP_CODE (
int)
The last response code. As of cURL 7.10.8, this is a legacy alias of
CURLINFO_RESPONSE_CODE.
CURLINFO_HTTP_CONNECTCODE (
int)
The CONNECT response code
CURLINFO_HTTP_VERSION (
int)
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. Available as of PHP 7.3.0 and cURL 7.50.0
CURLINFO_LASTONE (
int)
The last enum value in the underlying
CURLINFO enum in
libcurl.
CURLINFO_LOCAL_IP (
int)
Local (source) IP address of the most recent connection
CURLINFO_LOCAL_PORT (
int)
Local (source) port of the most recent connection
CURLINFO_NAMELOOKUP_TIME (
int)
Time in seconds until name resolving was complete
CURLINFO_NAMELOOKUP_TIME_T (
int)
Time in microseconds from the start until the name resolving was completed. Available as of PHP 7.3.0 and cURL 7.61.0
CURLINFO_NUM_CONNECTS (
int)
Number of connections curl had to create to achieve the previous transfer
CURLINFO_OS_ERRNO (
int)
Errno from a connect failure. The number is OS and system specific.
CURLINFO_PRETRANSFER_TIME (
int)
Time in seconds from start until just before file transfer begins
CURLINFO_PRETRANSFER_TIME_T (
int)
Time taken from the start until the file transfer is just about to begin, in microseconds. Available as of PHP 7.3.0 and cURL 7.61.0
CURLINFO_PRIMARY_IP (
int)
IP address of the most recent connection
CURLINFO_PRIMARY_PORT (
int)
Destination port of the most recent connection
CURLINFO_PRIVATE (
int)
Private data associated with this cURL handle, previously set with the
CURLOPT_PRIVATE option of
curl_setopt
CURLINFO_PROTOCOL (
int)
The protocol used in the last HTTP connection. The returned value will be exactly one of the
CURLPROTO_* values. Available as of PHP 7.3.0 and cURL 7.52.0. Deprecated since cURL 7.85.0. Use
CURLINFO_SCHEME instead.
CURLINFO_PROXYAUTH_AVAIL (
int)
Bitmask indicating the proxy authentication method(s) available according to the previous response
CURLINFO_PROXYAUTH_USED (
int)
Bitmask indicating the proxy authentication method(s) actually used in the previous request. Available as of PHP 8.5.0 and cURL 8.12.0.
CURLINFO_PROXY_ERROR (
int)
The detailed (SOCKS) proxy error code when the most recent transfer returned a
CURLE_PROXY error. The returned value will be exactly one of the
CURLPX_* values. The error code will be
CURLPX_OK if no response code was available. Available as of PHP 8.2.0 and cURL 7.73.0
CURLINFO_PROXY_SSL_VERIFYRESULT (
int)
The result of the certificate verification that was requested (using the
CURLOPT_PROXY_SSL_VERIFYPEER option). Only used for HTTPS proxies. Available as of PHP 7.3.0 and cURL 7.52.0
CURLINFO_QUEUE_TIME_T (
int)
The time, in microseconds, that the transfer was held in a waiting queue before it started, due to limits set with
CURLMOPT_MAX_TOTAL_CONNECTIONS or similar options. Available as of PHP 8.5.0 and cURL 8.6.0.
CURLINFO_REDIRECT_COUNT (
int)
Number of redirects, with the
CURLOPT_FOLLOWLOCATION option enabled
CURLINFO_REDIRECT_TIME (
int)
Time in seconds of all redirection steps before final transaction was started, with the
CURLOPT_FOLLOWLOCATION option enabled
CURLINFO_REDIRECT_TIME_T (
int)
Total time, in microseconds, it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started. Available as of PHP 7.3.0 and cURL 7.61.0
CURLINFO_REDIRECT_URL (
int)
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_REFERER (
int)
The
Referer header. Available as of PHP 8.2.0 and cURL 7.76.0
CURLINFO_REQUEST_SIZE (
int)
Total size of issued requests, currently only for HTTP requests
CURLINFO_RESPONSE_CODE (
int)
The last response code. Available as of cURL 7.10.8
CURLINFO_RETRY_AFTER (
int)
The information from the
Retry-After header, or zero if there was no valid header. Available as of PHP 8.2.0 and cURL 7.66.0
CURLINFO_RTSP_CLIENT_CSEQ (
int)
Next RTSP client CSeq
CURLINFO_RTSP_CSEQ_RECV (
int)
Recently received CSeq
CURLINFO_RTSP_SERVER_CSEQ (
int)
Next RTSP server CSeq
CURLINFO_RTSP_SESSION_ID (
int)
RTSP session ID
CURLINFO_SCHEME (
int)
The URL scheme used for the most recent connection. Available as of PHP 7.3.0 and cURL 7.52.0
CURLINFO_SIZE_DOWNLOAD (
int)
Total number of bytes downloaded. Deprecated since cURL 7.55.0. Use
CURLINFO_SIZE_DOWNLOAD_T instead.
CURLINFO_SIZE_DOWNLOAD_T (
int)
Total number of bytes that were downloaded. The number is only for the latest transfer and will be reset again for each new transfer. Available as of PHP 7.3.0 and cURL 7.50.0
CURLINFO_SIZE_UPLOAD (
int)
Total number of bytes uploaded. Deprecated since cURL 7.55.0. Use
CURLINFO_SIZE_UPLOAD_T instead.
CURLINFO_SIZE_UPLOAD_T (
int)
Total number of bytes that were uploaded. Available as of PHP 7.3.0 and cURL 7.50.0
CURLINFO_SPEED_DOWNLOAD (
int)
Average download speed. Deprecated since cURL 7.55.0. Use
CURLINFO_SPEED_DOWNLOAD_T instead.
CURLINFO_SPEED_DOWNLOAD_T (
int)
The average download speed in bytes/second that curl measured for the complete download. Available as of PHP 7.3.0 and cURL 7.50.0
CURLINFO_SPEED_UPLOAD (
int)
Average upload speed. Deprecated since cURL 7.55.0. Use
CURLINFO_SPEED_UPLOAD_T instead.
CURLINFO_SPEED_UPLOAD_T (
int)
The average upload speed in bytes/second that curl measured for the complete upload. Available as of PHP 7.3.0 and cURL 7.50.0
CURLINFO_SSL_ENGINES (
int)
OpenSSL crypto-engines supported
CURLINFO_SSL_VERIFYRESULT (
int)
Result of SSL certification verification requested by setting
CURLOPT_SSL_VERIFYPEER
CURLINFO_STARTTRANSFER_TIME (
int)
Time in seconds until the first byte is about to be transferred
CURLINFO_STARTTRANSFER_TIME_T (
int)
Time, in microseconds, it took from the start until the first byte is received. Available as of PHP 7.3.0 and cURL 7.61.0
CURLINFO_TOTAL_TIME (
int)
Total transaction time in seconds for last transfer
CURLINFO_TOTAL_TIME_T (
int)
Total time in microseconds for the previous transfer, including name resolving, TCP connect etc. Available as of PHP 7.3.0 and cURL 7.61.0
CURLINFO_USED_PROXY (
int)
Whether the previous transfer used a proxy; returns
1 if a proxy was used and
0 otherwise. Available as of PHP 8.5.0 and cURL 8.7.0.
CURLINFO_POSTTRANSFER_TIME_T (
int)
Time it took from the start until the last byte is sent, in microseconds. Available as of PHP 8.4.0 and cURL 8.10.0
constants_curl_multi
CURLM_ADDED_ALREADY (
int)
An easy handle already added to a multi handle was attempted to get added a second time. Available as of cURL 7.32.1.
CURLM_BAD_EASY_HANDLE (
int)
An easy handle was not good/valid. It could mean that it is not an easy handle at all, or possibly that the handle already is in use by this or another multi handle. Available as of cURL 7.9.6.
CURLM_BAD_HANDLE (
int)
The passed-in handle is not a valid multi handle. Available as of cURL 7.9.6.
CURLM_CALL_MULTI_PERFORM (
int)
As of cURL 7.20.0, this constant is not used. Before cURL 7.20.0, this status could be returned by
curl_multi_exec when
curl_multi_select or a similar function was called before it returned any other constant. Available as of cURL 7.9.6.
CURLM_INTERNAL_ERROR (
int)
Internal
libcurl error. Available as of cURL 7.9.6.
CURLM_OK (
int)
No errors. Available as of cURL 7.9.6.
CURLM_OUT_OF_MEMORY (
int)
Ran out of memory while processing multi handles. Available as of cURL 7.9.6.
constants_curl_multi_setopt
CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE (
int)
Specifies the chunk length threshold for pipelining in bytes. Available as of PHP 7.0.7 and cURL 7.30.0
CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE (
int)
Specifies the size threshold for pipelining penalty in bytes. Available as of PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAXCONNECTS (
int)
Specifies 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. Available as of cURL 7.16.3.
CURLMOPT_MAX_CONCURRENT_STREAMS (
int)
Specifies the maximum number of concurrent streams for connections that cURL should support on connections using HTTP/2. Valid values range from
1 to
2147483647 (
2^31 - 1). The value passed here would be honored based on other system resources properties. Default is
100. Available as of PHP 8.2.0 and cURL 7.67.0.
CURLMOPT_MAX_HOST_CONNECTIONS (
int)
Specifies the maximum number of connections to a single host. Available as of PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_PIPELINE_LENGTH (
int)
Specifies the maximum number of requests in a pipeline. Available as of PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_TOTAL_CONNECTIONS (
int)
Specifies the maximum number of simultaneously open connections. Available as of PHP 7.0.7 and cURL 7.30.0
CURLMOPT_PIPELINING (
int)
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 adding a second request that can use an already existing connection will "pipe" the second request on the same connection. As of cURL 7.43.0, the value is a bitmask, and passing 2 will try to multiplex the new transfer over an existing HTTP/2 connection. 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, the CURLPIPE_* constants can also be used. Available as of cURL 7.16.0.
CURLMOPT_PUSHFUNCTION (
int)
Pass a
callable that will be registered to handle server pushes and should have the following signature:
int
resource``parent_ch
resource``pushed_ch
array``headers
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. Available as of PHP 7.1.0 and cURL 7.44.0
constants_curl_pause
CURLPAUSE_ALL (
int)
Pause sending and receiving data. Available as of cURL 7.18.0.
CURLPAUSE_CONT (
int)
Unpause sending and receiving data. Available as of cURL 7.18.0.
CURLPAUSE_RECV (
int)
Pause receiving data. Available as of cURL 7.18.0.
CURLPAUSE_RECV_CONT (
int)
Unpause receiving data. Available as of cURL 7.18.0.
CURLPAUSE_SEND (
int)
Pause sending data. Available as of cURL 7.18.0.
CURLPAUSE_SEND_CONT (
int)
Unpause sending data. Available as of cURL 7.18.0.
constants_curl_setopt
CURLOPT_ABSTRACT_UNIX_SOCKET (
int)
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 as of PHP 7.3.0 and cURL 7.53.0.
CURLOPT_ACCEPT_ENCODING (
int)
Sets a
string with the contents of the
Accept-Encoding: header sent in an HTTP request. Set to ENTITY to disable sending the
Accept-Encoding: header. Defaults to ENTITY. Available as of cURL 7.21.6.
CURLOPT_ACCEPTTIMEOUT_MS (
int)
The maximum number of milliseconds to wait for a server to connect back to cURL when an active FTP connection is used. This option accepts any value that can be cast to a valid
int. Defaults to
60000 milliseconds. Available as of cURL 7.24.0.
CURLOPT_ADDRESS_SCOPE (
int)
The scope id value to use when connecting to IPv6 addresses. This option accepts any value that can be cast to a valid
int. Defaults to
0. Available as of cURL 7.19.0.
CURLOPT_ALTSVC (
int)
Pass a
string with the filename for cURL to use as the Alt-Svc cache file to read existing cache contents from and possibly also write it back to a after a transfer, unless
CURLALTSVC_READONLYFILE is set via
CURLOPT_ALTSVC_CTRL. Available as of PHP 8.2.0 and cURL 7.64.1.
CURLOPT_ALTSVC_CTRL (
int)
Populate the bitmask with the correct set of features to instruct cURL how to handle Alt-Svc for the transfers using this handle. cURL only accepts Alt-Svc headers over HTTPS. It will also only complete a request to an alternative origin if that origin is properly hosted over HTTPS. Setting any bit will enable the alt-svc engine. Set to any of the
CURLALTSVC_* constants. Defaults to Alt-Svc handling being disabled. Available as of PHP 8.2.0 and cURL 7.64.1.
CURLOPT_APPEND (
int)
Setting this option to
1 will cause FTP uploads to append to the remote file instead of overwriting it. Defaults to
0. Available as of cURL 7.17.0.
CURLOPT_AUTOREFERER (
int)
ENTITY to automatically set the
Referer: field in requests where it follows a
Location: redirect. Defaults to
0. Available as of cURL 7.1.0.
CURLOPT_AWS_SIGV4 (
int)
Provides AWS V4 signature authentication on HTTP(S) header as a
string. This option overrides any other authentication types that have been set in
CURLOPT_HTTPAUTH. This method cannot be combined with other authentication types. Available as of PHP 8.2.0 and cURL 7.75.0.
CURLOPT_BINARYTRANSFER (
int)
This constant is no longer used as of PHP 5.5.0. Deprecated as of PHP 8.4.0.
CURLOPT_BUFFERSIZE (
int)
The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. This option accepts any value that can be cast to a valid
int. Defaults to
CURL_MAX_WRITE_SIZE (currently, 16kB). Available as of cURL 7.10.
CURLOPT_CAINFO (
int)
A
string with 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. Available as of cURL 7.4.2.
CURLOPT_CAINFO_BLOB (
int)
A binary
string of PEM encoded content holding one or more certificates to verify the peer with. This option overrides
CURLOPT_CAINFO. Available as of PHP 8.2.0 and cURL 7.77.0.
CURLOPT_CAPATH (
int)
A
string with a directory that holds multiple CA certificates. Use this option alongside
CURLOPT_SSL_VERIFYPEER. Available as of cURL 7.9.8.
CURLOPT_CA_CACHE_TIMEOUT (
int)
Sets the maximum time in seconds any in memory cached CA certificate store may be kept and reused for new connections. This option accepts any value that can be cast to a valid
int. Defaults to
86400 (24 hours). Available as of PHP 8.3.0 and cURL 7.87.0
CURLOPT_CERTINFO (
int)
ENTITY to output SSL certification information to
STDERR on secure transfers. Requires
CURLOPT_VERBOSE to be on to have an effect. Defaults to ENTITY. Available as of cURL 7.19.1.
CURLOPT_CONNECTTIMEOUT (
int)
The number of seconds to wait while trying to connect. Use
0 to wait indefinitely. This option accepts any value that can be cast to a valid
int. Defaults to
300. Available as of cURL 7.7.0.
CURLOPT_CONNECTTIMEOUT_MS (
int)
The number of milliseconds to wait while trying to connect. Use
0 to wait indefinitely. If cURL 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. This option accepts any value that can be cast to a valid
int. Defaults to
300000. Available as of cURL 7.16.2.
CURLOPT_CONNECT_ONLY (
int)
ENTITY 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. Defaults to ENTITY. Available as of cURL 7.15.2.
CURLOPT_CONNECT_TO (
int)
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. Available as of PHP 7.0.7 and cURL 7.49.0.
CURLOPT_COOKIE (
int)
A
string with 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). Available as of cURL 7.1.0.
CURLOPT_COOKIEFILE (
int)
A
string with 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. Available as of cURL 7.1.0.
CURLOPT_COOKIEJAR (
int)
A
string with the name of a file to save all internal cookies to when the handle's destructor is called. Available as of cURL 7.9.0.
[!WARNING]
As of PHP 8.0.0,
curl_close is a no-op and does not destroy the handle. If cookies need to be written prior to the handle being automatically destroyed, run
curl_setopt($ch, CURLOPT_COOKIELIST, "FLUSH");.
CURLOPT_COOKIELIST (
int)
A cookie
string (i.e. a single line in Netscape/Mozilla format, or a regular HTTP-style Set-Cookie header) adds that single cookie to the internal cookie store.
ALL erases all cookies held in memory,
SESS erases all session cookies held in memory,
FLUSH writes all known cookies to the file specified by
CURLOPT_COOKIEJAR,
RELOAD loads all cookies from the files specified by
CURLOPT_COOKIEFILE. Available as of cURL 7.14.1.
CURLOPT_COOKIESESSION (
int)
ENTITY to mark this as a new cookie "session". It will force cURL to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, cURL 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. Available as of cURL 7.9.7.
CURLOPT_CRLF (
int)
ENTITY to convert Unix newlines to CRLF newlines on transfers. Available as of cURL 7.1.0.
CURLOPT_CRLFILE (
int)
Pass a
string naming a file with the concatenation of CRL (Certificate Revocation List) (in PEM format) to use in the certificate validation that occurs during the SSL exchange. When cURL is built to use GnuTLS, there is no way to influence the use of CRL passed to help in the verification process. When cURL is built with OpenSSL support,
X509_V_FLAG_CRL_CHECK and
X509_V_FLAG_CRL_CHECK_ALL are both set, requiring CRL check against all the elements of the certificate chain if a CRL file is passed. Also note that
CURLOPT_CRLFILE implies
CURLSSLOPT_NO_PARTIALCHAIN as of cURL 7.71.0 due to an OpenSSL bug. Available as of cURL 7.19.0.
CURLOPT_CUSTOMREQUEST (
int)
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. This option accepts a
string or ENTITY. Available as of cURL 7.1.0.
[!NOTE]
Don't do this without making sure the server supports the custom request method first.
CURLOPT_DEFAULT_PROTOCOL (
int)
A
string with the default protocol to use if the URL is missing a scheme name. Available as of PHP 7.0.7 and cURL 7.45.0.
CURLOPT_DIRLISTONLY (
int)
Setting this option to
1 will have different effects based on the protocol it is used with. FTP and SFTP based URLs will list only the names of files in a directory. POP3 will list the email message or messages on the POP3 server. For FILE, this option has no effect as directories are always listed in this mode. Using this option with
CURLOPT_WILDCARDMATCH will prevent the latter from having any effect. Defaults to
0. Available as of cURL 7.17.0.
CURLOPT_DISALLOW_USERNAME_IN_URL (
int)
ENTITY to not allow URLs that include a username. Usernames are allowed by default. Available as of PHP 7.3.0 and cURL 7.61.0.
CURLOPT_DNS_CACHE_TIMEOUT (
int)
The number of seconds to keep DNS entries in memory. This option is set to
120 (2 minutes) by default. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.9.3.
CURLOPT_DNS_INTERFACE (
int)
Set the name of the network interface that the DNS resolver should bind to. This must be an interface name (not an address). This option accepts a
string or ENTITY. Available as of PHP 7.0.7 and cURL 7.33.0
CURLOPT_DNS_LOCAL_IP4 (
int)
Set the local IPv4 address that the resolver should bind to. The argument should contain a single numerical IPv4 address. This option accepts a
string or ENTITY. Available as of PHP 7.0.7 and cURL 7.33.0.
CURLOPT_DNS_LOCAL_IP6 (
int)
Set the local IPv6 address that the resolver should bind to. The argument should contain a single numerical IPv6 address. This option accepts a
string or ENTITY. Available as of PHP 7.0.7 and cURL 7.33.0.
CURLOPT_DNS_SERVERS (
int)
Pass a
string with a comma-separated list of DNS servers to be used instead of the system default (e.g.:
192.168.1.100,192.168.1.101:8080). Available as of cURL 7.24.0.
CURLOPT_DNS_SHUFFLE_ADDRESSES (
int)
ENTITY 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. Available as of PHP 7.3.0 and cURL 7.60.0.
CURLOPT_DNS_USE_GLOBAL_CACHE (
int)
ENTITY 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.). Available as of cURL 7.9.3 and deprecated as of cURL 7.11.1. As of PHP 8.4, this option no longer has any effect.
CURLOPT_DOH_SSL_VERIFYHOST (
int)
Set to
2 to verify the DNS-over-HTTPS server's SSL certificate name fields against the host name. Available as of PHP 8.2.0 and cURL 7.76.0.
CURLOPT_DOH_SSL_VERIFYPEER (
int)
Set to
1 to enable and
0 to disable verification of the authenticity of the DNS-over-HTTPS server's SSL certificate. Available as of PHP 8.2.0 and cURL 7.76.0.
CURLOPT_DOH_SSL_VERIFYSTATUS (
int)
Set to
1 to enable and
0 to disable the verification of the status of the DNS-over-HTTPS server certificate using the "Certificate Status Request" TLS extension (OCSP stapling). Available as of PHP 8.2.0 and cURL 7.76.0.
CURLOPT_DOH_URL (
int)
Provides the DNS-over-HTTPS URL. This option accepts a
string or ENTITY. Available as of PHP 8.1.0 and cURL 7.62.0.
CURLOPT_EGDSOCKET (
int)
Like
CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket. Available as of cURL 7.7.0 and deprecated as of cURL 7.84.0.
CURLOPT_ENCODING (
int)
The contents of the
Accept-Encoding: header as a
string. This enables decoding of the response. Supported encodings are:
identity,
deflate,
gzip. If an empty
string is set, a header containing all supported encoding types is sent. Available as of cURL 7.10 and deprecated as of cURL 7.21.6.
CURLOPT_EXPECT_100_TIMEOUT_MS (
int)
The timeout for
Expect: 100-continue responses in milliseconds. Defaults to
1000 milliseconds. This option accepts any value that can be cast to a valid
int. Available as of PHP 7.0.7 and cURL 7.36.0.
CURLOPT_FAILONERROR (
int)
ENTITY 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. Available as of cURL 7.1.0.
CURLOPT_FILE (
int)
Accepts a file handle
resource to the file that the transfer should be written to. The default is
STDOUT (the browser window). Available as of cURL 7.1.0 and deprecated as of cURL 7.9.7.
CURLOPT_FILETIME (
int)
Set to ENTITY to attempt to retrieve the modification date of the remote document. This value can be retrieved using the
CURLINFO_FILETIME option with
curl_getinfo. Available as of cURL 7.5.0.
CURLOPT_FNMATCH_FUNCTION (
int)
Pass a
callable that will be used for wildcard matching. The signature of the callback should be:
int
resource``curlHandle
string``pattern
string``string
curlHandle
The cURL handle.
pattern
The wildcard pattern.
string
The
string to run the wildcard pattern matching on.
The callback should return
CURL_FNMATCHFUNC_MATCH if pattern matches the
string,
CURL_FNMATCHFUNC_NOMATCH if not or
CURL_FNMATCHFUNC_FAIL if an error occurred. Available as of cURL 7.21.0.
CURLOPT_FOLLOWLOCATION (
int)
Set to ENTITY to follow any
Location: header that the server sends as part of the HTTP header. See also
CURLOPT_MAXREDIRS. This constant is not available when open_basedir is enabled. Available as of cURL 7.1.0.
As of PHP 8.5.0, the value is treated as an integer.
CURLFOLLOW_ALL is equivalent to setting this option to ENTITY.
CURLFOLLOW_OBEYCODE follows redirects more strictly regarding allowed redirect codes.
CURLFOLLOW_FIRSTONLY follows only the first redirect.
CURLOPT_FORBID_REUSE (
int)
Set to ENTITY to force the connection to explicitly close when it has finished processing, and not be pooled for reuse. Available as of cURL 7.7.0.
CURLOPT_FRESH_CONNECT (
int)
Set to ENTITY to force the use of a new connection instead of a cached one. Available as of cURL 7.7.0.
CURLOPT_FTPAPPEND (
int)
Set to ENTITY to append to the remote file instead of overwriting it. Available as of cURL 7.1.0 and deprecated as of cURL 7.16.4.
CURLOPT_FTPASCII (
int)
An alias of
CURLOPT_TRANSFERTEXT. Use that instead. Available as of cURL 7.1, deprecated as of cURL 7.11.1 and last available in cURL 7.15.5. Removed as of PHP 7.3.0.
CURLOPT_FTPLISTONLY (
int)
Set to ENTITY to only list the names of an FTP directory. Available as of cURL 7.1.0 and deprecated as of cURL 7.16.4.
CURLOPT_FTPPORT (
int)
A
string 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 system's default IP address. This option accepts a
string or ENTITY. Available as of cURL 7.1.0.
CURLOPT_FTPSSLAUTH (
int)
Set the FTP over SSL authentication method (if activated) to any of the
CURLFTPAUTH_* constants. Defaults to
CURLFTPAUTH_DEFAULT. Available as of cURL 7.12.2.
CURLOPT_FTP_ACCOUNT (
int)
Pass a
string that will be sent as account information over FTP (using the
ACCT command) after username and password has been provided to the server. Set to ENTITY to disable sending the account information. Defaults to ENTITY. Available as of cURL 7.13.0.
CURLOPT_FTP_ALTERNATIVE_TO_USER (
int)
Pass a
string that will be used to try to authenticate over FTP if the
USER/PASS negotiation fails. Available as of cURL 7.15.5.
CURLOPT_FTP_CREATE_MISSING_DIRS (
int)
Set to ENTITY to create missing directories when an FTP operation encounters a path that currently doesn't exist. Available as of cURL 7.10.7.
CURLOPT_FTP_FILEMETHOD (
int)
Tell cURL which method to use to reach a file on a FTP(S) server. Possible values are any of the
CURLFTPMETHOD_* constants. Defaults to
CURLFTPMETHOD_MULTICWD. Available as of cURL 7.15.1.
CURLOPT_FTP_RESPONSE_TIMEOUT (
int)
A timeout in seconds cURL will wait for a response from an FTP server. This option overrides
CURLOPT_TIMEOUT. This option accepts any value that can be cast to a valid
int. This option name is replaced with
CURLOPT_SERVER_RESPONSE_TIMEOUT, available as of PHP 8.4.0. Available as of cURL 7.10.8 and deprecated as of cURL 7.85.0.
CURLOPT_FTP_SKIP_PASV_IP (
int)
If this option is set to
1 cURL will not use the IP address the server suggests in its 227-response to cURL's
PASV command but will use the IP address it used for the connection. The port number received from the 227-response will not be ignored by cURL. Defaults to
1 as of cURL 7.74.0 and
0 prior to that. Available as of cURL 7.15.0.
CURLOPT_FTP_SSL (
int)
Available as of cURL 7.11.0 and deprecated as of cURL 7.16.4.
CURLOPT_FTP_SSL_CCC (
int)
This option makes cURL use CCC (Clear Command Channel) which shuts down the SSL/TLS layer after authenticating making the rest of the control channel communication unencrypted. Use one of the
CURLFTPSSL_CCC_* constants. Defaults to
CURLFTPSSL_CCC_NONE. Available as of cURL 7.16.1.
CURLOPT_FTP_USE_EPRT (
int)
Set to ENTITY to use
EPRT (and
LPRT) when doing active FTP downloads. Set to ENTITY to disable
EPRT and
LPRT and use
PORT only. Available as of cURL 7.10.5.
CURLOPT_FTP_USE_EPSV (
int)
Set to ENTITY to first try an
EPSV command for FTP transfers before reverting back to
PASV. Set to ENTITY to disable
EPSV. Available as of cURL 7.9.2.
CURLOPT_FTP_USE_PRET (
int)
Set to
1 to send a
PRET command before
PASV (and
EPSV). Has no effect when using the active FTP transfers mode. Defaults to
0. Available as of cURL 7.20.0.
CURLOPT_GSSAPI_DELEGATION (
int)
Set to
CURLGSSAPI_DELEGATION_FLAG to allow unconditional GSSAPI credential delegation. Set to
CURLGSSAPI_DELEGATION_POLICY_FLAG to delegate only if the
OK-AS-DELEGATE flag is set in the service ticket. Defaults to
CURLGSSAPI_DELEGATION_NONE. Available as of cURL 7.22.0.
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS (
int)
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. This option accepts any value that can be cast to a valid
int. Available as of PHP 7.3.0 and cURL 7.59.0
CURLOPT_HAPROXYPROTOCOL (
int)
ENTITY to send an HAProxy
PROXY protocol v1 header at the start of the connection. The default action is not to send this header. Available as of PHP 7.3.0 and cURL 7.60.0.
CURLOPT_HEADER (
int)
Set to ENTITY to include the headers in the output sent to the callback defined by
CURLOPT_WRITEFUNCTION. Available as of cURL 7.1.0.
CURLOPT_HEADERFUNCTION (
int)
A
callable with the following signature:
int
resource``curlHandle
string``headerData
curlHandle
The cURL handle.
headerData
The header data which must be written by the callback.
The callback should return the number of bytes written. Available as of cURL 7.7.2.
CURLOPT_HEADEROPT (
int)
Send HTTP headers to both proxy and host or separately. Possible values are any of the
CURLHEADER_* constants. Defaults to
CURLHEADER_SEPARATE as of cURL 7.42.1, and
CURLHEADER_UNIFIED prior to that. Available as of PHP 7.0.7 and cURL 7.37.0.
CURLOPT_HSTS (
int)
string with HSTS (HTTP Strict Transport Security) cache file name or ENTITY to allow HSTS without reading from or writing to any file and clear the list of files to read HSTS data from. Available as of PHP 8.2.0 and cURL 7.74.0.
CURLOPT_HSTS_CTRL (
int)
Accepts a bitmask of HSTS (HTTP Strict Transport Security) features defined by the
CURLHSTS_* constants. Available as of PHP 8.2.0 and cURL 7.74.0.
CURLOPT_HTTP09_ALLOWED (
int)
Whether to allow HTTP/0.9 responses. Defaults to ENTITY as of cURL 7.66.0; formerly it defaulted to ENTITY. Available as of PHP 7.3.15 and 7.4.3, respectively, and cURL 7.64.0.
CURLOPT_HTTP200ALIASES (
int)
An
array of HTTP
200 responses that will be treated as valid responses and not as errors. Available as of cURL 7.10.3.
CURLOPT_HTTPAUTH (
int)
A bitmask of HTTP authentication method(s) to use. The options are:
CURLAUTH_BASIC,
CURLAUTH_DIGEST,
CURLAUTH_GSSNEGOTIATE,
CURLAUTH_NTLM,
CURLAUTH_AWS_SIGV4,
CURLAUTH_ANY,
CURLAUTH_ANYSAFE. If more than one method is used, cURL will poll the server to see what methods it supports and pick the best one.
CURLAUTH_ANY sets all bits. cURL will automatically select the one it finds most secure.
CURLAUTH_ANYSAFE sets all bits except
CURLAUTH_BASIC. cURL will automatically select the one it finds most secure. Available as of cURL 7.10.6.
CURLOPT_HTTPGET (
int)
Set to ENTITY to reset the HTTP request method to
GET. Since
GET is the default, this is only necessary if the request method has been changed. Available as of cURL 7.8.1.
CURLOPT_HTTPHEADER (
int)
An
array of HTTP header fields to set, in the format
array('Content-type: text/plain', 'Content-length: 100') Available as of cURL 7.1.0.
CURLOPT_HTTPPROXYTUNNEL (
int)
ENTITY to tunnel through a given HTTP proxy. Available as of cURL 7.3.0.
CURLOPT_HTTP_CONTENT_DECODING (
int)
ENTITY to get the raw HTTP response body. Available as of cURL 7.16.2.
CURLOPT_HTTP_TRANSFER_DECODING (
int)
If set to
0, transfer decoding is disabled. If set to
1, transfer decoding is enabled. cURL does chunked transfer decoding by default unless this option is set to
0. Defaults to
1. Available as of cURL 7.16.2.
CURLOPT_HTTP_VERSION (
int)
Set to one of the
CURL_HTTP_VERSION_* constants for cURL to use the specified HTTP version. Available as of cURL 7.9.1.
CURLOPT_IGNORE_CONTENT_LENGTH (
int)
If set to
1, ignore the
Content-Length header in the HTTP response and ignore asking for or relying on it for FTP transfers. Defaults to
0. Available as of cURL 7.14.1.
CURLOPT_INFILE (
int)
Accepts a file handle
resource to the file that the transfer should be read from when uploading. Available as of cURL 7.1.0 and deprecated as of cURL 7.9.7. Use
CURLOPT_READDATA instead.
CURLOPT_INFILESIZE (
int)
The expected size, in bytes, of the file when uploading a file to a remote site. Note that using this option will not stop cURL from sending more data, as exactly what is sent depends on
CURLOPT_READFUNCTION. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.1.0.
CURLOPT_INFILESIZE_LARGE (
int)
The expected size, in bytes, of the file when uploading a file to a remote site. This is the 64-bit variant of
CURLOPT_INFILESIZE, allowing sizes larger than 2 GB to be specified. Available as of PHP 8.5.0.
CURLOPT_INTERFACE (
int)
Set to a
string with the name of the outgoing network interface to use. This can be an interface name, an IP address or a host name. Available as of cURL 7.1.0.
CURLOPT_IPRESOLVE (
int)
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. Set to one of the
CURL_IPRESOLVE_* constants. Defaults to
CURL_IPRESOLVE_WHATEVER. Available as of cURL 7.10.8.
CURLOPT_ISSUERCERT (
int)
If set to a
string naming a file holding a CA certificate in PEM format, an additional check against the peer certificate is performed to verify the issuer is indeed the one associated with the certificate provided by the option. For the result of the check to be considered a failure, this option should be used in combination with the
CURLOPT_SSL_VERIFYPEER option. Available as of cURL 7.19.0.
CURLOPT_ISSUERCERT_BLOB (
int)
Pass a
string with binary data of a CA SSL certificate in PEM format. If set, an additional check against the peer certificate is performed to verify the issuer is the one associated with the certificate provided by the option. Available as of PHP 8.1.0 and cURL 7.71.0.
CURLOPT_KEEP_SENDING_ON_ERROR (
int)
Set to ENTITY 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 and cURL 7.51.0.
CURLOPT_KEYPASSWD (
int)
Set to a
string with the password required to use the
CURLOPT_SSLKEY or
CURLOPT_SSH_PRIVATE_KEYFILE private key. Setting this option to ENTITY disables using a password for these options. Available as of cURL 7.17.0.
CURLOPT_KRB4LEVEL (
int)
The KRB4 (Kerberos 4) security level. Any of the following
string 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 ENTITY will disable KRB4 security. Currently KRB4 security only works with FTP transactions. Available as of cURL 7.3.0 and deprecated as of cURL 7.17.0.
CURLOPT_KRBLEVEL (
int)
Set the kerberos security level for FTP and also enables kerberos awareness. This should be set to one of the following
strings:
clear,
safe,
confidential,
private. If the
string is set but does not match one of these,
private is used. Setting this option to ENTITY will disable kerberos support for FTP. Defaults to ENTITY. Available as of cURL 7.16.4 and deprecated as of cURL 8.17.0.
CURLOPT_LOCALPORT (
int)
Sets the local port number of the socket used for the connection. This option accepts any value that can be cast to a valid
int. Defaults to
0. Available as of cURL 7.15.2.
CURLOPT_LOCALPORTRANGE (
int)
The number of attempts cURL makes to find a working local port number, starting with the one set with
CURLOPT_LOCALPORT. This option accepts any value that can be cast to a valid
int. Defaults to
1. Available as of cURL 7.15.2.
CURLOPT_LOGIN_OPTIONS (
int)
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. Available as of PHP 7.0.7 and cURL 7.34.0.
CURLOPT_LOW_SPEED_LIMIT (
int)
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. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.1.0.
CURLOPT_LOW_SPEED_TIME (
int)
The number of seconds the transfer speed should be below
CURLOPT_LOW_SPEED_LIMIT before PHP considers the transfer too slow and aborts. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.1.0.
CURLOPT_MAIL_AUTH (
int)
Set a
string with the authentication address (identity) of a submitted message that is being relayed to another server. The address should not be specified within a pair of angled brackets (
ENTITYENTITY). If an empty
string is used then a pair of brackets are sent by cURL as required by RFC 2554. Available as of cURL 7.25.0.
CURLOPT_MAIL_FROM (
int)
Set a
string with the sender's email address when sending SMTP mail. The email address should be specified with angled brackets (
ENTITYENTITY) around it, which if not specified are added automatically. If this parameter is not specified then an empty address is sent to the SMTP server which might cause the email to be rejected. Available as of cURL 7.20.0.
CURLOPT_MAIL_RCPT (
int)
Set to an
array of
strings with the recipients to pass to the server in an SMTP mail request. Each recipient should be specified within a pair of angled brackets (
ENTITYENTITY). If an angled bracket is not used as the first character, cURL assumes a single email address has been provided and encloses that address within brackets. Available as of cURL 7.20.0.
CURLOPT_MAIL_RCPT_ALLLOWFAILS (
int)
Set to
1 to allow
RCPT TO command to fail for some recipients which makes cURL ignore errors for individual recipients and proceed with the remaining accepted recipients. If all recipients trigger failures and this flag is specified, cURL aborts the SMTP conversation and returns the error received from to the last
RCPT TO command. Replaced by
CURLOPT_MAIL_RCPT_ALLOWFAILS as of cURL 8.2.0. Available as of PHP 8.2.0 and cURL 7.69.0. Deprecated as of cURL 8.2.0.
CURLOPT_MAXAGE_CONN (
int)
The maximum idle time allowed for an existing connection to be considered for reuse. Default maximum age is set to
118 seconds. This option accepts any value that can be cast to a valid
int. Available as of PHP 8.2.0 and cURL 7.65.0.
CURLOPT_MAXCONNECTS (
int)
The maximum amount of persistent connections that are allowed. When the limit is reached, the oldest one in the cache is closed to prevent increasing the number of open connections. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.7.0.
CURLOPT_MAXFILESIZE (
int)
Sets the maximum accepted size (in bytes) of a file to download. If the file requested is found larger than this value, the transfer is aborted and
CURLE_FILESIZE_EXCEEDED is returned. Passing
0 disables this option, and passing a negative size returns a
CURLE_BAD_FUNCTION_ARGUMENT. If the file size is not known prior to the start of download, this option has no effect. For setting a size limit above
2GB,
CURLOPT_MAXFILESIZE_LARGE should be used. As of cURL 8.4.0, this option also stops ongoing transfers if they reach this threshold. This option accepts any value that can be cast to a valid
int. Defaults to
0. Available as of cURL 7.10.8.
CURLOPT_MAXFILESIZE_LARGE (
int)
The maximum file size in bytes allowed to download. If the file requested is found larger than this value, the transfer will not start and
CURLE_FILESIZE_EXCEEDED will be returned. The file size is not always known prior to download, and for such files this option has no effect even if the file transfer ends up being larger than this given limit. This option accepts any value that can be cast to a valid
int. Available as of PHP 8.2.0 and cURL 7.11.0.
CURLOPT_MAXLIFETIME_CONN (
int)
The maximum time in seconds, since the creation of the connection, that is allowed for an existing connection to have for it to be considered for reuse. If a connection is found in the cache that is older than this value, it will instead be closed once any in-progress transfers are complete. Default is
0 seconds, meaning the option is disabled and all connections are eligible for reuse. This option accepts any value that can be cast to a valid
int. Available as of PHP 8.2.0 and cURL 7.80.0.
CURLOPT_MAXREDIRS (
int)
The maximum amount of HTTP redirections to follow. Use this option alongside
CURLOPT_FOLLOWLOCATION. Default value of
20 is set to prevent infinite redirects. Setting to
-1 allows infinite redirects, and
0 refuses all redirects. Available as of cURL 7.5.0.
CURLOPT_MAX_RECV_SPEED_LARGE (
int)
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. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.15.5.
CURLOPT_MAX_SEND_SPEED_LARGE (
int)
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. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.15.5.
CURLOPT_MIME_OPTIONS (
int)
Set to a bitmask of
CURLMIMEOPT_* constants. Currently there is only one available option:
CURLMIMEOPT_FORMESCAPE. Available as of PHP 8.3.0 and cURL 7.81.0.
CURLOPT_MUTE (
int)
Set to ENTITY to be completely silent with regards to the cURL functions. Use
CURLOPT_RETURNTRANSFER instead. Available as of cURL 7.1.0, deprecated as of cURL 7.8.0 and last available in cURL 7.15.5. Removed as of PHP 7.3.0.
CURLOPT_NETRC (
int)
Set to ENTITY to scan the
~/.netrc file to find a username and password for the remote site that a connection is being established with. Available as of cURL 7.1.0.
CURLOPT_NETRC_FILE (
int)
Set a
string containing the full path name to a
.netrc file. If this option is omitted and
CURLOPT_NETRC is set, cURL checks for a
.netrc file in the current user's home directory. Available as of cURL 7.11.0.
CURLOPT_NEW_DIRECTORY_PERMS (
int)
Sets the value of the permissions (
int) that is set on newly created directories on the remote server. The default value is
0755. The only protocols that can use this are
sftp://,
scp:// and
file://. Available as of cURL 7.16.4.
CURLOPT_NEW_FILE_PERMS (
int)
Sets the value of the permissions (as an
int) that are set on newly created files on the remote server. The default value is
0644. The only protocols that can use this are
sftp://,
scp:// and
file://. Available as of cURL 7.16.4.
CURLOPT_NOBODY (
int)
Set to ENTITY to exclude the body from the output. For HTTP(S), cURL makes a HEAD request. For most other protocols, cURL is not asking for the body data at all. Changing this to ENTITY will result in body data being included in the output. Available as of cURL 7.1.0.
CURLOPT_NOPROGRESS (
int)
Set to ENTITY to disable the progress meter for cURL transfers.
[!NOTE]
PHP automatically sets this option to ENTITY, this should only be changed for debugging purposes.
Available as of cURL 7.1.0.
CURLOPT_NOPROXY (
int)
Set a
string consisting of a comma separated list of hostnames that do not require a proxy to get reached. Each name in this list is matched as either a domain which contains the hostname or the hostname itself. The only wildcard available in the
string is a single
* character which matches all hosts, effectively disabling the proxy. Setting this option to an empty
string enables the proxy for all hostnames. Since cURL 7.86.0, IP addresses set with this option can be provided using CIDR notation. Available as of cURL 7.19.4.
CURLOPT_NOSIGNAL (
int)
ENTITY 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. Available as of cURL 7.10.
CURLOPT_PASSWDFUNCTION (
int)
A
callable with the following signature:
string
resource``curlHandle
string``passwordPrompt
int``maximumPasswordLength
curlHandle
The cURL handle.
passwordPrompt
A password prompt.
maximumPasswordLength
The maximum length of the password.
The callback should return a
string containing the password. Available as of cURL 7.4.2, deprecated as of cURL 7.11.1 and last available in cURL 7.15.5. Removed as of PHP 7.3.0.
CURLOPT_PASSWORD (
int)
Set to a
string with the password to use in authentication. Available as of cURL 7.19.1.
CURLOPT_PATH_AS_IS (
int)
Set to ENTITY for cURL not alter URL paths before passing them on to the server. Defaults to ENTITY, which squashes sequences of
/../ or
/./ that may exist in the URL's path part which is supposed to be removed according to RFC 3986 section 5.2.4. Available as of PHP 7.0.7 and cURL 7.42.0.
CURLOPT_PINNEDPUBLICKEY (
int)
Set a
string with the pinned public key. The
string can be the file name of the pinned public key in a PEM or DER file format. The
string can also be any number of base64 encoded sha256 hashes preceded by
sha256// and separated by
;. Available as of PHP 7.0.7 and cURL 7.39.0.
CURLOPT_PIPEWAIT (
int)
Set to ENTITY to wait for an existing connection to confirm whether it can do multiplexing and use it if it can before creating and using a new connection. Available as of PHP 7.0.7 and cURL 7.43.0.
CURLOPT_PORT (
int)
An
int with an alternative port number to connect to instead of the one specified in the URL or the default port for the used protocol. Available as of cURL 7.1.0.
CURLOPT_POST (
int)
Set to ENTITY to do a HTTP
POST request. This request uses the
application/x-www-form-urlencoded header. Defaults to ENTITY. Available as of cURL 7.1.0.
CURLOPT_POSTFIELDS (
int)
The full data to post in a HTTP
POST operation. This parameter can either be passed as a urlencoded
string like '
para1=val1ENTITYpara2=val2ENTITY...' 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. Files can be sent using
CURLFile or
CURLStringFile, in which case
value must be an
array. Available as of cURL 7.1.0.
CURLOPT_POSTQUOTE (
int)
An
array of FTP command
strings to execute on the server after the FTP request has been performed. Available as of cURL 7.1.0.
CURLOPT_POSTREDIR (
int)
Set to a bitmask of
CURL_REDIR_POST_301,
CURL_REDIR_POST_302 and
CURL_REDIR_POST_303 if the HTTP
POST method should be maintained when
CURLOPT_FOLLOWLOCATION is set and a specific type of redirect occurs. Available as of cURL 7.19.1.
CURLOPT_PRE_PROXY (
int)
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 as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PREQUOTE (
int)
Set an
array of FTP command
strings to pass to the server after the transfer type is set. These commands are not performed when a directory listing is performed, only for file transfers. Available as of cURL 7.9.5.
CURLOPT_PRIVATE (
int)
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. Available as of cURL 7.10.3.
CURLOPT_PROGRESSFUNCTION (
int)
A
callable with the following signature:
int
resource``curlHandle
int``bytesToDownload
int``bytesDownloaded
int``bytesToUpload
int``bytesUploaded
curlHandle
The cURL handle.
bytesToDownload
The total number of bytes expected to be downloaded in this transfer.
bytesDownloaded
The number of bytes downloaded so far.
bytesToUpload
The total number of bytes expected to be uploaded in this transfer.
bytesUploaded
The number of bytes uploaded so far.
The callback should return an
int with a non-zero value to abort the transfer and set a
CURLE_ABORTED_BY_CALLBACK error.
[!NOTE]
The callback is only called when the
CURLOPT_NOPROGRESS option is set to ENTITY.
Available as of cURL 7.1.0 and deprecated as of cURL 7.32.0. Use
CURLOPT_XFERINFOFUNCTION instead.
CURLOPT_PROTOCOLS (
int)
Bitmask of
CURLPROTO_* values. If used, this bitmask limits what protocols cURL may use in the transfer. Defaults to
CURLPROTO_ALL, ie. cURL will accept all protocols it supports. See also
CURLOPT_REDIR_PROTOCOLS_STR. Available as of cURL 7.19.4 and deprecated as of cURL 7.85.0.
CURLOPT_PROTOCOLS_STR (
int)
Set to a
string with a comma separated list of case insensitive protocol names (URL schemes) to allow in the transfer. Set to
ALL to enable all protocols. By default, cURL accepts all protocols it was built with support for. Available protocols are:
DICT,
FILE,
FTP,
FTPS,
GOPHER,
GOPHERS,
HTTP,
HTTPS,
IMAP,
IMAPS,
LDAP,
LDAPS,
MQTT,
POP3,
POP3S,
RTMP,
RTMPE,
RTMPS,
RTMPT,
RTMPTE,
RTMPTS,
RTSP,
SCP,
SFTP,
SMB,
SMBS,
SMTP,
SMTPS,
TELNET,
TFTP,
WS,
WSS. Available as of PHP 8.3.0 and cURL 7.85.0.
CURLOPT_PROXY (
int)
A
string with the HTTP proxy to tunnel requests through. This should be the hostname, the dotted numerical IP address or a numerical IPv6 address written within [brackets]. Available as of cURL 7.1.0.
CURLOPT_PROXYAUTH (
int)
A bitmask of the HTTP authentication method(s) (
CURLAUTH_* constants) to use for the proxy connection. For proxy authentication, only
CURLAUTH_BASIC and
CURLAUTH_NTLM are currently supported. Defaults to
CURLAUTH_BASIC. Available as of cURL 7.10.7.
CURLOPT_PROXYHEADER (
int)
An
array of custom HTTP header
strings to pass to proxies. Available as of PHP 7.0.7 and cURL 7.37.0.
CURLOPT_PROXYPASSWORD (
int)
Set a
string with the password to be used for authentication with the proxy. Available as of cURL 7.19.1.
CURLOPT_PROXYPORT (
int)
An
int with the port number of the proxy to connect to. This port number can also be set in
CURLOPT_PROXY. Setting this to zero makes cURL use the default proxy port number or the port number specified in the proxy URL
string. Available as of cURL 7.1.0.
CURLOPT_PROXYTYPE (
int)
Sets the type of the proxy to one of the
CURLPROXY_* constants. Defaults to
CURLPROXY_HTTP. Available as of cURL 7.10.
CURLOPT_PROXYUSERNAME (
int)
Set a
string with the username to be used for authentication with the proxy. Available as of cURL 7.19.1.
CURLOPT_PROXYUSERPWD (
int)
A
string with a username and password formatted as
[username]:[password] to use for the connection to the proxy. Available as of cURL 7.1.0.
CURLOPT_PROXY_CAINFO (
int)
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 cURL's cacert bundle is assumed to be stored. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_CAINFO_BLOB (
int)
A
string with the name of a PEM 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 cURL's cacert bundle is assumed to be stored. Available as of PHP 8.2.0 and cURL 7.77.0.
CURLOPT_PROXY_CAPATH (
int)
A
string with the directory holding multiple CA certificates to verify the HTTPS proxy with. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_CRLFILE (
int)
Set to a
string with 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 as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_ISSUERCERT (
int)
Proxy issuer SSL certificate filename
string. Available as of PHP 8.1.0 and cURL 7.71.0.
CURLOPT_PROXY_ISSUERCERT_BLOB (
int)
A
string with the proxy issuer SSL certificate. Available as of PHP 8.1.0 and cURL 7.71.0.
CURLOPT_PROXY_KEYPASSWD (
int)
Set the
string be used as the password required to use the
CURLOPT_PROXY_SSLKEY private key. A passphrase is not needed to load a certificate but one is needed to load a private key. This option is for connecting to an HTTPS proxy, not an HTTPS server. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_PINNEDPUBLICKEY (
int)
Set the pinned public key for HTTPS proxy. The
string can be the file name of the pinned public key which is expected to be in a
PEM or
DER file format. The
string can also be any number of base64 encoded sha256 hashes preceded by
sha256// and separated by
;. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SERVICE_NAME (
int)
A
string with the proxy authentication service name. Available as of PHP 7.0.7, cURL 7.43.0 (for HTTP proxies) and cURL 7.49.0 (for SOCKS5 proxies).
CURLOPT_PROXY_SSLCERT (
int)
A
string with the file name of the 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 used for authentication as it is named in the security database. If a file from the current directory is to be used, it must be prefixed with
./ in order to avoid confusion with a nickname. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSLCERTTYPE (
int)
A
string with the format of the 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 as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSLCERT_BLOB (
int)
A
string with the SSL proxy client certificate. Available as of PHP 8.1.0 and cURL 7.71.0.
CURLOPT_PROXY_SSLKEY (
int)
A
string with the file name of the 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 if built with TLS enabled. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSLKEYTYPE (
int)
A
string with the format of the private key. Supported formats are:
PEM,
DER,
ENG. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSLKEY_BLOB (
int)
A
string with the private key for connecting to the HTTPS proxy. Available as of PHP 8.1.0 and cURL 7.71.0.
CURLOPT_PROXY_SSLVERSION (
int)
Set the preferred HTTPS proxy TLS version to one of the
CURL_SSLVERSION_* constants. Defaults to
CURL_SSLVERSION_DEFAULT.
[!WARNING]
It is better to not set this option and leave the default
CURL_SSLVERSION_DEFAULT which will attempt to figure out the remote SSL protocol version.
Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSL_CIPHER_LIST (
int)
A
string with a colon-separated list of ciphers to use for the connection to the HTTPS proxy. When used with OpenSSL commas and spaces are also acceptable as separators, and
!,
- and
+ can be used as operators. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSL_OPTIONS (
int)
Set proxy SSL behavior options, which is a bitmask of the
CURLSSLOPT_* constants. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSL_VERIFYHOST (
int)
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! Set to
1 in cURL 7.28.0 and earlier as a debug option. Set to
1 in cURL 7.28.1 to 7.65.3
CURLE_BAD_FUNCTION_ARGUMENT is returned. As of cURL 7.66.0
1 and
2 is treated as the same value. Defaults to
2. In production environments the value of this option should be kept at
2. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_SSL_VERIFYPEER (
int)
Set to ENTITY 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 ENTITY, the peer certificate verification succeeds regardless. ENTITY by default. Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_TLS13_CIPHERS (
int)
A
string with a colon-separated list of ciphers to use for the connection to the TLS 1.3 connection to a proxy. This option is currently used only when cURL is built to use OpenSSL 1.1.1 or later. When using a different SSL backend the TLS 1.3 cipher suites can be set with the
CURLOPT_PROXY_SSL_CIPHER_LIST option. Available as of PHP 7.3.0 and cURL 7.61.0.
CURLOPT_PROXY_TLSAUTH_PASSWORD (
int)
A
string with 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 as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_TYPE (
int)
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, the
CURLOPT_PROXY_TLSAUTH_USERNAME and
CURLOPT_PROXY_TLSAUTH_PASSWORD options must also be set.
Available as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_USERNAME (
int)
The username 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 as of PHP 7.3.0 and cURL 7.52.0.
CURLOPT_PROXY_TRANSFER_MODE (
int)
Set to
1 to set the transfer mode (binary or ASCII) for FTP transfers done via an HTTP proxy, by appending
type=a or
type=i to the URL. Without this setting or it being set to
0,
CURLOPT_TRANSFERTEXT has no effect when doing FTP via a proxy. Defaults to
0. Available as of cURL 7.18.0.
CURLOPT_PUT (
int)
ENTITY to HTTP PUT a file. The file to PUT must be set with
CURLOPT_READDATA and
CURLOPT_INFILESIZE. Available as of cURL 7.1.0 and deprecated as of cURL 7.12.1.
CURLOPT_QUICK_EXIT (
int)
Set to ENTITY for cURL to skip cleanup of resources when recovering from a timeout. This allows for a swift termination of the cURL process at the expense of a possible leak of associated resources. Available as of PHP 8.3.0 and cURL 7.87.0.
CURLOPT_QUOTE (
int)
An
array of FTP command
strings to execute on the server prior to the FTP request. Available as of cURL 7.1.0.
CURLOPT_RANDOM_FILE (
int)
A
string with a filename to be used to seed the random number generator for SSL. Available as of cURL 7.7.0 and deprecated as of cURL 7.84.0.
CURLOPT_RANGE (
int)
A
string with the 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. Set to ENTITY to disable requesting a byte range. Available as of cURL 7.1.0.
CURLOPT_READDATA (
int)
Sets a file pointer
resource that will be used by the file read function set with
CURLOPT_READFUNCTION. Available as of cURL 7.9.7.
CURLOPT_READFUNCTION (
int)
A
callable with the following signature:
string
resource``curlHandle
resource``streamResource
int``maxAmountOfDataToRead
curlHandle
The cURL handle.
streamResource
Stream
resource provided to cURL through the option
CURLOPT_READDATA.
maxAmountOfDataToRead
The maximum amount of data to be read.
The callback should 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. Available as of cURL 7.1.0.
CURLOPT_REDIR_PROTOCOLS (
int)
Bitmask of
CURLPROTO_* values which limit what protocols cURL may use in a transfer that it follows to in a redirect when
CURLOPT_FOLLOWLOCATION is enabled. This allows limiting specific transfers to only be allowed to use a subset of protocols in redirections. As of cURL 7.19.4, by default cURL will allow all protocols except for
FILE and
SCP. Prior to cURL 7.19.4, cURL would unconditionally follow to all supported protocols. See also
CURLOPT_PROTOCOLS for protocol constant values. Available as of cURL 7.19.4 and deprecated as of cURL 7.85.0.
CURLOPT_REDIR_PROTOCOLS_STR (
int)
Set to a
string with a comma separated list of case insensitive protocol names (URL schemes) to allow to follow to in a redirect when
CURLOPT_FOLLOWLOCATION is enabled. Set to
ALL to enable all protocols. As of cURL 7.65.2 it defaults to
FTP,
FTPS,
HTTP and
HTTPS. From cURL 7.40.0 to 7.65.1, this defaults to all protocols except
FILE,
SCP,
SMB and
SMBS. Prior to cURL 7.40.0, this defaults to all protocols except
FILE and
SCP. Available protocols are:
DICT,
FILE,
FTP,
FTPS,
GOPHER,
GOPHERS,
HTTP,
HTTPS,
IMAP,
IMAPS,
LDAP,
LDAPS,
MQTT,
POP3,
POP3S,
RTMP,
RTMPE,
RTMPS,
RTMPT,
RTMPTE,
RTMPTS,
RTSP,
SCP,
SFTP,
SMB,
SMBS,
SMTP,
SMTPS,
TELNET,
TFTP,
WS,
WSS. Available as of PHP 8.3.0 and cURL 7.85.0.
CURLOPT_REFERER (
int)
A
string with the contents of the
Referer: header to be used in a HTTP request. Available as of cURL 7.1.0.
CURLOPT_REQUEST_TARGET (
int)
A
string to use in the upcoming request instead of the path as extracted from the URL. Available as of PHP 7.3.0 and cURL 7.55.0.
CURLOPT_RESOLVE (
int)
Provide an
array of colon-separated
strings with custom addresses for specific host and port pairs in the following format:
array( "example.com:80:127.0.0.1", "example2.com:443:127.0.0.2", ) Available as of cURL 7.21.3.
CURLOPT_RESUME_FROM (
int)
The offset, in bytes, to resume a transfer from. This option accepts any value that can be cast to a valid
int. Available as of cURL 7.1.0.
CURLOPT_RETURNTRANSFER (
int)
ENTITY to return the transfer as a
string of the return value of
curl_exec instead of outputting it directly.
CURLOPT_RTSP_CLIENT_CSEQ (
int)
Set an
int with the CSEQ number to issue for the next RTSP request. Useful if the application is resuming a previously broken connection. The CSEQ increments from this new number henceforth. Defaults to
0. Available as of cURL 7.20.0.
CURLOPT_RTSP_REQUEST (
int)
Sets the kind of RTSP request to make. Must be one of the
CURL_RTSPREQ_* constants. Available as of cURL 7.20.0.
CURLOPT_RTSP_SERVER_CSEQ (
int)
Set an
int with the CSEQ number to expect for the next RTSP Server to Client request. This feature (listening for Server requests) is unimplemented. Defaults to
0. Available as of cURL 7.20.0.
CURLOPT_RTSP_SESSION_ID (
int)
Set a
string with the value of the current RTSP Session ID for the handle. Once this value is set to any non-ENTITY value, cURL returns
CURLE_RTSP_SESSION_ERROR if the ID received from the server does not match. If set to ENTITY, cURL automatically sets the ID the first time the server sets it in a response. Defaults to ENTITY Available as of cURL 7.20.0.
CURLOPT_RTSP_STREAM_URI (
int)
Sets a
string with the stream URI to operate on. If not set, cURL defaults to operating on generic server options by passing
* in the place of the RTSP Stream URI. When working with RTSP,
CURLOPT_RTSP_STREAM_URI indicates what URL to send to the server in the request header while the
CURLOPT_URL indicates where to make the connection to. Available as of cURL 7.20.0.
CURLOPT_RTSP_TRANSPORT (
int)
Set the
Transport: header for this RTSP session. Available as of cURL 7.20.0.
CURLOPT_SAFE_UPLOAD (
int)
Always ENTITY, what disables 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.
CURLOPT_SASL_AUTHZID (
int)
The authorization identity (authzid)
string for the transfer. Only applicable to the PLAIN SASL authentication mechanism where it is optional. When not specified, only the authentication identity (authcid) as specified by the username will be sent to the server, along with the password. The server will derive the authzid from the authcid when not provided, which it will then use internally. Available as of PHP 8.2.0 and cURL 7.66.0.
CURLOPT_SASL_IR (
int)
ENTITY to enable sending the initial response in the first packet. Available as of PHP 7.0.7 and cURL 7.31.0.
CURLOPT_SERVICE_NAME (
int)
A
string with the authentication service name. Available as of PHP 7.0.7 and cURL 7.43.0.
CURLOPT_SHARE (
int)
A result of
curl_share_init. Makes the cURL handle to use the data from the shared handle. Available as of cURL 7.10.
CURLOPT_SOCKS5_AUTH (
int)
The SOCKS5 authentication method(s) to use. The options are:
CURLAUTH_BASIC,
CURLAUTH_GSSAPI,
CURLAUTH_NONE. When more than one method is set, cURL will poll the server to see what methods it supports and pick the best one. Defaults to
CURLAUTH_BASIC|CURLAUTH_GSSAPI. Set the actual username and password with the
CURLOPT_PROXYUSERPWD option. Available as of PHP 7.3.0 and cURL 7.55.0.
CURLOPT_SOCKS5_GSSAPI_NEC (
int)
Set to
1 to enable and
0 to disable the unprotected exchange of the protection mode negotiation as part of the GSSAPI negotiation. Available as of cURL 7.19.4.
CURLOPT_SOCKS5_GSSAPI_SERVICE (
int)
Set a
string holding the name of the SOCKS5 service. Defaults to
rcmd. Available as of cURL 7.19.4 and deprecated as of cURL 7.49.0. Use
CURLOPT_PROXY_SERVICE_NAME instead.
CURLOPT_SSH_AUTH_TYPES (
int)
A bitmask consisting of one or more of the following constants:
CURLSSH_AUTH_PUBLICKEY,
CURLSSH_AUTH_PASSWORD,
CURLSSH_AUTH_HOST,
CURLSSH_AUTH_KEYBOARD,
CURLSSH_AUTH_AGENT,
CURLSSH_AUTH_ANY. Defaults to
CURLSSH_AUTH_ANY. Available as of cURL 7.16.1.
CURLOPT_SSH_COMPRESSION (
int)
ENTITY to enable, ENTITY to disable built-in SSH compression. Note that the server can disregard this request. Defaults to ENTITY. Available as of PHP 7.3.0 and cURL 7.56.0.
CURLOPT_SSH_HOSTKEYFUNCTION (
int)
A
callable that will be called when SSH host key verification is needed. The callback must have the following signature:
int
resource``curlHandle
int``keyType
string``key
int``keyLength
curlHandle
The cURL handle.
keyType
One of the
CURLKHTYPE_* key types.
key
The key to check.
keyLength
The length of the key in bytes.
This callback overrides
CURLOPT_SSH_KNOWNHOSTS. Available as of PHP 8.3.0 and cURL 7.84.0.
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 (
int)
A
string containing 32 hexadecimal digits which should contain the MD5 checksum of the remote host's public key, and cURL will reject the connection to the host unless the md5sums match. This option is only for SCP and SFTP transfers. Available as of cURL 7.17.1.
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 (
int)
A
string with the base64-encoded SHA256 hash of the remote host's public key. The transfer will fail if the given hash does not match the hash the remote host provides. Available as of PHP 8.2.0 and cURL 7.80.0.
CURLOPT_SSH_KNOWNHOSTS (
int)
Set to the filename of the
known_host file to use which should use the OpenSSH file format as supported by libssh2. Available as of cURL 7.19.6.
CURLOPT_SSH_PRIVATE_KEYFILE (
int)
The file name for a private key. If not used, cURL 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. Available as of cURL 7.16.1.
CURLOPT_SSH_PUBLIC_KEYFILE (
int)
The file name for a public key. If not used, cURL 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. Available as of cURL 7.16.1.
CURLOPT_SSLCERT (
int)
The name of a file containing a PEM formatted certificate. Available as of cURL 7.1.0.
CURLOPT_SSLCERTPASSWD (
int)
The password required to use the
CURLOPT_SSLCERT certificate. Available as of cURL 7.1.0 and deprecated as of cURL 7.17.0.
CURLOPT_SSLCERTTYPE (
int)
A
string with the format of the certificate. Supported formats are:
PEM,
DER,
ENG,
P12.
P12 (for PKCS#12-encoded files) is available as of OpenSSL 0.9.3. Defaults to
PEM. Available as of cURL 7.9.3.
CURLOPT_SSLCERT_BLOB (
int)
A
string with the SSL client certificate. Available as of PHP 8.1.0 and cURL 7.71.0.
CURLOPT_SSLENGINE (
int)
The
string identifier for the crypto engine of the private SSL key specified in
CURLOPT_SSLKEY. Available as of cURL 7.9.3.
CURLOPT_SSLENGINE_DEFAULT (
int)
The
string identifier for the crypto engine used for asymmetric crypto operations. Available as of cURL 7.9.3.
CURLOPT_SSLKEY (
int)
The name of a file containing a private SSL key. Available as of cURL 7.9.3.
CURLOPT_SSLKEYPASSWD (
int)
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.
Available as of cURL 7.9.3 and deprecated as of cURL 7.17.0.
CURLOPT_SSLKEYTYPE (
int)
The key type of the private SSL key specified in
CURLOPT_SSLKEY. Supported key types are:
PEM,
DER,
ENG. Defaults to
PEM. Available as of cURL 7.9.3.
CURLOPT_SSLKEY_BLOB (
int)
A
string private key for client cert. Available as of PHP 8.1.0 and cURL 7.71.0.
CURLOPT_SSLVERSION (
int)
One of the
CURL_SSLVERSION_* constants.
[!WARNING]
It is better to not set this option and leave the defaults. As setting this to
CURL_SSLVERSION_SSLv2 or
CURL_SSLVERSION_SSLv3 is very dangerous, given the known vulnerabilities in SSLv2 and SSLv3.
Defaults to
CURL_SSLVERSION_DEFAULT. Available as of cURL 7.1.0.
CURLOPT_SSL_CIPHER_LIST (
int)
A colon-separated
string of ciphers to use for the TLS 1.2 (1.1, 1.0) connection. Available as of cURL 7.9.
CURLOPT_SSL_EC_CURVES (
int)
A colon delimited list of elliptic curve algorithms. For example,
X25519:P-521 is a valid list of two elliptic curves. This option defines the client's key exchange algorithms in the SSL handshake, if the SSL backend cURL is built to use supports it. Available as of PHP 8.2.0 and cURL 7.73.0.
CURLOPT_SSL_ENABLE_ALPN (
int)
ENTITY to disable ALPN in the SSL handshake (if the SSL backend cURL is built to use supports it), which can be used to negotiate http2. Available as of PHP 7.0.7 and cURL 7.36.0.
CURLOPT_SSL_ENABLE_NPN (
int)
ENTITY to disable NPN in the SSL handshake (if the SSL backend cURL is built to use supports it), which can be used to negotiate http2. Available as of PHP 7.0.7 and cURL 7.36.0, and deprecated as of cURL 7.86.0.
CURLOPT_SSL_FALSESTART (
int)
ENTITY to enable and ENTITY to disable TLS false start which is a mode where a TLS client starts sending application data before verifying the server's
Finished message. Available as of PHP 7.0.7 and cURL 7.42.0. Deprecated since cURL 8.15.0.
CURLOPT_SSL_OPTIONS (
int)
Set SSL behavior options, which is a bitmask of the
CURLSSLOPT_* constants. Defaults to none of the bits being set. Available as of PHP 7.0.7. and cURL 7.25.0.
CURLOPT_SSL_SESSIONID_CACHE (
int)
Set to
0 to disable and
1 to enable SSL session-ID caching. By default all transfers are done using the cache enabled. Available as of cURL 7.16.0.
CURLOPT_SSL_VERIFYHOST (
int)
2 to verify that a Common Name field or a Subject Alternate Name field in the SSL peer certificate matches the provided hostname.
0 to not check the names.
1 should not be used. 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. Available as of cURL 7.8.1.
CURLOPT_SSL_VERIFYPEER (
int)
ENTITY 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. Defaults to ENTITY as of cURL 7.10. Default bundle of CA certificates installed as of cURL 7.10. Available as of cURL 7.4.2.
CURLOPT_SSL_VERIFYSTATUS (
int)
ENTITY to enable and ENTITY to disable verification of the certificate's status. Available as of PHP 7.0.7 and cURL 7.41.0.
CURLOPT_SSL_SIGNATURE_ALGORITHMS (
int)
A colon-separated list of signature algorithms to use for TLS authentication. Available as of PHP 8.5.0 and cURL 7.89.0.
CURLOPT_STDERR (
int)
Accepts a file handle
resource pointing to an alternative location to output errors to instead of
STDERR. Available as of cURL 7.1.0.
CURLOPT_STREAM_WEIGHT (
int)
Set the numerical stream weight (a number between
1 and
256). Available as of PHP 7.0.7 and cURL 7.46.0.
CURLOPT_SUPPRESS_CONNECT_HEADERS (
int)
ENTITY 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. Defaults to ENTITY. Available as of PHP 7.3.0 and cURL 7.54.0.
CURLOPT_TCP_FASTOPEN (
int)
ENTITY to enable and ENTITY to disable TCP Fast Open. Available as of PHP 7.0.7 and cURL 7.49.0.
CURLOPT_TCP_KEEPALIVE (
int)
If set to
1, TCP keepalive probes will be sent. The delay and frequency of these probes can be controlled by the
CURLOPT_TCP_KEEPIDLE and
CURLOPT_TCP_KEEPINTVL options, provided the operating system supports them. If set to
0 (default) keepalive probes are disabled. The maximum number of probes can be set with the
CURLOPT_TCP_KEEPCNT option. Available as of cURL 7.25.0.
CURLOPT_TCP_KEEPIDLE (
int)
Sets the delay, in seconds, that the operating system will wait while the connection is idle before sending keepalive probes, if
CURLOPT_TCP_KEEPALIVE is enabled. Not all operating systems support this option. The default is
60. Available as of cURL 7.25.0.
CURLOPT_TCP_KEEPINTVL (
int)
Sets the interval, in seconds, that the operating system will wait between sending keepalive probes, if
CURLOPT_TCP_KEEPALIVE is enabled. Not all operating systems support this option. The default is
60. Available as of cURL 7.25.0.
CURLOPT_TCP_KEEPCNT (
int)
Sets the maximum number of TCP keep-alive probes. The default is
9. Available as of PHP 8.4.0 and cURL 8.9.0.
CURLOPT_TCP_NODELAY (
int)
ENTITY to disable TCP's Nagle algorithm, which tries to minimize the number of small packets on the network. Defaults to ENTITY. Available as of cURL 7.11.2.
CURLOPT_TELNETOPTIONS (
int)
Set an
array of
strings to pass to the telnet negotiations. The variables should be in the format
ENTITYoption=valueENTITY. cURL supports the options
TTYPE,
XDISPLOC and
NEW_ENV. Available as of cURL 7.7.0.
CURLOPT_TFTP_BLKSIZE (
int)
Set the blocksize to use for TFTP data transmission. Valid range is
8-
65464 bytes. The default of
512 bytes is used if this option is not specified. The specified block size is only used if supported by the remote server. If the server does not return an option acknowledgment or returns an option acknowledgment with no block size, the default of
512 bytes is used. Available as of cURL 7.19.4.
CURLOPT_TFTP_NO_OPTIONS (
int)
ENTITY to not send TFTP options requests. Defaults to ENTITY. Available as of PHP 7.0.7 and cURL 7.48.0.
CURLOPT_TIMECONDITION (
int)
Set 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 ENTITY. Use
CURL_TIMECOND_IFUNMODSINCE for the reverse effect. Use
CURL_TIMECOND_NONE to ignore
CURLOPT_TIMEVALUE and always return the page.
CURL_TIMECOND_NONE is the default. Prior to cURL 7.46.0 the default was
CURL_TIMECOND_IFMODSINCE. Available as of cURL 7.1.0.
CURLOPT_TIMEOUT (
int)
The maximum number of seconds to allow cURL functions to execute. Defaults to
0, meaning that functions never time out during transfer. Available as of cURL 7.1.0.
CURLOPT_TIMEOUT_MS (
int)
The maximum number of milliseconds to allow cURL functions to execute. If cURL 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. Defaults to
0, meaning that functions never time out during transfer. Available as of cURL 7.16.2.
CURLOPT_TIMEVALUE (
int)
The time in seconds since January 1st, 1970. The time will be used by
CURLOPT_TIMECONDITION. Defaults to
0. Available as of cURL 7.1.0.
CURLOPT_TIMEVALUE_LARGE (
int)
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. Available as of PHP 7.3.0 and cURL 7.59.0.
CURLOPT_TLS13_CIPHERS (
int)
A
string with a colon-separated list of ciphers to use for the connection to the TLS 1.3 connection. This option is currently used only when cURL is built to use OpenSSL 1.1.1 or later. When using a different SSL backend the TLS 1.3 cipher suites can be set with the
CURLOPT_SSL_CIPHER_LIST option. Available as of PHP 7.3.0 and cURL 7.61.0.
CURLOPT_TLSAUTH_PASSWORD (
int)
Set a password to use for the TLS authentication method specified with the
CURLOPT_TLSAUTH_TYPE option. Requires that the
CURLOPT_TLSAUTH_USERNAME option also be set. This feature relies on TLS SRP which does not work with TLS 1.3. Available as of cURL 7.21.4.
CURLOPT_TLSAUTH_TYPE (
int)
Set a
string with the method of the TLS authentication. Supported method is
SRP (TLS Secure Remote Password authentication). Available as of cURL 7.21.4.
CURLOPT_TLSAUTH_USERNAME (
int)
Set a
string with the username to use for the TLS authentication method specified with the
CURLOPT_TLSAUTH_TYPE option. Requires that the
CURLOPT_TLSAUTH_PASSWORD option also be set. This feature relies on TLS SRP which does not work with TLS 1.3. Available as of cURL 7.21.4.
CURLOPT_TRANSFER_ENCODING (
int)
Set to
1 to enable and
0 to disable requesting compressed
Transfer Encoding in the outgoing HTTP request. If the server responds with a compressed
Transfer Encoding, cURL will automatically uncompress it on reception. Defaults to
0. Available as of cURL 7.21.6.
CURLOPT_TRANSFERTEXT (
int)
ENTITY 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. Defaults to ENTITY. Available as of cURL 7.1.1.
CURLOPT_UNIX_SOCKET_PATH (
int)
Enables the use of Unix domain sockets as connection endpoint and sets the path to the given
string. Set to ENTITY to disable. Defaults to ENTITY. Available as of PHP 7.0.7 and cURL 7.40.0.
CURLOPT_UNRESTRICTED_AUTH (
int)
ENTITY to keep sending the username and password when following locations (using
CURLOPT_FOLLOWLOCATION), even when the hostname has changed. Defaults to ENTITY. Available as of cURL 7.10.4.
CURLOPT_UPKEEP_INTERVAL_MS (
int)
Some protocols have "connection upkeep" mechanisms. These mechanisms usually send some traffic on existing connections in order to keep them alive. This option defines the connection upkeep interval. Currently, the only protocol with a connection upkeep mechanism is HTTP/2. When the connection upkeep interval is exceeded, an HTTP/2 PING frame is sent on the connection. Defaults to
CURL_UPKEEP_INTERVAL_DEFAULT which is currently
60 seconds. Available as of PHP 8.2.0 and cURL 7.62.0.
CURLOPT_UPLOAD (
int)
ENTITY to prepare for and perform an upload. Defaults to ENTITY. Available as of cURL 7.1.0.
CURLOPT_UPLOAD_BUFFERSIZE (
int)
Preferred buffer size in bytes for the cURL upload buffer. The upload buffer size by default is 64 kilobytes. The maximum buffer size allowed to be set is 2 megabytes. The minimum buffer size allowed to be set is 16 kilobytes. Available as of PHP 8.2.0 and cURL 7.62.0.
CURLOPT_URL (
int)
The URL to fetch. This can also be set when initializing a session with
curl_init. Available as of cURL 7.1.0.
CURLOPT_USE_SSL (
int)
Sets the desired level of SSL/TLS for the transfer when using FTP, SMTP, POP3, IMAP, etc. These are all protocols that start out plain text and get "upgraded" to SSL using the STARTTLS command. Set to one of the
CURLUSESSL_* constants. Available as of cURL 7.17.0.
CURLOPT_USERAGENT (
int)
The contents of the
User-Agent: header to be used in a HTTP request. Available as of cURL 7.1.0.
CURLOPT_USERNAME (
int)
The user name to use in authentication. Available as of cURL 7.19.1.
CURLOPT_USERPWD (
int)
A username and password formatted as
[username]:[password] to use for the connection. Available as cURL 7.1.0.
CURLOPT_VERBOSE (
int)
ENTITY to output verbose information. Writes output to
STDERR, or the file specified using
CURLOPT_STDERR. Defaults to ENTITY. Available as of cURL 7.1.0.
CURLOPT_WILDCARDMATCH (
int)
Set to
1 to transfer multiple files according to a filename pattern. The pattern can be specified as part of the
CURLOPT_URL option, using an fnmatch-like pattern (Shell Pattern Matching) in the last part of URL (filename). Available as of cURL 7.21.0.
CURLOPT_WRITEFUNCTION (
int)
A
callable with the following signature:
int
resource``curlHandle
string``data
curlHandle
The cURL handle.
data
The data to be written.
The data must be saved by the callback and the callback must return the exact number of bytes written or the transfer will be aborted with an error. Available as of cURL 7.1.0.
CURLOPT_WRITEHEADER (
int)
Accepts a file handle
resource to the file that the header part of the transfer is written to. Available as of cURL 7.1.0.
CURLOPT_WS_OPTIONS (
int)
Accepts a bitmask setting WebSocket behavior options. The only available option is
CURLWS_RAW_MODE. Defaults to
0. Available as of PHP 8.3.0 and cURL 7.86.0.
CURLOPT_XFERINFOFUNCTION (
int)
A
callable with the following signature:
int
resource``curlHandle
int``bytesToDownload
int``bytesDownloaded
int``bytesToUpload
int``bytesUploaded
curlHandle
The cURL handle.
bytesToDownload
The total number of bytes expected to be downloaded in this transfer.
bytesDownloaded
The number of bytes downloaded so far.
bytesToUpload
The total number of bytes expected to be uploaded in this transfer.
bytesUploaded
The number of bytes uploaded so far.
Return
1 to abort the transfer and set a
CURLE_ABORTED_BY_CALLBACK error. Available as of PHP 8.2.0 and cURL 7.32.0.
CURLOPT_SERVER_RESPONSE_TIMEOUT (
int)
A timeout in seconds cURL will wait for a response from an FTP, SFTP, IMAP, SCP, SMTP, or a POP3 server. This option replaces the existing
CURLOPT_FTP_RESPONSE_TIMEOUT option which is deprecated in cURL 7.85.0. Available as of PHP 8.4.0.
CURLOPT_XOAUTH2_BEARER (
int)
Specifies the OAuth 2.0 access token. Set to ENTITY to disable. Defaults to ENTITY. Available as of PHP 7.0.7 and cURL 7.33.0.
CURLOPT_PREREQFUNCTION (
int)
A
callable with the following signature that gets called after the connection is established, but before the request payload (for example, the GET/POST/DELETE request of an HTTP connection) is sent, and can be used to abort or allow the connection depending on the source and destination IP address and port numbers:
int
CurlHandle``curlHandle
string``destination_ip
string``local_ip
int``destination_port
int``local_port
curlHandle
The cURL handle.
destination_ip
The primary IP of the remote server established with this connection. For FTP, this is the IP for the control connection. IPv6 addresses are represented without surrounding brackets.
local_ip
The originating IP for this connection. IPv6 addresses are represented without surrounding brackets.
destination_port
The primary port number on the remote server established with this connection. For FTP, this is the port for the control connection. This can be a TCP or a UDP port number depending on the protocol.
local_port
The originating port number for this connection. This can be a TCP or a UDP port number depending on the protocol.
Return
CURL_PREREQFUNC_OK to allow the request, or
CURL_PREREQFUNC_ABORT to abort the transfer. Available as of PHP 8.4.0 and cURL 7.80.0.
CURLOPT_DEBUGFUNCTION (
int)
Available as of PHP 8.4.0. This option requires
CURLOPT_VERBOSE option enabled. A
callable to replace the standard cURL verbose output. This callback gets called during various stages of the request with verbose debug information. The callback should match the following signature:
void
CurlHandle``curlHandle
int``type
string``data
curlHandle
The cURL handle.
type
One of the following constants indicating the type of the
data value:
CURLINFO_TEXT (
int)
Informational text.
CURLINFO_HEADER_IN (
int)
Header (or header-like) data received from the peer.
CURLINFO_HEADER_OUT (
int)
Header (or header-like) data sent to the peer.
CURLINFO_DATA_IN (
int)
Unprocessed protocol data received from the peer. Even if the data is encoded or compressed, it is not provided decoded nor decompressed to this callback.
CURLINFO_DATA_OUT (
int)
Protocol data sent to the peer.
CURLINFO_SSL_DATA_IN (
int)
SSL/TLS (binary) data received from the peer.
CURLINFO_SSL_DATA_OUT (
int)
SSL/TLS (binary) data sent to the peer.
data
Verbose debug data of the type indicate by the
type parameter.
constants_curl_share_setopt
CURL_LOCK_DATA_CONNECT (
int)
Shares/unshares the connection cache. Available as of PHP 7.3.0 and cURL 7.10.3.
CURL_LOCK_DATA_COOKIE (
int)
Shares/unshares cookie data. Available as of cURL 7.10.3.
CURL_LOCK_DATA_DNS (
int)
Shares/unshares DNS cache. Note that when you use cURL multi handles, all handles added to the same multi handle will share DNS cache by default. Available as of cURL 7.10.3.
CURL_LOCK_DATA_PSL (
int)
Shares/unshares the Public Suffix List. Available as of PHP 7.3.0 and cURL 7.61.0.
CURL_LOCK_DATA_SSL_SESSION (
int)
Shares/unshares 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. Available as of cURL 7.10.3.
CURLSHOPT_NONE (
int)
Available as of cURL 7.10.3.
CURLSHOPT_SHARE (
int)
Specifies a type of data that should be shared. Available as of cURL 7.10.3.
CURLSHOPT_UNSHARE (
int)
Specifies a type of data that will be no longer shared. Available as of cURL 7.10.3.
constants_curlproto
CURLPROTO_ALL (
int)
Available as of cURL 7.19.4.
CURLPROTO_DICT (
int)
Available as of cURL 7.19.4.
CURLPROTO_FILE (
int)
Available as of cURL 7.19.4.
CURLPROTO_FTP (
int)
Available as of cURL 7.19.4.
CURLPROTO_FTPS (
int)
Available as of cURL 7.19.4.
CURLPROTO_GOPHER (
int)
Available as of cURL 7.21.2.
CURLPROTO_HTTP (
int)
Available as of cURL 7.19.4.
CURLPROTO_HTTPS (
int)
Available as of cURL 7.19.4.
CURLPROTO_IMAP (
int)
Available as of cURL 7.20.0.
CURLPROTO_IMAPS (
int)
Available as of cURL 7.20.0.
CURLPROTO_LDAP (
int)
Available as of cURL 7.19.4.
CURLPROTO_LDAPS (
int)
Available as of cURL 7.19.4.
CURLPROTO_MQTT (
int)
Available as of PHP 8.2.0 and cURL 7.71.0.
CURLPROTO_POP3 (
int)
Available as of cURL 7.20.0.
CURLPROTO_POP3S (
int)
Available as of cURL 7.20.0.
CURLPROTO_RTMP (
int)
Available as of cURL 7.21.0.
CURLPROTO_RTMPE (
int)
Available as of cURL 7.21.0.
CURLPROTO_RTMPS (
int)
Available as of cURL 7.21.0.
CURLPROTO_RTMPT (
int)
Available as of cURL 7.21.0.
CURLPROTO_RTMPTE (
int)
Available as of cURL 7.21.0.
CURLPROTO_RTMPTS (
int)
Available as of cURL 7.21.0.
CURLPROTO_RTSP (
int)
Available as of cURL 7.20.0.
CURLPROTO_SCP (
int)
Available as of cURL 7.19.4.
CURLPROTO_SFTP (
int)
Available as of cURL 7.19.4.
CURLPROTO_SMB (
int)
Available as of PHP 7.0.7 and cURL 7.40.0.
CURLPROTO_SMBS (
int)
Available as of PHP 7.0.7 and cURL 7.40.0.
CURLPROTO_SMTP (
int)
Available as of cURL 7.20.0.
CURLPROTO_SMTPS (
int)
Available as of cURL 7.20.0.
CURLPROTO_TELNET (
int)
Available as of cURL 7.19.4.
CURLPROTO_TFTP (
int)
Available as of cURL 7.19.4.
curlfile
ENTITY
This class or
CURLStringFile should be used to upload a file with
CURLOPT_POSTFIELDS.
Unserialization of
CURLFile instances is not allowed. As of PHP 7.4.0, serialization is forbidden in the first place.
ENTITY
CURLFile
ENTITY
public
string
name
""
public
string
mime
""
public
string
postname
""
ENTITY
ENTITY
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).
ENTITY
curl_setopt,
CURLStringFile
ENTITY
construct
CURLFile::__construct
curl_file_create
Create a CURLFile object
ENTITY
ENTITY
public
CURLFile::__construct
string
filename
string
null
mime_type
ENTITY
string
null
posted_filename
ENTITY
ENTITY
CURLFile
curl_file_create
string
filename
string
null
mime_type
ENTITY
string
null
posted_filename
ENTITY
Creates a
CURLFile object, used to upload a file with
CURLOPT_POSTFIELDS.
ENTITY
filename
Path to the file which will be uploaded.
mime_type
Mimetype of the file.
posted_filename
Name of the file to be used in the upload data.
ENTITY
Returns a
CURLFile object.
ENTITY
ENTITY
ENTITY
8.0.0
mime_type and
posted_filename are nullable now; previously their default was
0.
ENTITY
CURLFile::__construct example
ENTITY
*/
// 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);
?>
ENTITY
*/
// 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);
?>
ENTITY
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)
}
}
CURLFile::__construct uploading multiple files example
ENTITY
new CURLFile(realpath('first-file.jpg'), 'image/jpeg'),
'blob[1]' => new CURLFile(realpath('second-file.txt'), 'text/plain'),
'blob[2]' => new CURLFile(realpath('third-file.exe'), 'application/octet-stream'),
]);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
var_dump(curl_getinfo($request));
ENTITY
curl_file_create(realpath('first-file.jpg'), 'image/jpeg'),
'blob[1]' => curl_file_create(realpath('second-file.txt'), 'text/plain'),
'blob[2]' => curl_file_create(realpath('third-file.exe'), 'application/octet-stream'),
]);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
var_dump(curl_getinfo($request));
ENTITY
array(26) {
["url"]=>
string(31) "http://www.example.com/upload.php"
["content_type"]=>
string(24) "text/html; charset=UTF-8"
["http_code"]=>
int(200)
["header_size"]=>
int(198)
["request_size"]=>
int(196)
["filetime"]=>
int(-1)
["ssl_verify_result"]=>
int(0)
["redirect_count"]=>
int(0)
["total_time"]=>
float(0.060062)
["namelookup_time"]=>
float(0.028575)
["connect_time"]=>
float(0.029011)
["pretransfer_time"]=>
float(0.029121)
["size_upload"]=>
float(3230730)
["size_download"]=>
float(811)
["speed_download"]=>
float(13516)
["speed_upload"]=>
float(53845500)
["download_content_length"]=>
float(811)
["upload_content_length"]=>
float(3230730)
["starttransfer_time"]=>
float(0.030355)
["redirect_time"]=>
float(0)
["redirect_url"]=>
string(0) ""
["primary_ip"]=>
string(13) "0.0.0.0"
["certinfo"]=>
array(0) {
}
["primary_port"]=>
int(80)
["local_ip"]=>
string(12) "0.0.0.0"
["local_port"]=>
int(34856)
}
ENTITY
curl_setopt
getfilename
CURLFile::getFilename
Get file name
ENTITY
public
string
CURLFile::getFilename
ENTITY ENTITY
ENTITY
Returns file name.
getmimetype
CURLFile::getMimeType
Get MIME type
ENTITY
public
string
CURLFile::getMimeType
ENTITY ENTITY
ENTITY
Returns MIME type.
getpostfilename
CURLFile::getPostFilename
Get file name for POST
ENTITY
public
string
CURLFile::getPostFilename
ENTITY ENTITY
ENTITY
Returns file name for POST.
setmimetype
CURLFile::setMimeType
Set MIME type
ENTITY
public
void
CURLFile::setMimeType
string
mime_type
ENTITY
mime_type
MIME type to be used in POST data.
ENTITY
ENTITY
setpostfilename
CURLFile::setPostFilename
Set file name for POST
ENTITY
public
void
CURLFile::setPostFilename
string
posted_filename
ENTITY
posted_filename
Filename to be used in POST data.
ENTITY
ENTITY
curlhandle
ENTITY
A fully opaque class which replaces
curl resources as of PHP 8.0.0.
ENTITY
final
CurlHandle
curlmultihandle
ENTITY
A fully opaque class which replaces
curl_multi resources as of PHP 8.0.0.
ENTITY
final
CurlMultiHandle
curlsharehandle
ENTITY
A fully opaque class which replaces
curl_share resources as of PHP 8.0.0.
ENTITY
final
CurlShareHandle
curlsharepersistenthandle
ENTITY
Represents a persistent cURL "share" handle, created by
curl_share_init_persistent. Unlike
CurlShareHandle (created with
curl_share_init), this handle persists across requests. Use
curl_share_setopt to configure what data is shared.
ENTITY
final
CurlSharePersistentHandle
ENTITY
public
readonly
array
options
ENTITY
options
The
CURL_LOCK_DATA_* caches shared between requests using this handle.
ENTITY
ENTITY
ENTITY
8.5.0
The class was added.
curlstringfile
ENTITY
CURLStringFile makes it possible to upload a file directly from a variable. This is similar to
CURLFile, but works with the contents of the file, not filename. This class or
CURLFile should be used to upload the contents of the file with
CURLOPT_POSTFIELDS.
ENTITY
CURLStringFile
ENTITY
public
string
data
public
string
postname
public
string
mime
ENTITY
ENTITY
data
The contents to be uploaded.
postname
The name of the file to be used in the upload data.
mime
MIME type of the file (default is
application/octet-stream).
ENTITY
curl_setopt,
CURLFile
ENTITY
construct
CURLStringFile::__construct
Create a CURLStringFile object
ENTITY
public
CURLStringFile::__construct
string
data
string
postname
string
mime
"application/octet-stream"
Creates a
CURLStringFile object, used to upload a file with
CURLOPT_POSTFIELDS.
ENTITY
data
The contents to be uploaded.
postname
The name of the file to be used in the upload data.
mime
MIME type of the file (default is
application/octet-stream).
ENTITY
CURLStringFile::__construct example
*/
// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');
// Create a CURLStringFile object
$cstringfile = new CURLStringFile('test upload contents','test.txt','text/plain');
// Assign POST data
$data = array('test_string' => $cstringfile);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Execute the handle
curl_exec($ch);
?>
ENTITY
array(1) {
["test_string"]=>
array(5) {
["name"]=>
string(8) "test.txt"
["type"]=>
string(10) "text/plain"
["tmp_name"]=>
string(14) "/tmp/phpTtaoCz"
["error"]=>
int(0)
["size"]=>
int(20)
}
}
string(20) "test upload contents"
ENTITY
curl_setopt
examples
ENTITY
Basic curl examples
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.
Here is a simple example that uses the cURL functions to send a POST request:
Using PHP's cURL module to send a POST request
'bar', 'baz' => 48];
$url = "http://www.example.com/handler.php";
$ch = curl_init($url);
// tell CURL to return the response instead of sending it to stdout
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// set the POST data, corresponding method and headers
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// send the request and get the response
$response = curl_exec($ch);
if(curl_error($ch)) {
// handle the error
throw new RuntimeException(curl_error($ch));
}
Another example that uses the cURL functions to send a raw JSON POST request:
Using PHP's cURL module to send a JSON POST request
'bar', 'baz' => 48];
$url = "http://www.example.com/api/endpoint";
$ch = curl_init($url);
// tell CURL to return the response instead of sending it to stdout
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// set the POST data and corresponding method
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
// set the required header
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
// send the request and get the response
$response = curl_exec($ch);
if(curl_error($ch)) {
// handle the error, or just
throw new RuntimeException(curl_error($ch));
}
Here is another example that uses the cURL functions to fetch the example.com homepage into a file:
Using PHP's cURL module to fetch the example.com homepage
ENTITY
curl_init,
curl_multi_close
curl-copy-handle
curl_copy_handle
Copy a cURL handle along with all of its preferences
ENTITY
CurlHandle
false
curl_copy_handle
CurlHandle
handle
Copies a cURL handle keeping the same preferences.
ENTITY
ENTITY
Returns a new cURL handle, ENTITY.
ENTITY
ENTITY
ENTITY
8.0.0
On success, this function returns a
CurlHandle instance now; previously, a
resource was returned.
ENTITY
Copying a cURL handle
curl-errno
curl_errno
Return the last error number
ENTITY
int
curl_errno
CurlHandle
handle
Returns the error number for the last cURL operation.
ENTITY
ENTITY
Returns the error number or
0 (zero) if no error occurred.
[!NOTE]
When a
CurlHandle is executed via
curl_multi_exec, this function returns
0 until
curl_multi_info_read has returned the message for that handle. The error code for each individual handle is available as the
result key returned by
curl_multi_info_read.
ENTITY
ENTITY
ENTITY
ENTITY
curl_errno example
ENTITY
curl_error,
curl_multi_info_read, Curl error codes
curl-error
curl_error
Return a string containing the last error for the current session
ENTITY
string
curl_error
CurlHandle
handle
Returns a clear text error message for the last cURL operation.
ENTITY
ENTITY
Returns the error message or
'' (the empty string) if no error occurred.
[!NOTE]
When a
CurlHandle is executed via
curl_multi_exec, this function returns
'' (the empty string) until
curl_multi_info_read has returned the message for that handle. To retrieve the error string for each individual handle, pass the
result key returned by
curl_multi_info_read to
curl_strerror.
ENTITY
ENTITY
ENTITY
ENTITY
curl_error example
ENTITY
curl_errno,
curl_strerror,
curl_multi_info_read, Curl error codes
curl-escape
curl_escape
URL encodes the given string
ENTITY
string
false
curl_escape
CurlHandle
handle
string
string
This function URL encodes the given string according to RFC 3986.
ENTITY
string
The string to be encoded.
ENTITY
Returns escaped stringENTITY.
ENTITY
ENTITY
ENTITY
ENTITY
curl_escape example
ENTITY
curl_unescape,
urlencode,
rawurlencode, RFC 3986
curl-exec
curl_exec
Perform a cURL session
ENTITY
string
bool
curl_exec
CurlHandle
handle
Execute the given cURL session.
This function should be called after initializing a cURL session and all the options for the session are set.
ENTITY
ENTITY
On success, this function flushes the result directly to the
stdout and returns ENTITY, ENTITY. However, if the
CURLOPT_RETURNTRANSFER option is set, it will return the result on success, ENTITY on failure.
If
CURLOPT_FILE or
CURLOPT_WRITEFUNCTION is set, the result is written to that file or passed to that callback instead, nothing is written to
stdout, and ENTITY is returned on success. Whichever of these options and
CURLOPT_RETURNTRANSFER was set last decides where the result goes.
ENTITY
[!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.
ENTITY
ENTITY
ENTITY
ENTITY
Fetching a web page
ENTITY
curl_multi_exec
curl-getinfo
curl_getinfo
Get information regarding a specific transfer
ENTITY
mixed
curl_getinfo
CurlHandle
handle
int
null
option
ENTITY
Gets information about the last transfer.
ENTITY
option
One of the
CURLINFO_* constants.
ENTITY
If
option is given, returns its value. Otherwise, returns an associative array with the following elements (which correspond to
option), or ENTITY 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
CURLINFO_HEADER_OUT is set by a previous call to
curl_setopt)
"posttransfer_time_us" (Available as of PHP 8.4.0 and cURL 8.10.0)
Note that private data is not included in the associative array and must be retrieved individually with the
CURLINFO_PRIVATE option.
ENTITY
ENTITY
ENTITY
8.4.0
Introduced
CURLINFO_POSTTRANSFER_TIME_T constant and
posttransfer_time_us (Curl 8.10.0 or later).
8.3.0
Introduced
CURLINFO_CAINFO and
CURLINFO_CAPATH.
8.2.0
Introduced
CURLINFO_PROXY_ERROR,
CURLINFO_REFERER,
CURLINFO_RETRY_AFTER.
8.0.0
option is nullable now; previously, the default was
0.
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.
ENTITY
curl_getinfo example
curl_getinfo example with
option parameter
ENTITY
[!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.
curl-init
curl_init
Initialize a cURL session
ENTITY
CurlHandle
false
curl_init
string
null
url
ENTITY
Initializes a new session and returns a cURL handle.
ENTITY
url
If provided, the
CURLOPT_URL option will be set to its value. This can be set manually using the
curl_setopt function.
[!NOTE]
The
file protocol is disabled by cURL if open_basedir is set.
ENTITY
Returns a cURL handle on success, ENTITY on errors.
ENTITY
ENTITY
ENTITY
8.0.0
On success, this function returns a
CurlHandle instance now; previously, a
resource was returned.
8.0.0
url is nullable now.
ENTITY
Initializing a new cURL session and fetching a web page
ENTITY
curl_multi_init
curl-multi-add-handle
curl_multi_add_handle
Add a normal cURL handle to a cURL multi handle
ENTITY
int
curl_multi_add_handle
CurlMultiHandle
multi_handle
CurlHandle
handle
Adds the
handle handle to the multi handle
multi_handle
ENTITY
ENTITY
Returns 0 on success, or one of the
CURLM_* errors code.
ENTITY
ENTITY
ENTITY
ENTITY
curl_multi_remove_handle,
curl_multi_init,
curl_init
curl-multi-close
curl_multi_close
Remove all cURL handles from a multi handle
ENTITY
void
curl_multi_close
CurlMultiHandle
multi_handle
Removes all
CurlHandles attached to the
CurlMultiHandle, as if
curl_multi_remove_handle was called for each of them.
Prior to PHP 8.0.0 this function also closed the cURL multi handle resource, making it unusable.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
curl_multi_init
curl-multi-errno
curl_multi_errno
Return the last multi curl error number
ENTITY
int
curl_multi_errno
CurlMultiHandle
multi_handle
Return an integer containing the last multi curl error number.
ENTITY
ENTITY
Return an integer containing the last multi curl error number.
ENTITY
ENTITY
ENTITY
8.0.0
The function no longer returns ENTITY on failure.
ENTITY
curl_errno
curl-multi-exec
curl_multi_exec
Processes each of the handles in the stack
ENTITY
int
curl_multi_exec
CurlMultiHandle
multi_handle
int
still_running
Processes each of the handles in the stack. This method can be called whether or not a handle needs to read or write data.
ENTITY
still_running
A reference to a flag to tell whether the operations are still running.
ENTITY
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.
ENTITY
ENTITY
ENTITY
ENTITY
curl_multi_exec example
This example will create curl handles for a list of URLs, add them to a multi handle, and process them asynchronously.
ENTITY
curl_multi_init,
curl_multi_select,
curl_exec
curl-multi-get-handles
curl_multi_get_handles
Return an array of CurlHandle objects currently attached to a CurlMultiHandle
ENTITY
array
curl_multi_get_handles
CurlMultiHandle
multi_handle
Returns all
CurlHandle objects currently attached to the given
CurlMultiHandle. This includes handles added using
curl_multi_add_handle and handles accepted by a
CURLMOPT_PUSHFUNCTION callback.
ENTITY
ENTITY
Returns an array of
CurlHandle objects.
ENTITY
ENTITY
ENTITY
8.5.0
The function was added.
ENTITY
curl_multi_add_handle
curl_multi_remove_handle
curl-multi-getcontent
curl_multi_getcontent
Return the content of a cURL handle if
CURLOPT_RETURNTRANSFER
is set
ENTITY
string
null
curl_multi_getcontent
CurlHandle
handle
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.
ENTITY
ENTITY
Return the content of a cURL handle if
CURLOPT_RETURNTRANSFER is set or ENTITY if not set.
ENTITY
ENTITY
ENTITY
ENTITY
curl_multi_init
curl-multi-info-read
curl_multi_info_read
Get information about the current transfers
ENTITY
array
false
curl_multi_info_read
CurlMultiHandle
multi_handle
int
queued_messages
ENTITY
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 ENTITY is returned as a signal that there is no more to get at this point. The integer pointed to with
queued_messages 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.
ENTITY
queued_messages
Number of messages that are still in the queue
ENTITY
On success, returns an associative array for the message, ENTITY on failure.
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.
Contents of the returned array
ENTITY
ENTITY
ENTITY
ENTITY
curl_multi_init
curl-multi-init
curl_multi_init
Returns a new cURL multi handle
ENTITY
CurlMultiHandle
curl_multi_init
Allows the processing of multiple cURL handles asynchronously.
ENTITY ENTITY
ENTITY
Returns a cURL multi handle.
ENTITY
ENTITY
ENTITY
8.0.0
On success, this function returns a
CurlMultiHandle instance now; previously, a
resource was returned.
ENTITY
curl_init,
curl_multi_close
curl-multi-remove-handle
curl_multi_remove_handle
Remove a handle from a set of cURL handles
ENTITY
int
curl_multi_remove_handle
CurlMultiHandle
multi_handle
CurlHandle
handle
Removes a given
handle from the given
multi_handle. When the
handle has been removed, it is again perfectly legal to run
curl_exec on this handle. Removing the
handle while being used, will effectively halt the transfer in progress involving that handle.
ENTITY
ENTITY
Returns 0 on success, or one of the
CURLM_* error codes.
ENTITY
ENTITY
ENTITY
ENTITY
curl_init,
curl_multi_init,
curl_multi_add_handle
curl-multi-select
curl_multi_select
Wait until reading or writing is possible for any cURL multi handle connection
ENTITY
int
curl_multi_select
CurlMultiHandle
multi_handle
float
timeout
1.0
Blocks the execution of the script until a cURL handle attached to the cURL multi handle would be able to make progress on the next call to
curl_multi_exec or until the timeout strikes (whichever comes first).
ENTITY
timeout
Time, in seconds, to wait for a response from the active cURL multi handle connections.
ENTITY
On success, returns the number of active 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).
ENTITY
Throws a ValueError if
timeout is less than
0 or greater than
PHP_INT_MAX.
ENTITY
ENTITY
ENTITY
8.4.0
Now throws a ValueError if
timeout is less than
0 or greater than
PHP_INT_MAX.
ENTITY
curl_multi_init
curl-multi-setopt
curl_multi_setopt
Set a cURL multi option
ENTITY
bool
curl_multi_setopt
CurlMultiHandle
multi_handle
int
option
mixed
value
Sets an option on the given cURL multi handle.
ENTITY
option
One of the
CURLMOPT_* constants.
value
The value to be set on
option. See the description of the
CURLMOPT_* constants for details on the type of values each constant expects.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.2.0
Introduced
CURLMOPT_MAX_CONCURRENT_STREAMS.
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.
curl-multi-strerror
curl_multi_strerror
Return string describing error code
ENTITY
string
null
curl_multi_strerror
int
error_code
Returns a text error message describing the given
CURLM_* error code.
ENTITY
error_code
One of the
CURLM_* constants.
ENTITY
Returns the error description. For an unknown error code this is
"Unknown error".
ENTITY
curl_strerror, cURL error codes
curl-pause
curl_pause
Pause and unpause a connection
ENTITY
int
curl_pause
CurlHandle
handle
int
flags
Pause or unpause a cURL session. A session can be paused while a transfer is in progress, in either the read, write or both directions, by calling this function from a callback registered with
curl_setopt.
ENTITY
flags
One of
CURLPAUSE_* constants.
ENTITY
Returns an error code (
CURLE_OK for no error).
ENTITY
ENTITY
ENTITY
curl-reset
curl_reset
Reset all options of a libcurl session handle
ENTITY
void
curl_reset
CurlHandle
handle
This function re-initializes all options set on the given cURL handle to the default values.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
curl_reset example
ENTITY
[!NOTE]
curl_reset also resets the URL given as the
curl_init parameter.
ENTITY
curl_setopt
curl-setopt-array
curl_setopt_array
Set multiple options for a cURL transfer
ENTITY
bool
curl_setopt_array
CurlHandle
handle
array
options
Sets multiple options for a cURL session. This function is useful for setting a large number of cURL options without repetitively calling
curl_setopt.
ENTITY
options
An
array specifying which options to set and their values. The keys should be valid
curl_setopt constants or their integer equivalents.
ENTITY
Returns ENTITY if all options were successfully set. If an option could not be successfully set, ENTITY is immediately returned, ignoring any future options in the
options array.
ENTITY
Throws a ValueError when
options contains an invalid cURL option.
ENTITY
ENTITY
ENTITY
8.0.0
curl_setopt_array now throws a ValueError if
options contains an unknown option or a string key. Previously, unknown options were silently ignored, and a string key emitted an
E_WARNING and returned ENTITY.
ENTITY
Initializing a new cURL session and fetching a web page
'http://www.example.com/',
CURLOPT_HEADER => false
);
curl_setopt_array($ch, $options);
// grab URL and pass it to the browser
curl_exec($ch);
?>
ENTITY
[!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.
ENTITY
curl_setopt
curl-setopt
curl_setopt
Set an option for a cURL transfer
ENTITY
bool
curl_setopt
CurlHandle
handle
int
option
mixed
value
Sets an option on the given cURL session handle.
ENTITY
option
The
CURLOPT_* option to set.
value
The value to be set on
option. See the description of the
CURLOPT_* constants for details on the type of values each constant expects.
ENTITY
ENTITY
ENTITY
Throws a ValueError when
option is not a valid cURL option.
ENTITY
ENTITY
ENTITY
8.4.0
CURLOPT_DNS_USE_GLOBAL_CACHE no longer has any effect, and enabling it on thread-safe PHP builds no longer triggers a warning.
8.0.0
curl_setopt now throws a ValueError if
option is not a valid cURL option. Previously, unknown options were silently ignored, and an
E_WARNING was emitted, with ENTITY returned, only for values less than or equal to zero.
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.
ENTITY
Initializing a new cURL session and fetching a web page
ENTITY
[!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.
ENTITY
curl_setopt_array,
CURLFile,
CURLStringFile
curl-share-close
curl_share_close
Close a cURL share handle
ENTITY
ENTITY
#[\Deprecated(since: '8.5', message: "as it has no effect since PHP 8.0")]
void
curl_share_close
CurlShareHandle
share_handle
ENTITY
Closes a cURL share handle and frees all resources.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.5.0
This function has been deprecated.
8.0.0
This function is a NOP now.
ENTITY
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.
ENTITY
curl_share_init
curl-share-errno
curl_share_errno
Return the last share curl error number
ENTITY
int
curl_share_errno
CurlShareHandle
share_handle
Return an integer containing the last share curl error number.
ENTITY
ENTITY
Returns an integer containing the last share curl error number.
ENTITY
ENTITY
ENTITY
8.0.0
The function no longer returns ENTITY on failure.
ENTITY
curl_errno
curl-share-init-persistent
curl_share_init_persistent
Initialize a
persistent
cURL share handle
ENTITY
CurlSharePersistentHandle
curl_share_init_persistent
array
share_options
Initialize a persistent cURL share handle with the given share options. Unlike
curl_share_init, handles created by this function will not be destroyed at the end of the PHP request. If a persistent share handle with the same set of
share_options is found, it will be reused.
ENTITY
share_options
A non-empty array of
CURL_LOCK_DATA_* constants.
[!NOTE]
CURL_LOCK_DATA_COOKIE is not allowed and, if specified, this function will throw a ValueError. Sharing cookies between PHP requests may lead to inadvertently mixing up sensitive cookies between users.
ENTITY
Returns a
CurlSharePersistentHandle.
ENTITY
If
share_options is empty, this function throws a ValueError.
If
share_options contains a value not matching a
CURL_LOCK_DATA_*, this function throws a
ValueError.
If
share_options contains
CURL_LOCK_DATA_COOKIE, this function throws a ValueError.
If
share_options contains a non-integer value, this function throws a TypeError.
ENTITY
curl_share_init_persistent example
This example will create a persistent cURL share handle and demonstrate sharing connections between them. If this is executed in a long-lived PHP SAPI,
$sh will survive between SAPI requests.
ENTITY
curl_setopt
curl_share_init
curl-share-init
curl_share_init
Initialize a cURL share handle
ENTITY
CurlShareHandle
curl_share_init
Allows to share data between cURL handles.
ENTITY ENTITY
ENTITY
Returns a cURL share handle.
ENTITY
ENTITY
ENTITY
8.0.0
This function returns a
CurlShareHandle instance now; previously, a
resource was returned.
ENTITY
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.
ENTITY
curl_share_setopt,
curl_share_init_persistent
curl-share-setopt
curl_share_setopt
Set an option for a cURL share handle
ENTITY
bool
curl_share_setopt
CurlShareHandle
share_handle
int
option
mixed
value
Sets an option on the given cURL share handle.
ENTITY
option
One of the
CURLSHOPT_* constants.
value
One of the
CURL_LOCK_DATA_* constants.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
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.
curl-share-strerror
curl_share_strerror
Return string describing the given error code
ENTITY
string
null
curl_share_strerror
int
error_code
Returns a text error message describing the given error code.
ENTITY
error_code
One of the cURL error codes constants.
ENTITY
Returns the error description. For an unknown error code this is
"CURLSHcode unknown".
ENTITY
curl_share_errno
curl_strerror
curl-strerror
curl_strerror
Return string describing the given error code
ENTITY
string
null
curl_strerror
int
error_code
Returns a text error message describing the given error code.
ENTITY
error_code
One of the cURL error codes constants.
ENTITY
Returns the error description. For an unknown error code this is
"Unknown error".
ENTITY
curl_errno example
ENTITY
cURL error (1):
Unsupported protocol
ENTITY
curl_errno,
curl_error, Curl error codes
curl-unescape
curl_unescape
Decodes the given URL encoded string
ENTITY
string
false
curl_unescape
CurlHandle
handle
string
string
This function decodes the given URL encoded string.
ENTITY
string
The URL encoded string to be decoded.
ENTITY
Returns decoded string ENTITY.
ENTITY
ENTITY
ENTITY
ENTITY
curl_unescape example
ENTITY
[!NOTE]
curl_unescape does not decode plus symbols (+) into spaces.
urldecode does.
ENTITY
curl_escape,
urlencode,
urldecode,
rawurlencode,
rawurldecode
curl-upkeep
curl_upkeep
Performs any connection upkeep checks
ENTITY
bool
curl_upkeep
CurlHandle
handle
Available if built against libcurl ENTITY= 7.62.0.
Some protocols have "connection upkeep" mechanisms. These mechanisms usually send some traffic on existing connections in order to keep them alive; this can prevent connections from being closed due to overzealous firewalls, for example.
Connection upkeep is currently available only for HTTP/2 connections. A small amount of traffic is usually sent to keep a connection alive. HTTP/2 maintains its connection by sending a HTTP/2 PING frame.
ENTITY
ENTITY
ENTITY
ENTITY
curl_upkeep example
ENTITY
curl_init
curl-version
curl_version
Gets cURL version information
ENTITY
array
false
curl_version
Returns information about the cURL version.
ENTITY ENTITY
ENTITY
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
Always
0, libcurl does not set it anymore
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
The age of the version info returned by libcurl. Newer libcurl versions have a higher age
features
A bitmask of the
CURL_VERSION_* constants
protocols
An array of protocols names supported by cURL
feature_list
An associative array of all known cURL features, and whether they are supported (ENTITY) or not (ENTITY)
ares
c-ares version, as a string, or an empty string if cURL was built without c-ares
ares_num
c-ares version number, or
0 if cURL was built without c-ares
libidn
libidn2 version, as a string, or an empty string if cURL was built without libidn2
iconv_ver_num
iconv version number, or
0 if cURL was built without iconv
libssh_version
SSH library name and version, as a string, or an empty string if cURL was built without SSH support
brotli_ver_num
Brotli version number, or
0 if cURL was built without Brotli
brotli_version
Brotli version, as a string, or an empty string if cURL was built without Brotli
ENTITY
ENTITY
ENTITY
8.4.0
feature_list added.
8.0.0
The optional
age parameter has been removed.
7.4.0
The optional
age parameter has been deprecated; if a value is passed, it is ignored.
ENTITY
curl_version example
This example will check which features are available in the cURL build by using the
'features' bitmask returned by
curl_version.
ini
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
curl.cainfo
NULL
INI_SYSTEM
cURL Configuration Options
ENTITY
ENTITY
curl.cainfo
string
A default value for the
CURLOPT_CAINFO option. This is required to be an absolute path.
reference
ENTITY
setup
ENTITY
ENTITY
In order to use PHP's cURL functions you need to install the libcurl package. PHP requires libcurl version 7.10.5 or later. As of PHP 7.3.0, version 7.15.5 or later is required. As of PHP 8.0.0, version 7.29.0 or later is required. As of PHP 8.4.0, version 7.61.0 or later is required.
ENTITY ENTITY
ENTITY
Prior to PHP 8.0.0, this extension defined three resource types: a
curl handle, a
curl_multi handle, and a
curl_share handle.
book
ENTITY
This extension implements the JavaScript Object Notation (JSON) data-interchange format. PHP comes with a parser that is specifically written for PHP and licensed under the PHP license.
ENTITY
ENTITY ENTITY ENTITY ENTITY ENTITY
constants
ENTITY ENTITY
The following constants indicate the type of error returned by
json_last_error or stored as the
code of a
JsonException.
JSON_ERROR_NONE (
int)
No error has occurred.
JSON_ERROR_DEPTH (
int)
The maximum stack depth has been exceeded.
JSON_ERROR_STATE_MISMATCH (
int)
Occurs with underflow or with the modes mismatch.
JSON_ERROR_CTRL_CHAR (
int)
Control character error, possibly incorrectly encoded.
JSON_ERROR_SYNTAX (
int)
Syntax error.
JSON_ERROR_UTF8 (
int)
Malformed UTF-8 characters, possibly incorrectly encoded.
JSON_ERROR_RECURSION (
int)
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, ENTITY will be encoded in the place of the recursive reference.
JSON_ERROR_INF_OR_NAN (
int)
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.
JSON_ERROR_UNSUPPORTED_TYPE (
int)
A value of an unsupported type was given to
json_encode, such as a ENTITY. If the
JSON_PARTIAL_OUTPUT_ON_ERROR option was given, ENTITY will be encoded in the place of the unsupported value.
JSON_ERROR_INVALID_PROPERTY_NAME (
int)
A key starting with \u0000 character was in the string passed to
json_decode when decoding a JSON object into a PHP object.
JSON_ERROR_UTF16 (
int)
Single unpaired UTF-16 surrogate in unicode escape contained in the JSON string passed to
json_decode.
JSON_ERROR_NON_BACKED_ENUM (
int)
The value passed to
json_encode includes a non-backed enum which cannot be serialized. Available as of PHP 8.1.0.
The following constants can be combined to form options for
json_decode.
JSON_BIGINT_AS_STRING (
int)
Decodes large integers as their original string value.
JSON_OBJECT_AS_ARRAY (
int)
Decodes JSON objects as PHP array. This option can be added automatically by calling
json_decode with the second parameter equal to ENTITY.
The following constants can be combined to form options for
json_encode.
JSON_HEX_TAG (
int)
All ENTITY and ENTITY are converted to \u003C and \u003E.
JSON_HEX_AMP (
int)
All ENTITY are converted to \u0026.
JSON_HEX_APOS (
int)
All ' are converted to \u0027.
JSON_HEX_QUOT (
int)
All " are converted to \u0022.
JSON_FORCE_OBJECT (
int)
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.
JSON_NUMERIC_CHECK (
int)
Encodes numeric strings as numbers.
JSON_PRETTY_PRINT (
int)
Use whitespace in returned data to format it.
JSON_UNESCAPED_SLASHES (
int)
Don't escape
/.
JSON_UNESCAPED_UNICODE (
int)
Encode multibyte Unicode characters literally (default is to escape as \uXXXX).
JSON_PARTIAL_OUTPUT_ON_ERROR (
int)
Substitute some unencodable values instead of failing.
JSON_PRESERVE_ZERO_FRACTION (
int)
Ensures that ENTITY values are always encoded as a float value.
JSON_UNESCAPED_LINE_TERMINATORS (
int)
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 (
int)
Ignore invalid UTF-8 characters. Available as of PHP 7.2.0.
JSON_INVALID_UTF8_SUBSTITUTE (
int)
Convert invalid UTF-8 characters to \0xfffd (Unicode Character 'REPLACEMENT CHARACTER') Available as of PHP 7.2.0.
JSON_THROW_ON_ERROR (
int)
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.
json-decode
json_decode
Decodes a JSON string
ENTITY
mixed
json_decode
string
json
bool
null
associative
ENTITY
int
depth
512
int
flags
0
Takes a JSON encoded string and converts it into a PHP value.
ENTITY
json
The
json
string being decoded.
This function only works with UTF-8 encoded strings.
ENTITY
associative
When ENTITY, JSON objects will be returned as associative ENTITYs; when ENTITY, JSON objects will be returned as ENTITYs. When ENTITY, JSON objects will be returned as associative ENTITYs or ENTITYs depending on whether
JSON_OBJECT_AS_ARRAY is set in the
flags.
depth
Maximum nesting depth of the structure being decoded. The value must be greater than
0, and less than or equal to
2147483647.
flags
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.
ENTITY
Returns the value encoded in
json as an appropriate PHP type. Unquoted values
true,
false and
null are returned as ENTITY, ENTITY and ENTITY respectively. ENTITY is returned if the
json cannot be decoded or if the encoded data is deeper than the nesting limit.
ENTITY
If
depth is outside the allowed range, a
ValueError is thrown as of PHP 8.0.0, while previously, an error of level
E_WARNING was raised.
ENTITY
ENTITY
ENTITY
7.3.0
JSON_THROW_ON_ERROR
flags was added.
7.2.0
associative is nullable now.
7.2.0
JSON_INVALID_UTF8_IGNORE, and
JSON_INVALID_UTF8_SUBSTITUTE
flags 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_.
ENTITY
json_decode examples
ENTITY
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)
}
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.
{'foo-bar'}; // 12345
?>
common mistakes using
json_decode
depth errors
array -> array -> string)
$json = json_encode(
array(
1 => array(
'English' => array(
'One',
'January'
),
'French' => array(
'Une',
'Janvier'
)
)
)
);
// Show the errors for different depths.
var_dump(json_decode($json, true, 4));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
var_dump(json_decode($json, true, 3));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
?>
ENTITY
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: No error
NULL
Last error: Maximum stack depth exceeded
json_decode of large integers
ENTITY
object(stdClass)#1 (1) {
["number"]=>
float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
["number"]=>
string(20) "12345678901234567890"
}
ENTITY
[!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.
ENTITY
json_encode,
json_last_error,
json_last_error_msg
json-encode
json_encode
Returns the JSON representation of a value
ENTITY
string
false
json_encode
mixed
value
int
flags
0
int
depth
512
Returns a string containing the JSON representation of the supplied
value. If the parameter is an ENTITY or ENTITY, it will be serialized recursively.
If a value to be serialized is an object, then by default only publicly visible properties will be included. Alternatively, a class may implement JsonSerializable to control how its values are serialized to JSON.
The encoding is affected by the supplied
flags and additionally the encoding of float values depends on the value of serialize_precision.
ENTITY
value
The
value being encoded. Can be any type except a ENTITY.
All string data must be UTF-8 encoded.
ENTITY
flags
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.
ENTITY
Returns a JSON encoded ENTITY on success ENTITY.
ENTITY
ENTITY
ENTITY
7.3.0
JSON_THROW_ON_ERROR
flags was added.
7.2.0
JSON_INVALID_UTF8_IGNORE, and
JSON_INVALID_UTF8_SUBSTITUTE
flags were added.
7.1.0
JSON_UNESCAPED_LINE_TERMINATORS
flags was added.
7.1.0
serialize_precision is used instead of precision when encoding
float values.
ENTITY
A
json_encode example
1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
ENTITY
{"a":1,"b":2,"c":3,"d":4,"e":5}
A
json_encode example showing some flags in use
',"'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";
?>
ENTITY
Normal: ["","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["","'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"}
JSON_NUMERIC_CHECK option example
ENTITY
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"]"
Sequential versus non-sequential array example
"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)
);
?>
ENTITY
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"}"
JSON_PRESERVE_ZERO_FRACTION option example
ENTITY
string(4) "12.0"
string(2) "12"
ENTITY
[!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 ENTITY, ENTITY, ENTITY or ENTITY 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.
ENTITY
JsonSerializable,
json_decode,
json_last_error,
json_last_error_msg,
serialize
json-last-error-msg
json_last_error_msg
Returns the error string of the last json_validate(), json_encode() or json_decode() call
ENTITY
string
json_last_error_msg
Returns the error string of the last
json_validate,
json_encode or
json_decode call, which did not specify
JSON_THROW_ON_ERROR.
ENTITY ENTITY
ENTITY
Returns the error message on success, or
"No error" if no error has occurred.
ENTITY
json_last_error
json-last-error
json_last_error
Returns the last error occurred
ENTITY
int
json_last_error
Returns the last error (if any) occurred during the last JSON validation/encoding/decoding, which did not specify
JSON_THROW_ON_ERROR.
ENTITY ENTITY
ENTITY
Returns an integer, the value can be one of the following constants:
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
JSON_ERROR_RECURSION
One or more recursive references in the value to be encoded
JSON_ERROR_INF_OR_NAN
One or more
NAN or
INF values in the value to be encoded
JSON_ERROR_UNSUPPORTED_TYPE
A value of a type that cannot be encoded was given
JSON_ERROR_INVALID_PROPERTY_NAME
A property name that cannot be encoded was given
JSON_ERROR_UTF16
Malformed UTF-16 characters, possibly incorrectly encoded
JSON_ERROR_NON_BACKED_ENUM
Value contains a non-backed enum which cannot be serialized
ENTITY
ENTITY
ENTITY
8.1.0
JSON_ERROR_NON_BACKED_ENUM was added.
ENTITY
json_last_error example
ENTITY
Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON
json_last_error with
json_encode
ENTITY
string(4) "null"
bool(true)
json_last_error and
JSON_THROW_ON_ERROR
ENTITY
bool(true)
ENTITY
json_last_error_msg,
json_decode,
json_encode
json-validate
json_validate
Checks if a string contains valid JSON
ENTITY
bool
json_validate
string
json
int
depth
512
int
flags
0
Returns whether the given ENTITY is syntactically valid JSON. If
json_validate returns ENTITY,
json_decode will successfully decode the given string when using the same
depth and
flags.
If
json_validate returns ENTITY, the cause can be retrieved using
json_last_error and
json_last_error_msg.
json_validate uses less memory than
json_decode if the decoded JSON payload is not used, because it does not need to build the array or object structure containing the payload.
[!CAUTION]
Calling
json_validate immediately before
json_decode will unnecessarily parse the string twice, as
json_decode implicitly performs validation during decoding.
json_validate should therefore only be used if the decode JSON payload is not immediately used and knowing whether the string contains valid JSON is needed.
ENTITY
json
The string to validate.
This function only works with UTF-8 encoded strings.
ENTITY
depth
Maximum nesting depth of the structure being decoded. The value must be greater than
0, and less than or equal to
2147483647.
flags
Currently only
JSON_INVALID_UTF8_IGNORE is accepted.
ENTITY
Returns ENTITY if the given string is syntactically valid JSON, otherwise returns ENTITY.
ENTITY
If
depth is outside the allowed range, a
ValueError is thrown.
If
flags is not a valid flag, a
ValueError is thrown.
ENTITY
json_validate examples
ENTITY
bool(true)
bool(false)
ENTITY
json_decode,
json_last_error,
json_last_error_msg
jsonexception
ENTITY
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.
ENTITY
JsonException
extends
Exception
ENTITY
ENTITY
jsonserializable
ENTITY
Objects implementing JsonSerializable can customize their JSON representation when encoded with
json_encode.
ENTITY
JsonSerializable
ENTITY
ENTITY
jsonserialize
JsonSerializable::jsonSerialize
Specify data which should be serialized to JSON
ENTITY
public
mixed
JsonSerializable::jsonSerialize
Serializes the object to a value that can be serialized natively by
json_encode.
ENTITY ENTITY
ENTITY
Returns data which can be serialized by
json_encode, which is a value of any type other than a ENTITY.
ENTITY
JsonSerializable::jsonSerialize example returning an ENTITY
array = $array;
}
public function jsonSerialize(): mixed {
return $this->array;
}
}
$array = [1, 2, 3];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>
ENTITY
[
1,
2,
3
]
JsonSerializable::jsonSerialize example returning an associative ENTITY
array = $array;
}
public function jsonSerialize() {
return $this->array;
}
}
$array = ['foo' => 'bar', 'quux' => 'baz'];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>
ENTITY
{
"foo": "bar",
"quux": "baz"
}
JsonSerializable::jsonSerialize example returning an ENTITY
number = (int) $number;
}
public function jsonSerialize() {
return $this->number;
}
}
echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>
ENTITY
1
JsonSerializable::jsonSerialize example returning a ENTITY
string = (string) $string;
}
public function jsonSerialize() {
return $this->string;
}
}
echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>
ENTITY
"Hello!"
reference
ENTITY
setup
ENTITY
ENTITY
The JSON extension is a core PHP extension, so it is always enabled.
Prior to PHP 8.0.0, the JSON extension was bundled and compiled into PHP by default, but could be explicitly disabled using
--disable-json.
book
ENTITY
While there are many languages in which every necessary character can be represented by a one-to-one mapping to an 8-bit value, there are also several languages which require so many characters for written communication that they cannot be contained within the range a mere byte can code (A byte is made up of eight bits. Each bit can contain only two distinct values, one or zero. Because of this, a byte can only represent 256 unique values (two to the power of eight)). Multibyte character encoding schemes were developed to express more than 256 characters in the regular bytewise coding system.
When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.
mbstring provides multibyte specific string functions that help you deal with multibyte encodings in PHP. In addition to that,
mbstring handles character encoding conversion between the possible encoding pairs.
mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed in Supported Character Encodings).
The Unicode data tables used by
mbstring have been updated to Unicode 16.0 as of PHP 8.4.0, and to Unicode 17.0 as of PHP 8.5.0.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
configure
ENTITY
mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the
configure option. See the Install section for details.
The following configure options are related to the
mbstring module.
--enable-mbstring: Enable
mbstring functions. This option is required to use
mbstring functions.
libmbfl is necessary for
mbstring. libmbfl is bundled with
mbstring. Prior to PHP 7.3.0, if libmbfl is already installed on the system,
--with-libmbfl[=DIR] can be specified to use the installed library.
--disable-mbregex: Disable regular expression functions with multibyte character support.
Oniguruma is necessary for the regular expression functions with multibyte character support. As of PHP 7.4.0, pkg-config is used to detect the libonig library. Prior to PHP 7.4.0, Oniguruma was bundled with
mbstring, but it was possible to build against an already installed libonig by passing
--with-onig[=DIR].
It is possible to disable the multibyte regex backtrack check by specifying
--disable-mbregex-backtrack.
constants
ENTITY ENTITY
MB_OVERLOAD_MAIL (
int)
Removed as of PHP 8.0.0.
MB_OVERLOAD_STRING (
int)
Removed as of PHP 8.0.0.
MB_OVERLOAD_REGEX (
int)
Removed as of PHP 8.0.0.
MB_CASE_UPPER (
int)
Performs a full upper-case folding. This may change the length of the string. This is the mode used by mb_strtoupper().
MB_CASE_LOWER (
int)
Performs a full lower-case folding. This may change the length of the string. This is the mode used by mb_strtolower().
MB_CASE_TITLE (
int)
Performs a full title-case conversion based on the Cased and CaseIgnorable derived Unicode properties. In particular this improves handling of quotes and apostrophes. This may change the length of the string.
MB_CASE_FOLD (
int)
Performs a full case fold conversion which removes case distinctions present in the string. This is used for caseless matching. This may change the length of the string. Available since PHP 7.3.
MB_CASE_LOWER_SIMPLE (
int)
Performs a simple lower-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
MB_CASE_UPPER_SIMPLE (
int)
Performs simple upper-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
MB_CASE_TITLE_SIMPLE (
int)
Performs simple title-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
MB_CASE_FOLD_SIMPLE (
int)
Performs a simple case fold conversion which removes case distinctions present in the string. This is used for caseless matching. This does not change the length of the string. Used by case-insensitive operations internally by the MBString extension. Available as of PHP 7.3.
MB_ONIGURUMA_VERSION (
string)
The Oniguruma version, e.g.
6.9.4. Available as of PHP 7.4.
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.
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 ENTITYencodingENTITY 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 ENTITYencodingENTITY 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
mb-check-encoding
mb_check_encoding
Check if strings are valid for the specified encoding
ENTITY
bool
mb_check_encoding
array
string
null
value
ENTITY
string
null
encoding
ENTITY
Checks if the specified byte stream is valid for the specified encoding. If
value is of type ENTITY, all keys and values are validated recursively. It is useful to prevent so-called "Invalid Encoding Attack".
ENTITY
value
The byte stream or ENTITY to check. If it is omitted, this function checks all the input from the beginning of the request.
[!WARNING]
As of PHP 8.1.0, omitting this parameter or passing ENTITY is deprecated.
encoding
The expected encoding.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.1.0
Calling this function with ENTITY as
value or without argument is deprecated.
8.0.0
value and
encoding are nullable now.
7.2.0
This function now also accepts an ENTITY as
value. Formerly, only ENTITYs have been supported.
mb-chr
mb_chr
Return character by Unicode code point value
ENTITY
string
false
mb_chr
int
codepoint
string
null
encoding
ENTITY
Returns a string containing the character specified by the Unicode code point value, encoded in the specified encoding.
This function complements
mb_ord.
ENTITY
codepoint
A Unicode codepoint value, e.g.
128024 for U+1F418 ELEPHANT
encoding
ENTITY
ENTITY
A string containing the requested character, if it can be represented in the specified encoding ENTITY.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
string(1) "A"
string(1) "A"
string(1) "?"
string(1) "?"
string(3) "€"
bool(false)
string(4) "🐘"
bool(false)
ENTITY
mb_internal_encoding,
mb_ord,
IntlChar::ord,
chr
mb-convert-case
mb_convert_case
Perform case folding on a string
ENTITY
string
mb_convert_case
string
string
int
mode
string
null
encoding
ENTITY
Performs case folding on a
string, converted in the way specified by
mode.
ENTITY
string
The
string being converted.
mode
The mode of the conversion. It can be one of
MB_CASE_UPPER,
MB_CASE_LOWER,
MB_CASE_TITLE,
MB_CASE_FOLD,
MB_CASE_UPPER_SIMPLE,
MB_CASE_LOWER_SIMPLE,
MB_CASE_TITLE_SIMPLE,
MB_CASE_FOLD_SIMPLE.
encoding
ENTITY
ENTITY
A case folded version of
string converted in the way specified by
mode.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.3.0
Implemented conditional casing rules for the Greek letter sigma which only apply to
MB_CASE_LOWER and
MB_CASE_TITLE modes, not to
MB_CASE_LOWER_SIMPLE and
MB_CASE_TITLE_SIMPLE.
7.3.0
Added support for
MB_CASE_FOLD,
MB_CASE_UPPER_SIMPLE,
MB_CASE_LOWER_SIMPLE,
MB_CASE_TITLE_SIMPLE, and
MB_CASE_FOLD_SIMPLE as
mode.
ENTITY
mb_convert_case example
mb_convert_case example with non-Latin UTF-8 text
ENTITY
By contrast to the standard case folding functions such as
strtolower and
strtoupper, case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such a-umlaut (ä).
For more information about the Unicode properties, please see ENTITY.
ENTITY
mb_strtolower,
mb_strtoupper,
strtolower,
strtoupper,
ucfirst,
ucwords
mb-convert-encoding
mb_convert_encoding
Convert a string from one character encoding to another
ENTITY
array
string
false
mb_convert_encoding
array
string
string
string
to_encoding
array
string
null
from_encoding
ENTITY
Converts
string from
from_encoding, or the current internal encoding, to
to_encoding. If
string is an ENTITY, all its ENTITY values will be converted recursively.
ENTITY
string
The ENTITY or ENTITY to be converted.
to_encoding
The desired encoding of the result.
from_encoding
The current encoding used to interpret
string. Multiple encodings may be specified as an ENTITY or comma separated list, in which case the correct encoding will be guessed using the same algorithm as
mb_detect_encoding.
If
from_encoding is omitted or ENTITY, the mbstring.internal_encoding setting will be used if set, otherwise the default_charset setting.
See supported encodings for valid values of
to_encoding and
from_encoding.
ENTITY
The encoded ENTITY or ENTITY on success, ENTITY.
ENTITY
As of PHP 8.0.0, a
ValueError is thrown if the value of
to_encoding or
from_encoding is an invalid encoding. Prior to PHP 8.0.0, a
E_WARNING was emitted instead.
ENTITY
ENTITY
ENTITY
8.2.0
mb_convert_encoding will no longer return the following non text encodings:
"Base64",
"QPrint",
"UUencode",
"HTML entities",
"7 bit" and
"8 bit".
8.0.0
mb_convert_encoding will now throw a
ValueError when
to_encoding is passed an invalid encoding.
8.0.0
mb_convert_encoding will now throw a
ValueError when
from_encoding is passed an invalid encoding.
8.0.0
from_encoding is nullable now.
7.2.0
This function now also accepts an ENTITY as
string. Formerly, only ENTITYs have been supported.
ENTITY
mb_convert_encoding example
ENTITY
mb_detect_order, UConverter::transcode,
iconv
mb-convert-kana
mb_convert_kana
Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
ENTITY
string
mb_convert_kana
string
string
string
mode
"KV"
string
null
encoding
ENTITY
Performs a "han-kaku" - "zen-kaku" conversion for
string
string. This function is only useful for Japanese.
ENTITY
string
The
string being converted.
mode
The conversion option.
Specify with a combination of following 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"
Applicable Conversion Options
encoding
ENTITY
ENTITY
The converted
string.
ENTITY
Throws a
ValueError if the combination of different
modes is invalid. For example
"sS".
ENTITY
ENTITY
ENTITY
ENTITY
8.2.0
A
ValueError is now thrown if the combination of different
modes is invalid.
ENTITY
mb_convert_kana example
ENTITY
やまだ はなこ
コウザバンゴウ 0123456
mb-convert-variables
mb_convert_variables
Convert character code in variable(s)
ENTITY
string
false
mb_convert_variables
string
to_encoding
array
string
from_encoding
mixed
var
mixed
vars
Converts character encoding of variables
var and
vars in encoding
from_encoding to encoding
to_encoding.
mb_convert_variables join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.
ENTITY
to_encoding
The encoding that the
string is being converted to.
from_encoding
The current encoding of the variables. Multiple encodings may be specified as an
array or comma separated
string, in which case the encoding is detected among the listed encodings.
"auto" is expanded according to the mbstring.language INI setting.
var
var is the reference to the variable being converted. String, Array and Object are accepted.
mb_convert_variables assumes all parameters have the same encoding.
vars
Additional
vars.
ENTITY
The character encoding before conversion for success, or ENTITY for failure.
ENTITY
mb_convert_variables example
mb-decode-mimeheader
mb_decode_mimeheader
Decode string in MIME header field
ENTITY
string
mb_decode_mimeheader
string
string
Decodes encoded-word
string
string in MIME header.
ENTITY
string
The
string being decoded.
ENTITY
The decoded
string in internal character encoding.
ENTITY
ENTITY
ENTITY
8.3.0
Underscores are converted to spaces as specified by RFC 2047.
ENTITY
mb_encode_mimeheader
mb-decode-numericentity
mb_decode_numericentity
Decode HTML numeric string reference to character
ENTITY
string
mb_decode_numericentity
string
string
array
map
string
null
encoding
ENTITY
Convert numeric string reference of
string
string in a specified block to character.
ENTITY
string
The
string being decoded.
map
map is an
array that specifies the code area to convert.
encoding
ENTITY
ENTITY
The converted
string.
ENTITY
Throws a ValueError if
map contains any value that is not an ENTITY, ENTITY, ENTITY, ENTITY, or a numeric string.
ENTITY
ENTITY
ENTITY
ENTITY
8.4.0
The
mb_decode_numericentity function now throws a ValueError if
map contains any value that cannot be implicitly converted to int.
ENTITY
map example
map example escapes JavaScript string
ENTITY
mb_encode_numericentity
mb-detect-encoding
mb_detect_encoding
Detect character encoding
ENTITY
string
false
mb_detect_encoding
string
string
array
string
null
encodings
ENTITY
bool
strict
ENTITY
Detects the most likely character encoding for
string
string from a list of candidates.
As of PHP 8.1 this function uses heuristics to detect which of the valid text encodings in the specified list is most likely to be correct and may not be in order of
encodings provided.
Automatic detection of the intended character encoding can never be entirely reliable; without some additional information, it is similar to decoding an encrypted string without the key. It is always preferable to use an indication of character encoding stored or transmitted with the data, such as a "Content-Type" HTTP header.
This function is most useful with multibyte encodings, where not all sequences of bytes form a valid string. If the input string contains such a sequence, that encoding will be rejected.
[!WARNING]
The name of this function is misleading, it performs "guessing" rather than "detection".
The guesses are far from accurate, and therefore you cannot use this function to accurately detect the correct character encoding.
ENTITY
string
The
string being inspected.
encodings
A list of character encodings to try. The list may be specified as an array of strings, or a single string separated by commas.
If
encodings is omitted or ENTITY, the current detect_order (set with the mbstring.detect_order configuration option, or
mb_detect_order function) will be used.
strict
Controls the behaviour when
string is not valid in any of the listed
encodings. If
strict is set to ENTITY, the closest matching encoding will be returned; if
strict is set to ENTITY, ENTITY will be returned.
The default value for
strict can be set with the mbstring.strict_detection configuration option.
ENTITY
The detected character encoding, or ENTITY if the string is not valid in any of the listed encodings.
ENTITY
ENTITY
ENTITY
8.2.0
mb_detect_encoding will no longer return the following non text encodings:
"Base64",
"QPrint",
"UUencode",
"HTML entities",
"7 bit" and
"8 bit".
ENTITY
mb_detect_encoding example
ENTITY
string(5) "ASCII"
string(5) "ASCII"
string(8) "SJIS-win"
string(5) "ASCII"
Effect of
strict parameter
ENTITY
string(5) "UTF-8"
bool(false)
string(10) "ISO-8859-1"
string(10) "ISO-8859-1"
In some cases, the same sequence of bytes may form a valid string in multiple character encodings, and it is impossible to know which interpretation was intended. For instance, among many others, the byte sequence "\xC4\xA2" could be:
"Ä¢" (U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS followed by U+00A2 CENT SIGN) encoded in any of ISO-8859-1, ISO-8859-15, or Windows-1252, "ФЂ" (U+0424 CYRILLIC CAPITAL LETTER EF followed by U+0402 CYRILLIC CAPITAL LETTER DJE) encoded in ISO-8859-5, "Ģ" (U+0122 LATIN CAPITAL LETTER G WITH CEDILLA) encoded in UTF-8
Effect of order when multiple encodings match
ENTITY
string(5) "UTF-8"
string(10) "ISO-8859-1"
string(10) "ISO-8859-1"
string(10) "ISO-8859-5"
ENTITY
mb_detect_order
mb-detect-order
mb_detect_order
Set/Get character encoding detection order
ENTITY
array
bool
mb_detect_order
array
string
null
encoding
ENTITY
Sets the automatic character encoding detection order to
encoding.
ENTITY
encoding
encoding is an
array or comma separated list of character encoding. See supported encodings.
If
encoding is omitted or ENTITY, 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.
ENTITY
When setting the encoding detection order, ENTITY is returned on success or ENTITY on failure.
When getting the encoding detection order, an ordered array of the encodings is returned.
ENTITY
ENTITY
ENTITY
ENTITY
mb_detect_order examples
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
ENTITY
mb_internal_encoding,
mb_http_input,
mb_http_output,
mb_send_mail
mb-encode-mimeheader
mb_encode_mimeheader
Encode string for MIME header
ENTITY
string
mb_encode_mimeheader
string
string
string
null
charset
ENTITY
string
null
transfer_encoding
ENTITY
string
newline
"\r\n"
int
indent
0
Encodes a given
string
string by the MIME header encoding scheme.
ENTITY
string
The
string being encoded. Its encoding should be same as
mb_internal_encoding.
charset
charset specifies the name of the character set in which
string is represented in. The default value is determined by the current NLS setting (
mbstring.language).
transfer_encoding
transfer_encoding specifies the scheme of MIME encoding. It should be either
"B" (Base64) or
"Q" (Quoted-Printable). Falls back to
"B" if not given.
newline
newline specifies the EOL (end-of-line) marker with which
mb_encode_mimeheader performs line-folding (a RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to
"\r\n" (CRLF) if not given.
indent
Indentation of the first line (number of characters in the header before
string).
ENTITY
A converted version of the
string represented in ASCII.
ENTITY
ENTITY
ENTITY
8.3.0
NUL (0) bytes are no longer dropped when encoded using Quoted-Printable encoding, but encoded as
=00.
8.0.0
charset and
transfer_encoding are nullable now.
ENTITY
mb_encode_mimeheader example
";
echo $addr;
?>
ENTITY
"=?UTF-7?Q?+WSqQzg-?="
ENTITY
[!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.
ENTITY
mb_decode_mimeheader
mb-encode-numericentity
mb_encode_numericentity
Encode character to HTML numeric string reference
ENTITY
string
mb_encode_numericentity
string
string
array
map
string
null
encoding
ENTITY
bool
hex
ENTITY
Converts specified character codes in
string
string from character code to HTML numeric character reference.
ENTITY
string
The
string being encoded.
map
map is array specifies code area to convert.
encoding
ENTITY
hex
Whether the returned entity reference should be in hexadecimal notation (otherwise it is in decimal notation).
ENTITY
The converted
string.
ENTITY
Throws a ValueError if
map contains any value that is not an ENTITY, ENTITY, ENTITY, ENTITY, or a numeric string.
ENTITY
ENTITY
ENTITY
ENTITY
8.4.0
The
mb_encode_numericentity function now throws a ValueError if
map contains any value that cannot be implicitly converted to int.
ENTITY
map example
mb_encode_numericentity example
ENTITY
string(46) "aAæÆあア鸽"
string(28) "aAæÆあア鸽"
ENTITY
mb_decode_numericentity
mb-encoding-aliases
mb_encoding_aliases
Get aliases of a known encoding type
ENTITY
array
mb_encoding_aliases
string
encoding
Returns an array of aliases for a known
encoding type.
ENTITY
encoding
The encoding type being checked, for aliases.
ENTITY
Returns a numerically indexed array of encoding aliases.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_encoding_aliases example
ENTITY
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
)
ENTITY
mb_list_encodings
mb-ereg-match
mb_ereg_match
Regular expression match for multibyte string
ENTITY
bool
mb_ereg_match
string
pattern
string
string
string
null
options
ENTITY
A regular expression match for a multibyte string
[!NOTE]
pattern is only matched at the beginning of
string.
ENTITY
pattern
The regular expression pattern.
string
The
string being evaluated.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
Returns ENTITY if
string matches the regular expression
pattern, ENTITY if not.
ENTITY
ENTITY
ENTITY
8.0.0
options is nullable now.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg
mb-ereg-replace-callback
mb_ereg_replace_callback
Perform a regular expression search and replace with multibyte support using a callback
ENTITY
string
false
null
mb_ereg_replace_callback
string
pattern
callable
callback
string
string
string
null
options
ENTITY
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.
ENTITY
pattern
The regular expression pattern.
Multibyte characters may be used in
pattern.
callback
A callback that will be called and passed an array of matched elements in the
string string. The callback should return the replacement string.
You'll often need the
callback function for a
mb_ereg_replace_callback in just one place. In this case you can use an anonymous function to declare the callback within the call to
mb_ereg_replace_callback. By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else.
string
The
string being checked.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
The resultant
string on success, or ENTITY on error. If
string is not valid for the current encoding, ENTITY is returned.
ENTITY
ENTITY
ENTITY
8.0.0
options is nullable now.
7.1.0
The function checks whether
string is valid for the current encoding.
ENTITY
mb_ereg_replace_callback example
ENTITY
April fools day is 04/01/2003
Last christmas was 12/24/2002
mb_ereg_replace_callback using anonymous function
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_replace, Anonymous functions
mb-ereg-replace
mb_ereg_replace
Replace regular expression with multibyte support
ENTITY
string
false
null
mb_ereg_replace
string
pattern
string
replacement
string
string
string
null
options
ENTITY
Scans
string for matches to
pattern, then replaces the matched text with
replacement
ENTITY
pattern
The regular expression pattern.
Multibyte characters may be used in
pattern.
replacement
The replacement text.
string
The
string being checked.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
The resultant
string on success, or ENTITY on error. If
string is not valid for the current encoding, ENTITY is returned.
ENTITY
ENTITY
ENTITY
8.0.0
options is nullable now.
7.1.0
The function checks whether
string is valid for the current encoding.
7.1.0
The
e modifier has been deprecated.
ENTITY ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_eregi_replace
mb-ereg-search-getpos
mb_ereg_search_getpos
Returns start point for next regular expression match
ENTITY
int
mb_ereg_search_getpos
Returns the start point for the next regular expression match.
ENTITY ENTITY
ENTITY
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.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_search_setpos
mb-ereg-search-getregs
mb_ereg_search_getregs
Retrieve the result from the last multibyte regular expression match
ENTITY
array
false
mb_ereg_search_getregs
Retrieve the result from the last multibyte regular expression match
ENTITY ENTITY
ENTITY
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 ENTITY on error.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_search_init
mb-ereg-search-init
mb_ereg_search_init
Setup string and regular expression for a multibyte regular expression match
ENTITY
bool
mb_ereg_search_init
string
string
string
null
pattern
ENTITY
string
null
options
ENTITY
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.
ENTITY
string
The search string.
pattern
The search pattern.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.0.0
pattern and
options are nullable now.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_search_regs
mb-ereg-search-pos
mb_ereg_search_pos
Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
ENTITY
array
false
mb_ereg_search_pos
string
null
pattern
ENTITY
string
null
options
ENTITY
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.
ENTITY
pattern
The search pattern.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
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, ENTITY is returned.
ENTITY
ENTITY
ENTITY
8.0.0
pattern and
options are nullable now.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_search_init
mb-ereg-search-regs
mb_ereg_search_regs
Returns the matched part of a multibyte regular expression
ENTITY
array
false
mb_ereg_search_regs
string
null
pattern
ENTITY
string
null
options
ENTITY
Returns the matched part of a multibyte regular expression.
ENTITY
pattern
The search pattern.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
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 ENTITY on error.
ENTITY
ENTITY
ENTITY
8.0.0
pattern and
options are nullable now.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_search_init
mb-ereg-search-setpos
mb_ereg_search_setpos
Set start point of next regular expression match
ENTITY
bool
mb_ereg_search_setpos
int
offset
mb_ereg_search_setpos sets the starting point of a match for
mb_ereg_search.
ENTITY
offset
The position to set. If it is negative, it counts from the end of the string.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
7.1.0
Support for negative
offsets has been added.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_search_init
mb-ereg-search
mb_ereg_search
Multibyte regular expression match for predefined multibyte string
ENTITY
bool
mb_ereg_search
string
null
pattern
ENTITY
string
null
options
ENTITY
Performs a multibyte regular expression match for a predefined multibyte string.
ENTITY
pattern
The search pattern.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
mb_ereg_search returns ENTITY if the multibyte string matches with the regular expression, or ENTITY otherwise. The
string for matching is set by
mb_ereg_search_init. If
pattern is not specified, the previous one is used.
ENTITY
ENTITY
ENTITY
8.0.0
pattern and
options are nullable now.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_search_init
mb-ereg
mb_ereg
Regular expression match with multibyte support
ENTITY
bool
mb_ereg
string
pattern
string
string
array
matches
ENTITY
Executes the regular expression match with multibyte support.
ENTITY
pattern
The search pattern.
string
The search
string.
matches
If matches are found for parenthesized substrings of
pattern and the function is called with the third argument
matches, the matches will be stored in the elements of the array
matches. If no matches are found,
matches is set to an empty array.
$matches[1] will contain the substring which starts at the first left parenthesis;
$matches[2] will contain the substring starting at the second, and so on.
$matches[0] will contain a copy of the complete string matched.
ENTITY
Returns whether
pattern matches
string.
ENTITY
ENTITY
ENTITY
8.0.0
This function returns ENTITY on success now. Previously, it returned the byte length of the matched string if a match for
pattern was found in
string and
matches was passed. If the optional parameter
matches was not passed or the length of the matched string was
0, this function returned
1.
7.1.0
mb_ereg will now set
matches to an empty
array, if nothing matched. Formerly,
matches was not modified in that case.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_eregi
mb-eregi-replace
mb_eregi_replace
Replace regular expression with multibyte support ignoring case
ENTITY
string
false
null
mb_eregi_replace
string
pattern
string
replacement
string
string
string
null
options
ENTITY
Scans
string for matches to
pattern, then replaces the matched text with
replacement.
ENTITY
pattern
The regular expression pattern. Multibyte characters may be used. The case will be ignored.
replacement
The replacement text.
string
The searched
string.
options
The search option. See
mb_regex_set_options for explanation.
ENTITY
The resultant
string or ENTITY on error. If
string is not valid for the current encoding, ENTITY is returned.
ENTITY
ENTITY
ENTITY
8.0.0
options is nullable now.
7.1.0
The function checks whether
string is valid for the current encoding.
7.1.0
The
e modifier has been deprecated.
ENTITY ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg_replace
mb-eregi
mb_eregi
Regular expression match ignoring case with multibyte support
ENTITY
bool
mb_eregi
string
pattern
string
string
array
matches
ENTITY
Executes the case insensitive regular expression match with multibyte support.
ENTITY
pattern
The regular expression pattern.
string
The
string being searched.
matches
If matches are found for parenthesized substrings of
pattern and the function is called with the third argument
matches, the matches will be stored in the elements of the array
matches. If no matches are found,
matches is set to an empty array.
$matches[1] will contain the substring which starts at the first left parenthesis;
$matches[2] will contain the substring starting at the second, and so on.
$matches[0] will contain a copy of the complete string matched.
ENTITY
Returns whether
pattern matches
string.
ENTITY
ENTITY
ENTITY
8.0.0
This function returns ENTITY on success now. Previously, it returned the byte length of the matched string if a match for
pattern was found in
string and
matches was passed. If the optional parameter
matches was not passed or the length of the matched string was
0, this function returned
1.
7.1.0
mb_eregi will now set
matches to an empty
array, if nothing matched. Formerly,
matches was not modified in that case.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg
mb-get-info
mb_get_info
Get internal settings of mbstring
ENTITY
array
string
int
false
null
mb_get_info
string
type
"all"
mb_get_info returns the internal setting parameters of mbstring.
ENTITY
type
If
type is not specified or is specified as
"all",
"internal_encoding",
"http_input",
"http_output",
"http_output_conv_mimetypes",
"mail_charset",
"mail_header_encoding",
"mail_body_encoding",
"illegal_chars",
"encoding_translation",
"language",
"detect_order",
"substitute_character" and
"strict_detection" will be returned.
If
type is specified as
"internal_encoding",
"http_input",
"http_output",
"http_output_conv_mimetypes",
"mail_charset",
"mail_header_encoding",
"mail_body_encoding",
"illegal_chars",
"encoding_translation",
"language",
"detect_order",
"substitute_character" or
"strict_detection" the specified setting parameter will be returned.
ENTITY
An
array of type information if
type is not specified, otherwise a specific
type, ENTITY.
ENTITY
ENTITY
ENTITY
8.0.0
The
types
"func_overload" and
"func_overload_list" are no longer supported.
ENTITY
mb_regex_encoding,
mb_http_output
mb-http-input
mb_http_input
Detect HTTP input character encoding
ENTITY
array
string
false
mb_http_input
string
null
type
ENTITY
Detects the HTTP input character encoding.
ENTITY
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.
ENTITY
The character encoding name, as per the
type, or an array of character encoding names, if
type is
"I". If
mb_http_input does not process specified HTTP input, it returns ENTITY.
ENTITY
Throws a ValueError if
type is invalid.
ENTITY
ENTITY
ENTITY
8.0.0
mb_http_input now throws a ValueError if
type is invalid.
type is nullable now.
ENTITY
mb_internal_encoding,
mb_http_output,
mb_detect_order
mb-http-output
mb_http_output
Set/Get HTTP output character encoding
ENTITY
string
bool
mb_http_output
string
null
encoding
ENTITY
Set/Get the HTTP output character encoding. Output after this function is called will be converted from the set internal encoding to
encoding.
ENTITY
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.
ENTITY
If
encoding is omitted,
mb_http_output returns the current HTTP output character encoding. Otherwise, ENTITY
ENTITY
Throws a ValueError if
encoding contains null bytes.
ENTITY
ENTITY
ENTITY
ENTITY
8.4.0
mb_http_output now throws a ValueError if
encoding contains null bytes.
ENTITY
mb_internal_encoding,
mb_http_input,
mb_detect_order
mb-internal-encoding
mb_internal_encoding
Set/Get internal character encoding
ENTITY
string
bool
mb_internal_encoding
string
null
encoding
ENTITY
Set/Get the internal character encoding
ENTITY
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.
ENTITY
If
encoding is set, then ENTITY In this case, the character encoding for multibyte regex is NOT changed. If
encoding is omitted, then the current character encoding name is returned.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_internal_encoding example
ENTITY
mb_http_input,
mb_http_output,
mb_detect_order,
mb_regex_encoding
mb-language
mb_language
Set/Get current language
ENTITY
string
bool
mb_language
string
null
language
ENTITY
Set/Get the current language.
ENTITY
language
Used for encoding e-mail messages. The valid languages are listed in the following table.
mb_send_mail uses this setting to encode e-mail.
Language
Charset
Encoding
Alias
German/de
ISO-8859-15
Quoted-Printable
Deutsch
English/en
ISO-8859-1
Quoted-Printable
Armenian/hy
ArmSCII-8
Quoted-Printable
Japanese/ja
ISO-2022-JP
BASE64
Korean/ko
ISO-2022-KR
BASE64
neutral
UTF-8
BASE64
Russian/ru
KOI8-R
Quoted-Printable
Turkish/tr
ISO-8859-9
Quoted-Printable
Ukrainian/ua
KOI8-U
Quoted-Printable
uni
UTF-8
BASE64
universal
Simplified Chinese/zh-cn
HZ
BASE64
Traditional Chinese/zh-tw
BIG-5
BASE64
ENTITY
If
language is set and
language is valid, it returns ENTITY. Otherwise, it returns ENTITY. When
language is omitted or ENTITY, it returns the language name as a
string.
ENTITY
ENTITY
ENTITY
8.0.0
language is nullable now.
ENTITY
mb_send_mail
mb-lcfirst
mb_lcfirst
Make a string's first character lowercase
ENTITY
string
mb_lcfirst
string
string
string
null
encoding
ENTITY
Performs a multi-byte safe
lcfirst operation, and returns a string with the first character of
string lowercased.
ENTITY
string
The input string.
encoding
ENTITY
ENTITY
Returns the resulting string.
ENTITY
mb_ucfirst
lcfirst
mb-list-encodings
mb_list_encodings
Returns an array of all supported encodings
ENTITY
array
mb_list_encodings
Returns an array containing all supported encodings.
ENTITY ENTITY
ENTITY
Returns a numerically indexed array.
ENTITY
This function does not emit any errors.
ENTITY
mb_list_encodings example
ENTITY
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
)
ENTITY
mb_encoding_aliases
mb-ltrim
mb_ltrim
Strip whitespace (or other characters) from the beginning of a string
ENTITY
string
mb_ltrim
string
string
string
null
characters
ENTITY
string
null
encoding
ENTITY
Performs a multi-byte safe
ltrim operation. Strip whitespace (or other characters) from the beginning of a string.
Without the second parameter,
mb_ltrim will strip these characters:
ENTITY
ENTITY
string
The input string.
characters
ENTITY
encoding
ENTITY
ENTITY
This function returns a string with whitespace stripped from the beginning of
string.
ENTITY
mb_trim
mb_rtrim
ltrim
mb-ord
mb_ord
Get Unicode code point of character
ENTITY
int
false
mb_ord
string
string
string
null
encoding
ENTITY
Returns the Unicode code point value of the given character.
This function complements
mb_chr.
ENTITY
string
A string
encoding
ENTITY
ENTITY
The Unicode code point for the first character of
string ENTITY.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
A basic
mb_ord example
ENTITY
int(65)
int(128024)
int(128)
int(8364)
ENTITY
mb_internal_encoding,
mb_chr,
IntlChar::ord,
ord
mb-output-handler
mb_output_handler
Callback function converts character encoding in output buffer
ENTITY
string
mb_output_handler
string
string
int
status
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.
ENTITY
string
The contents of the output buffer.
status
The status of the output buffer.
ENTITY
The converted
string.
ENTITY
mb_output_handler example
ENTITY
[!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.
ENTITY
ob_start
mb-parse-str
mb_parse_str
Parse GET/POST/COOKIE data and set global variable
ENTITY
bool
mb_parse_str
string
string
array
result
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.
ENTITY
string
The URL encoded data.
result
An
array containing decoded and character encoded converted values.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.0.0
The second parameter was no longer optional.
7.2.0
Calling
mb_parse_str without the second parameter was deprecated.
ENTITY
mb_detect_order,
mb_internal_encoding
mb-preferred-mime-name
mb_preferred_mime_name
Get MIME charset string
ENTITY
string
false
mb_preferred_mime_name
string
encoding
Get a MIME charset
string for a specific encoding.
ENTITY
encoding
The encoding being checked.
ENTITY
The MIME
charset
string for character encoding
encoding, or ENTITY if no charset is preferred for the given
encoding.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_preferred_mime_name example
mb-regex-encoding
mb_regex_encoding
Set/Get character encoding for multibyte regex
ENTITY
string
bool
mb_regex_encoding
string
null
encoding
ENTITY
Set/Get character encoding for a multibyte regex.
ENTITY
encoding
ENTITY
ENTITY
If
encoding is set, then ENTITY 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.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_internal_encoding,
mb_ereg
mb-regex-set-options
mb_regex_set_options
Set/Get the default options for mbregex functions
ENTITY
string
mb_regex_set_options
string
null
options
ENTITY
Sets the default options described by
options for multibyte regex functions.
ENTITY
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.
Option
Meaning
ENTITY
i
Ambiguity match on
x
Enables extended pattern form
m
'.' matches with newlines
s
'^' ->
'\A',
'$' ->
'\Z'
p
Same as both the
m and
s options
l
Finds longest matches
n
Ignores empty matches
e
eval resulting code
Deprecated as of PHP 7.1.0 and removed as of PHP 8.0.0
Regex options
[!NOTE]
The
"e" option has no effect when set through
mb_regex_set_options. Use it with
mb_ereg_replace or
mb_eregi_replace.
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
Regex syntax modes (only one may be set)
ENTITY
The previous options. If
options is omitted or ENTITY, it returns the
string that describes the current options.
ENTITY
ENTITY
ENTITY
8.0.0
If the parameter
options is given and not ENTITY, the previous options are returned. Formerly, the current options have been returned.
8.0.0
options is nullable now.
8.0.0
The
"e" option now throws a
ValueError.
7.1.0
The
"e" option now emits an
E_DEPRECATED.
ENTITY
mb_split,
mb_ereg,
mb_eregi
mb-rtrim
mb_rtrim
Strip whitespace (or other characters) from the end of a string
ENTITY
string
mb_rtrim
string
string
string
null
characters
ENTITY
string
null
encoding
ENTITY
Performs a multi-byte safe
rtrim operation, and returns a string with whitespace (or other characters) stripped from the end of
string.
Without the second parameter,
mb_rtrim will strip these characters:
ENTITY
ENTITY
string
The input string.
characters
ENTITY
encoding
ENTITY
ENTITY
Returns the modified string.
ENTITY
mb_trim
mb_ltrim
rtrim
mb-scrub
mb_scrub
Replace ill-formed byte sequences with the substitute character
ENTITY
string
mb_scrub
string
string
string
null
encoding
ENTITY
Perform a character set conversion from the specified encoding, or the default encoding if no encoding was specified, to the same encoding. This has the effect of replacing any invalid byte sequences with the substitute character.
ENTITY
string
The input string.
encoding
The encoding used to interpret
string. If it is omitted or ENTITY, the mbstring.internal_encoding setting will be used if set, otherwise the default_charset setting will be used.
ENTITY
The ENTITY result with invalid byte sequences replaced.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
Byte-level replacement performed by
mb_scrub
bin2hex is used here because terminals, browsers and fonts may render an ill-formed byte sequence with a replacement character of their own, which hides what the string actually contains.
ENTITY
41ff42
413f42
41efbfbd42
Using
mb_scrub before UTF-8 aware processing
PCRE patterns using the
u modifier reject subjects that are not well-formed UTF-8. Scrubbing the input first makes it acceptable.
ENTITY
bool(false)
Malformed UTF-8 characters, possibly incorrectly encoded
int(3)
ENTITY
mb_substitute_character
mb_check_encoding
mb_convert_encoding
mb-send-mail
mb_send_mail
Send encoded mail
ENTITY
bool
mb_send_mail
string
to
string
subject
string
message
array
string
additional_headers
[]
string
null
additional_params
ENTITY
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.
ENTITY
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 ENTITY.
Failing to do this will result in an error message similar to
Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. The
From header sets also
Return-Path under Windows.
[!NOTE]
If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with RFC 2822.
additional_params
additional_params is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.
This parameter is escaped by
escapeshellcmd internally to prevent command execution.
escapeshellcmd prevents command execution, but allows to add additional parameters. For security reason, this parameter should be validated.
Since
escapeshellcmd is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. Programs that are required to use these characters
mail cannot be used.
The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is
/etc/mail/trusted-users.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.0.0
additional_params is nullable now.
7.2.0
The
additional_headers parameter now also accepts an
array.
ENTITY
mail,
mb_encode_mimeheader,
mb_language
mb-split
mb_split
Split multibyte string using regular expression
ENTITY
array
false
mb_split
string
pattern
string
string
int
limit
-1
Split a multibyte
string using regular expression
pattern and returns the result as an
array.
ENTITY
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.
ENTITY
The result as an
array, ENTITY.
ENTITY ENTITY
ENTITY
mb_regex_encoding,
mb_ereg,
explode
mb-str-pad
mb_str_pad
Pad a multibyte string to a certain length with another multibyte string
ENTITY
string
mb_str_pad
string
string
int
length
string
pad_string
" "
int
pad_type
STR_PAD_RIGHT
string
null
encoding
ENTITY
This function returns the
string padded on the left, the right, or both sides to the specified padding length, where the length is measured in Unicode codepoints. If the optional argument
pad_string is not supplied, the
string is padded with spaces, otherwise it is padded with characters from
pad_string up to the limit.
ENTITY
string
The input string.
length
If the value of
length is negative, less than, or equal to the length of the input string, no padding takes place, and
string will be returned.
pad_string
[!NOTE]
The
pad_string may be truncated if the required number of padding characters can't be evenly divided by the
pad_string's length.
pad_type
Optional argument
pad_type can be
STR_PAD_RIGHT,
STR_PAD_LEFT, or
STR_PAD_BOTH. By default
STR_PAD_RIGHT.
encoding
ENTITY
ENTITY
Returns the padded string.
ENTITY
mb_str_pad example
mb-str-split
mb_str_split
Given a multibyte string, return an array of its characters
ENTITY
array
mb_str_split
string
string
int
length
1
string
null
encoding
ENTITY
This function will return an array of strings, it is a version of
str_split with support for encodings of variable character size as well as fixed-size encodings of 1,2 or 4 byte characters. If the
length parameter is specified, the string is broken down into chunks of the specified length in characters (not bytes). The
encoding parameter can be optionally specified and it is good practice to do so.
ENTITY
string
The ENTITY to split into characters or chunks.
length
If specified, each element of the returned array will be composed of multiple characters instead of a single character.
encoding
ENTITY
A string specifying one of the supported encodings.
ENTITY
mb_str_split returns an array of strings.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.0.0
This function no longer returns ENTITY on failure.
ENTITY
str_split,
grapheme_str_split,
explode
mb-strcut
mb_strcut
Get part of string
ENTITY
string
mb_strcut
string
string
int
start
int
null
length
ENTITY
string
null
encoding
ENTITY
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.
ENTITY
string
The
string being cut.
start
If
start is non-negative, the returned string will start at the
start'th byte position in
string, counting from zero. For instance, in the string '
abcdef', the byte at position
0 is '
a', the byte at position
2 is '
c', and so forth.
If
start is negative, the returned string will start at the
start'th byte counting back from the end of
string. However, if the magnitude of a negative
start is greater than the length of the string, the returned portion will start from the beginning of
string.
length
Length in bytes. If omitted or ENTITY is passed, extract all bytes to the end of the string.
If
length is negative, the returned string will end at the
length'th byte counting back from the end of
string. However, if the magnitude of a negative
length is greater than the number of characters after the
start position, an empty string will be returned.
encoding
ENTITY
ENTITY
mb_strcut returns the portion of
string specified by the
start and
length parameters.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.4.0
The behavior is more consistent now on invalid
UTF-8 and
UTF-16 strings.
ENTITY
mb_substr,
mb_internal_encoding
mb-strimwidth
mb_strimwidth
Get truncated string with specified width
ENTITY
string
mb_strimwidth
string
string
int
start
int
width
string
trim_marker
""
string
null
encoding
ENTITY
Truncates
string
string to specified
width, where halfwidth characters count as
1, and fullwidth characters count as
2. See ENTITY11/ for details regarding East Asian character widths.
ENTITY
string
The
string being decoded.
start
The start position offset. Number of characters from the beginning of string (first character is 0), or if start is negative, number of characters from the end of the string.
width
The width of the desired trim. If negative width is specified, count from the end of the string.
[!NOTE]
Passing negative width is deprecated as of PHP 8.3.0.
trim_marker
A string that is added to the end of string when string is truncated.
encoding
ENTITY
ENTITY
The truncated
string. If
trim_marker is set,
trim_marker replaces the last chars to match the
width.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.3.0
Passing a negative
width to
mb_strimwidth is now deprecated.
7.1.0
Support for negative
starts and
widths has been added.
ENTITY
mb_strimwidth example
ENTITY
mb_strwidth,
mb_internal_encoding
mb-stripos
mb_stripos
Finds position of first occurrence of a string within another, case insensitive
ENTITY
int
false
mb_stripos
string
haystack
string
needle
int
offset
0
string
null
encoding
ENTITY
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 ENTITY.
ENTITY
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
ENTITY
ENTITY
Return the numeric position of the first occurrence of
needle in the
haystack string, or ENTITY if
needle is not found.
ENTITY
If
offset is greater than the length of
haystack, a
ValueError will be thrown.
ENTITY
ENTITY
ENTITY
ENTITY
7.1.0
Support for negative
offsets has been added.
ENTITY
stripos,
strpos,
mb_strpos
mb-stristr
mb_stristr
Finds first occurrence of a string within another, case insensitive
ENTITY
string
false
mb_stristr
string
haystack
string
needle
bool
before_needle
ENTITY
string
null
encoding
ENTITY
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 ENTITY.
ENTITY
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 ENTITY, it returns all of
haystack from the beginning to the first occurrence of
needle (excluding needle). If set to ENTITY, it returns all of
haystack from the first occurrence of
needle to the end (including needle).
encoding
ENTITY
ENTITY
Returns the portion of
haystack, or ENTITY if
needle is not found.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
stristr,
strstr,
mb_strstr
mb-strlen
mb_strlen
Get string length
ENTITY
int
mb_strlen
string
string
string
null
encoding
ENTITY
Gets the length of a
string.
ENTITY
string
The
string being checked for length.
encoding
ENTITY
ENTITY
Returns the number of characters in
string
string having character encoding
encoding. A multi-byte character is counted as 1.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_internal_encoding,
grapheme_strlen,
iconv_strlen,
strlen
mb-strpos
mb_strpos
Find position of first occurrence of string in a string
ENTITY
int
false
mb_strpos
string
haystack
string
needle
int
offset
0
string
null
encoding
ENTITY
Finds position of the first occurrence of
needle in the
haystack string.
Performs a multi-byte safe
strpos operation based on number of characters. The first character's position is 0, the second character position is 1, and so on.
ENTITY
haystack
The string from which to get the position of the first occurrence of
needle.
needle
The string to find in
haystack. In contrast with
strpos, numeric values are not applied as the ordinal value of a character.
offset
The search offset in characters. If it is not specified, 0 is used. A negative offset counts from the end of the string.
encoding
ENTITY
ENTITY
Returns the character position (not byte position) of the first occurrence of
needle in the
haystack
string, counting from
0. Returns ENTITY if
needle is not found.
ENTITY
If
offset is greater than the length of
haystack, a
ValueError will be thrown.
ENTITY
ENTITY
ENTITY
ENTITY
7.1.0
Support for negative
offsets has been added.
ENTITY
mb_strpos returns a character offset, not a byte offset
ENTITY
int(3)
int(2)
ENTITY
mb_strrpos,
mb_stripos,
mb_internal_encoding,
strpos
mb-strrchr
mb_strrchr
Finds the last occurrence of a character in a string within another
ENTITY
string
false
mb_strrchr
string
haystack
string
needle
bool
before_needle
ENTITY
string
null
encoding
ENTITY
mb_strrchr finds the last occurrence of
needle in
haystack and returns the portion of
haystack. If
needle is not found, it returns ENTITY.
ENTITY
haystack
The string from which to get the last occurrence of
needle.
needle
The string to find in
haystack.
before_needle
Determines which portion of
haystack this function returns. If set to ENTITY, it returns all of
haystack from the beginning to the last occurrence of
needle. If set to ENTITY, it returns all of
haystack from the last occurrence of
needle to the end.
encoding
ENTITY
ENTITY
Returns the portion of
haystack. or ENTITY if
needle is not found.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
strrchr,
mb_strstr,
mb_strrichr
mb-strrichr
mb_strrichr
Finds the last occurrence of a character in a string within another, case insensitive
ENTITY
string
false
mb_strrichr
string
haystack
string
needle
bool
before_needle
ENTITY
string
null
encoding
ENTITY
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 ENTITY.
ENTITY
haystack
The string from which to get the last occurrence of
needle.
needle
The string to find in
haystack.
before_needle
Determines which portion of
haystack this function returns. If set to ENTITY, it returns all of
haystack from the beginning to the last occurrence of
needle. If set to ENTITY, it returns all of
haystack from the last occurrence of
needle to the end.
encoding
ENTITY
ENTITY
Returns the portion of
haystack. or ENTITY if
needle is not found.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_stristr,
mb_strrchr
mb-strripos
mb_strripos
Finds position of last occurrence of a string within another, case insensitive
ENTITY
int
false
mb_strripos
string
haystack
string
needle
int
offset
0
string
null
encoding
ENTITY
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.
ENTITY
haystack
The string from which to get the position of the last occurrence of
needle.
needle
The string to find in
haystack.
offset
May be specified to begin searching an arbitrary number of characters into the
haystack. Negative values will stop searching at an arbitrary point prior to the end of the
haystack.
encoding
ENTITY
ENTITY
Return the numeric position of the last occurrence of
needle in the
haystack string, or ENTITY if
needle is not found.
ENTITY
If
offset is greater than the length of
haystack, a
ValueError will be thrown.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
strripos,
strrpos,
mb_strrpos
mb-strrpos
mb_strrpos
Find position of last occurrence of a string in a string
ENTITY
int
false
mb_strrpos
string
haystack
string
needle
int
offset
0
string
null
encoding
ENTITY
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.
ENTITY
haystack
The
string being checked, for the last occurrence of
needle
needle
The
string to find in
haystack.
offset
May be specified to begin searching an arbitrary number of characters into the
haystack. Negative values will stop searching at an arbitrary point prior to the end of the
haystack.
encoding
ENTITY
ENTITY
Returns the numeric position of the last occurrence of
needle in the
haystack
string. If
needle is not found, it returns ENTITY.
ENTITY
If
offset is greater than the length of
haystack, a
ValueError will be thrown.
ENTITY
ENTITY
ENTITY
ENTITY
8.0.0
Passing the
encoding as the third argument instead of an
offset has been removed.
ENTITY
mb_strpos,
mb_internal_encoding,
strrpos
mb-strstr
mb_strstr
Finds first occurrence of a string within another
ENTITY
string
false
mb_strstr
string
haystack
string
needle
bool
before_needle
ENTITY
string
null
encoding
ENTITY
mb_strstr finds the first occurrence of
needle in
haystack and returns the portion of
haystack. If
needle is not found, it returns ENTITY.
ENTITY
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 ENTITY, it returns all of
haystack from the beginning to the first occurrence of
needle (excluding needle). If set to ENTITY, it returns all of
haystack from the first occurrence of
needle to the end (including needle).
encoding
ENTITY
ENTITY
Returns the portion of
haystack, or ENTITY if
needle is not found.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.3.2
On invalid strings (those with encoding errors) and on
SJIS-mac (MacJapanese) strings, the portion of
haystack returned when
before_needle is ENTITY is now determined from the same character indices as the other mbstring functions.
ENTITY
stristr,
strstr,
mb_stristr
mb-strtolower
mb_strtolower
Make a string lowercase
ENTITY
string
mb_strtolower
string
string
string
null
encoding
ENTITY
Returns
string with all alphabetic characters converted to lowercase.
ENTITY
string
The
string being lowercased.
encoding
ENTITY
ENTITY
string with all alphabetic characters converted to lowercase.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.3.0
Implemented conditional casing rules for the Greek letter sigma.
ENTITY
mb_strtolower example
mb_strtolower example with non-Latin UTF-8 text
ENTITY
By contrast to
strtolower, 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).
For more information about the Unicode properties, please see ENTITY.
ENTITY
mb_strtoupper,
mb_convert_case,
strtolower
mb-strtoupper
mb_strtoupper
Make a string uppercase
ENTITY
string
mb_strtoupper
string
string
string
null
encoding
ENTITY
Returns
string with all alphabetic characters converted to uppercase.
ENTITY
string
The
string being uppercased.
encoding
ENTITY
ENTITY
string with all alphabetic characters converted to uppercase.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_strtoupper example
mb_strtoupper example with non-Latin UTF-8 text
ENTITY
By contrast to
strtoupper, 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).
For more information about the Unicode properties, please see ENTITY.
ENTITY
mb_strtolower,
mb_convert_case,
strtoupper
mb-strwidth
mb_strwidth
Return width of string
ENTITY
int
mb_strwidth
string
string
string
null
encoding
ENTITY
Returns the width of
string
string, where halfwidth characters count as
1, and fullwidth characters count as
2. See ENTITY11/ for details regarding East Asian character widths.
The fullwidth characters are:
U+1100-
U+115F,
U+11A3-
U+11A7,
U+11FA-
U+11FF,
U+2329-
U+232A,
U+2E80-
U+2E99,
U+2E9B-
U+2EF3,
U+2F00-
U+2FD5,
U+2FF0-
U+2FFB,
U+3000-
U+303E,
U+3041-
U+3096,
U+3099-
U+30FF,
U+3105-
U+312D,
U+3131-
U+318E,
U+3190-
U+31BA,
U+31C0-
U+31E3,
U+31F0-
U+321E,
U+3220-
U+3247,
U+3250-
U+32FE,
U+3300-
U+4DBF,
U+4E00-
U+A48C,
U+A490-
U+A4C6,
U+A960-
U+A97C,
U+AC00-
U+D7A3,
U+D7B0-
U+D7C6,
U+D7CB-
U+D7FB,
U+F900-
U+FAFF,
U+FE10-
U+FE19,
U+FE30-
U+FE52,
U+FE54-
U+FE66,
U+FE68-
U+FE6B,
U+FF01-
U+FF60,
U+FFE0-
U+FFE6,
U+1B000-
U+1B001,
U+1F200-
U+1F202,
U+1F210-
U+1F23A,
U+1F240-
U+1F248,
U+1F250-
U+1F251,
U+20000-
U+2FFFD,
U+30000-
U+3FFFD. All other characters are halfwidth characters.
ENTITY
string
The
string being decoded.
encoding
ENTITY
ENTITY
The width of
string
string.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_strwidth example
ENTITY
int(1)
int(2)
ENTITY
mb_strimwidth,
mb_internal_encoding
mb-substitute-character
mb_substitute_character
Set/Get substitution character
ENTITY
string
int
bool
mb_substitute_character
string
int
null
substitute_character
ENTITY
Specifies a substitution character when input character encoding is invalid or character code does not exist in output character encoding. Invalid characters may be substituted
"none" (no output),
string or
int value (Unicode character code value).
This setting affects
mb_convert_encoding,
mb_convert_variables,
mb_output_handler,
mb_scrub, and
mb_send_mail.
ENTITY
substitute_character
Specify the Unicode value as an
int, or as one of the following
strings:
"none": no output
"long": Output character code value (Example:
U+3000,
JIS+7E7E)
"entity": Output character entity (Example:
ENTITY#x200;)
ENTITY
If
substitute_character is set, it returns ENTITY for success, otherwise returns ENTITY. If
substitute_character is not set, it returns the current setting.
ENTITY
ENTITY
ENTITY
8.0.0
Passing an empty string to
substitute_character is no longer supported;
"none" should be passed instead.
ENTITY
mb_substitute_character example
mb-substr-count
mb_substr_count
Count the number of substring occurrences
ENTITY
int
mb_substr_count
string
haystack
string
needle
string
null
encoding
ENTITY
Counts the number of times the
needle substring occurs in the
haystack
string.
ENTITY
haystack
The
string being checked.
needle
The
string being found.
encoding
ENTITY
ENTITY
The number of times the
needle substring occurs in the
haystack
string.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mb_substr_count example
ENTITY
mb_strpos,
mb_substr,
substr_count
mb-substr
mb_substr
Get part of string
ENTITY
string
mb_substr
string
string
int
start
int
null
length
ENTITY
string
null
encoding
ENTITY
Performs a multi-byte safe
substr operation based on number of characters. Position is counted from the beginning of
string. First character's position is 0. Second character position is 1, and so on.
ENTITY
string
The
string to extract the substring from.
start
If
start is non-negative, the returned string will start at the
start'th position in
string, counting from zero. For instance, in the string '
abcdef', the character at position
0 is '
a', the character at position
2 is '
c', and so forth.
If
start is negative, the returned string will start at the
start'th character from the end of
string.
length
Maximum number of characters to use from
string. If omitted or ENTITY is passed, extract all characters to the end of the string.
encoding
ENTITY
ENTITY
mb_substr returns the portion of
string specified by the
start and
length parameters.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.3.2
On invalid strings (those with encoding errors), character indices are now interpreted in the same manner as most other mbstring functions. This means that character indices returned by
mb_strpos can be passed directly. For
SJIS-mac (MacJapanese) strings, character indices now refer to the indices of the Unicode codepoints produced when the string is converted to Unicode, which differ from the character indices for the
SJIS-mac characters that convert to a sequence of several codepoints.
ENTITY
mb_strcut
mb_internal_encoding
mb-trim
mb_trim
Strip whitespace (or other characters) from the beginning and end of a string
ENTITY
string
mb_trim
string
string
string
null
characters
ENTITY
string
null
encoding
ENTITY
Performs a multi-byte safe
trim operation, and returns a string with whitespace stripped from the beginning and end of
string. Without the second parameter,
mb_trim will strip these characters:
ENTITY
ENTITY
string
The
string that will be trimmed.
characters
ENTITY
encoding
ENTITY
ENTITY
The trimmed string.
ENTITY
mb_ltrim
mb_rtrim
trim
mb-ucfirst
mb_ucfirst
Make a string's first character uppercase
ENTITY
string
mb_ucfirst
string
string
string
null
encoding
ENTITY
Performs a multi-byte safe
ucfirst operation, and returns a string with the first character of
string title-cased.
ENTITY
string
The input string.
encoding
The string encoding.
ENTITY
Returns the resulting string.
ENTITY
[!NOTE]
By contrast to the standard case folding functions such as
strtolower and
strtoupper, case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such a-umlaut (ä).
For more information about the Unicode properties, please see ENTITY.
ENTITY
mb_lcfirst
mb_convert_case
ucfirst
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 ENTITY 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 ENTITY.
Disable HTTP input conversion in ENTITY
;; 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 ENTITY or per directory with ENTITY. 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 ENTITY, another is using
ob_start with
mb_output_handler as the
ob_start callback function.
ENTITY 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
Script example
ini
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mbstring.language
"neutral"
INI_ALL
mbstring.detect_order
NULL
INI_ALL
mbstring.http_input
"pass"
INI_ALL
Deprecated
mbstring.http_output
"pass"
INI_ALL
Deprecated
mbstring.internal_encoding
NULL
INI_ALL
Deprecated
mbstring.substitute_character
NULL
INI_ALL
mbstring.func_overload
"0"
INI_SYSTEM
Deprecated as of PHP 7.2.0; removed as of PHP 8.0.0.
mbstring.encoding_translation
"0"
INI_PERDIR
mbstring.http_output_conv_mimetypes
"^(text/|application/xhtml\+xml)"
INI_ALL
mbstring.strict_detection
"0"
INI_ALL
mbstring.regex_retry_limit
"1000000"
INI_ALL
Available as of PHP 7.4.0.
mbstring.regex_stack_limit
"100000"
INI_ALL
Available as of PHP 7.3.5.
mbstring configuration options
ENTITY
ENTITY
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 ENTITY
mbstring.encoding_translation
bool
Enables the transparent character encoding filter for the incoming HTTP queries, which performs detection and conversion of the input encoding to the internal character encoding.
mbstring.internal_encoding
string
[!WARNING]
ENTITY
Defines the default internal character encoding.
Users should leave this empty and set
default_charset instead.
mbstring.http_input
string
[!WARNING]
ENTITY
Defines the default HTTP input character encoding.
Users should leave this empty and set
default_charset instead.
mbstring.http_output
string
[!WARNING]
ENTITY
Defines the default HTTP output character encoding (output will be converted from the internal encoding to the HTTP output encoding upon output).
Users should leave this empty and set
default_charset instead.
mbstring.detect_order
string
Defines default character code detection order. See also
mb_detect_order.
mbstring.substitute_character
string
Defines character to substitute for invalid character encoding. See
mb_substitute_character for supported values.
mbstring.func_overload
string
ENTITY
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 ENTITY file.
mbstring.http_output_conv_mimetypes
string
mbstring.strict_detection
bool
Enables strict encoding detection. See
mb_detect_encoding for a description and examples.
mbstring.regex_retry_limit
int
Limits the amount of backtracking that may be performed during one mbregex match.
This setting only takes effect when linking against oniguruma >= 6.8.0.
mbstring.regex_stack_limit
int
Limits the stack depth of mbstring regular expressions.
According to the HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See
mb_http_input to detect character encoding used by browsers.
Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the
charset parameter in the
Content-Type HTTP header to the appropriate value by
header or default_charset ini setting.
ENTITY 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
ENTITY 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
ENTITY 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
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 ENTITYzen-kakuENTITY in Japanese, which means ENTITYfull widthENTITY. Other, narrower, characters are called ENTITYhan-kakuENTITY, which means ENTITYhalf widthENTITY. The graphical properties of the characters, however, depends upon the type faces used to display them.
Some character encodings use shift(escape) sequences defined in ISO-2022 to switch the code map of the specific code area (
00h to
7fh).
ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.
Web pages created for mobile phone services such as i-mode or EZweb are supposed to use Shift_JIS.
Emoji used for mobile phone service such as i-mode or EZweb are supported.
Function Overloading Feature
ENTITY
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 ENTITY 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.
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
Functions to be overloaded
[!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.
reference
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
ENTITY
Japanese/Korean/Chinese character information
ENTITY
ENTITY
setup
ENTITY ENTITY ENTITY
Supported Character Encodings
Currently the following character encodings are supported by the
mbstring module. Any of those Character encodings can be specified in the
encoding parameter of
mbstring functions.
The following character encodings are supported in this PHP extension:
UCS-4*
UCS-4BE
UCS-4LE*
UCS-2
UCS-2BE
UCS-2LE
UTF-32*
UTF-32BE*
UTF-32LE*
UTF-16*
UTF-16BE*
UTF-16LE*
UTF-7
UTF7-IMAP
UTF-8*
ASCII*
EUC-JP*
SJIS*
eucJP-win*
SJIS-win*
ISO-2022-JP
ISO-2022-JP-MS
CP932
CP51932
SJIS-mac (alias: MacJapanese)
SJIS-Mobile#DOCOMO (alias: SJIS-DOCOMO)
SJIS-Mobile#KDDI (alias: SJIS-KDDI)
SJIS-Mobile#SOFTBANK (alias: SJIS-SOFTBANK)
UTF-8-Mobile#DOCOMO (alias: UTF-8-DOCOMO)
UTF-8-Mobile#KDDI-A
UTF-8-Mobile#KDDI-B (alias: UTF-8-KDDI)
UTF-8-Mobile#SOFTBANK (alias: UTF-8-SOFTBANK)
ISO-2022-JP-MOBILE#KDDI (alias: ISO-2022-JP-KDDI)
JIS
JIS-ms
CP50220
CP50220raw
CP50221
CP50222
ISO-8859-1*
ISO-8859-2*
ISO-8859-3*
ISO-8859-4*
ISO-8859-5*
ISO-8859-6*
ISO-8859-7*
ISO-8859-8*
ISO-8859-9*
ISO-8859-10*
ISO-8859-13*
ISO-8859-14*
ISO-8859-15*
ISO-8859-16*
byte2be
byte2le
byte4be
byte4le
BASE64
HTML-ENTITIES (alias: HTML)
7bit
8bit
EUC-CN*
CP936
GB18030
HZ
EUC-TW*
CP950
BIG-5*
EUC-KR*
UHC (alias: CP949)
ISO-2022-KR
Windows-1251 (alias: CP1251)
Windows-1252 (alias: CP1252)
CP866 (alias: IBM866)
KOI8-R*
KOI8-U*
ArmSCII-8 (alias: ArmSCII8)
* denotes encodings usable also in regular expressions.
Any ENTITY entry which accepts an encoding name can also use the values ENTITY
autoENTITY and ENTITY
passENTITY.
mbstring functions which accept an encoding name can also use the value ENTITY
autoENTITY.
If ENTITY
passENTITY is set, no character encoding conversion is performed.
If ENTITY
autoENTITY 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 ENTITY
ASCII,JIS,UTF-8,EUC-JP,SJISENTITY.
See also
mb_detect_order
book
ENTITY
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 ENTITY
An overview of software available for using MySQL from PHP can be found at ???
Documentation for MySQL can be found at ENTITY.
Parts of this documentation were included from the MySQL manual with permission of Oracle Corporation.
Examples use either the world or sakila database, which are freely available.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
ENTITY
ENTITY
configure
ENTITY
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, and as of PHP 8.2.0 the only 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.
PHP ENTITY
ENTITY
ENTITY: mysqlnd
ENTITY:
libmysqlclient
ENTITY
8.2.0 and later
mysqlnd
--with-mysqli
libmysqlclient is not supported
mysqlnd is the only option
5.4.0 through 8.1.x
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
ENTITY
--with-mysqli=/path/to/mysql_config
mysqlnd is not supported
mysqli compile time support matrix {#mysqli.installation.time.matrix}
Installation on Windows Systems
On Windows,
php_mysqli.dll DLL must be enabled in ENTITY.
As with enabling any PHP extension (such as
php_mysqli.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example
extension_dir value is
c:\php\ext.
[!NOTE]
If when starting the web server an error similar to the following occurs:
"Unable to load dynamic library './php_mysqli.dll'", this is because
php_mysqli.dll cannot be found by the system.
constants
ENTITY ENTITY
MYSQLI_READ_DEFAULT_GROUP (
int)
Read options from the named group from
my.cnf or the file specified with
MYSQLI_READ_DEFAULT_FILE.
MYSQLI_READ_DEFAULT_FILE (
int)
Read options from the named option file instead of from
my.cnf.
MYSQLI_OPT_CAN_HANDLE_EXPIRED_PASSWORDS (
int)
Indicates to the server that the client can handle sandbox mode for expired passwords. Can be used with
mysqli_options.
MYSQLI_OPT_LOAD_DATA_LOCAL_DIR (
int)
If enabled, this option specifies the directory from which client-side
LOCAL data loading is permitted in
LOAD DATA LOCAL statements.
MYSQLI_OPT_CONNECT_TIMEOUT (
int)
Connect timeout in seconds.
MYSQLI_OPT_READ_TIMEOUT (
int)
Command execution result timeout in seconds. Available as of PHP 7.2.0.
MYSQLI_OPT_LOCAL_INFILE (
int)
Enables command
LOAD LOCAL INFILE.
MYSQLI_OPT_INT_AND_FLOAT_NATIVE (
int)
Convert integer and float columns back to PHP numbers. Only valid for mysqlnd.
MYSQLI_OPT_NET_CMD_BUFFER_SIZE (
int)
The size of the internal command/network buffer. Only valid for mysqlnd.
MYSQLI_OPT_NET_READ_BUFFER_SIZE (
int)
Maximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd.
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT (
int)
MYSQLI_INIT_COMMAND (
int)
Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.
MYSQLI_CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS (
int)
Indicates to the server that the client can handle sandbox mode for expired passwords. Can be used with
mysqli_real_connect.
MYSQLI_CLIENT_FOUND_ROWS (
int)
Return number of matched rows, not the number of affected rows.
MYSQLI_CLIENT_SSL_VERIFY_SERVER_CERT (
int)
Verify server certificate.
MYSQLI_CLIENT_SSL (
int)
Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library.
MYSQLI_CLIENT_COMPRESS (
int)
Use compression protocol.
MYSQLI_CLIENT_INTERACTIVE (
int)
Allow
interactive_timeout seconds (instead of
wait_timeout seconds) of inactivity before closing the connection. The client's session
wait_timeout variable will be set to the value of the session
interactive_timeout variable.
MYSQLI_CLIENT_IGNORE_SPACE (
int)
Allow spaces after function names. Makes all functions names reserved words.
MYSQLI_CLIENT_NO_SCHEMA (
int)
Don't allow the
db_name.tbl_name.col_name syntax.
MYSQLI_CLIENT_MULTI_QUERIES
Allows multiple semicolon-delimited queries in a single
mysqli_query call.
MYSQLI_STORE_RESULT (
int)
For using buffered result sets. It has a value of
0.
MYSQLI_STORE_RESULT_COPY_DATA (
int)
As of PHP 8.1, this constant no longer has any effect. Before PHP 8.1, this constant is used to copy results from the internal
mysqlnd buffer into the PHP variables fetched. By default,
mysqlnd will use a reference logic to avoid copying and duplicating results held in memory. For certain result sets, for example, result sets with many small rows, the copy approach can reduce the overall memory usage because PHP variables holding results may be released earlier. Available with
mysqlnd only. Deprecated as of PHP 8.4.0.
MYSQLI_USE_RESULT (
int)
For using unbuffered result sets. It has a value of
1.
MYSQLI_ASSOC (
int)
Columns are returned into the array having the fieldname as the array index.
MYSQLI_NUM (
int)
Columns are returned into the array having an enumerated index.
MYSQLI_BOTH (
int)
Columns are returned into the array having both a numerical index and the fieldname as the associative index.
MYSQLI_NOT_NULL_FLAG (
int)
Indicates that a field is defined as
NOT NULL.
MYSQLI_PRI_KEY_FLAG (
int)
Field is part of a primary index.
MYSQLI_UNIQUE_KEY_FLAG (
int)
Field is part of a unique index.
MYSQLI_MULTIPLE_KEY_FLAG (
int)
Field is part of an index.
MYSQLI_BLOB_FLAG (
int)
Field is defined as
BLOB.
MYSQLI_UNSIGNED_FLAG (
int)
Field is defined as
UNSIGNED.
MYSQLI_ZEROFILL_FLAG (
int)
Field is defined as
ZEROFILL.
MYSQLI_AUTO_INCREMENT_FLAG (
int)
Field is defined as
AUTO_INCREMENT.
MYSQLI_TIMESTAMP_FLAG (
int)
Field is defined as
TIMESTAMP.
MYSQLI_SET_FLAG (
int)
Field is defined as
SET.
MYSQLI_NUM_FLAG (
int)
Field is defined as
NUMERIC.
MYSQLI_PART_KEY_FLAG (
int)
Field is part of a multi-index.
MYSQLI_GROUP_FLAG (
int)
Field is part of
GROUP BY.
MYSQLI_NO_DEFAULT_VALUE_FLAG (
int)
A column has no
DEFAULT clause in its definition. This does not apply to
NULL or to
AUTO_INCREMENT columns because such columns have a default value of
NULL and an implied default value respectively.
MYSQLI_TYPE_DECIMAL (
int)
Field is defined as
DECIMAL.
MYSQLI_TYPE_NEWDECIMAL (
int)
Precision math
DECIMAL or
NUMERIC field.
MYSQLI_TYPE_BIT (
int)
Field is defined as
BIT.
MYSQLI_TYPE_TINY (
int)
Field is defined as
TINYINT.
MYSQLI_TYPE_SHORT (
int)
Field is defined as
SMALLINT.
MYSQLI_TYPE_LONG (
int)
Field is defined as
INT.
MYSQLI_TYPE_FLOAT (
int)
Field is defined as
FLOAT.
MYSQLI_TYPE_DOUBLE (
int)
Field is defined as
DOUBLE.
MYSQLI_TYPE_NULL (
int)
Field is defined as
DEFAULT NULL.
MYSQLI_TYPE_TIMESTAMP (
int)
Field is defined as
TIMESTAMP.
MYSQLI_TYPE_LONGLONG (
int)
Field is defined as
BIGINT.
MYSQLI_TYPE_INT24 (
int)
Field is defined as
MEDIUMINT.
MYSQLI_TYPE_DATE (
int)
Field is defined as
DATE.
MYSQLI_TYPE_TIME (
int)
Field is defined as
TIME.
MYSQLI_TYPE_DATETIME (
int)
Field is defined as
DATETIME.
MYSQLI_TYPE_YEAR (
int)
Field is defined as
YEAR.
MYSQLI_TYPE_NEWDATE (
int)
Field is defined as
DATE.
MYSQLI_TYPE_INTERVAL (
int)
Alias of
MYSQLI_TYPE_ENUM. Removed as of PHP 8.4.0.
MYSQLI_TYPE_ENUM (
int)
Field is defined as
ENUM.
MYSQLI_TYPE_SET (
int)
Field is defined as
SET.
MYSQLI_TYPE_TINY_BLOB (
int)
Field is defined as
TINYBLOB.
MYSQLI_TYPE_MEDIUM_BLOB (
int)
Field is defined as
MEDIUMBLOB.
MYSQLI_TYPE_LONG_BLOB (
int)
Field is defined as
LONGBLOB.
MYSQLI_TYPE_BLOB (
int)
Field is defined as
BLOB.
MYSQLI_TYPE_VAR_STRING (
int)
Field is defined as
VARCHAR.
MYSQLI_TYPE_STRING (
int)
Field is defined as
CHAR or
BINARY.
MYSQLI_TYPE_CHAR (
int)
Field is defined as
TINYINT. For
CHAR, see
MYSQLI_TYPE_STRING.
MYSQLI_TYPE_GEOMETRY (
int)
Field is defined as
GEOMETRY.
MYSQLI_TYPE_JSON (
int)
Field is defined as
JSON. Only valid for mysqlnd and MySQL 5.7.8 and up.
MYSQLI_TYPE_VECTOR (
int)
Field is defined as
VECTOR. Available as of PHP 8.4.0, for MySQL 9.0 and later.
MYSQLI_NEED_DATA
More data available for bind variable.
MYSQLI_ENUM_FLAG (
int)
Field is defined as
ENUM.
MYSQLI_BINARY_FLAG (
int)
Field is defined as
BINARY.
MYSQLI_CURSOR_TYPE_FOR_UPDATE (
int)
Removed as of PHP 8.4.0.
MYSQLI_CURSOR_TYPE_NO_CURSOR (
int)
MYSQLI_CURSOR_TYPE_READ_ONLY (
int)
MYSQLI_CURSOR_TYPE_SCROLLABLE (
int)
Removed as of PHP 8.4.0.
MYSQLI_STMT_ATTR_CURSOR_TYPE (
int)
MYSQLI_STMT_ATTR_PREFETCH_ROWS (
int)
Removed as of PHP 8.4.0.
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH (
int)
MYSQLI_SET_CHARSET_NAME (
int)
MYSQLI_REPORT_INDEX (
int)
Report if no index or bad index was used in a query.
MYSQLI_REPORT_ERROR (
int)
Report errors from mysqli function calls.
MYSQLI_REPORT_STRICT (
int)
Throw a
mysqli_sql_exception for errors instead of warnings.
MYSQLI_REPORT_ALL (
int)
Set all options on (report all).
MYSQLI_REPORT_OFF (
int)
Turns reporting off.
MYSQLI_DEBUG_TRACE_ENABLED (
int)
Is set to 1 if
mysqli_debug functionality is enabled.
MYSQLI_SERVER_PUBLIC_KEY (
int)
MYSQLI_REFRESH_GRANT (
int)
Refreshes the grant tables. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_LOG (
int)
Flushes the logs, like executing the
FLUSH LOGS SQL statement. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_TABLES (
int)
Flushes the table cache, like executing the
FLUSH TABLES SQL statement. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_HOSTS (
int)
Flushes the host cache, like executing the
FLUSH HOSTS SQL statement. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_REPLICA (
int)
Alias of
MYSQLI_REFRESH_SLAVE constant. Available as of PHP 8.1.0. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_STATUS (
int)
Reset the status variables, like executing the
FLUSH STATUS SQL statement. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_THREADS (
int)
Flushes the thread cache. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_SLAVE (
int)
On a slave replication server: resets the master server information, and restarts the slave. Like executing the
RESET SLAVE SQL statement. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_MASTER (
int)
On a master replication server: removes the binary log files listed in the binary log index, and truncates the index file. Like executing the
RESET MASTER SQL statement. Deprecated as of PHP 8.4.0.
MYSQLI_REFRESH_BACKUP_LOG (
int)
Closes and reopens the backup log files. Deprecated as of PHP 8.4.0.
MYSQLI_TRANS_COR_AND_CHAIN (
int)
Appends "AND CHAIN" to
mysqli_commit or
mysqli_rollback.
MYSQLI_TRANS_COR_AND_NO_CHAIN (
int)
Appends "AND NO CHAIN" to
mysqli_commit or
mysqli_rollback.
MYSQLI_TRANS_COR_RELEASE (
int)
Appends "RELEASE" to
mysqli_commit or
mysqli_rollback.
MYSQLI_TRANS_COR_NO_RELEASE (
int)
Appends "NO RELEASE" to
mysqli_commit or
mysqli_rollback.
MYSQLI_TRANS_START_READ_ONLY (
int)
Start the transaction as "START TRANSACTION READ ONLY" with
mysqli_begin_transaction.
MYSQLI_TRANS_START_READ_WRITE (
int)
Start the transaction as "START TRANSACTION READ WRITE" with
mysqli_begin_transaction.
MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT (
int)
Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".
MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT (
int)
Requires MySQL 5.6.5 and up.
MYSQLI_IS_MARIADB (
bool)
Whether the mysqli extension has been built against a MariaDB client library. Available as of PHP 8.1.2.
MYSQLI_ASYNC (
int)
The query is performed asynchronously and no result set is immediately returned. Available with
mysqlnd only.
MYSQLI_ON_UPDATE_NOW_FLAG (
int)
If a field is updated it will get the current time value.
mysqli-execute
mysqli_execute
ENTITY
mysqli_stmt_execute
ENTITY
ENTITY
ENTITY
mysqli_stmt_execute.
ENTITY
mysqli_stmt_execute
mysqli-get-client-stats
mysqli_get_client_stats
Returns client per-process statistics
ENTITY
array
mysqli_get_client_stats
Returns client per-process statistics.
[!NOTE]
ENTITY
ENTITY ENTITY
ENTITY
Returns an array with client stats.
ENTITY
A
mysqli_get_client_stats example
ENTITY
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
)
ENTITY
Stats description
mysqli-get-links-stats
mysqli_get_links_stats
Return information about open and cached links
ENTITY
array
mysqli_get_links_stats
mysqli_get_links_stats returns information about open and cached MySQL links.
ENTITY ENTITY
ENTITY
mysqli_get_links_stats returns an associative array with three elements, keyed as follows:
total
An
int indicating the total number of open links in any state.
active_plinks
An
int representing the number of active persistent connections.
cached_plinks
An
int representing the number of inactive persistent connections.
ini
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
mysqli.allow_local_infile
"0"
INI_SYSTEM
Before PHP 7.2.16 and 7.3.3 the default was "1".
mysqli.local_infile_directory
INI_SYSTEM
Available as of PHP 8.1.0.
mysqli.allow_persistent
"1"
INI_SYSTEM
mysqli.max_persistent
"-1"
INI_SYSTEM
mysqli.max_links
"-1"
INI_SYSTEM
mysqli.default_port
"3306"
INI_ALL
mysqli.default_socket
NULL
INI_ALL
mysqli.default_host
NULL
INI_ALL
mysqli.default_user
NULL
INI_ALL
mysqli.default_pw
NULL
INI_ALL
mysqli.reconnect
"0"
INI_SYSTEM
Removed as of PHP 8.2.0
mysqli.rollback_on_cached_plink
"0"
INI_SYSTEM
MySQLi Configuration Options {#mysqli.configuration.options}
For further details and definitions of the preceding INI_* constants, see the chapter on configuration changes.
ENTITY
mysqli.allow_local_infile
bool
Allow accessing, from PHP's perspective, local files with LOAD DATA statements
mysqli.local_infile_directory
string
Allows restricting LOCAL DATA loading to files located in this designated directory.
mysqli.allow_persistent
bool
Enable the ability to create persistent connections using
mysqli_connect.
mysqli.max_persistent
int
The maximum number of persistent connections that can be made. Set to 0 for unlimited.
mysqli.max_links
int
The maximum number of connections per process.
mysqli.default_port
int
The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the
MYSQL_TCP_PORT environment variable, the
mysql-tcp entry in
/etc/services or the compile-time
MYSQL_PORT constant, in that order. Win32 will only use the
MYSQL_PORT constant.
mysqli.default_socket
string
The default socket name to use when connecting to a local database server if no other socket name is specified.
mysqli.default_host
string
The default server host to use when connecting to the database server if no other host is specified.
mysqli.default_user
string
The default user name to use when connecting to the database server if no other name is specified.
mysqli.default_pw
string
The default password to use when connecting to the database server if no other password is specified.
mysqli.reconnect
int
Automatically reconnect if the connection was lost.
[!NOTE]
This ENTITY setting had been ignored by the mysqlnd driver, and was removed as of PHP 8.2.0.
mysqli.rollback_on_cached_plink
bool
If this option is enabled, closing a persistent connection will rollback any pending transactions of this connection before it is put back into the persistent connection pool. Otherwise, pending transactions will be rolled back only when the connection is reused, or when it is actually closed.
Users cannot set
MYSQL_OPT_READ_TIMEOUT through an API call or runtime configuration setting. Note that if it were possible there would be differences between how
libmysqlclient and streams would interpret the value of
MYSQL_OPT_READ_TIMEOUT.
mysqli
ENTITY
Represents a connection between PHP and a MySQL database.
ENTITY
mysqli
ENTITY
public
readonly
int
string
affected_rows
public
readonly
string
client_info
public
readonly
int
client_version
public
readonly
int
connect_errno
public
readonly
string
null
connect_error
public
readonly
int
errno
public
readonly
string
error
public
readonly
array
error_list
public
readonly
int
field_count
public
readonly
string
host_info
public
readonly
string
null
info
public
readonly
int
string
insert_id
public
readonly
string
server_info
public
readonly
int
server_version
public
readonly
string
sqlstate
public
readonly
int
protocol_version
public
readonly
int
thread_id
public
readonly
int
warning_count
ENTITY
ENTITY
affected-rows
mysqli::$affected_rows
mysqli_affected_rows
Gets the number of affected rows in a previous MySQL operation
ENTITY
ENTITY
int
string
mysqli-ENTITYaffected_rows
ENTITY
int
string
mysqli_affected_rows
mysqli
mysql
Returns the number of rows affected by the last
INSERT,
UPDATE,
REPLACE or
DELETE query. Works like
mysqli_num_rows for
SELECT statements.
ENTITY
ENTITY
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an
UPDATE statement, no rows matched the
WHERE clause in the query or that no query has yet been executed.
-1 indicates that the query returned an error or that
mysqli_affected_rows was called for an unbuffered
SELECT query.
[!NOTE]
If the number of affected rows is greater than the maximum int value (
PHP_INT_MAX), the number of affected rows will be returned as a string.
ENTITY
$mysqli-ENTITYaffected_rows example
ENTITY
query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
/* Delete table Language */
$mysqli->query("DROP TABLE Language");
ENTITY
50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));
/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));
/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");
ENTITY
Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169
ENTITY
mysqli_num_rows,
mysqli_info
autocommit
mysqli::autocommit
mysqli_autocommit
Turns on or off auto-committing database modifications
ENTITY
ENTITY
public
bool
mysqli::autocommit
bool
enable
ENTITY
bool
mysqli_autocommit
mysqli
mysql
bool
enable
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.
ENTITY
enable
Whether to turn on auto-commit or not.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
mysqli::autocommit example
ENTITY
query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Turn autocommit off */
$mysqli->autocommit(false);
$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);
try {
/* Prepare insert statement */
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
/* Insert some values */
$language_code = 'DE';
$native_speakers = 50_123_456;
$stmt->execute();
$language_code = 'FR';
$native_speakers = 40_546_321;
$stmt->execute();
/* Commit the data in the database. This doesn't set autocommit=true */
$mysqli->commit();
print "Committed 2 rows in the database\n";
$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);
/* Try to insert more values */
$language_code = 'PL';
$native_speakers = 30_555_444;
$stmt->execute();
$language_code = 'DK';
$native_speakers = 5_222_444;
$stmt->execute();
/* Setting autocommit=true will trigger a commit */
$mysqli->autocommit(true);
print "Committed 2 row in the database\n";
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();
throw $exception;
}
ENTITY
query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Start transaction */
$mysqli->begin_transaction();
try {
/* Insert some values */
$mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");
/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
$stmt->execute();
/* If code reaches this point without errors then commit the data in the database */
$mysqli->commit();
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();
throw $exception;
}
ENTITY
query("SET @a:=1");
$mysqli->change_user("my_user", "my_password", "world");
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);
$result = $mysqli->query("SELECT @a");
$row = $result->fetch_row();
if ($row[0] === null) {
printf("Value of variable a is NULL\n");
}
ENTITY
change_user("my_user", "my_password", null);
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);
ENTITY
Default database:
ENTITY
[!NOTE]
Using this command will always cause the current database connection to behave as if it 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.
ENTITY
mysqli_connect,
mysqli_select_db
character-set-name
mysqli::character_set_name
mysqli_character_set_name
Returns the current character set of the database connection
ENTITY
ENTITY
public
string
mysqli::character_set_name
ENTITY
string
mysqli_character_set_name
mysqli
mysql
Returns the current character set of the database connection.
ENTITY
ENTITY
The current character set of the connection
ENTITY
mysqli::character_set_name example
ENTITY
set_charset('utf8mb4');
/* Print current character set */
$charset = $mysqli->character_set_name();
printf("Current character set is %s\n", $charset);
ENTITY
query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
/* Close the connection as soon as it's no longer needed */
$mysqli->close();
foreach ($result as $row) {
/* Processing of the data retrieved from the database */
}
ENTITY
connect_errno
ENTITY
int
mysqli_connect_errno
Returns the error code from the last connection attempt.
ENTITY ENTITY
ENTITY
An error code for the last connection attempt, if it failed. Zero means no error occurred.
Returns the last connection error code regardless of the instance on which it is called.
ENTITY
$mysqli->connect_errno example
ENTITY
connect_errno) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_errno);
}
ENTITY
connect_error) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_error);
}
ENTITY
set_charset('utf8mb4');
printf("Success... %s\n", $mysqli->host_info);
ENTITY
set_charset($charset);
}
}
$db = new FooMysqli('localhost', 'my_user', 'my_password', 'my_db', 3306, null, 'utf8mb4');
Manual error handling
If error reporting is disabled, the developer is responsible for checking and handling failures
ENTITY
connect_errno) {
throw new RuntimeException('mysqli connection error: ' . $mysqli->connect_error);
}
/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
if ($mysqli->errno) {
throw new RuntimeException('mysqli error: ' . $mysqli->error);
}
ENTITY
:: Each field consists of a mandatory flag character followed by an optional
, and comma separated list of modifiers:
flag[,modifier,modifier,...,modifier]
options character
Description
O
MYSQLND_DEBUG_FLUSH
A/a
MYSQLND_DEBUG_APPEND
F
MYSQLND_DEBUG_DUMP_FILE
i
MYSQLND_DEBUG_DUMP_PID
L
MYSQLND_DEBUG_DUMP_LINE
m
MYSQLND_DEBUG_TRACE_MEMORY_CALLS
n
MYSQLND_DEBUG_DUMP_LEVEL
o
output to file
T
MYSQLND_DEBUG_DUMP_TIME
t
MYSQLND_DEBUG_DUMP_TRACE
x
MYSQLND_DEBUG_PROFILE_CALLS
Recognized Flag Characters
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.0.0
This function now always returns ENTITY. Previously it returned ENTITY on failure.
ENTITY
Generating a Trace File
ENTITY
[!NOTE]
To use the
mysqli_debug function you must compile the MySQL client library to support debugging.
ENTITY
mysqli_dump_debug_info,
mysqli_report
dump-debug-info
mysqli::dump_debug_info
mysqli_dump_debug_info
Dump debugging information into the log
ENTITY
ENTITY
public
bool
mysqli::dump_debug_info
ENTITY
bool
mysqli_dump_debug_info
mysqli
mysql
This function is designed to be executed by a user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection.
ENTITY
ENTITY
ENTITY
ENTITY
mysqli_debug
errno
mysqli::$errno
mysqli_errno
Returns the error code for the most recent function call
ENTITY
ENTITY
int
mysqli-ENTITYerrno
ENTITY
int
mysqli_errno
mysqli
mysql
Returns the last error code for the most recent MySQLi function call that can succeed or fail.
ENTITY
ENTITY
An error code value for the last call, if it failed.
0 means no error occurred.
ENTITY
$mysqli-ENTITYerrno example
ENTITY
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();
?>
ENTITY
ENTITY
Errorcode: 1193
ENTITY
mysqli_connect_errno,
mysqli_connect_error,
mysqli_error,
mysqli_sqlstate
error-list
mysqli::$error_list
mysqli_error_list
Returns a list of errors from the last command executed
ENTITY
ENTITY
array
mysqli-ENTITYerror_list
ENTITY
array
mysqli_error_list
mysqli
mysql
Returns an array of errors for the most recent MySQLi function call that can succeed or fail.
ENTITY
ENTITY
A list of errors, each as an associative
array containing the errno, error, and sqlstate.
ENTITY
$mysqli-ENTITYerror_list example
ENTITY
query("SET a=1")) {
print_r($mysqli->error_list);
}
/* close connection */
$mysqli->close();
?>
ENTITY
ENTITY
Array
(
[0] => Array
(
[errno] => 1193
[sqlstate] => HY000
[error] => Unknown system variable 'a'
)
)
ENTITY
mysqli_connect_errno,
mysqli_connect_error,
mysqli_error,
mysqli_sqlstate
error
mysqli::$error
mysqli_error
Returns a string description of the last error
ENTITY
ENTITY
string
mysqli-ENTITYerror
ENTITY
string
mysqli_error
mysqli
mysql
Returns the last error message for the most recent MySQLi function call that can succeed or fail.
ENTITY
ENTITY
A string that describes the error. An empty string if no error occurred.
ENTITY
$mysqli-ENTITYerror example
ENTITY
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();
?>
ENTITY
ENTITY
Error message: Unknown system variable 'a'
ENTITY
mysqli_connect_errno,
mysqli_connect_error,
mysqli_errno,
mysqli_sqlstate
escape-string
mysqli::escape_string
mysqli_escape_string
ENTITY
mysqli_real_escape_string
ENTITY
ENTITY
mysqli_real_escape_string.
execute-query
mysqli::execute_query
mysqli_execute_query
Prepares, binds parameters, and executes SQL statement
ENTITY
ENTITY
public
mysqli_result
bool
mysqli::execute_query
string
query
array
null
params
ENTITY
ENTITY
mysqli_result
bool
mysqli_execute_query
mysqli
mysql
string
query
array
null
params
ENTITY
Prepares the SQL query, binds parameters, and executes it. The mysqli::execute_query method is a shortcut for mysqli::prepare, mysqli_stmt::bind_param, mysqli_stmt::execute, and mysqli_stmt::get_result.
The statement template can contain zero or more question mark (
?) parameter markers—also called placeholders. The parameter values must be provided as an ENTITY using
params parameter.
A prepared statement is created under the hood but itENTITYs never exposed outside of the function. ItENTITYs impossible to access properties of the statement as one would do with the
mysqli_stmt object. Due to this limitation, the status information is copied to the
mysqli object and is available using its methods, e.g.
mysqli_affected_rows or
mysqli_error.
[!NOTE]
In the case where a statement is passed to
mysqli_execute_query that is longer than
max_allowed_packet of the server, the returned error codes are different depending on the operating system. The behavior is as follows:
On Linux returns an error code of 1153. The error message means “got a packet bigger than
max_allowed_packet bytes”.
On Windows returns an error code 2006. This error message means “server has gone away”.
ENTITY
query
The query, as a string. It must consist of a single SQL statement.
The SQL statement may contain zero or more parameter markers represented by question mark (
?) characters at the appropriate positions.
[!NOTE]
The markers are legal only in certain places in SQL statements. For example, they are permitted in the
VALUES() list of an
INSERT statement (to specify column values for a row), or in a comparison with a column in a
WHERE clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).
params
An optional list ENTITY with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a ENTITY.
ENTITY
Returns ENTITY on failure. For successful queries which produce a result set, such as
SELECT, SHOW, DESCRIBE or
EXPLAIN, returns a
mysqli_result object. For other successful queries, returns ENTITY.
ENTITY
mysqli::execute_query example
ENTITY
execute_query($query, ['DEU']);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["District"]);
}
ENTITY
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();
?>
ENTITY
get-charset
mysqli::get_charset
mysqli_get_charset
Returns a character set object
ENTITY
ENTITY
public
object
null
mysqli::get_charset
ENTITY
object
null
mysqli_get_charset
mysqli
mysql
Returns a character set object providing several properties of the current active character set.
ENTITY
ENTITY
The function returns a character set object with the following properties:
charset
Character set name
collation
Collation name
dir
Directory the character set description was fetched from or "" for built-in character sets
min_length
Minimum character length in bytes
max_length
Maximum character length in bytes
number
Internal character set number
state
As of PHP 8.2.0, it is always
1
ENTITY
mysqli::get_charset example
ENTITY
real_connect("localhost","root","","test");
$db->set_charset('latin1');
var_dump($db->get_charset());
?>
ENTITY
ENTITY
object(stdClass)#2 (7) {
["charset"]=>
string(6) "latin1"
["collation"]=>
string(17) "latin1_swedish_ci"
["dir"]=>
string(0) ""
["min_length"]=>
int(1)
["max_length"]=>
int(1)
["number"]=>
int(8)
["state"]=>
int(1)
}
ENTITY
mysqli_character_set_name,
mysqli_set_charset
get-client-info
mysqli::$client_info
mysqli::get_client_info
mysqli_get_client_info
Get MySQL client info
ENTITY
ENTITY
string
mysqli-ENTITYclient_info
#[\Deprecated(since: '8.1', message: 'use mysqli_get_client_info() instead')]
public
string
mysqli::get_client_info
ENTITY
string
mysqli_get_client_info
mysqli
null
mysql
ENTITY
Returns a string that represents the MySQL client library version.
ENTITY ENTITY
ENTITY
A string that represents the MySQL client library version.
ENTITY
ENTITY
ENTITY
8.1.0
Calling
mysqli_get_client_info with the
mysql argument has been deprecated. This function never required a parameter, but incorrectly allowed it as an optional parameter.
8.1.0
The object-oriented style mysqli::get_client_info has been deprecated.
ENTITY
mysqli_get_client_info
ENTITY
mysqli_get_client_version,
mysqli_get_server_info,
mysqli_get_server_version
get-client-version
mysqli::$client_version
mysqli_get_client_version
Returns the MySQL client version as an integer
ENTITY
ENTITY
int
mysqli-ENTITYclient_version
ENTITY
int
mysqli_get_client_version
Returns client version number as an integer.
ENTITY ENTITY
ENTITY
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.
ENTITY
mysqli_get_client_version
ENTITY
mysqli_get_client_info,
mysqli_get_server_info,
mysqli_get_server_version
get-connection-stats
mysqli::get_connection_stats
mysqli_get_connection_stats
Returns statistics about the client connection
ENTITY
ENTITY
public
array
mysqli::get_connection_stats
ENTITY
array
mysqli_get_connection_stats
mysqli
mysql
Returns statistics about the client connection.
[!NOTE]
ENTITY
ENTITY
ENTITY
Returns an array with connection stats.
ENTITY
A
mysqli_get_connection_stats example
ENTITY
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
)
ENTITY
Stats description
get-host-info
mysqli::$host_info
mysqli_get_host_info
Returns a string representing the type of connection used
ENTITY
ENTITY
string
mysqli-ENTITYhost_info
ENTITY
string
mysqli_get_host_info
mysqli
mysql
Returns a string describing the connection represented by the
mysql parameter (including the server host name).
ENTITY
ENTITY
A character string representing the server hostname and the connection type.
ENTITY
$mysqli-ENTITYhost_info example
ENTITY
host_info);
ENTITY
protocol_version);
ENTITY
server_info);
ENTITY
server_version);
ENTITY
query("SELECT 1/0, CAST('NULL' AS UNSIGNED)");
if ($mysqli->warning_count > 0) {
$warning = $mysqli->get_warnings();
if ($warning !== false) {
do {
printf("Error number: %s\n", $warning->errno);
printf("Message: %s\n", $warning->message);
} while ($warning->next());
}
}
ENTITY
0) {
$warning = mysqli_get_warnings($link);
if ($warning !== false) {
do {
printf("Error number: %s\n", $warning->errno);
printf("Message: %s\n", $warning->message);
} while ($warning->next());
}
}
ENTITY
Error number: 1365
Message: Division by 0
Error number: 1292
Message: Truncated incorrect INTEGER value: 'NULL'
info
mysqli::$info
mysqli_info
Retrieves information about the most recently executed query
ENTITY
ENTITY
string
null
mysqli-ENTITYinfo
ENTITY
string
null
mysqli_info
mysqli
mysql
The
mysqli_info function returns a string providing information about the last query executed. The nature of this string is provided below:
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
Possible mysqli_info return values {#mysqli.info.description}
[!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.
ENTITY
ENTITY
A character string representing additional information about the most recently executed query.
ENTITY
$mysqli-ENTITYinfo example
ENTITY
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);
ENTITY
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");
ENTITY
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();
?>
ENTITY
ENTITY
Error: MySQL server has gone away
ENTITY
mysqli_thread_id
more-results
mysqli::more_results
mysqli_more_results
Check if there are any more query results from a multi query
ENTITY
ENTITY
public
bool
mysqli::more_results
ENTITY
bool
mysqli_more_results
mysqli
mysql
Indicates if one or more result sets are available from a previous call to
mysqli_multi_query.
ENTITY
ENTITY
Returns ENTITY if one or more result sets (including errors) are available from a previous call to
mysqli_multi_query, otherwise ENTITY.
ENTITY
See
mysqli_multi_query.
ENTITY
mysqli_multi_query,
mysqli_next_result,
mysqli_store_result,
mysqli_use_result
multi-query
mysqli::multi_query
mysqli_multi_query
Performs one or more queries on the database
ENTITY
ENTITY
public
bool
mysqli::multi_query
string
query
ENTITY
bool
mysqli_multi_query
mysqli
mysql
string
query
Executes one or multiple queries which are concatenated by a semicolon.
ENTITY
Queries are sent in a single call to the database and processed sequentially. mysqli_multi_query waits for the first query to complete before returning control to PHP. In the meantime, the MySQL server will continue processing the remaining queries asynchronously from PHP and make the results available for fetching.
It is recommended to use do-while to process multiple queries. The connection will be busy until all queries have completed and their results are fetched to PHP. No other statement can be issued on the same connection until all queries are processed. To proceed to the next query in the sequence, use
mysqli_next_result. If the next result is not ready yet, mysqli will wait for the response from the MySQL server. To check if there are more results, use
mysqli_more_results.
For queries which produce a result set, such as
SELECT, SHOW, DESCRIBE or
EXPLAIN,
mysqli_use_result or
mysqli_store_result can be used to retrieve the result set. For queries which do not produce a result set, the same functions can be used to retrieve information such as the number of affected rows.
[!TIP]
Executing
CALL statements for stored procedures can produce multiple result sets. If the stored procedure contains
SELECT statements, the result sets are returned in the order that they are produced as the procedure executes. In general, the caller cannot know how many result sets a procedure will return and must be prepared to retrieve multiple results. The final result from the procedure is a status result that includes no result set. The status indicates whether the procedure succeeded or an error occurred.
ENTITY
query
A string containing the queries to be executed. Multiple queries must be separated by a semicolon.
ENTITY
Returns ENTITY if the first statement failed. To retrieve subsequent errors from other statements you have to call
mysqli_next_result first.
ENTITY ENTITY
ENTITY
mysqli::multi_query example
ENTITY
multi_query($query);
do {
/* store the result set in PHP */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
ENTITY
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();
?>
ENTITY
ENTITY
Our connection is ok!
poll
mysqli::poll
mysqli_poll
Poll connections
ENTITY
ENTITY
public
static
int
false
mysqli::poll
array
null
read
array
null
error
array
reject
int
seconds
int
microseconds
0
ENTITY
int
false
mysqli_poll
array
null
read
array
null
error
array
reject
int
seconds
int
microseconds
0
Poll connections. The method can be used as static.
[!NOTE]
ENTITY
ENTITY
read
List of connections to check for outstanding results that can be read.
error
List of connections on which an error occurred, for example, query failure or lost connection.
reject
List of connections rejected because no pending asynchronous query exists to poll.
seconds
Maximum number of seconds to wait, must be non-negative.
microseconds
Maximum number of microseconds to wait, must be non-negative.
ENTITY
Returns number of ready connections upon success, ENTITY otherwise.
ENTITY
A
ValueError is thrown when neither the
read nor
error arguments are passed.
ENTITY
ENTITY
ENTITY
8.3.0
Now throws a
ValueError exception when neither the
read nor
error arguments are passed.
ENTITY
A
mysqli_poll example
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));
?>
ENTITY
Array
(
[0] => test
)
ENTITY
mysqli_query,
mysqli_reap_async_query
prepare
mysqli::prepare
mysqli_prepare
Prepares an SQL statement for execution
ENTITY
ENTITY
public
mysqli_stmt
false
mysqli::prepare
string
query
ENTITY
mysqli_stmt
false
mysqli_prepare
mysqli
mysql
string
query
Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.
The statement template can contain zero or more question mark (
?) parameter markers—also called placeholders. The parameter markers must be bound to application variables using
mysqli_stmt_bind_param before executing the statement.
ENTITY
query
The query, as a string. It must consist of a single SQL statement.
The SQL statement may contain zero or more parameter markers represented by question mark (
?) characters at the appropriate positions.
[!NOTE]
The markers are legal only in certain places in SQL statements. For example, they are permitted in the
VALUES() list of an
INSERT statement (to specify column values for a row), or in a comparison with a column in a
WHERE clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).
ENTITY
mysqli_prepare returns a statement object or ENTITY if an error occurred.
ENTITY ENTITY
ENTITY
mysqli::prepare example
ENTITY
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);
ENTITY
query("CREATE TEMPORARY TABLE myCity LIKE City");
printf("Table myCity successfully created.\n");
/* Select queries return a resultset */
$result = $mysqli->query("SELECT Name FROM City LIMIT 10");
printf("Select returned %d rows.\n", $result->num_rows);
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
$result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT);
/* Note, that we can't execute any functions which interact with the
server until all records have been fully retrieved or the result
set was closed. All calls will return an 'out of sync' error */
$mysqli->query("SET @a:='this will not work'");
ENTITY
quote_string($city));
$result = $mysqli->query($query);
printf("Select returned %d rows.\n", $result->num_rows);
/* this query will fail, because we didn't quote and escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = $mysqli->query($query);
ENTITY
options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db', null, null, MYSQLI_CLIENT_COMPRESS|MYSQLI_CLIENT_FOUND_ROWS);
echo 'Success... ' . $mysqli->host_info . "\n";
ENTITY when extending mysqli class
host_info . "\n";
ENTITY
real_escape_string($city));
$result = $mysqli->query($query);
printf("Select returned %d rows.\n", $result->num_rows);
/* this query will fail, because we didn't escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = $mysqli->query($query);
ENTITY
query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
/* change default database to "world" */
$mysqli->select_db("world");
/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
ENTITY
character_set_name());
/* change character set to utf8mb4 */
$mysqli->set_charset("utf8mb4");
printf("Current character set: %s\n", $mysqli->character_set_name());
ENTITY
query("CREATE TABLE City (ID INT, Name VARCHAR(30))");
} catch (mysqli_sql_exception) {
printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}
ENTITY
stat());
ENTITY
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();
?>
ENTITY
ENTITY
Error: MySQL server has gone away
ENTITY
mysqli_kill
thread-safe
mysqli::thread_safe
mysqli_thread_safe
Returns whether thread safety is given or not
ENTITY
ENTITY
public
bool
mysqli::thread_safe
ENTITY
bool
mysqli_thread_safe
Tells whether the client library is compiled as thread-safe.
ENTITY ENTITY
ENTITY
ENTITY if the client library is thread-safe, otherwise ENTITY.
use-result
mysqli::use_result
mysqli_use_result
Initiate a result set retrieval
ENTITY
ENTITY
public
mysqli_result
false
mysqli::use_result
ENTITY
mysqli_result
false
mysqli_use_result
mysqli
mysql
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 with 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.
ENTITY ENTITY
ENTITY
Returns an unbuffered result object or ENTITY if an error occurred.
ENTITY ENTITY
ENTITY
mysqli::use_result example
ENTITY
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();
?>
ENTITY
ENTITY
my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer
ENTITY
mysqli_real_query,
mysqli_store_result
warning-count
mysqli::$warning_count
mysqli_warning_count
Returns the number of warnings generated by the most recently executed query
ENTITY
ENTITY
int
mysqli-ENTITYwarning_count
ENTITY
int
mysqli_warning_count
mysqli
mysql
Returns the number of warnings generated by the most recently executed query.
[!NOTE]
For retrieving warning messages the following SQL command can be used:
SHOW WARNINGS [limit row_count].
ENTITY
ENTITY
Number of warnings or zero if there are no warnings.
ENTITY
$mysqli-ENTITYwarning_count example
ENTITY
query("SELECT 42/0");
if ($mysqli->warning_count > 0) {
$result = $mysqli->query("SHOW WARNINGS");
$row = $result->fetch_row();
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
}
ENTITY
0) {
$result = mysqli_query($link, "SHOW WARNINGS");
$row = mysqli_fetch_row($result);
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
}
ENTITY
Warning (1365): Division by 0
ENTITY
mysqli_errno,
mysqli_error,
mysqli_sqlstate
mysqli_driver
ENTITY
The
mysqli_driver class is an instance of the monostate pattern, i.e. there is only one driver which can be accessed through an arbitrary amount of
mysqli_driver instances.
ENTITY
final
mysqli_driver
ENTITY
public
readonly
string
client_info
public
readonly
int
client_version
public
readonly
int
driver_version
public
int
report_mode
ENTITY
client_info
The Client API header version
client_version
The Client version
driver_version
The MySQLi Driver version
[!WARNING]
This property has been deprecated as of PHP 8.1.0. Relying on this property is highly discouraged.
embedded
Whether MySQLi Embedded support is enabled
[!WARNING]
This property has been removed as of PHP 8.0.0.
reconnect
Allow or prevent reconnect (see the mysqli.reconnect INI directive)
[!WARNING]
This property has been removed along with the mysqli.reconnect INI directive as of PHP 8.2.0.
report_mode
Set to
MYSQLI_REPORT_OFF,
MYSQLI_REPORT_ALL or any combination of
MYSQLI_REPORT_STRICT (throw Exceptions for errors),
MYSQLI_REPORT_ERROR (report errors) and
MYSQLI_REPORT_INDEX (errors regarding indexes). See also
mysqli_report.
ENTITY
ENTITY
ENTITY
8.2.0
mysqli_driver::$reconnect was removed.
8.1.0
mysqli_driver::$driver_version has been deprecated.
8.0.0
mysqli_driver::$embedded was removed.
7.4.0
mysqli_driver::embedded_server_start and mysqli_driver:embedded_server_end were removed.
ENTITY
embedded-server-end
mysqli_driver::embedded_server_end
mysqli_embedded_server_end
Stop embedded server
ENTITY
ENTITY
ENTITY
public
void
mysqli_driver::embedded_server_end
ENTITY
void
mysqli_embedded_server_end
ENTITY
embedded-server-start
mysqli_driver::embedded_server_start
mysqli_embedded_server_start
Initialize and start embedded server
ENTITY
ENTITY
ENTITY
public
bool
mysqli_driver::embedded_server_start
int
start
array
arguments
array
groups
ENTITY
bool
mysqli_embedded_server_start
int
start
array
arguments
array
groups
ENTITY
report-mode
mysqli_driver::$report_mode
mysqli_report
Sets mysqli error reporting mode
ENTITY
ENTITY
int
mysqli_driver-ENTITYreport_mode
ENTITY
true
mysqli_report
int
flags
Depending on the flags, it sets mysqli error reporting mode to exception, warning or none. When set to
MYSQLI_REPORT_ALL or
MYSQLI_REPORT_INDEX it will also inform about queries that don't use an index (or use a bad index).
As of PHP 8.1.0, the default setting is
MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT. Previously, it was
MYSQLI_REPORT_OFF.
ENTITY
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)
Supported flags {#mysqli-driver.report-mode.parameters}
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.1.0
The default value is now `MYSQLI_REPORT_ERROR
ENTITY
ENTITY
report_mode = MYSQLI_REPORT_ALL;
try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this query should report a bad index if the column population doesn't have an index */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}
ENTITY
50000");
/* this query should report a bad index if the column population doesn't have an index */
$result = mysqli_query($link, "SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}
Error reporting except bad index errors
query("SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this WILL NOT report any errors even if index is not available */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}
ENTITY
mysqli_sql_exception,
set_exception_handler,
error_reporting
mysqli_result
ENTITY
Represents the result set obtained from a query against the database.
ENTITY
mysqli_result
implements
IteratorAggregate
ENTITY
public
readonly
int
current_field
public
readonly
int
field_count
public
readonly
array
null
lengths
public
readonly
int
string
num_rows
public
int
type
ENTITY
ENTITY
type
Stores whether the result is buffered or unbuffered as an ENTITY (
MYSQLI_STORE_RESULT or
MYSQLI_USE_RESULT, respectively).
ENTITY
ENTITY
ENTITY
8.0.0
mysqli_result implements IteratorAggregate now. Previously, Traversable was implemented instead.
ENTITY
construct
mysqli_result::__construct
Constructs a
mysqli_result
object
ENTITY
public
mysqli_result::__construct
mysqli
mysql
int
result_mode
MYSQLI_STORE_RESULT
This method constructs a new
mysqli_result object.
It can be used to create the
mysqli_result object after calling the
mysqli_real_query or
mysqli_multi_query function. Constructing the object manually is equivalent to calling the
mysqli_store_result or
mysqli_use_result function.
ENTITY
result_mode
The result mode can be one of 2 constants indicating how the result will be returned from the MySQL server.
MYSQLI_STORE_RESULT (default) - creates a
mysqli_result object with buffered result set.
MYSQLI_USE_RESULT - creates a
mysqli_result object with unbuffered result set. As long as there are pending records waiting to be fetched, the connection line will be busy and all subsequent calls will return error
Commands out of sync. To avoid the error all records must be fetched from the server or the result set must be discarded by calling
mysqli_free_result. The connection must remain open for the rows to be fetched.
ENTITY ENTITY
ENTITY
Creation of a
mysqli_result object
real_query("SELECT Name FROM City LIMIT 10");
$result = new mysqli_result($mysqli);
printf("Select returned %d rows.\n", $result->num_rows);
ENTITY
Select returned 10 rows.
ENTITY
mysqli_multi_query,
mysqli_real_query,
mysqli_store_result,
mysqli_use_result
current-field
mysqli_result::$current_field
mysqli_field_tell
Get current field offset of a result pointer
ENTITY
ENTITY
int
mysqli_result->current_field
ENTITY
int
mysqli_field_tell
mysqli_result
result
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.
ENTITY
ENTITY
Returns current offset of field cursor.
ENTITY
ENTITY
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();
?>
ENTITY
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);
?>
ENTITY
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
ENTITY
mysqli_fetch_field,
mysqli_field_seek
data-seek
mysqli_result::data_seek
mysqli_data_seek
Adjusts the result pointer to an arbitrary row in the result
ENTITY
ENTITY
public
bool
mysqli_result::data_seek
int
offset
ENTITY
bool
mysqli_data_seek
mysqli_result
result
int
offset
The
mysqli_data_seek function seeks to an arbitrary result pointer specified by the
offset in the result set.
ENTITY
offset
The row offset. Must be between zero and the total number of rows minus one (0..
mysqli_num_rows - 1).
ENTITY
ENTITY
ENTITY
mysqli::data_seek example
ENTITY
query($query);
/* Seek to row no. 401 */
$result->data_seek(400);
/* Fetch single row */
$row = $result->fetch_row();
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
ENTITY
query($query);
/* Iterate the result set in reverse order */
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
/* Fetch single row */
$row = $result->fetch_row();
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}
/* Reset pointer to the beginning of the result set */
$result->data_seek(0);
print "\n";
/* Iterate the same result set again */
while ($row = $result->fetch_row()) {
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}
ENTITY
City: Acmbaro Countrycode: MEX
City: Abuja Countrycode: NGA
City: Abu Dhabi Countrycode: ARE
City: Abottabad Countrycode: PAK
City: Abottabad Countrycode: PAK
City: Abu Dhabi Countrycode: ARE
City: Abuja Countrycode: NGA
City: Acmbaro Countrycode: MEX
ENTITY
[!NOTE]
This function can only be used with buffered results attained from the use of the
mysqli_store_result,
mysqli_query or
mysqli_stmt_get_result functions.
ENTITY
mysqli_store_result,
mysqli_fetch_row,
mysqli_fetch_array,
mysqli_fetch_assoc,
mysqli_fetch_object,
mysqli_query,
mysqli_num_rows
fetch-all
mysqli_result::fetch_all
mysqli_fetch_all
Fetch all result rows as an associative array, a numeric array, or both
ENTITY
ENTITY
public
array
mysqli_result::fetch_all
int
mode
MYSQLI_NUM
ENTITY
array
mysqli_fetch_all
mysqli_result
result
int
mode
MYSQLI_NUM
Returns a two-dimensional array of all result rows as an associative array, a numeric array, or both.
[!NOTE]
Prior to PHP 8.1.0, available only with mysqlnd.
ENTITY
mode
This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants
MYSQLI_ASSOC,
MYSQLI_NUM, or
MYSQLI_BOTH.
ENTITY
Returns an array of associative or numeric arrays holding result rows.
ENTITY
ENTITY
ENTITY
8.1.0
Now also available when linking against libmysqlclient.
ENTITY
mysqli_result::fetch_all example
ENTITY
query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
$rows = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
ENTITY
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"]);
ENTITY
query($query);
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
ENTITY
query($query);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
echo "\n==================\n";
// Not using iterators
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
ENTITY
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
==================
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
ENTITY
mysqli_fetch_array,
mysqli_fetch_column,
mysqli_fetch_row,
mysqli_fetch_object,
mysqli_query,
mysqli_data_seek
fetch-column
mysqli_result::fetch_column
mysqli_fetch_column
Fetch a single column from the next row of a result set
ENTITY
ENTITY
public
null
int
float
string
false
mysqli_result::fetch_column
int
column
0
ENTITY
null
int
float
string
false
mysqli_fetch_column
mysqli_result
result
int
column
0
Fetches one row of data from the result set and returns the 0-indexed column. Each subsequent call to this function will return the value from the next row within the result set, or ENTITY if there are no more rows.
ENTITY
ENTITY
column
0-indexed number of the column you wish to retrieve from the row. If no value is supplied, the first column will be returned.
ENTITY
Returns a single column from the next row of a result set or ENTITY if there are no more rows.
[!WARNING]
There is no way to return another column from the same row if you use this function to retrieve data.
ENTITY
mysqli_result::fetch_column example
ENTITY
query($query);
/* fetch a single value from the second column */
while ($Name = $result->fetch_column(1)) {
printf("%s\n", $Name);
}
ENTITY
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();
?>
ENTITY
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);
?>
ENTITY
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
ENTITY
mysqli_num_fields,
mysqli_fetch_field,
mysqli_fetch_fields
fetch-field
mysqli_result::fetch_field
mysqli_fetch_field
Returns the next field in the result set
ENTITY
ENTITY
public
object
false
mysqli_result::fetch_field
ENTITY
object
false
mysqli_fetch_field
mysqli_result
result
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.
ENTITY
ENTITY
Returns an object which contains field definition information or ENTITY if no field information is available.
ENTITY
ENTITY
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();
?>
ENTITY
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);
?>
ENTITY
Name: Name
Table: Country
max. Len: 11
Flags: 1
Type: 254
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
ENTITY
mysqli_num_fields,
mysqli_fetch_field_direct,
mysqli_fetch_fields,
mysqli_field_seek
fetch-fields
mysqli_result::fetch_fields
mysqli_fetch_fields
Returns an array of objects representing the fields in a result set
ENTITY
ENTITY
public
array
mysqli_result::fetch_fields
ENTITY
array
mysqli_fetch_fields
mysqli_result
result
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.
ENTITY
ENTITY
Returns an array of objects containing field definition information.
Property
Description
name
The name of the column
orgname
Original column name if an alias was specified
table
The name of the table this field belongs to (if not calculated)
orgtable
Original table name if an alias was specified
def
Unused. Always an empty string
db
The name of the database
catalog
Unused. Always
"def"
max_length
The maximum width of the field for the result set. As of PHP 8.1, this value is always
0.
length
The width of the field in bytes. For string columns, the length value depends on the connection character set. For example, if the character set is
latin1, a single-byte character set, the length value for a
SELECT 'abc' query is 3. If the character set is
utf8mb4, a multibyte character set in which characters take up to 4 bytes, the length value is 12.
charsetnr
The character set number for the field.
flags
An integer representing the bit-flags for the field.
type
The data type used for this field
decimals
The number of decimals for numeric fields, and the fractional seconds precision for temporal fields.
Object properties
ENTITY
ENTITY
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();
?>
ENTITY
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);
?>
ENTITY
======================
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
ENTITY
mysqli_num_fields,
mysqli_fetch_field_direct,
mysqli_fetch_field
fetch-object
mysqli_result::fetch_object
mysqli_fetch_object
Fetch the next row of a result set as an object
ENTITY
ENTITY
public
object
null
false
mysqli_result::fetch_object
string
class
"stdClass"
array
constructor_args
[]
ENTITY
object
null
false
mysqli_fetch_object
mysqli_result
result
string
class
"stdClass"
array
constructor_args
[]
Fetches one row of data from the result set and returns it as an object, where each property represents the name of the result set's column. Each subsequent call to this function will return the next row within the result set, or ENTITY if there are no more rows.
If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name,
mysqli_fetch_row may be used to fetch the numerically indexed array, or aliases may be used in the SQL query select list to give columns different names.
[!NOTE]
This function sets the properties of the object before calling the object constructor.
ENTITY ENTITY
ENTITY
class
The name of the class to instantiate, set the properties of and return. If not specified, a
stdClass object is returned.
constructor_args
An optional
array of parameters to pass to the constructor for
class objects.
ENTITY
Returns an object representing the fetched row, where each property represents the name of the result set's column, ENTITY if there are no more rows in the result set, ENTITY.
ENTITY
A
ValueError is thrown when the
constructor_args is non-empty with the class not having a constructor.
ENTITY
ENTITY
ENTITY
8.3.0
Now throws a
ValueError exception when the
constructor_args is non-empty with the class not having a constructor; previously an
Exception was thrown.
8.0.0
constructor_args now accepts
[] for constructors with 0 parameters; previously an exception was thrown.
ENTITY
mysqli_result::fetch_object example
ENTITY
query($query);
while ($obj = $result->fetch_object()) {
printf("%s (%s)\n", $obj->Name, $obj->CountryCode);
}
ENTITY
Name, $obj->CountryCode);
}
ENTITY
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
ENTITY
mysqli_fetch_array,
mysqli_fetch_assoc,
mysqli_fetch_column,
mysqli_fetch_row,
mysqli_query,
mysqli_data_seek
fetch-row
mysqli_result::fetch_row
mysqli_fetch_row
Fetch the next row of a result set as an enumerated array
ENTITY
ENTITY
public
array
null
false
mysqli_result::fetch_row
ENTITY
array
null
false
mysqli_fetch_row
mysqli_result
result
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 ENTITY if there are no more rows.
ENTITY
ENTITY
ENTITY
Returns an enumerated array representing the fetched row, ENTITY if there are no more rows in the result set, ENTITY.
ENTITY
mysqli_result::fetch_row example
ENTITY
query($query);
/* fetch object array */
while ($row = $result->fetch_row()) {
printf("%s (%s)\n", $row[0], $row[1]);
}
ENTITY
field_count
ENTITY
int
mysqli_num_fields
mysqli_result
result
Returns the number of fields in the result set.
ENTITY
ENTITY
An
int representing the number of fields.
ENTITY
ENTITY
query("SELECT Name, CountryCode, District, Population FROM City ORDER BY ID LIMIT 1");
/* Get the number of fields in the result set */
$field_cnt = $result->field_count;
printf("Result set has %d fields.\n", $field_cnt);
ENTITY
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();
?>
ENTITY
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);
?>
ENTITY
Name: SurfaceArea
Table: Country
max. Len: 10
Flags: 32769
Type: 4
ENTITY
mysqli_fetch_field
free
mysqli_result::free
mysqli_result::close
mysqli_result::free_result
mysqli_free_result
Frees the memory associated with a result
ENTITY
ENTITY
public
void
mysqli_result::free
public
void
mysqli_result::close
public
void
mysqli_result::free_result
ENTITY
void
mysqli_free_result
mysqli_result
result
Frees the memory associated with the result.
ENTITY
ENTITY
ENTITY
ENTITY
mysqli_query,
mysqli_stmt_get_result,
mysqli_store_result,
mysqli_use_result
getiterator
mysqli_result::getIterator
Retrieve an external iterator
ENTITY
public
Iterator
mysqli_result::getIterator
ENTITY
ENTITY ENTITY
ENTITY
lengths
mysqli_result::$lengths
mysqli_fetch_lengths
Returns the lengths of the columns of the current row in the result set
ENTITY
ENTITY
array
null
mysqli_result-ENTITYlengths
ENTITY
array
false
mysqli_fetch_lengths
mysqli_result
result
The
mysqli_fetch_lengths function returns an array containing the lengths of every column of the current row within the result set.
ENTITY
ENTITY
An array of integers representing the size of each column (not including any terminating null characters). ENTITY if an error occurred.
mysqli_fetch_lengths is valid only for the current row of the result set. It returns ENTITY if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.
ENTITY
ENTITY
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();
?>
ENTITY
$val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
ENTITY
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
num-rows
mysqli_result::$num_rows
mysqli_num_rows
Gets the number of rows in the result set
ENTITY
ENTITY
int
string
mysqli_result-ENTITYnum_rows
ENTITY
int
string
mysqli_num_rows
mysqli_result
result
Returns the number of rows in the result set.
The behaviour of
mysqli_num_rows depends on whether buffered or unbuffered result sets are being used. This function returns
0 for unbuffered result sets unless all rows have been fetched from the server.
ENTITY
ENTITY
An ENTITY representing the number of fetched rows. Returns
0 in unbuffered mode unless all rows have been fetched from the server.
ENTITY
ENTITY
ENTITY
query("SELECT Code, Name FROM Country ORDER BY Name");
/* Get the number of rows in the result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
ENTITY
query("CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
$stmt = $mysqli->prepare($query);
/* Bind variable for placeholder */
$code = 'A%';
$stmt->bind_param("s", $code);
/* execute statement */
$stmt->execute();
printf("Rows inserted: %d\n", $stmt->affected_rows);
ENTITY
prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
$stmt->execute();
printf("%d row inserted.\n", $stmt->affected_rows);
/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d row deleted.\n", $mysqli->affected_rows);
ENTITY
prepare("SELECT Language FROM CountryLanguage WHERE CountryCode IN (?, ?)");
/* Using ... to provide arguments */
$stmt->bind_param('ss', ...['DEU', 'POL']);
$stmt->execute();
$stmt->store_result();
printf("%d rows found.\n", $stmt->num_rows());
ENTITY
10 rows found.
ENTITY
mysqli_stmt_bind_result,
mysqli_stmt_execute,
mysqli_stmt_fetch,
mysqli_prepare,
mysqli_stmt_send_long_data,
mysqli_stmt_errno,
mysqli_stmt_error
bind-result
mysqli_stmt::bind_result
mysqli_stmt_bind_result
Binds variables to a prepared statement for result storage
ENTITY
ENTITY
public
bool
mysqli_stmt::bind_result
mixed
var
mixed
vars
ENTITY
bool
mysqli_stmt_bind_result
mysqli_stmt
statement
mixed
var
mixed
vars
Binds columns in the result set to variables.
When
mysqli_stmt_fetch is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables
var/
vars.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time
mysqli_stmt_fetch is called.
[!NOTE]
All columns must be bound after
mysqli_stmt_execute and prior to calling
mysqli_stmt_fetch.
[!NOTE]
Depending on column types bound variables can silently change to the corresponding PHP type.
[!TIP]
This function is useful for simple results. To retrieve an iterable result set, or fetch each row as an array or object, use
mysqli_stmt_get_result.
ENTITY
var
The first variable to be bound.
vars
Further variables to be bound.
ENTITY
ENTITY
ENTITY
ENTITY
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);
}
ENTITY
prepare($query);
$stmt->execute();
$stmt->bind_result($name, $code);
$stmt->store_result();
/* seek to row no. 400 */
$stmt->data_seek(399);
$stmt->fetch();
printf("City: %s Countrycode: %s\n", $name, $code);
ENTITY
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();
?>
ENTITY
ENTITY
Error: 1146.
ENTITY
mysqli_stmt_error,
mysqli_stmt_sqlstate
error-list
mysqli_stmt::$error_list
mysqli_stmt_error_list
Returns a list of errors from the last statement executed
ENTITY
ENTITY
array
mysqli_stmt-ENTITYerror_list
ENTITY
array
mysqli_stmt_error_list
mysqli_stmt
statement
Returns an array of errors for the most recently invoked statement function that can succeed or fail.
ENTITY
ENTITY
A list of errors, each as an associative
array containing the errno, error, and sqlstate.
ENTITY
ENTITY
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();
?>
ENTITY
ENTITY
Error:
Array
(
[0] => Array
(
[errno] => 1146
[sqlstate] => 42S02
[error] => Table 'world.myCountry' doesn't exist
)
)
ENTITY
mysqli_stmt_error,
mysqli_stmt_errno,
mysqli_stmt_sqlstate
error
mysqli_stmt::$error
mysqli_stmt_error
Returns a string description for last statement error
ENTITY
ENTITY
string
mysqli_stmt-ENTITYerror
ENTITY
string
mysqli_stmt_error
mysqli_stmt
statement
Returns a string containing the error message for the most recently invoked statement function that can succeed or fail.
ENTITY
ENTITY
A string that describes the error. An empty string if no error occurred.
ENTITY
ENTITY
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();
?>
ENTITY
ENTITY
Error: Table 'world.myCountry' doesn't exist.
ENTITY
mysqli_stmt_errno,
mysqli_stmt_sqlstate
execute
mysqli_stmt::execute
mysqli_stmt_execute
Executes a prepared statement
ENTITY
ENTITY
public
bool
mysqli_stmt::execute
array
null
params
ENTITY
ENTITY
bool
mysqli_stmt_execute
mysqli_stmt
statement
array
null
params
ENTITY
Executes a previously prepared statement. The statement must be successfully prepared prior to execution, using either the
mysqli_prepare or
mysqli_stmt_prepare function, or by passing the second argument to mysqli_stmt::__construct.
If the statement is
UPDATE,
DELETE, or
INSERT, the total number of affected rows can be determined by using the
mysqli_stmt_affected_rows function. If the query yields a result set, it can be fetched using
mysqli_stmt_get_result function or by fetching it row by row directly from the statement using
mysqli_stmt_fetch function.
ENTITY
params
An optional list ENTITY with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a ENTITY.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
8.1.0
The optional
params parameter has been added.
ENTITY
Execute a prepared statement with bound variables
ENTITY
query("CREATE TEMPORARY TABLE myCity LIKE City");
/* Prepare an insert statement */
$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");
/* Bind variables to parameters */
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
$stmt->execute();
/* Retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
ENTITY
query('CREATE TEMPORARY TABLE myCity LIKE City');
/* Prepare an insert statement */
$stmt = $mysqli->prepare('INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');
/* Execute the statement */
$stmt->execute(['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);
/* Retrieve all rows from myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
ENTITY
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();
?>
ENTITY
ENTITY
Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)
ENTITY
mysqli_prepare,
mysqli_stmt_errno,
mysqli_stmt_error,
mysqli_stmt_bind_result
field-count
mysqli_stmt::$field_count
mysqli_stmt_field_count
Returns the number of columns in the given statement
ENTITY
ENTITY
int
mysqli_stmt-ENTITYfield_count
ENTITY
int
mysqli_stmt_field_count
mysqli_stmt
statement
Returns the number of columns in the prepared statement.
ENTITY
ENTITY
Returns an integer representing the number of columns.
ENTITY
ENTITY
prepare("SELECT Name FROM Country WHERE Code=?");
$stmt->bind_param('s', $code);
$stmt->execute();
$row = $stmt->get_result()->fetch_row();
for ($i = 0; $i < $stmt->field_count; $i++) {
printf("Value of column number %d is %s", $i, $row[$i]);
}
ENTITY
prepare($query);
$stmt->bind_param("s", $continent);
$continentList = array('Europe', 'Africa', 'Asia', 'North America');
foreach ($continentList as $continent) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
}
ENTITY
query("CREATE TEMPORARY TABLE myCity LIKE City");
$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District, Population) VALUES (?, ?, ?, ?)");
$name = 'Stuttgart';
$countryCode = 'DEU';
$district = 'Stuttgart';
$population = 617000;
$stmt->bind_param('sssi', $name, $countryCode, $district, $population);
$stmt->execute();
printf("New record has ID %d.\n", $stmt->insert_id);
ENTITY
prepare($query);
$stmt->execute();
/* store the result in an internal buffer */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
ENTITY
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();
?>
ENTITY
ENTITY
Statement has 2 markers.
ENTITY
mysqli_prepare
prepare
mysqli_stmt::prepare
mysqli_stmt_prepare
Prepares an SQL statement for execution
ENTITY
ENTITY
public
bool
mysqli_stmt::prepare
string
query
ENTITY
bool
mysqli_stmt_prepare
mysqli_stmt
statement
string
query
Prepares a statement for execution. The query must consist of a single SQL statement.
The statement template can contain zero or more question mark (
?) parameter markers—also called placeholders. The parameter markers must be bound to application variables using
mysqli_stmt_bind_param before executing the statement.
[!NOTE]
In the case where a statement is passed to
mysqli_stmt_prepare that is longer than
max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (
mysqlnd) or MySQL Client Library (
libmysqlclient). The behavior is as follows:
mysqlnd on Linux returns an error code of 1153. The error message means “got a packet bigger than
max_allowed_packet bytes”.
mysqlnd on Windows returns an error code 2006. This error message means “server has gone away”.
libmysqlclient on all platforms returns an error code 2006. This error message means “server has gone away”.
ENTITY
query
The query, as a string. It must consist of a single SQL statement.
The SQL statement may contain zero or more parameter markers represented by question mark (
?) characters at the appropriate positions.
[!NOTE]
The markers are legal only in certain places in SQL statements. For example, they are permitted in the
VALUES() list of an
INSERT statement (to specify column values for a row), or in a comparison with a column in a
WHERE clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
mysqli_stmt::prepare example
ENTITY
stmt_init();
$stmt->prepare("SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
ENTITY
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);
?>
ENTITY
name);
?>
ENTITY
mysqli_prepare,
mysqli_free_result,
mysqli_stmt_get_result
send-long-data
mysqli_stmt::send_long_data
mysqli_stmt_send_long_data
Send data in blocks
ENTITY
ENTITY
public
bool
mysqli_stmt::send_long_data
int
param_num
string
data
ENTITY
bool
mysqli_stmt_send_long_data
mysqli_stmt
statement
int
param_num
string
data
Allows sending 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.
ENTITY
param_num
Indicates which parameter to associate the data with. Parameters are numbered beginning with 0.
data
A string containing data to be sent.
ENTITY
ENTITY
ENTITY
ENTITY
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();
?>
ENTITY
mysqli_prepare,
mysqli_stmt_bind_param
sqlstate
mysqli_stmt::$sqlstate
mysqli_stmt_sqlstate
Returns SQLSTATE error from previous statement operation
ENTITY
ENTITY
string
mysqli_stmt-ENTITYsqlstate
ENTITY
string
mysqli_stmt_sqlstate
mysqli_stmt
statement
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 ENTITY.
ENTITY
ENTITY
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters.
'00000' means no error.
ENTITY
ENTITY
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();
?>
ENTITY
ENTITY
Error: 42S02.
ENTITY
[!NOTE]
Note that not all MySQL errors are yet mapped to SQLSTATEs. The value
HY000 (general error) is used for unmapped errors.
ENTITY
mysqli_stmt_errno,
mysqli_stmt_error
store-result
mysqli_stmt::store_result
mysqli_stmt_store_result
Stores a result set in an internal buffer
ENTITY
ENTITY
public
bool
mysqli_stmt::store_result
ENTITY
bool
mysqli_stmt_store_result
mysqli_stmt
statement
This function should be called for queries that successfully produce a result set (e.g.
SELECT, SHOW, DESCRIBE, EXPLAIN) only if the complete result set needs to be buffered in PHP. Each subsequent
mysqli_stmt_fetch call will return buffered data.
[!NOTE]
It is unnecessary to call
mysqli_stmt_store_result for other queries, but if you do, it will not harm or cause any notable performance loss in all cases. You can detect whether the query produced a result set by checking if
mysqli_stmt_result_metadata returns ENTITY.
ENTITY
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
ENTITY
prepare($query);
$stmt->execute();
/* store the result in an internal buffer */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
ENTITY
query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $result->fetch_assoc();
echo $row['_msg'];
ENTITY
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.
Bad coding style
fetch_assoc()) {
echo $row['_msg'];
}
ENTITY
Possible but bad style.
See also
mysqli::__construct, mysqli::query, mysqli_result::fetch_assoc, $mysqli::connect_errno, $mysqli::connect_error, $mysqli::errno, $mysqli::error
Connections
The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.
The hostname
localhost has a special meaning. It is bound to the use of Unix domain sockets. To open a TCP/IP connection to the localhost,
127.0.0.1 must be used instead of the hostname
localhost.
Special meaning of localhost
host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
echo $mysqli->host_info . "\n";
ENTITY
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.
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 nor a Windows named pipe-based connection is to be established and the port parameter value is unset, the library will default to port
3306.
The mysqlnd library and the MySQL Client Library (libmysqlclient) implement the same logic for determining defaults.
Connection options
Connection options are available to, for example, set init commands which are executed upon connect, or for requesting use of a certain charset. Connection options must be set before a network connection is established.
For setting a connection option, the connect operation has to be performed in three steps: creating a connection handle with
mysqli_init or mysqli::__construct, setting the requested options using mysqli::options, and establishing the network connection with mysqli::real_connect.
Connection pooling
The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default, every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.
Every PHP process is using its own mysqli connection pool. Depending on the web server deployment model, a PHP process may serve one or multiple requests. Therefore, a pooled connection may be used by one or more scripts subsequently.
Persistent connection
If an unused persistent connection for a given combination of host, username, password, socket, port and default database cannot be found in the connection pool, then mysqli opens a new connection. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links. The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent. Please note that the web server may spawn many PHP processes.
A common complaint about persistent connections is that their state is not reset before reuse. For example, open and unfinished transactions are not automatically rolled back. But also, authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. This may be seen as an unwanted side-effect. On the contrary, the name
persistent may be understood as a promise that the state is persisted.
The mysqli extension supports both interpretations of a persistent connection: state persisted, and state reset before reuse. The default is reset. Before a persistent connection is reused, the mysqli extension implicitly calls mysqli::change_user to reset the state. The persistent connection appears to the user as if it was just opened. No artifacts from previous usages are visible.
The mysqli::change_user call is an expensive operation. For best performance, users may want to recompile the extension with the compile flag
MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set.
It is left to the user to choose between safe behavior and best performance. Both are valid optimization goals. For ease of use, the safe behavior has been made the default at the expense of maximum performance.
See also
mysqli::__construct,
mysqli_init, mysqli::options, mysqli::real_connect, mysqli::change_user, $mysqli::host_info, MySQLi Configuration Options, Persistent Database Connections
Executing statements
Statements can be executed with the mysqli::query, mysqli::real_query and mysqli::multi_query. The mysqli::query function is the most common, and combines the executing statement with a buffered fetch of its result set, if any, in one call. Calling mysqli::query is identical to calling mysqli::real_query followed by mysqli::store_result.
Executing queries
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
Buffered result sets
After statement execution, results can be either retrieved all at once or read row by row from the server. Client-side result set buffering allows the server to free resources associated with the statement's results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli::query combines statement execution and result set buffering.
PHP applications can navigate freely through buffered results. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.
Navigation through buffered results
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$result = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
echo "Reverse order...\n";
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
$row = $result->fetch_assoc();
echo " id = " . $row['id'] . "\n";
}
echo "Result set order...\n";
foreach ($result as $row) {
echo " id = " . $row['id'] . "\n";
}
ENTITY
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.
Navigation through unbuffered results
real_query("SELECT id FROM test ORDER BY id ASC");
$result = $mysqli->use_result();
echo "Result set order...\n";
foreach ($result as $row) {
echo " id = " . $row['id'] . "\n";
}
Result set values data types
The mysqli::query, mysqli::real_query and mysqli::multi_query functions are used to execute non-prepared statements. At the level of the MySQL Client Server Protocol, the command
COM_QUERY and the text protocol are used for statement execution. With the text protocol, the MySQL server converts all data of a result sets into strings before sending. This conversion is done regardless of the SQL result set column data type. The mysql client libraries receive all column values as strings. No further client-side casting is done to convert columns back to their native types. Instead, all values are provided as PHP strings.
Text protocol returns strings by default
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");
$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
ENTITY
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.
Native data types with mysqlnd and connection option
options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");
$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
ENTITY
id = 1 (integer)
label = a (string)
See also
mysqli::__construct, mysqli::options, mysqli::real_connect, mysqli::query, mysqli::multi_query, mysqli::use_result, mysqli::store_result
Prepared Statements
The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency and protect against SQL injections.
Basic workflow
The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is sent to the database server. The server performs a syntax check and initializes server internal resources for later use.
The MySQL server supports using anonymous, positional placeholder with
?.
Prepare is followed by execute. During execute the client binds parameter values and sends them to the server. The server executes the statement with the bound values using the previously created internal resources.
Prepared statement
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
$label = 'PHP';
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string
$stmt->execute();
Repeated execution
A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.
INSERT prepared once, executed multiple times
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");
/* Prepared statement, stage 2: bind and execute */
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string
$data = [
1 => 'PHP',
2 => 'Java',
3 => 'C++'
];
foreach ($data as $id => $label) {
$stmt->execute();
}
$result = $mysqli->query('SELECT id, label FROM test');
var_dump($result->fetch_all(MYSQLI_ASSOC));
ENTITY
array(3) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["label"]=>
string(3) "PHP"
}
[1]=>
array(2) {
["id"]=>
string(1) "2"
["label"]=>
string(4) "Java"
}
[2]=>
array(2) {
["id"]=>
string(1) "3"
["label"]=>
string(3) "C++"
}
}
Every prepared statement occupies server resources. Statements should be closed explicitly immediately after use. If not done explicitly, the statement will be closed when the statement handle is freed by PHP.
Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement. This is why the
SELECT is not run as a prepared statement above.
Also, consider the use of the MySQL multi-INSERT SQL syntax for INSERTs. For the example, multi-INSERT requires fewer round-trips between the server and client than the prepared statement shown above.
Less round trips using multi-INSERT SQL
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$values = [1, 2, 3, 4];
$stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?), (?), (?), (?)");
$stmt->bind_param('iiii', ...$values);
$stmt->execute();
Result set values data types
The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. Client libraries receive binary data and try to convert the values into appropriate PHP data types. For example, results from an SQL
INT column will be provided as PHP integer variables.
Native datatypes
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
ENTITY
id = 1 (integer)
label = PHP (string)
This behavior differs from non-prepared statements. By default, non-prepared statements return all results as strings. This default can be changed using a connection option. If the connection option is used, there are no differences.
Fetching results using bound variables
Results from prepared statements can either be retrieved by binding output variables, or by requesting a
mysqli_result object.
Output variables must be bound after statement execution. One variable must be bound for every column of the statements result set.
Output variable binding
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$stmt->bind_result($out_id, $out_label);
while ($stmt->fetch()) {
printf("id = %s (%s), label = %s (%s)\n", $out_id, gettype($out_id), $out_label, gettype($out_label));
}
ENTITY
id = 1 (integer), label = PHP (string)
Prepared statements return unbuffered result sets by default. The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. The result set takes server resources until all results have been fetched by the client. Thus it is recommended to consume results timely. If a client fails to fetch all results or the client closes the statement before having fetched all data, the data has to be fetched implicitly by
mysqli.
It is also possible to buffer the results of a prepared statement using mysqli_stmt::store_result.
Fetching results using mysqli_result interface
Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt::get_result returns a buffered result set.
Using mysqli_result to fetch results
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$result = $stmt->get_result();
var_dump($result->fetch_all(MYSQLI_ASSOC));
ENTITY
array(1) {
[0]=>
array(2) {
["id"]=>
int(1)
["label"]=>
string(3) "PHP"
}
}
Using the
mysqli_result interface offers the additional benefit of flexible client-side result set navigation.
Buffered result set for flexible read out
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP'), (2, 'Java'), (3, 'C++')");
$stmt = $mysqli->prepare("SELECT id, label FROM test");
$stmt->execute();
$result = $stmt->get_result();
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
var_dump($result->fetch_assoc());
}
ENTITY
array(2) {
["id"]=>
int(3)
["label"]=>
string(3) "C++"
}
array(2) {
["id"]=>
int(2)
["label"]=>
string(4) "Java"
}
array(2) {
["id"]=>
int(1)
["label"]=>
string(3) "PHP"
}
Escaping and SQL injection
Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly. A hint must be provided to the server for the type of bound variable, to create an appropriate conversion. See the mysqli_stmt::bind_param function for more information.
Such a separation is sometimes considered the only security feature to prevent SQL injection, but the same degree of security can be achieved with non-prepared statements, if all the values are formatted correctly. It should be noted that correct formatting is not the same as escaping and involves more logic than simple escaping. Thus, prepared statements are simply a more convenient and less error-prone approach to this element of database security.
Client-side prepared statement emulation
The API does not include support for client-side prepared statement emulation.
See also
mysqli::__construct, mysqli::query, mysqli::prepare, mysqli_stmt::prepare, mysqli_stmt::execute, mysqli_stmt::bind_param, mysqli_stmt::bind_result
Stored Procedures
The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The
CALL SQL statement is used to execute a stored procedure.
Parameter
Stored procedures can have
IN,
INOUT and
OUT parameters, depending on the MySQL version. The mysqli interface has no special notion for the different kinds of parameters.
IN parameter
Input parameters are provided with the
CALL statement. Please, make sure values are escaped correctly.
Calling a stored procedure
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;");
$mysqli->query("CALL p(1)");
$result = $mysqli->query("SELECT id FROM test");
var_dump($result->fetch_assoc());
ENTITY
array(1) {
["id"]=>
string(1) "1"
}
INOUT/OUT parameter
The values of
INOUT/
OUT parameters are accessed using session variables.
Using session variables
query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;');
$mysqli->query("SET @msg = ''");
$mysqli->query("CALL p(@msg)");
$result = $mysqli->query("SELECT @msg as _p_out");
$row = $result->fetch_assoc();
echo $row['_p_out'];
ENTITY
Hi!
Application and framework developers may be able to provide a more convenient API using a mix of session variables and database 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.
Fetching results from stored procedures
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$mysqli->multi_query("CALL p()");
do {
if ($result = $mysqli->store_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($mysqli->next_result());
ENTITY
---
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.
Stored Procedures and Prepared Statements
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$stmt = $mysqli->prepare("CALL p()");
$stmt->execute();
do {
if ($result = $stmt->get_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($stmt->next_result());
ENTITY
---
array(3) {
[0]=>
array(1) {
[0]=>
int(1)
}
[1]=>
array(1) {
[0]=>
int(2)
}
[2]=>
array(1) {
[0]=>
int(3)
}
}
---
array(3) {
[0]=>
array(1) {
[0]=>
int(2)
}
[1]=>
array(1) {
[0]=>
int(3)
}
[2]=>
array(1) {
[0]=>
int(4)
}
}
Of course, use of the bind API for fetching is supported as well.
Stored Procedures and Prepared Statements using bind API
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$stmt = $mysqli->prepare("CALL p()");
$stmt->execute();
do {
if ($stmt->store_result()) {
$stmt->bind_result($id_out);
while ($stmt->fetch()) {
echo "id = $id_out\n";
}
}
} while ($stmt->next_result());
ENTITY
id = 1
id = 2
id = 3
id = 2
id = 3
id = 4
See also
mysqli::query, mysqli::multi_query, mysqli::next_result, mysqli::more_results
Multiple Statements
MySQL optionally allows having multiple statements in one statement string, but it requires special handling.
Multiple statements or multi queries must be executed with mysqli::multi_query. The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.
The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.
Multiple Statements
query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
do {
if ($result = $mysqli->store_result()) {
var_dump($result->fetch_all(MYSQLI_ASSOC));
$result->free();
}
} while ($mysqli->next_result());
ENTITY
array(1) {
[0]=>
array(1) {
["_num"]=>
string(1) "0"
}
}
array(1) {
[0]=>
array(1) {
["_num"]=>
string(1) "1"
}
}
Security considerations
The API functions mysqli::query and mysqli::real_query do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the damage of accidental SQL injection attacks. An attacker may try to add statements such as
; DROP DATABASE mysql or
; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli::multi_query is not used, the server will not execute the injected and malicious SQL statement.
SQL Injection
query("SELECT 1; DROP TABLE mysql.user");
?>
ENTITY
PHP Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to
use near 'DROP TABLE mysql.user' at line 1
Prepared statements
Use of the multiple statement with prepared statements is not supported.
See also
mysqli::query, mysqli::multi_query, mysqli::next_result, mysqli::more_results
API support for transactions
The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, the default storage engine is InnoDB. InnoDB has full ACID transaction support.
Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the
autocommit mode and for committing and rolling back transactions.
Setting
autocommit mode with SQL and through the API
autocommit(false);
/* Won't be monitored and recognized by the replication and the load balancing plugin */
$mysqli->query('SET AUTOCOMMIT = 0');
Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting
autocommit mode, committing or rolling back a transaction.
Commit and rollback
autocommit(false);
$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->rollback();
$mysqli->query("INSERT INTO test(id) VALUES (2)");
$mysqli->commit();
Please note, that the MySQL server cannot roll back all statements. Some statements cause an implicit commit.
See also
mysqli::autocommit, mysqli::begin_transaction, mysqli::commit, mysqli::rollback
Metadata
A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the
mysqli interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.
Meta data is access through the
mysqli_result interface.
Accessing result set meta data
query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($result->fetch_fields());
ENTITY
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.
Prepared statements metadata
prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$result = $stmt->result_metadata();
var_dump($result->fetch_fields());
See also
mysqli::query, mysqli_result::fetch_fields
reference
ENTITY
setup
ENTITY
ENTITY
In order to have these functions available, you must compile PHP with support for the mysqli extension.
MySQL 8
When running a PHP version before 7.1.16, or PHP 7.2 before 7.2.4, set MySQL 8 Server's default password plugin to mysql_native_password or else you will see errors similar to The server requested authentication method unknown to the client [caching_sha2_password] even when caching_sha2_password is not used.
This is because MySQL 8 defaults to caching_sha2_password, a plugin that is not recognized by the older PHP (mysqlnd) releases. Instead, change it by setting
default_authentication_plugin=mysql_native_password in
my.cnf. The caching_sha2_password plugin is fully supported as of PHP 7.4.4. For older releases, the mysql_xdevapi extension does support it.
ENTITY ENTITY
book
ENTITY
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.
The
php and
php_binary serialize handlers place restrictions on root-level keys in
$_SESSION. Nested keys inside arrays or objects stored in the session are not subject to these restrictions. The following root-level keys are not allowed:
Numeric keys (for example
$_SESSION[0]). Such keys are skipped when the session is written, and a warning is emitted.
String keys that contain
| when using the
php serialize handler. Using such a key causes session write failure (and a warning as of PHP 8.5.0).
The
php_serialize handler does not have these limitations, and may be used when numeric keys or keys containing
| must be stored at the root of
$_SESSION.
[!NOTE]
Please note when working with sessions that a record of a session is not created until a variable has been registered 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.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
configure
ENTITY
ENTITY
--disable-session
To use shared memory allocation (mm) for session storage configure PHP
--with-mm[=DIR].
ENTITY
[!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.
constants
ENTITY ENTITY
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.
[!WARNING]
This constant has been deprecated as of PHP 8.4.0.
PHP_SESSION_DISABLED (
int)
Return value of
session_status if sessions are disabled.
PHP_SESSION_NONE (
int)
Return value of
session_status if sessions are enabled, but no session exists.
PHP_SESSION_ACTIVE (
int)
Return value of
session_status if sessions are enabled, and a session exists.
examples
ENTITY
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.
Registering a variable with
$_SESSION.
Unregistering a variable with
$_SESSION.
[!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.
[!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 ENTITY directive allows to customize the argument separator. For full XHTML conformance, specify ENTITYamp; 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.
Counting the number of hits of a single user
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. A session handlers may be created using the
SessionHandlerInterface or extending PHP's internal 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-abort
session_abort
Discard session array changes and finish session
ENTITY
bool
session_abort
session_abort finishes session without saving data. Thus the original values in session data are kept.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
7.2.0
The return type of this function is
bool now. Formerly, it has been
void.
ENTITY
$_SESSION, The session.auto_start configuration directive,
session_start,
session_reset,
session_commit
session-cache-expire
session_cache_expire
Get and/or set current cache expire
ENTITY
int
false
session_cache_expire
int
null
value
ENTITY
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).
ENTITY
value
If
value is given and not ENTITY, the current cache expire is replaced with
value.
[!NOTE]
Setting
value is of value only, if
session.cache_limiter is set to a value different from
nocache.
ENTITY
Returns the current setting of
session.cache_expire. The value returned should be read in minutes, defaults to 180. On failure to change the value, ENTITY is returned.
ENTITY
ENTITY
ENTITY
8.0.0
value is nullable now.
ENTITY
session_cache_expire example
";
echo "The cached session pages expire after $cache_expire minutes";
?>
ENTITY
session.cache_expire, session.cache_limiter,
session_cache_limiter
session-cache-limiter
session_cache_limiter
Get and/or set the current cache limiter
ENTITY
string
false
session_cache_limiter
string
null
value
ENTITY
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).
ENTITY
value
If
value is specified and not ENTITY, 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 the current script)
private_no_expire
Cache-Control: private, max-age=(session.cache_expire in the future)
Last-Modified: (the timestamp of the current script)
private
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=(session.cache_expire in the future)
Last-Modified: (the timestamp of the current script)
nocache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
ENTITY
Returns the name of the current cache limiter. On failure to change the value, ENTITY is returned.
ENTITY
ENTITY
ENTITY
8.0.0
value is nullable now.
ENTITY
session_cache_limiter example
";
?>
ENTITY
session.cache_limiter
session-commit
session_commit
ENTITY
session_write_close
ENTITY
ENTITY
session_write_close.
session-create-id
session_create_id
Create new session id
ENTITY
string
false
session_create_id
string
prefix
""
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.
ENTITY
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-zA-Z0-9,-] are allowed. Maximum length is 256 characters.
ENTITY
session_create_id returns new collision free session id for the current session. If it is used without active session, it omits collision check. On failure, ENTITY is returned.
ENTITY
session_create_id example with
session_regenerate_id
ENTITY
session_regenerate_id,
session_start, session.use_strict_mode, SessionHandler::create_sid
session-decode
session_decode
Decodes session data from a session encoded string
ENTITY
bool
session_decode
string
data
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.
ENTITY
data
The encoded data to be stored.
ENTITY
ENTITY
ENTITY
session_encode, session.serialize_handler
session-destroy
session_destroy
Destroys all data registered to a session
ENTITY
bool
session_destroy
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.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
Destroying a session with
$_SESSION
ENTITY
session.use_strict_mode,
session_reset,
session_regenerate_id,
unset,
setcookie
session-encode
session_encode
Encodes the current session data as a session encoded string
ENTITY
string
false
session_encode
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.
ENTITY ENTITY
ENTITY
Returns the contents of the current session encoded, ENTITY.
ENTITY
[!WARNING]
Must call
session_start before using
session_encode.
ENTITY
session_decode, session.serialize_handler
session-gc
session_gc
Perform session data garbage collection
ENTITY
int
false
session_gc
By default, PHP uses session.gc_probability to run the session garbage collector probabilistically on each request. There are some limitations with this approach:
Low traffic sites may not have their session data deleted within the preferred duration.
High traffic sites may have the garbage collector run too frequently, performing unnecessary extra work.
Garbage collection is performed on the user's request, and the user may experience a delay.
For production systems, it is recommended to disable the probability-based garbage collection by setting session.gc_probability to
0 and explicitly trigger the garbage collector periodically, for example by using "cron" on UNIX-like systems to run a script that calls
session_gc.
[!NOTE]
When calling
session_gc from a command-line php script, the session.save_path must be set to the same value as web requests, and the script must have access and delete permissions for the session files. This may be affected by the user the script runs as, and container or sandboxing features such as systemd's
PrivateTmp= option.
ENTITY ENTITY
ENTITY
session_gc returns the number of deleted session entries on success, ENTITY.
[!NOTE]
Old session save handlers do not return the number of deleted session entries, but rather only a success/failure flag. If this is the case,
1 is returned regardless of how many session entries are actually deleted.
ENTITY
session_gc example for task managers like cron
session_gc example for user accessible script
ENTITY
session_start
session_destroy
session.gc_probability
session-get-cookie-params
session_get_cookie_params
Get the session cookie parameters
ENTITY
array
session_get_cookie_params
Gets the session cookie parameters.
ENTITY ENTITY
ENTITY
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.
"partitioned" - The cookie is marked as Partitioned (CHIPS).
"httponly" - The cookie can only be accessed through the HTTP protocol.
"samesite" - Controls the cross-domain sending of the cookie.
ENTITY
ENTITY
ENTITY
8.5.0
The "partitioned" entry was added in the returned array.
7.3.0
The "samesite" entry was added in the returned array.
ENTITY
session.cookie_lifetime, session.cookie_path, session.cookie_domain, session.cookie_secure, session.cookie_httponly, session.cookie_partitioned, session.cookie_samesite,
session_set_cookie_params
session-id
session_id
Get and/or set the current session id
ENTITY
string
false
session_id
string
null
id
ENTITY
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.
ENTITY
id
If
id is specified and not ENTITY, 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-zA-Z0-9,-]!
[!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.
ENTITY
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). On failure, ENTITY is returned.
ENTITY
ENTITY
ENTITY
8.0.0
id is nullable now.
ENTITY
session_regenerate_id,
session_start,
session_set_save_handler, session.save_handler
session-module-name
session_module_name
Get and/or set the current session module
ENTITY
string
false
session_module_name
string
null
module
ENTITY
session_module_name gets the name of the current session module, which is also known as session.save_handler.
ENTITY
module
If
module is specified and not ENTITY, 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.
ENTITY
Returns the name of the current session module, ENTITY.
ENTITY
ENTITY
ENTITY
8.0.0
module is nullable now.
7.2.0
It is now explicitly forbidden to set the module name to
"user". Formerly, this has been silently ignored.
session-name
session_name
Get and/or set the current session name
ENTITY
string
false
session_name
string
null
name
ENTITY
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 outputs the content when session.use_trans_sid is enabled). Once the HTTP cookie has been sent, calling
session_name raises an
E_WARNING.
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).
ENTITY
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 and not ENTITY, 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.
ENTITY
Returns the name of the current session. If
name is given and function updates the session name, name of the old session is returned, ENTITY.
ENTITY
ENTITY
ENTITY
8.0.0
name is nullable now.
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.
ENTITY
session_name example
";
?>
ENTITY
The session.name configuration directive
session-regenerate-id
session_regenerate_id
Update the current session id with a newly generated one
ENTITY
bool
session_regenerate_id
bool
delete_old_session
ENTITY
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.
ENTITY
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.
ENTITY
ENTITY
ENTITY
A
session_regenerate_id example
";
echo "New Session: $new_sessionid ";
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.
Avoiding lost session by
session_regenerate_id
ENTITY
session_id,
session_create_id,
session_start,
session_destroy,
session_reset,
session_name
session-register-shutdown
session_register_shutdown
Session shutdown function
ENTITY
void
session_register_shutdown
Registers
session_write_close as a shutdown function.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
Emits
E_WARNING if registering the shutdown function fails.
session-reset
session_reset
Re-initialize session array with original values
ENTITY
bool
session_reset
session_reset reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
7.2.0
The return type of this function is
bool now. Formerly, it has been
void.
ENTITY
$_SESSION, The session.auto_start configuration directive,
session_start,
session_abort,
session_commit
session-save-path
session_save_path
Get and/or set the current session save path
ENTITY
string
false
session_save_path
string
null
path
ENTITY
session_save_path returns the path of the current directory used to save session data.
ENTITY
path
Session data path. If specified and not ENTITY, 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.
ENTITY
Returns the path of the current directory used for data storage, ENTITY.
ENTITY
ENTITY
ENTITY
8.0.0
path is nullable now.
ENTITY
The session.save_path configuration directive
session-set-cookie-params
session_set_cookie_params
Set the session cookie parameters
ENTITY
bool
session_set_cookie_params
int
lifetime_or_options
string
null
path
ENTITY
string
null
domain
ENTITY
bool
null
secure
ENTITY
bool
null
httponly
ENTITY
Alternative signature available as of PHP 7.3.0:
bool
session_set_cookie_params
array
lifetime_or_options
Set cookie parameters defined in the ENTITY 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.
ENTITY
lifetime_or_options
When using the first signature, lifetime of the session cookie, defined in seconds.
When using the second signature, an associative
array which may have any of the keys
lifetime,
path,
domain,
secure,
httponly,
partitioned 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.
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 ENTITY cookie will only be sent over secure connections.
httponly
If set to ENTITY then PHP will attempt to send the httponly flag when setting the session cookie.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.5.0
The "partitioned" entry was added in the
lifetime_or_options array. If set to
true, the cookie will be marked as Partitioned (CHIPS).
8.0.0
path,
domain,
secure and
httponly are nullable now.
7.3.0
An alternative signature supporting an
lifetime_or_options ENTITY has been added. This signature supports also setting of the SameSite cookie attribute.
7.2.0
ENTITY Formerly the function returned
void.
ENTITY
session.cookie_lifetime, session.cookie_path, session.cookie_domain, session.cookie_secure, session.cookie_httponly, session.cookie_partitioned, session.cookie_samesite,
session_get_cookie_params
session-set-save-handler
session_set_save_handler
Sets user-level session storage functions
ENTITY
bool
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
Alternative signature (not supported with named arguments):
bool
session_set_save_handler
object
sessionhandler
bool
register_shutdown
ENTITY
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.
ENTITY
This function has two prototypes.
sessionhandler
An instance of a class implementing SessionHandlerInterface, and optionally SessionIdInterface and/or SessionUpdateTimestampHandlerInterface, such as
SessionHandler, to register as the session handler.
register_shutdown
Register
session_write_close as a
register_shutdown_function function.
or
open
A callable with the following signature:
bool
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 ENTITY for success, ENTITY for failure.
close
A callable with the following signature:
bool
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 ENTITY for success, ENTITY for failure.
read
A callable with the following signature:
stringfalse
string``sessionId
The
read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read. It must return ENTITY to report a failure:
session_start then emits an
E_WARNING and returns ENTITY.
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
A callable with the following signature:
bool
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
A callable with the following signature:
bool
string``sessionId
This callback is executed when a session is destroyed with
session_destroy or with
session_regenerate_id with the destroy parameter set to ENTITY. Return value should be ENTITY for success, ENTITY for failure.
gc
A callable with the following signature:
bool
int``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 ENTITY for success, ENTITY for failure.
create_sid
A callable with the following signature:
string
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.
validate_sid
A callable with the following signature:
bool
string``key
This callback is executed when a session is to be started, a session ID is supplied and session.use_strict_mode is enabled. The
key is the session ID to validate. A session ID is valid, if a session with that ID already exists. The return value should be ENTITY for success, ENTITY for failure.
update_timestamp
A callable with the following signature:
bool
string``key
string``val
This callback is executed when a session is updated.
key is the session ID,
val is the session data. The return value should be ENTITY for success, ENTITY for failure.
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
8.4.0
Calling
session_set_save_handler with more than two arguments is now deprecated. Use the two argument signature instead.
ENTITY
Custom session handler: see full code in
SessionHandlerInterface synopsis.
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.
page 2';
// Or maybe pass along the session id, if needed
echo ' page 2';
?>
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.
page2.php
';
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 ' page 1';
?>
Providing options to
session_start
Overriding the cookie lifetime
86400,
]);
?>
Reading the session and closing it
86400,
'read_and_close' => true,
]);
ENTITY
[!NOTE]
To use cookie-based sessions,
session_start must be called before outputting 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.
ENTITY
$_SESSION, The session.auto_start configuration directive,
session_id
session-status
session_status
Returns the current session status
ENTITY
int
session_status
session_status is used to return the current session status.
ENTITY ENTITY
ENTITY
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.
ENTITY
session_start
session-unset
session_unset
Free all session variables
ENTITY
bool
session_unset
The
session_unset function frees all session variables currently registered.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
7.2.0
The return type of this function is
bool now. Formerly, it has been
void.
ENTITY
[!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]
The use of
session_unset is identical to
$_SESSION = [].
[!CAUTION]
This function works only if a session is active. It will not clear the
$_SESSION array if the session has not been started yet or has already been destroyed. Use
$_SESSION = [] to unset all session variables even if the session is not active.
session-write-close
session_write_close
Write session data and end session
ENTITY
bool
session_write_close
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.
ENTITY ENTITY
ENTITY
Returns ENTITY if no session is active, ENTITY otherwise. ENTITY is also returned if the save handler fails to write the session data.
ENTITY
ENTITY
ENTITY
8.5.0
If
$_SESSION contains a key with a pipe character (`
7.2.0
The return type of this function is
bool now. Formerly, it has been
void.
ENTITY
session_register_shutdown
session_start
session_abort
ini
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
session.save_path
""
INI_ALL
session.name
"PHPSESSID"
INI_ALL
session.save_handler
"files"
INI_ALL
session.auto_start
"0"
INI_PERDIR
session.gc_probability
"1"
INI_ALL
session.gc_divisor
"100"
INI_ALL
session.gc_maxlifetime
"1440"
INI_ALL
session.serialize_handler
"php"
INI_ALL
session.cookie_lifetime
"0"
INI_ALL
session.cookie_path
"/"
INI_ALL
session.cookie_domain
""
INI_ALL
session.cookie_secure
"0"
INI_ALL
Prior to PHP 7.2.0, the default was
"".
session.cookie_httponly
"0"
INI_ALL
Prior to PHP 7.2.0, the default was
"".
session.cookie_partitioned
"0"
INI_ALL
Available as of PHP 8.5.0.
session.cookie_samesite
""
INI_ALL
Available as of PHP 7.3.0.
session.use_strict_mode
"0"
INI_ALL
session.use_cookies
"1"
INI_ALL
session.use_only_cookies
"1"
INI_ALL
Disabling this setting is deprecated as of PHP 8.4.0.
session.referer_check
""
INI_ALL
Setting a non-empty value is deprecated as of PHP 8.4.0.
session.cache_limiter
"nocache"
INI_ALL
session.cache_expire
"180"
INI_ALL
session.use_trans_sid
"0"
INI_ALL
Enabling this setting is deprecated as of PHP 8.4.0.
session.trans_sid_tags
"a=href,area=href,frame=src,form="
INI_ALL
Available as of PHP 7.1.0. Changing this setting is deprecated as of PHP 8.4.0.
session.trans_sid_hosts
$_SERVER['HTTP_HOST']
INI_ALL
Available as of PHP 7.1.0. Setting a non-empty value is deprecated as of PHP 8.4.0.
session.sid_length
"32"
INI_ALL
Available as of PHP 7.1.0. Changing this setting is deprecated as of PHP 8.4.0.
session.sid_bits_per_character
"4"
INI_ALL
Available as of PHP 7.1.0. Changing this setting is deprecated as of PHP 8.4.0.
session.upload_progress.enabled
"1"
INI_PERDIR
session.upload_progress.cleanup
"1"
INI_PERDIR
session.upload_progress.prefix
"upload_progress_"
INI_PERDIR
session.upload_progress.name
"PHP_SESSION_UPLOAD_PROGRESS"
INI_PERDIR
session.upload_progress.freq
"1%"
INI_PERDIR
session.upload_progress.min_freq
"1"
INI_PERDIR
session.lazy_write
"1"
INI_ALL
session.hash_function
"0"
INI_ALL
Removed as of PHP 7.1.0.
session.hash_bits_per_character
"4"
INI_ALL
Removed as of PHP 7.1.0.
session.entropy_file
""
INI_ALL
Removed as of PHP 7.1.0.
session.entropy_length
"0"
INI_ALL
Removed as of PHP 7.1.0.
Session configuration options
ENTITY
The session management system supports a number of configuration options which you can place in your ENTITY 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 ENTITY 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 ENTITY.
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 this is 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.
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
bool
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 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
int
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. Must be greater than or equal to
0. See session.gc_divisor for details.
session.gc_divisor
int
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. Must be greater than
0.
session.gc_maxlifetime
int
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). Defaults to
1440 (24 minutes).
[!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.
[!WARNING]
Setting
session.referer_check to a non-empty value is deprecated as of PHP 8.4.0.
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. 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.
session.entropy_file defaults to
/dev/urandom or
/dev/arandom if it is available.
session.entropy_length
int
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
bool
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 IDs. If an uninitialized session ID is sent from the browser, a new session ID is sent to the 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.
[!WARNING]
If a custom session handler registered via
session_set_save_handler does not implement SessionUpdateTimestampHandlerInterface::validateId, nor supplies the
validate_sid callback, respectively, strict session ID mode is effectively disabled, regardless of the value of this directive. Particularly note that
SessionHandler does not implement SessionHandler::validateId.
session.use_cookies
bool
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
bool
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 that involve passing session IDs in URLs. Defaults to
1 (enabled).
[!WARNING]
Disabling
session.use_only_cookies is deprecated as of PHP 8.4.0.
session.cookie_lifetime
int
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
bool
session.cookie_secure specifies whether cookies should only be sent over secure connections. With this option set to
on, sessions only work with HTTPS connections. If it is
off, then sessions work with both HTTP and HTTPS connections. Defaults to
off. See also
session_get_cookie_params and
session_set_cookie_params.
session.cookie_httponly
bool
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_partitioned
bool
Marks the cookie as partitioned (CHIPS), which means that the cookie will be isolated to a first-party context. This setting can help mitigate cross-site tracking (although it is not supported by all browsers).
If enabled, session.cookie_secure must also be enabled, otherwise the session cookie will not be sent and a warning is raised.
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 send 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
int
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
bool
session.use_trans_sid whether transparent sid support is enabled or not. Defaults to
0 (disabled).
[!WARNING]
Enabling
session.use_trans_sid is deprecated as of PHP 8.4.0.
[!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,form=
form is special tag.
ENTITYinput hidden="session_id" name="session_name"ENTITY is added as form variable.
[!WARNING]
Changing
session.trans_sid_tags from its default value is deprecated as of PHP 8.4.0.
[!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
[!WARNING]
Setting
session.trans_sid_hosts to a non-empty value is deprecated as of PHP 8.4.0.
session.sid_length
int
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. A longer session ID is harder to guess.
[!WARNING]
Changing
session.sid_length from its default value is deprecated as of PHP 8.4.0.
[!NOTE]
Available as of PHP 7.1.0.
session.sid_bits_per_character
int
session.sid_bits_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. More bits result in a stronger session ID.
[!WARNING]
Changing
session.sid_bits_per_character from its default value is deprecated as of PHP 8.4.0.
[!NOTE]
Available as of 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).
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]
Removed in PHP 7.1.0.
session.hash_bits_per_character
int
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
bool
Enables upload progress tracking, populating the
$_SESSION variable. Defaults to 1, enabled.
[!WARNING]
Upload progress writes the client-supplied file name and field name to the session store while the upload in progress, to allow polling the process from a separate request. In applications that do not use upload progress bars, consider disabling this option; file names and field names are not validated and may contain PHP code, making any local file inclusion vulnerability trivial to exploit.
session.upload_progress.cleanup
bool
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
int
The minimum delay between updates, in seconds. Defaults to "1" (one second).
session.lazy_write
bool
session.lazy_write, when set to 1, means that session data is only rewritten if it changes. Defaults to 1, enabled.
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.
reference
ENTITY
Sessions and Security
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.
Non-adaptive Session Management
PHP's session manager is adaptive by default currently. An adaptive session manager bears additional risks.
When session.use_strict_mode 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 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. (
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. session.use_strict_mode=On is mandatory for general session ID security! All sites are advised to enable session.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 website. 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 or POST 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
Disabling transparent session ID management improves the general session ID security by eliminating the possibility of a session ID injection and/or leak.
[!WARNING]
Enabling
session.use_trans_sid is deprecated as of PHP 8.4.0.
[!NOTE]
Session ID may leak from bookmarked URLs, e-mailed URLs, saved HTML source, etc.
session.trans_sid_tags="a=href,area=href,frame=src,form="
Unneeded HTML tags should not be rewritten. The default value is sufficient for most usages. Older PHP versions use url_rewriter.tags instead.
[!WARNING]
Changing
session.trans_sid_tags from its default value is deprecated as of PHP 8.4.0.
session.trans_sid_hosts=""
This setting lists the hosts for which the session ID may be added to URLs. Untrusted hosts must never be added. When it is empty, the session module only allows
$_SERVER['HTTP_HOST'].
[!WARNING]
Setting
session.trans_sid_hosts to a non-empty value is deprecated as of PHP 8.4.0.
session.referer_check=""
When session.use_trans_sid is enabled, a non-empty value reduces the risk of session ID injection: the session ID sent by the client is discarded unless the
Referer header contains that value. Note that with HTTPS browsers will not send the
Referer header, and browsers may omit it by configuration. Therefore, this setting is not a reliable security measure.
[!WARNING]
Setting
session.referer_check to a non-empty value is deprecated as of PHP 8.4.0.
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.save_path=[non world-readable directory]
If this is 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.
sessionhandler
ENTITY
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 that 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 to
session_set_save_handler.
ENTITY
SessionHandler
implements
SessionHandlerInterface
SessionIdInterface
ENTITY
ENTITY
[!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.
ENTITY
Using
SessionHandler to add encryption to internal PHP save handlers.
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 ENTITY 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.
ENTITY
close
SessionHandler::close
Close the session
ENTITY
public
bool
SessionHandler::close
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 inheritance, calling the parent
close method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows the method to be overridden and or intercepted.
For more information on what this method is expected to do, please refer to the documentation at
SessionHandlerInterface::close.
ENTITY ENTITY
ENTITY
ENTITY
create-sid
SessionHandler::create_sid
Return a new session ID
ENTITY
public
string
SessionHandler::create_sid
Generates and returns a new session ID.
ENTITY ENTITY
ENTITY
A session ID valid for the default session handler.
ENTITY
session_id,
session_create_id
destroy
SessionHandler::destroy
Destroy a session
ENTITY
public
bool
SessionHandler::destroy
string
id
Destroys a session. Called internally by PHP with
session_regenerate_id (assuming the
destroy is set to ENTITY, 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 inheritance, calling the parent
destroy method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered.
For more information on what this method is expected to do, please refer to the documentation at
SessionHandlerInterface::destroy.
ENTITY
id
The session ID being destroyed.
ENTITY
ENTITY
gc
SessionHandler::gc
Cleanup old sessions
ENTITY
public
int
false
SessionHandler::gc
int
max_lifetime
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 inheritance, 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 overridden and or intercepted and filtered.
For more information on what this method is expected to do, please refer to the documentation at
SessionHandlerInterface::gc.
ENTITY
max_lifetime
Sessions that have not updated for the last
max_lifetime seconds will be removed.
ENTITY
Returns the number of deleted sessions on success, ENTITY. Note this value is returned internally to PHP for processing.
ENTITY
ENTITY
ENTITY
7.1.0
Prior to this version, the function returned ENTITY on success.
open
SessionHandler::open
Initialize session
ENTITY
public
bool
SessionHandler::open
string
path
string
name
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 inheritance, calling the parent
open method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered.
For more information on what this method is expected to do, please refer to the documentation at
SessionHandlerInterface::open.
ENTITY
path
The path where to store/retrieve the session.
name
The session name.
ENTITY
ENTITY
ENTITY
The session.auto-start configuration directive.
read
SessionHandler::read
Read session data
ENTITY
public
string
false
SessionHandler::read
string
id
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 explicitly with
session_start and is preceded 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 therefore invoke the associated internal callback. This allows the method to be overridden and or intercepted and filtered (for example, decrypting the
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.
ENTITY
id
The session id to read data for.
ENTITY
Returns the encoded session data from the internal save handler, an empty string if it holds no data for the session ID, or ENTITY if the internal save handler failed to read. Note this value is returned internally to PHP for processing.
ENTITY
The session.serialize_handler configuration directive.
write
SessionHandler::write
Write session data
ENTITY
public
bool
SessionHandler::write
string
id
string
data
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 inheritance, calling the parent
write method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden 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.
ENTITY
id
The session id.
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.
ENTITY
ENTITY
ENTITY
The session.serialize_handler configuration directive.
sessionhandlerinterface
ENTITY
SessionHandlerInterface is an interface which defines the minimal 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 can 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.
ENTITY
SessionHandlerInterface
ENTITY
ENTITY
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.
savePath = $savePath;
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}
return true;
}
public function close(): bool
{
return true;
}
#[\ReturnTypeWillChange]
public function read($id)
{
return (string) @file_get_contents("$this->savePath/sess_$id");
}
public function write($id, $data): bool
{
return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}
public function destroy($id): bool
{
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}
return true;
}
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
$deleted = 0;
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $maxlifetime < time() && file_exists($file) && unlink($file)) {
$deleted++;
}
}
return $deleted;
}
}
$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
// proceed to set and retrieve values by key from $_SESSION
ENTITY
close
SessionHandlerInterface::close
Close the session
ENTITY
public
bool
SessionHandlerInterface::close
Closes the current session. This function is automatically executed when closing the session, or explicitly via
session_write_close.
ENTITY ENTITY
ENTITY
ENTITY
destroy
SessionHandlerInterface::destroy
Destroy a session
ENTITY
public
bool
SessionHandlerInterface::destroy
string
id
Destroys a session. Called by
session_regenerate_id (with $destroy = ENTITY),
session_destroy and when
session_decode fails.
ENTITY
id
The session ID being destroyed.
ENTITY
ENTITY
gc
SessionHandlerInterface::gc
Cleanup old sessions
ENTITY
public
int
false
SessionHandlerInterface::gc
int
max_lifetime
Cleans up expired sessions. Called by
session_start, based on session.gc_divisor, session.gc_probability and session.gc_maxlifetime settings.
ENTITY
max_lifetime
Sessions that have not updated for the last
max_lifetime seconds will be removed.
ENTITY
Returns the number of deleted sessions on success, ENTITY. Note this value is returned internally to PHP for processing.
ENTITY
ENTITY
ENTITY
7.1.0
Prior to this version, the function returned ENTITY on success.
open
SessionHandlerInterface::open
Initialize session
ENTITY
public
bool
SessionHandlerInterface::open
string
path
string
name
Re-initialize existing session, or creates a new one. Called when a session starts or when
session_start is invoked.
ENTITY
path
The path where to store/retrieve the session.
name
The session name.
ENTITY
ENTITY
ENTITY
session_name, The session.auto-start configuration directive.
read
SessionHandlerInterface::read
Read session data
ENTITY
public
string
false
SessionHandlerInterface::read
string
id
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. Return an empty string when no data is stored for the given session ID; return ENTITY only to report a failure.
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.
ENTITY
id
The session id.
ENTITY
Returns an encoded string of the read data, or an empty string if no data is stored for the session ID. Returning ENTITY reports a failure:
session_start then emits an
E_WARNING and returns ENTITY. Note this value is returned internally to PHP for processing.
ENTITY
The session.serialize_handler configuration directive.
write
SessionHandlerInterface::write
Write session data
ENTITY
public
bool
SessionHandlerInterface::write
string
id
string
data
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
ENTITY
id
The session id.
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.
ENTITY
ENTITY
ENTITY
The session.serialize_handler configuration directive.
sessionidinterface
ENTITY
SessionIdInterface is an interface which defines optional methods 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 can implement this interface.
Note that the callback methods of classes implementing this interface are designed to be called internally by PHP and are not meant to be called from user-space code.
ENTITY
SessionIdInterface
ENTITY
ENTITY
create-sid
SessionIdInterface::create_sid
Create session ID
ENTITY
public
string
SessionIdInterface::create_sid
Creates a new session ID.This function is automatically executed when a new session ID needs to be created.
ENTITY ENTITY
ENTITY
The new session ID. Note that this value is returned internally to PHP for processing.
ENTITY
SessionHandler::create_sid
sessionupdatetimestamphandlerinterface
ENTITY
SessionUpdateTimestampHandlerInterface is an interface which defines optional methods 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 can implement this interface.
Note that the callback methods of classes implementing this interface are designed to be called internally by PHP and are not meant to be called from user-space code.
ENTITY
SessionUpdateTimestampHandlerInterface
ENTITY
ENTITY
updatetimestamp
SessionUpdateTimestampHandlerInterface::updateTimestamp
Update timestamp
ENTITY
public
bool
SessionUpdateTimestampHandlerInterface::updateTimestamp
string
id
string
data
Updates the last modification timestamp of the session. This function is automatically executed when a session is updated.
ENTITY
id
The session ID.
data
The session data. The serialized session data may be used to determine whether the session data has changed and therefore should be updated.
ENTITY
Returns ENTITY if the timestamp was updated, ENTITY otherwise. Note that this value is returned internally to PHP for processing.
validateid
SessionUpdateTimestampHandlerInterface::validateId
Validate ID
ENTITY
public
bool
SessionUpdateTimestampHandlerInterface::validateId
string
id
Validates a given session ID. A session ID is valid, if a session with that ID already exists. This function is automatically executed when a session is to be started, a session ID is supplied and session.use_strict_mode is enabled.
ENTITY
id
The session ID.
ENTITY
Returns ENTITY for valid ID, ENTITY otherwise. Note that this value is returned internally to PHP for processing.
setup
ENTITY
ENTITY ENTITY
[!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.
ENTITY ENTITY
Session Upload Progress
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.
It is also possible to cancel the currently in-progress file upload, by setting the
$_SESSION[$key]["cancel_upload"] key to ENTITY. 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 information
Example of the structure of the progress upload array.
The data stored in the session will look like this:
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 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. This also means that user session handlers are never used for the session information for upload progress information, since there is no code that could have set the session handler to be a user handler by calling
session_set_save_handler.