Reference
- book
- configure
- constants
- constants_curl_error
- constants_curl_getinfo
- constants_curl_multi
- constants_curl_multi_setopt
- constants_curl_pause
- constants_curl_setopt
- constants_curl_share_setopt
- constants_curlproto
- curlfile
- construct
- getfilename
- getmimetype
- getpostfilename
- setmimetype
- setpostfilename
- curlhandle
- curlmultihandle
- curlsharehandle
- curlsharepersistenthandle
- curlstringfile
- construct
- examples
- curl-close
- curl-copy-handle
- curl-errno
- curl-error
- curl-escape
- curl-exec
- curl-getinfo
- curl-init
- curl-multi-add-handle
- curl-multi-close
- curl-multi-errno
- curl-multi-exec
- curl-multi-get-handles
- curl-multi-getcontent
- curl-multi-info-read
- curl-multi-init
- curl-multi-remove-handle
- curl-multi-select
- curl-multi-setopt
- curl-multi-strerror
- curl-pause
- curl-reset
- curl-setopt-array
- curl-setopt
- curl-share-close
- curl-share-errno
- curl-share-init-persistent
- curl-share-init
- curl-share-setopt
- curl-share-strerror
- curl-strerror
- curl-unescape
- curl-upkeep
- curl-version
- ini
- reference
- setup
- book
- constants
- json-decode
- json-encode
- json-last-error-msg
- json-last-error
- json-validate
- jsonexception
- jsonserializable
- jsonserialize
- reference
- setup
- book
- configure
- constants
- PHP Character Encoding Requirements
- Summaries of supported encodings
- mb-check-encoding
- mb-chr
- mb-convert-case
- mb-convert-encoding
- mb-convert-kana
- mb-convert-variables
- mb-decode-mimeheader
- mb-decode-numericentity
- mb-detect-encoding
- mb-detect-order
- mb-encode-mimeheader
- mb-encode-numericentity
- mb-encoding-aliases
- mb-ereg-match
- mb-ereg-replace-callback
- mb-ereg-replace
- 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-ereg-search
- mb-ereg
- mb-eregi-replace
- mb-eregi
- mb-get-info
- mb-http-input
- mb-http-output
- mb-internal-encoding
- mb-language
- mb-lcfirst
- mb-list-encodings
- mb-ltrim
- mb-ord
- mb-output-handler
- mb-parse-str
- mb-preferred-mime-name
- mb-regex-encoding
- mb-regex-set-options
- mb-rtrim
- mb-scrub
- mb-send-mail
- mb-split
- mb-str-pad
- mb-str-split
- mb-strcut
- mb-strimwidth
- mb-stripos
- mb-stristr
- mb-strlen
- mb-strpos
- mb-strrchr
- mb-strrichr
- mb-strripos
- mb-strrpos
- mb-strstr
- mb-strtolower
- mb-strtoupper
- mb-strwidth
- mb-substitute-character
- mb-substr-count
- mb-substr
- mb-trim
- mb-ucfirst
- HTTP Input and Output
- ini
- Basics of Japanese multi-byte encodings
- Function Overloading Feature
- reference
- setup
- Supported Character Encodings
- book
- configure
- constants
- mysqli-execute
- mysqli-get-client-stats
- mysqli-get-links-stats
- ini
- mysqli
- affected-rows
- autocommit
- begin-transaction
- change-user
- character-set-name
- close
- commit
- connect-errno
- connect-error
- construct
- debug
- dump-debug-info
- errno
- error-list
- error
- escape-string
- execute-query
- field-count
- get-charset
- get-client-info
- get-client-version
- get-connection-stats
- get-host-info
- get-proto-info
- get-server-info
- get-server-version
- get-warnings
- info
- init
- insert-id
- kill
- more-results
- multi-query
- next-result
- options
- ping
- poll
- prepare
- query
- quote-string
- real-connect
- real-escape-string
- real-query
- reap-async-query
- refresh
- release-savepoint
- rollback
- savepoint
- select-db
- set-charset
- set-opt
- sqlstate
- ssl-set
- stat
- stmt-init
- store-result
- thread-id
- thread-safe
- use-result
- warning-count
- mysqli_driver
- embedded-server-end
- embedded-server-start
- report-mode
- mysqli_result
- construct
- current-field
- data-seek
- fetch-all
- fetch-array
- fetch-assoc
- fetch-column
- fetch-field-direct
- fetch-field
- fetch-fields
- fetch-object
- fetch-row
- field-count
- field-seek
- free
- getiterator
- lengths
- num-rows
- mysqli_sql_exception
- getsqlstate
- mysqli_stmt
- affected-rows
- attr-get
- attr-set
- bind-param
- bind-result
- close
- construct
- data-seek
- errno
- error-list
- error
- execute
- fetch
- field-count
- free-result
- get-result
- get-warnings
- insert-id
- more-results
- next-result
- num-rows
- param-count
- prepare
- reset
- result-metadata
- send-long-data
- sqlstate
- store-result
- mysqli_warning
- construct
- next
- Overview
- The mysqli Extension and Persistent Connections
- Quick start guide
- reference
- setup
- book
- configure
- constants
- examples
- session-abort
- session-cache-expire
- session-cache-limiter
- session-commit
- session-create-id
- session-decode
- session-destroy
- session-encode
- session-gc
- session-get-cookie-params
- session-id
- session-module-name
- session-name
- session-regenerate-id
- session-register-shutdown
- session-reset
- session-save-path
- session-set-cookie-params
- session-set-save-handler
- session-start
- session-status
- session-unset
- session-write-close
- ini
- reference
- Sessions and Security
- sessionhandler
- close
- create-sid
- destroy
- gc
- open
- read
- write
- sessionhandlerinterface
- close
- destroy
- gc
- open
- read
- write
- sessionidinterface
- create-sid
- sessionupdatetimestamphandlerinterface
- updatetimestamp
- validateid
- setup
- Session Upload Progress
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.dllandssleay32.dll, or, as of OpenSSL 1.1libcrypto-*.dllandlibssl-*.dll, must be present in yourPATH. Alsolibssh2.dllmust be present in yourPATH.You don't need
libcurl.dllfrom 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<pushfunction> 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_closeis a no-op and does not destroy the handle. If cookies need to be written prior to the handle being automatically destroyed, runcurl_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<callback> 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<callback> 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<callback> 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<callback> 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_NOPROGRESSoption 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_DEFAULTwhich 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_USERNAMEandCURLOPT_PROXY_TLSAUTH_PASSWORDoptions 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<callback> 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<callback> 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_SSLv2orCURL_SSLVERSION_SSLv3is 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<callback> 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<callback> 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<callback> 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<callback> 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
<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/
// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');
// Create a CURLFile object
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');
// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Execute the handle
curl_exec($ch);
?>
ENTITY
<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/
// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');
// Create a CURLFile object
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');
// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Execute the handle
curl_exec($ch);
?>
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
<?php
$request = curl_init('http://www.example.com/upload.php');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($request, CURLOPT_POSTFIELDS, [
'blob[0]' => 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
<?php
// procedural
$request = curl_init('http://www.example.com/upload.php');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($request, CURLOPT_POSTFIELDS, [
'blob[0]' => 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
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
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
<?php
/* http://example.com/upload.php:
<?php
var_dump($_FILES);
var_dump(file_get_contents($_FILES['test_string']['tmp_name']));
?>
*/
// 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
<?php
$data = ['foo' => '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
<?php
$post_data = ['foo' => '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
<?php
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_error($ch)) {
fwrite($fp, curl_error($ch));
}
fclose($fp);
curl-close
curl_close
Close a cURL session
ENTITY
ENTITY
#[\Deprecated(since: '8.5', message: "as it has no effect since PHP 8.0")]
void
curl_close
CurlHandle
handle
ENTITY
Closes a cURL session and frees all resources. The cURL handle, handle, is also deleted.
ENTITY
ENTITY
ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.5.0 | This function has been deprecated. |
| 8.0.0 | This function is a NOP now. |
ENTITY
Initializing a new cURL session and fetching a web page
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
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
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);
// copy the handle
$ch2 = curl_copy_handle($ch);
// grab URL (http://www.example.com/) and pass it to the browser
curl_exec($ch2);
?>
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
CurlHandleis executed viacurl_multi_exec, this function returns0untilcurl_multi_info_readhas returned the message for that handle. The error code for each individual handle is available as theresultkey returned bycurl_multi_info_read.
ENTITY
| ENTITY | ENTITY |
|---|
ENTITY
curl_errno example
<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
// Execute
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
// Check if any error occurred
if(curl_errno($ch))
{
echo 'Curl error: ' . curl_error($ch);
}
?>
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
CurlHandleis executed viacurl_multi_exec, this function returns''(the empty string) untilcurl_multi_info_readhas returned the message for that handle. To retrieve the error string for each individual handle, pass theresultkey returned bycurl_multi_info_readtocurl_strerror.
ENTITY
| ENTITY | ENTITY |
|---|
ENTITY
curl_error example
<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}
?>
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
<?php
// Create a curl handle
$ch = curl_init();
// Escape a string used as a GET parameter
$location = curl_escape($ch, 'Hofbräuhaus / München');
// Result: Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen
// Compose an URL with the escaped string
$url = "http://example.com/add_location.php?location={$location}";
// Result: http://example.com/add_location.php?location=Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen
// Set options and send HTTP request
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
?>
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_getinfocan be used to check for these.
ENTITY
| ENTITY | ENTITY |
|---|
ENTITY
Fetching a web page
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
?>
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_OUTis set by a previous call tocurl_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
<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');
// Execute
curl_exec($ch);
// Check if any error occurred
if (!curl_errno($ch)) {
$info = curl_getinfo($ch);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
}
?>
curl_getinfo example with option parameter
<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');
// Execute
curl_exec($ch);
// Check HTTP status code
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
}
}
?>
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
fileprotocol 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
<?php
// Initializes a new cURL session
$ch = curl_init();
// Set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// Grab URL and pass it to the browser
curl_exec($ch);
?>
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.
<?php
$urls = [
"https://www.php.net/",
"https://www.example.com/",
];
$mh = curl_multi_init();
$map = new WeakMap();
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($mh, $ch);
$map[$ch] = $url;
}
do {
$status = curl_multi_exec($mh, $unfinishedHandles);
if ($status !== CURLM_OK) {
throw new \Exception(curl_multi_strerror(curl_multi_errno($mh)));
}
while (($info = curl_multi_info_read($mh)) !== false) {
if ($info['msg'] === CURLMSG_DONE) {
$handle = $info['handle'];
curl_multi_remove_handle($mh, $handle);
$url = $map[$handle];
if ($info['result'] === CURLE_OK) {
$statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
echo "Request to {$url} finished with HTTP status {$statusCode}:", PHP_EOL;
echo curl_multi_getcontent($handle);
echo PHP_EOL, PHP_EOL;
} else {
echo "Request to {$url} failed with error: ", PHP_EOL;
echo curl_strerror($info['result']);
echo PHP_EOL, PHP_EOL;
}
}
}
if ($unfinishedHandles) {
if (($updatedHandles = curl_multi_select($mh)) === -1) {
throw new \Exception(curl_multi_strerror(curl_multi_errno($mh)));
}
}
} while ($unfinishedHandles);
curl_multi_close($mh);
?>
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
<?php
// Create a curl handle
$ch = curl_init();
// Set CURLOPT_USERAGENT option
curl_setopt($ch, CURLOPT_USERAGENT, "My test user-agent");
// Reset all previously set options
curl_reset($ch);
// Send HTTP request
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_exec($ch); // the previously set user-agent will be not sent, it has been reset by curl_reset
?>
ENTITY
[!NOTE]
curl_resetalso resets the URL given as thecurl_initparameter.
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
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
$options = array(CURLOPT_URL => 'http://www.example.com/',
CURLOPT_HEADER => false
);
curl_setopt_array($ch, $options);
// grab URL and pass it to the browser
curl_exec($ch);
?>
ENTITY
[!NOTE] As with
curl_setopt, passing an array toCURLOPT_POSTwill 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
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
curl_exec($ch);
?>
ENTITY
[!NOTE] Passing an array to
CURLOPT_POSTFIELDSwill 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
ENTITY
ENTITY
#[\Deprecated(since: '8.5', message: "as it has no effect since PHP 8.0")]
void
ENTITY
ENTITY
ENTITY
ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.5.0 | This function has been deprecated. |
| 8.0.0 | This function is a NOP now. |
ENTITY
ENTITY
curl-share-errno
Return the last share curl error number
ENTITY
int
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
Initialize a
persistent
ENTITY
array
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
[!NOTE]
CURL_LOCK_DATA_COOKIEis 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
ENTITY
ENTITY
ENTITY
curl_setopt
curl-share-init
Initialize a cURL share handle
ENTITY
ENTITY ENTITY
ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | This function returns a CurlShareHandle instance now; previously, a resource was returned. |
ENTITY
ENTITY
curl-share-setopt
Set an option for a cURL share handle
ENTITY
bool
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-strerror
Return string describing the given error code
ENTITY
string
null
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_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
<?php
// Create a curl handle with a misspelled protocol in URL
$ch = curl_init("htp://example.com/");
// Send request
curl_exec($ch);
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
?>
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
<?php
// Create a curl handle
$ch = curl_init('http://example.com/redirect.php');
// Send HTTP request and follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
// Get the last effective URL
$effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
// ie. "http://example.com/show_location.php?loc=M%C3%BCnchen"
// Decode the URL
$effective_url_decoded = curl_unescape($ch, $effective_url);
// "http://example.com/show_location.php?loc=München"
?>
ENTITY
[!NOTE]
curl_unescapedoes not decode plus symbols (+) into spaces.urldecodedoes.
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
<?php
$url = "https://example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_UPKEEP_INTERVAL_MS, 200);
if (curl_exec($ch)) {
usleep(300000);
var_dump(curl_upkeep($ch));
}
?>
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.
<?php
// Get curl version array
$version = curl_version();
// These are the bitfields that can be used
// to check for features in the curl build
$bitfields = Array(
'CURL_VERSION_IPV6',
'CURL_VERSION_KERBEROS4',
'CURL_VERSION_SSL',
'CURL_VERSION_LIBZ'
);
foreach($bitfields as $feature)
{
echo $feature . ($version['features'] & constant($feature) ? ' matches' : ' does not match');
echo PHP_EOL;
}
?>
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
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
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.
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
common mistakes using json_decode
<?php
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
?>
depth errors
<?php
// Encode some data with a maximum depth of 4 (array -> 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
<?php
$json = '{"number": 12345678901234567890}';
var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));
?>
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_errorcan 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
<?php
$arr = array('a' => 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
<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");
echo "Normal: ", json_encode($a), "\n";
echo "Tags: ", json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";
$b = array();
echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";
$c = array(array(1,2,3));
echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";
$d = array('foo' => 'bar', 'baz' => 'long');
echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>
ENTITY
Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]
Empty array output as array: []
Empty array output as object: {}
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}
Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}
JSON_NUMERIC_CHECK option example
<?php
echo "Strings representing numbers automatically turned into numbers".PHP_EOL;
$numbers = array('+123123', '-123123', '1.2e3', '0.00001');
var_dump(
$numbers,
json_encode($numbers, JSON_NUMERIC_CHECK)
);
echo "Strings containing improperly formatted numbers".PHP_EOL;
$strings = array('+a33123456789', 'a123');
var_dump(
$strings,
json_encode($strings, JSON_NUMERIC_CHECK)
);
?>
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
<?php
echo "Sequential array".PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
$sequential,
json_encode($sequential)
);
echo PHP_EOL."Non-sequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
$nonsequential,
json_encode($nonsequential)
);
echo PHP_EOL."Sequential array with one key unset".PHP_EOL;
unset($sequential[1]);
var_dump(
$sequential,
json_encode($sequential)
);
?>
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
<?php
var_dump(json_encode(12.0, JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
?>
ENTITY
string(4) "12.0"
string(2) "12"
ENTITY
[!NOTE] In the event of a failure to encode,
json_last_errorcan 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_encodewill 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 inputvalue. 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
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';
// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
}
?>
ENTITY
Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON
json_last_error with json_encode
<?php
// An invalid UTF8 sequence
$text = "\xB1\x31";
$json = json_encode($text);
$error = json_last_error();
var_dump($json, $error === JSON_ERROR_UTF8);
?>
ENTITY
string(4) "null"
bool(true)
json_last_error and JSON_THROW_ON_ERROR
<?php
// An invalid UTF8 sequence which causes JSON_ERROR_UTF8
json_encode("\xB1\x31");
// The following does not cause a JSON error
json_encode('okay', JSON_THROW_ON_ERROR);
// The global error state has not been changed by the former json_encode()
var_dump(json_last_error() === JSON_ERROR_UTF8);
?>
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_validateimmediately beforejson_decodewill unnecessarily parse the string twice, asjson_decodeimplicitly performs validation during decoding.
json_validateshould 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
<?php
var_dump(json_validate('{ "test": { "foo": "bar" } }'));
var_dump(json_validate('{ "": "": "" } }'));
?>
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
<?php
class ArrayValue implements JsonSerializable {
private $array;
public function __construct(array $array) {
$this->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
<?php
class ArrayValue implements JsonSerializable {
private $array;
public function __construct(array $array) {
$this->array = $array;
}
public function jsonSerialize() {
return $this->array;
}
}
$array = ['foo' => 'bar', 'quux' => 'baz'];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>
ENTITY
{
"foo": "bar",
"quux": "baz"
}
JsonSerializable::jsonSerialize example returning an ENTITY
<?php
class IntegerValue implements JsonSerializable {
private $number;
public function __construct($number) {
$this->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
<?php
class StringValue implements JsonSerializable {
private $string;
public function __construct($string) {
$this->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: Enablembstringfunctions. This option is required to usembstringfunctions.libmbfl is necessary for
mbstring. libmbfl is bundled withmbstring. 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
00hto7fh.
- which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of
-
A multibyte encoding,
-
which has ASCII-compatible mappings for the characters in range of
00hto7fh. -
which don't use ISO2022 escape sequences.
-
which don't use a value from
00hto7fhin 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 encodingfor 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
<?php
$values = [65, 63, 0x20AC, 128024];
foreach ($values as $value) {
var_dump(mb_chr($value, 'UTF-8'));
var_dump(mb_chr($value, 'ISO-8859-1'));
}
?>
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
<?php
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str, PHP_EOL;
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str, PHP_EOL;
?>
mb_convert_case example with non-Latin UTF-8 text
<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str, PHP_EOL;
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str, PHP_EOL;
?>
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
<?php
/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");
/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");
/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");
/* If mbstring.language is "Japanese", "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?>
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
<?php
/* Convert all "han-kaku" "kata-kana" to "zen-kaku" "hira-gana" */
echo mb_convert_kana('ヤマダ ハナコ', "HV") . "\n";
/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
and "zen-kaku" alphanumeric to "han-kaku" */
echo mb_convert_kana('コウザバンゴウ 0123456', "KVa") . "\n";
?>
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
<?php
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?>
mb-decode-mimeheader
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
<?php
$convmap = array(
int start_code1, int end_code1, int offset1, int mask1,
int start_code2, int end_code2, int offset2, int mask2,
// ........
int start_codeN, int end_codeN, int offsetN, int maskN
);
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.
?>
map example escapes JavaScript string
<?php
function escape_javascript_string($str)
{
$map = [
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,0,0, // 49
0,0,0,0,0,0,0,0,1,1,
1,1,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,1,0,0,0, // 99
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 149
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 199
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 249
1,1,1,1,1,1,1, // 255
];
// Char encoding is UTF-8
$mblen = mb_strlen($str, 'UTF-8');
$utf32 = bin2hex(mb_convert_encoding($str, 'UTF-32', 'UTF-8'));
for ($i=0, $encoded=''; $i < $mblen; $i++) {
$u = substr($utf32, $i * 8, 8);
$v = base_convert($u, 16, 10);
if ($v < 256 && $map[$v]) {
$encoded .= '\\x' . substr($u, 6,2);
} else if ($v == 2028) {
$encoded .= '\\u2028';
} else if ($v == 2029) {
$encoded .= '\\u2029';
} else {
$encoded .= mb_convert_encoding(hex2bin($u), 'UTF-8', 'UTF-32');
}
}
return $encoded;
}
// Test data
$convmap = [ 0x0, 0xffff, 0, 0xffff ];
$msg = '';
for ($i=0; $i < 1000; $i++) {
// chr() cannot generate correct UTF-8 data larger value than 128, use mb_decode_numericentity().
$msg .= mb_decode_numericentity('&#' . $i . ';', $convmap, 'UTF-8');
}
// var_dump($msg);
var_dump(escape_javascript_string($msg));
?>
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
<?php
$str = "\x95\xB6\x8E\x9A\x83\x52\x81\x5B\x83\x68";
// Detect character encoding with current detect_order
var_dump(mb_detect_encoding($str));
// "auto" is expanded according to mbstring.language
var_dump(mb_detect_encoding($str, "auto"));
// Specify "encodings" parameter by list separated by comma
var_dump(mb_detect_encoding($str, "JIS, eucjp-win, sjis-win"));
// Use array to specify "encodings" parameter
$encodings = [
"ASCII",
"JIS",
"EUC-JP"
];
var_dump(mb_detect_encoding($str, $encodings));
?>
ENTITY
string(5) "ASCII"
string(5) "ASCII"
string(8) "SJIS-win"
string(5) "ASCII"
Effect of strict parameter
<?php
// 'áéóú' encoded in ISO-8859-1
$str = "\xE1\xE9\xF3\xFA";
// The string is not valid ASCII or UTF-8, but UTF-8 is considered a closer match
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], false));
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], true));
// If a valid encoding is found, the strict parameter does not change the result
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], false));
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], true));
?>
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
<?php
$str = "\xC4\xA2";
// The string is valid in all three encodings, but the first one listed may not always be the one returned
var_dump(mb_detect_encoding($str, ['UTF-8']));
var_dump(mb_detect_encoding($str, ['UTF-8', 'ISO-8859-1', 'ISO-8859-5'])); // as of php8.1 this returns ISO-8859-1 instead of UTF-8
var_dump(mb_detect_encoding($str, ['ISO-8859-1', 'ISO-8859-5', 'UTF-8']));
var_dump(mb_detect_encoding($str, ['ISO-8859-5', 'UTF-8', 'ISO-8859-1']));
?>
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
<?php
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");
/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);
/* Display current detection order */
echo implode(", ", mb_detect_order());
?>
Example 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
<?php
$name = "太郎"; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = '"' . addcslashes(mb_encode_mimeheader($name, "UTF-7", "Q"), '"') . '" <' . $mbox . "@" . $doma . ">";
echo $addr;
?>
ENTITY
"=?UTF-7?Q?+WSqQzg-?=" <kru@gtinn.mon>
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
<?php
$convmap = array(
int start_code1, int end_code1, int offset1, int mask1,
int start_code2, int end_code2, int offset2, int mask2,
// ........
int start_codeN, int end_codeN, int offsetN, int maskN
);
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then converts value to numeric string reference.
?>
mb_encode_numericentity example
<?php
$str = "aAæÆあア𩸽";
/* Convert all UTF8 characters up to 4 bytes to HTML numeric character reference */
$convmap = [0, 0x1FFFFF, 0, 0x10FFFF];
var_dump(mb_encode_numericentity($str, $convmap, "utf8"));
/* Converts only 2-byte and 4-byte UTF8 characters to HTML numeric character reference */
$convmap = [
0x80, 0x7FF, 0, 0x10FFFF,
0x10000, 0x1FFFFF, 0, 0x10FFFF,
];
var_dump(mb_encode_numericentity($str, $convmap, "utf8"));
?>
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
<?php
$encoding = 'ASCII';
$known_encodings = mb_list_encodings();
if (in_array($encoding, $known_encodings)) {
$aliases = mb_encoding_aliases($encoding);
print_r($aliases);
} else {
echo "Unknown ($encoding) encoding.\n";
}
?>
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]
patternis only matched at the beginning ofstring.
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
<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
"next_year",
$text);
?>
ENTITY
April fools day is 04/01/2003
Last christmas was 12/24/2002
mb_ereg_replace_callback using anonymous function
<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
echo mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
function ($matches) {
return $matches[1].($matches[2]+1);
},
$text);
?>
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
<?php
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");
/* Display current internal character encoding */
echo mb_internal_encoding();
?>
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
<?php
print_r(mb_list_encodings());
?>
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
<?php
var_dump(mb_ord("A", "UTF-8"));
var_dump(mb_ord("🐘", "UTF-8"));
var_dump(mb_ord("\x80", "ISO-8859-1"));
var_dump(mb_ord("\x80", "Windows-1252"));
?>
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
<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>
ENTITY
[!NOTE] If you want to output binary data, such as an image, a Content-Type: header must be set using
headerbefore 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
<?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?>
mb-regex-encoding
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 throughmb_regex_set_options. Use it withmb_ereg_replaceormb_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.
<?php
// The byte 0xFF cannot appear in a valid UTF-8 string.
$input = "A\xFFB";
echo bin2hex($input), "\n";
// The default substitute character is "?" (0x3F).
echo bin2hex(mb_scrub($input, 'UTF-8')), "\n";
// U+FFFD REPLACEMENT CHARACTER is encoded as EF BF BD in UTF-8.
mb_substitute_character(0xFFFD);
echo bin2hex(mb_scrub($input, 'UTF-8')), "\n";
?>
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.
<?php
$input = "A\xFFB";
var_dump(preg_match_all('/./us', $input));
echo preg_last_error_msg(), "\n";
$clean = mb_scrub($input, 'UTF-8');
var_dump(preg_match_all('/./us', $clean));
?>
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
Fromheader. This can be set with theadditional_headersparameter, 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. TheFromheader sets alsoReturn-Pathunder 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_stringmay be truncated if the required number of padding characters can't be evenly divided by thepad_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
<?php
var_dump(mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_RIGHT)); // string(18) "▶▶❤❓❇❤"
var_dump(mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_LEFT)); // string(18) "❤❓❇❤▶▶"
var_dump(mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_BOTH)); // string(18) "❤❓▶▶❤❓"
var_dump(mb_str_pad("🎉", 3, "祝", STR_PAD_LEFT)); // string(10) "祝祝🎉"
?>
mb-str-split
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
<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// output: "Hello W..."
?>
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
offsetis greater than the length ofhaystack, aValueErrorwill 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
offsetis greater than the length ofhaystack, aValueErrorwill 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
<?php
// "🐘" is 4 bytes but 1 character; "é" is 2 bytes but 1 character
$str = "🐘H🐘é";
var_dump(mb_strpos($str, "é")); // character 3, not byte 9
var_dump(mb_strpos($str, "🐘", 1)); // character 2, skipping the first "🐘"
?>
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
offsetis greater than the length ofhaystack, aValueErrorwill 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
offsetis greater than the length ofhaystack, aValueErrorwill 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
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>
mb_strtolower example with non-Latin UTF-8 text
<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtolower($str, 'UTF-8');
echo $str; // Prints τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός
?>
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
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>
mb_strtoupper example with non-Latin UTF-8 text
<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtoupper($str, 'UTF-8');
echo $str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
?>
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
<?php
var_dump(
mb_strwidth('a'), // LATIN SMALL LETTER A
mb_strwidth("\u{ff41}") // FULLWIDTH LATIN SMALL LETTER A
);
?>
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
<?php
/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);
/* Set hex format */
mb_substitute_character("long");
/* Display current setting */
echo mb_substitute_character();
?>
mb-substr-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
<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>
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
strtolowerandstrtoupper, 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
enctypefor HTML form is set tomultipart/form-dataandmbstring.encoding_translationis 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 = OffWhen 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_startwithmb_output_handleras theob_startcallback 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
<?php
// Enable output character encoding conversion only for this page
// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');
// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');
?>
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 (
00hto7fh). -
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.
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 ENTITYautoENTITY and ENTITYpassENTITY. mbstring functions which accept an encoding name can also use the value ENTITYautoENTITY.
If ENTITYpassENTITY is set, no character encoding conversion is performed.
If ENTITYautoENTITY 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 ENTITYASCII,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 becausephp_mysqli.dllcannot 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
<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>
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
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
/* Delete table Language */
$mysqli->query("DROP TABLE Language");
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));
mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");
/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));
/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));
/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");
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
<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Turn autocommit off */
$mysqli->autocommit(false);
$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);
try {
/* Prepare insert statement */
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
/* Insert some values */
$language_code = 'DE';
$native_speakers = 50_123_456;
$stmt->execute();
$language_code = 'FR';
$native_speakers = 40_546_321;
$stmt->execute();
/* Commit the data in the database. This doesn't set autocommit=true */
$mysqli->commit();
print "Committed 2 rows in the database\n";
$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);
/* Try to insert more values */
$language_code = 'PL';
$native_speakers = 30_555_444;
$stmt->execute();
$language_code = 'DK';
$native_speakers = 5_222_444;
$stmt->execute();
/* Setting autocommit=true will trigger a commit */
$mysqli->autocommit(true);
print "Committed 2 row in the database\n";
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();
throw $exception;
}
ENTITY
<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Turn autocommit off */
mysqli_autocommit($mysqli, false);
$result = mysqli_query($mysqli, "SELECT @@autocommit");
$row = mysqli_fetch_row($result);
printf("Autocommit is %s\n", $row[0]);
try {
/* Prepare insert statement */
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);
/* Insert some values */
$language_code = 'DE';
$native_speakers = 50_123_456;
mysqli_stmt_execute($stmt);
$language_code = 'FR';
$native_speakers = 40_546_321;
mysqli_stmt_execute($stmt);
/* Commit the data in the database. This doesn't set autocommit=true */
mysqli_commit($mysqli);
print "Committed 2 rows in the database\n";
$result = mysqli_query($mysqli, "SELECT @@autocommit");
$row = mysqli_fetch_row($result);
printf("Autocommit is %s\n", $row[0]);
/* Try to insert more values */
$language_code = 'PL';
$native_speakers = 30_555_444;
mysqli_stmt_execute($stmt);
$language_code = 'DK';
$native_speakers = 5_222_444;
mysqli_stmt_execute($stmt);
/* Setting autocommit=true will trigger a commit */
mysqli_autocommit($mysqli, true);
print "Committed 2 row in the database\n";
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);
throw $exception;
}
ENTITY
Autocommit is 0
Committed 2 rows in the database
Autocommit is 0
Committed 2 row in the database
Autocommit is 0
Committed 2 rows in the database
Autocommit is 0
Committed 2 row in the database
ENTITY
[!NOTE] This function does not work with non transactional table types (like MyISAM or ISAM).
ENTITY
mysqli_begin_transaction, mysqli_commit, mysqli_rollback
begin-transaction
mysqli::begin_transaction
mysqli_begin_transaction
Starts a transaction
ENTITY
ENTITY
public
bool
mysqli::begin_transaction
int
flags
0
string
null
name
ENTITY
ENTITY:
bool
mysqli_begin_transaction
mysqli
mysql
int
flags
0
string
null
name
ENTITY
Begins a transaction. Requires the InnoDB engine (it is enabled by default). For additional details about how MySQL transactions work, see ENTITY.
ENTITY
flags
Valid flags are:
-
MYSQLI_TRANS_START_READ_ONLY: Start the transaction as "START TRANSACTION READ ONLY". Requires MySQL 5.6 and above. -
MYSQLI_TRANS_START_READ_WRITE: Start the transaction as "START TRANSACTION READ WRITE". Requires MySQL 5.6 and above. -
MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT: Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".
name
Savepoint name for the transaction.
ENTITY
ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | name is now nullable. |
ENTITY
mysqli::begin_transaction example
ENTITY
<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Start transaction */
$mysqli->begin_transaction();
try {
/* Insert some values */
$mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");
/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
$stmt->execute();
/* If code reaches this point without errors then commit the data in the database */
$mysqli->commit();
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();
throw $exception;
}
ENTITY
<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Start transaction */
mysqli_begin_transaction($mysqli);
try {
/* Insert some values */
mysqli_query($mysqli, "INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");
/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);
mysqli_stmt_execute($stmt);
/* If code reaches this point without errors then commit the data in the database */
mysqli_commit($mysqli);
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);
throw $exception;
}
ENTITY
[!NOTE] This function does not work with non transactional table types (like MyISAM or ISAM).
ENTITY
mysqli_autocommit, mysqli_commit, mysqli_rollback
change-user
mysqli::change_user
mysqli_change_user
Changes the user of the database connection
ENTITY
ENTITY
public
bool
mysqli::change_user
string
username
#[\SensitiveParameter]
string
password
string
null
database
ENTITY
bool
mysqli_change_user
mysqli
mysql
string
username
#[\SensitiveParameter]
string
password
string
null
database
Attempts to connect to the specified database using the provided credentials.
In comparison to mysqli::connect, this method will not disconnect the current connection if the new connection cannot be opened.
In order to successfully change users, a valid username and password must be provided, and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.
ENTITY
username
The MySQL user name.
password
The MySQL password.
database
The database name. If ENTITY or an empty string is passed, the connection to the server will be opened with no default database.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
Resetting the connection session
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->query("SET @a:=1");
$mysqli->change_user("my_user", "my_password", "world");
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);
$result = $mysqli->query("SELECT @a");
$row = $result->fetch_row();
if ($row[0] === null) {
printf("Value of variable a is NULL\n");
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
mysqli_query($link, "SET @a:=1");
mysqli_change_user($link, "my_user", "my_password", "world");
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database: %s\n", $row[0]);
$result = mysqli_query($link, "SELECT @a");
$row = mysqli_fetch_row($result);
if ($row[0] === null) {
printf("Value of variable a is NULL\n");
}
ENTITY
Default database: world
Value of variable a is NULL
If database is ENTITY the connection is opened without selecting any default database
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->change_user("my_user", "my_password", null);
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Set the default character set */
$mysqli->set_charset('utf8mb4');
/* Print current character set */
$charset = $mysqli->character_set_name();
printf("Current character set is %s\n", $charset);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Set the default character set */
mysqli_set_charset($mysqli, 'utf8mb4');
/* Print current character set */
$charset = mysqli_character_set_name($mysqli);
printf("Current character set is %s\n", $charset);
ENTITY
Current character set is utf8mb4
ENTITY
mysqli_set_charset, mysqli_real_escape_string
close
mysqli::close
mysqli_close
Closes a previously opened database connection
ENTITY
ENTITY
public
true
mysqli::close
ENTITY
true
mysqli_close
mysqli
mysql
Closes a previously opened database connection.
Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.
ENTITY
ENTITY
ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | This function now always returns ENTITY. Previously it returned ENTITY on failure. |
ENTITY
mysqli::close example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
/* Close the connection as soon as it's no longer needed */
$mysqli->close();
foreach ($result as $row) {
/* Processing of the data retrieved from the database */
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($mysqli, "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
/* Close the connection as soon as it's no longer needed */
mysqli_close($mysqli);
foreach ($result as $row) {
/* Processing of the data retrieved from the database */
}
ENTITY
[!NOTE]
mysqli_closewill not close persistent connections. For additional details, see the manual page on persistent connections.
ENTITY
mysqli::__construct, mysqli_init, mysqli_real_connect, mysqli_free_result
commit
mysqli::commit
mysqli_commit
Commits the current transaction
ENTITY
ENTITY
public
bool
mysqli::commit
int
flags
0
string
null
name
ENTITY
ENTITY
bool
mysqli_commit
mysqli
mysql
int
flags
0
string
null
name
ENTITY
Commits the current transaction for the database connection.
ENTITY
flags
A bitmask of MYSQLI_TRANS_COR_* constants.
name
If provided then COMMIT/*name*/ is executed.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | name is now nullable. |
ENTITY
See the mysqli::begin_transaction example.
ENTITY
[!NOTE] This function does not work with non transactional table types (like MyISAM or ISAM).
ENTITY
mysqli_autocommit, mysqli_begin_transaction, mysqli_rollback, mysqli_savepoint
connect-errno
mysqli::$connect_errno
mysqli_connect_errno
Returns the error code from last connect call
ENTITY
ENTITY
int
mysqli->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
<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$mysqli = @new mysqli('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if ($mysqli->connect_errno) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_errno);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$link = @mysqli_connect('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if (!$link) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . mysqli_connect_errno());
}
ENTITY
mysqli_connect, mysqli_connect_error, mysqli_errno, mysqli_error, mysqli_sqlstate
connect-error
mysqli::$connect_error
mysqli_connect_error
Returns a description of the last connection error
ENTITY
ENTITY
string
null
mysqli-ENTITYconnect_error
ENTITY
string
null
mysqli_connect_error
Returns the error message from the last connection attempt.
ENTITY ENTITY
ENTITY
A string that describes the error. ENTITY is returned if no error occurred.
Returns the last connection error regardless of the instance on which it is called.
ENTITY
$mysqli-ENTITYconnect_error example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$mysqli = @new mysqli('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if ($mysqli->connect_error) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_error);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$link = @mysqli_connect('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if (!$link) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . mysqli_connect_error());
}
ENTITY
mysqli_connect, mysqli_connect_errno, mysqli_errno, mysqli_error, mysqli_sqlstate
construct
mysqli::__construct
mysqli::connect
mysqli_connect
Open a new connection to the MySQL server
ENTITY
ENTITY
public
mysqli::__construct
string
null
hostname
ENTITY
string
null
username
ENTITY
#[\SensitiveParameter]
string
null
password
ENTITY
string
null
database
ENTITY
int
null
port
ENTITY
string
null
socket
ENTITY
public
bool
mysqli::connect
string
null
hostname
ENTITY
string
null
username
ENTITY
#[\SensitiveParameter]
string
null
password
ENTITY
string
null
database
ENTITY
int
null
port
ENTITY
string
null
socket
ENTITY
ENTITY
mysqli
false
mysqli_connect
string
null
hostname
ENTITY
string
null
username
ENTITY
#[\SensitiveParameter]
string
null
password
ENTITY
string
null
database
ENTITY
int
null
port
ENTITY
string
null
socket
ENTITY
Opens a connection to the MySQL Server.
ENTITY
hostname
Can be either a host name or an IP address. When passing ENTITY, the value is retrieved from mysqli.default_host. When possible, pipes will be used instead of the TCP/IP protocol. The TCP/IP protocol is used if a host name and port number are provided together e.g. localhost:3308.
Prepending host by p: opens a persistent connection. mysqli_change_user is automatically called on connections opened from the connection pool.
username
The MySQL username or ENTITY to assume the username based on the mysqli.default_user ini option.
password
The MySQL password or ENTITY to assume the password based on the mysqli.default_pw ini option.
database
The default database to be used when performing queries or ENTITY.
port
The port number to attempt to connect to the MySQL server or ENTITY to assume the port based on the mysqli.default_port ini option.
socket
The socket or named pipe that should be used or ENTITY to assume the socket based on the mysqli.default_socket ini option.
[!NOTE] Specifying the
socketparameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by thehostnameparameter.
ENTITY
mysqli::__construct always returns an object which represents the connection to a MySQL Server, regardless of it being successful or not.
mysqli_connect returns an object which represents the connection to a MySQL Server, ENTITY.
mysqli::connect returns ENTITY on successENTITY. Prior to PHP 8.1.0, returns ENTITY on success.
ENTITY ENTITY
As of PHP 8.5.0, calling the constructor on an already-constructed object throws an Error.
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.5.0 | Calling the constructor on an already-constructed object now throws an Error. |
| 8.1.0 | mysqli::connect now returns ENTITY instead of ENTITY on success. |
| 7.4.0 | All parameters are now nullable. |
ENTITY
mysqli::__construct example
ENTITY
<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
printf("Success... %s\n", $mysqli->host_info);
ENTITY
<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
printf("Success... %s\n", mysqli_get_host_info($mysqli));
ENTITY
Success... localhost via TCP/IP
Extending mysqli class
<?php
class FooMysqli extends mysqli {
public function __construct($host, $user, $pass, $db, $port, $socket, $charset) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $user, $pass, $db, $port, $socket);
$this->set_charset($charset);
}
}
$db = new FooMysqli('localhost', 'my_user', 'my_password', 'my_db', 3306, null, 'utf8mb4');
Manual error handling
If error reporting is disabled, the developer is responsible for checking and handling failures
ENTITY
<?php
error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
throw new RuntimeException('mysqli connection error: ' . $mysqli->connect_error);
}
/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
if ($mysqli->errno) {
throw new RuntimeException('mysqli error: ' . $mysqli->error);
}
ENTITY
<?php
error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (mysqli_connect_errno()) {
throw new RuntimeException('mysqli connection error: ' . mysqli_connect_error());
}
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
if (mysqli_errno($mysqli)) {
throw new RuntimeException('mysqli error: ' . mysqli_error($mysqli));
}
ENTITY ENTITY
[!NOTE] ENTITY only: If the connection fails, an object is still returned. To check whether the connection failed, use either the
mysqli_connect_errorfunction or the mysqli-ENTITYconnect_error property as in the preceding examples.
[!NOTE] If it is necessary to set options, such as the connection timeout,
mysqli_real_connectmust be used instead.
[!NOTE] Calling the constructor with no parameters is the same as calling
mysqli_init.
[!NOTE] Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character
E. On Windows, if the environment is not copied theSYSTEMROOTenvironment variable won't be available and PHP will have problems loading Winsock.
ENTITY
mysqli_real_connect, mysqli_options, mysqli_connect_errno, mysqli_connect_error, mysqli_close
debug
mysqli::debug
mysqli_debug
Performs debugging operations
ENTITY
ENTITY
public
true
mysqli::debug
string
options
ENTITY
true
mysqli_debug
string
options
Performs debugging operations using the Fred Fish debugging library.
ENTITY
options
A string representing the debugging operation to perform
The debug control string is a sequence of colon separated fields as follows: <field_1>:<field_2>:<field_N> Each field consists of a mandatory flag character followed by an optional , and comma separated list of modifiers: flag[,modifier,modifier,...,modifier]
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
<?php
/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:o,/tmp/client.trace");
?>
ENTITY
[!NOTE] To use the
mysqli_debugfunction 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
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if (!$mysqli->query("SET a=1")) {
printf("Errorcode: %d\n", $mysqli->errno);
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($link, "SET a=1")) {
printf("Errorcode: %d\n", mysqli_errno($link));
}
/* close connection */
mysqli_close($link);
?>
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
<?php
$mysqli = new mysqli("localhost", "nobody", "");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$mysqli->query("SET a=1")) {
print_r($mysqli->error_list);
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($link, "SET a=1")) {
print_r(mysqli_error_list($link));
}
/* close connection */
mysqli_close($link);
?>
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
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if (!$mysqli->query("SET a=1")) {
printf("Error message: %s\n", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($link, "SET a=1")) {
printf("Error message: %s\n", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>
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_querythat is longer thanmax_allowed_packetof 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_packetbytes”.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 anINSERTstatement (to specify column values for a row), or in a comparison with a column in aWHEREclause 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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$query = 'SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5';
$result = $mysqli->execute_query($query, ['DEU']);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["District"]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = 'SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5';
$result = mysqli_execute_query($link, $query, ['DEU']);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["District"]);
}
ENTITY
Aachen (Nordrhein-Westfalen)
Augsburg (Baijeri)
Bergisch Gladbach (Nordrhein-Westfalen)
Berlin (Berliini)
Bielefeld (Nordrhein-Westfalen)
ENTITY
mysqli_prepare, mysqli_stmt_execute, mysqli_stmt_bind_param, mysqli_stmt_get_result
field-count
mysqli::$field_count
mysqli_field_count
Returns the number of columns for the most recent query
ENTITY
ENTITY
int
mysqli-ENTITYfield_count
ENTITY
int
mysqli_field_count
mysqli
mysql
Returns the number of columns for the most recent query on the connection represented by the mysql parameter. This function can be useful when using the mysqli_store_result function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.
ENTITY
ENTITY
An integer representing the number of fields in a result set.
ENTITY
$mysqli-ENTITYfield_count example
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");
$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$mysqli->real_query("SELECT * FROM friends");
if ($mysqli->field_count) {
/* this was a select/show or describe query */
$result = $mysqli->store_result();
/* process resultset */
$row = $result->fetch_row();
/* free resultset */
$result->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");
mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
mysqli_real_query($link, "SELECT * FROM friends");
if (mysqli_field_count($link)) {
/* this was a select/show or describe query */
$result = mysqli_store_result($link);
/* process resultset */
$row = mysqli_fetch_row($result);
/* free resultset */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
$db = mysqli_init();
$db->real_connect("localhost","root","","test");
$db->set_charset('latin1');
var_dump($db->get_charset());
?>
ENTITY
<?php
$db = mysqli_init();
mysqli_real_connect($db, "localhost","root","","test");
mysqli_set_charset($db, 'latin1');
var_dump(mysqli_get_charset($db));
?>
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
<?php
/* We don't need a connection to determine
the version of mysql client library */
printf("Client library version: %s\n", mysqli_get_client_info());
?>
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
<?php
/* We don't need a connection to determine
the version of mysql client library */
printf("Client library version: %d\n", mysqli_get_client_version());
?>
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
<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>
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
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* print host information */
printf("Host info: %s\n", $mysqli->host_info);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));
ENTITY
Host info: Localhost via UNIX socket
ENTITY
mysqli_get_proto_info
get-proto-info
mysqli::$protocol_version
mysqli_get_proto_info
Returns the version of the MySQL protocol used
ENTITY
ENTITY
int
mysqli-ENTITYprotocol_version
ENTITY
int
mysqli_get_proto_info
mysqli
mysql
Returns an integer representing the MySQL protocol version used by the connection represented by the mysql parameter.
ENTITY
ENTITY
Returns an integer representing the protocol version.
ENTITY
$mysqli-ENTITYprotocol_version example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");
/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");
/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));
ENTITY
Protocol version: 10
ENTITY
mysqli_get_host_info
get-server-info
mysqli::$server_info
mysqli::get_server_info
mysqli_get_server_info
Returns the version of the MySQL server
ENTITY
ENTITY
string
mysqli-ENTITYserver_info
public
string
mysqli::get_server_info
ENTITY
string
mysqli_get_server_info
mysqli
mysql
Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.
ENTITY
ENTITY
A character string representing the server version.
ENTITY
$mysqli-ENTITYserver_info example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %s\n", $mysqli->server_info);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));
ENTITY
Server version: 8.0.21
ENTITY
mysqli_get_client_info, mysqli_get_client_version, mysqli_get_server_version
get-server-version
mysqli::$server_version
mysqli_get_server_version
Returns the version of the MySQL server as an integer
ENTITY
ENTITY
int
mysqli-ENTITYserver_version
ENTITY
int
mysqli_get_server_version
mysqli
mysql
The mysqli_get_server_version function returns the version of the server connected to (represented by the mysql parameter) as an integer.
ENTITY
ENTITY
An integer representing the server version.
The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).
ENTITY
$mysqli-ENTITYserver_version example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %d\n", $mysqli->server_version);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");
/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));
ENTITY
Server version: 80021
ENTITY
mysqli_get_client_info, mysqli_get_client_version, mysqli_get_server_info
get-warnings
mysqli::get_warnings
mysqli_get_warnings
Get result of SHOW WARNINGS
ENTITY
ENTITY
public
mysqli_warning
false
mysqli::get_warnings
ENTITY
mysqli_warning
false
mysqli_get_warnings
mysqli
mysql
Returns a singly linked list comprised of mysqli_warning or ENTITY if there are no warnings. Each object in the list corresponds to a single line from the result of SHOW WARNINGS. Calling mysqli_warning::next will refill the object with the values from the next row.
[!NOTE] To retrieve warning messages, it is recommended to use the SQL command
SHOW WARNINGS [limit row_count]instead of this function.
[!WARNING] The linked list cannot be rewound or retrieved again.
ENTITY
ENTITY
Returns a singly linked list comprised of mysqli_warning or ENTITY if there are no warnings.
ENTITY
Traversing the linked list to fetch all warnings
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("SELECT 1/0, CAST('NULL' AS UNSIGNED)");
if ($mysqli->warning_count > 0) {
$warning = $mysqli->get_warnings();
if ($warning !== false) {
do {
printf("Error number: %s\n", $warning->errno);
printf("Message: %s\n", $warning->message);
} while ($warning->next());
}
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "user", "password", "test");
mysqli_query($link, "SELECT 1/0, CAST('NULL' AS UNSIGNED)");
if (mysqli_warning_count($link) > 0) {
$warning = mysqli_get_warnings($link);
if ($warning !== false) {
do {
printf("Error number: %s\n", $warning->errno);
printf("Message: %s\n", $warning->message);
} while ($warning->next());
}
}
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_infowill return an empty string.
ENTITY
ENTITY
A character string representing additional information about the most recently executed query.
ENTITY
$mysqli-ENTITYinfo example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");
/* INSERT INTO ... SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");
/* INSERT INTO ... SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));
ENTITY
Records: 150 Duplicates: 0 Warnings: 0
ENTITY
mysqli_affected_rows, mysqli_warning_count, mysqli_num_rows
init
mysqli::init
mysqli_init
Initializes MySQLi and returns an object for use with mysqli_real_connect()
ENTITY
ENTITY
#[\Deprecated(since: '8.1', message: 'replace calls to parent::init() with parent::__construct()')]
public
bool
null
mysqli::init
ENTITY
mysqli
false
mysqli_init
Allocates or initializes a MYSQL object suitable for mysqli_options and mysqli_real_connect.
[!NOTE] Any subsequent call to any mysqli function (except
mysqli_optionsandmysqli_ssl_set) will fail untilmysqli_real_connectis called.
ENTITY ENTITY
ENTITY
mysqli::init returns ENTITY on success, ENTITY. mysqli_init returns an object on success, ENTITY.
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.1.0 | The object-oriented style mysqli::init method has been deprecated. Replace calls to parent::init with parent::__construct. |
ENTITY
See mysqli_real_connect.
ENTITY
mysqli_options, mysqli_close, mysqli_real_connect, mysqli_connect
insert-id
mysqli::$insert_id
mysqli_insert_id
Returns the value generated for an AUTO_INCREMENT column by the last query
ENTITY
ENTITY
int
string
mysqli-ENTITYinsert_id
ENTITY
int
string
mysqli_insert_id
mysqli
mysql
Returns the ID generated by an INSERT or UPDATE query on a table with a column having the AUTO_INCREMENT attribute. In the case of a multiple-row INSERT statement, it returns the first automatically generated value that was successfully inserted.
Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() MySQL function will also modify the value returned by mysqli_insert_id. If LAST_INSERT_ID(expr) was used to generate the value of AUTO_INCREMENT, it returns the value of the last expr instead of the generated AUTO_INCREMENT value.
Returns 0 if the previous statement did not change an AUTO_INCREMENT value. mysqli_insert_id must be called immediately after the statement that generated the value.
ENTITY
ENTITY
The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
Only statements issued using the current connection affect the return value. The value is not affected by statements issued using other connections or clients.
[!NOTE] If the number is greater than the maximum int value, it will be returned as a string.
ENTITY
$mysqli-ENTITYinsert_id example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf("New record has ID %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);
printf("New record has ID %d.\n", mysqli_insert_id($link));
/* drop table */
mysqli_query($link, "DROP TABLE myCity");
ENTITY
New record has ID 1.
kill
mysqli::kill
mysqli_kill
Asks the server to kill a MySQL thread
ENTITY
ENTITY
ENTITY
#[\Deprecated(since: '8.4', message: 'use KILL CONNECTION/QUERY SQL statement instead')]
public
bool
mysqli::kill
int
process_id
ENTITY
#[\Deprecated(since: '8.4', message: 'use KILL CONNECTION/QUERY SQL statement instead')]
bool
mysqli_kill
mysqli
mysql
int
process_id
This function is used to ask the server to kill a MySQL thread specified by the process_id parameter. This value must be retrieved by calling the mysqli_thread_id function.
To stop a running query you should use the SQL command KILL QUERY processid.
ENTITY
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.4.0 | Both mysqli::kill and mysqli_kill are now deprecated. Use the KILL SQL command instead. |
ENTITY
mysqli::kill example
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = $mysqli->thread_id;
/* Kill connection */
$mysqli->kill($thread_id);
/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = mysqli_thread_id($link);
/* Kill connection */
mysqli_kill($link, $thread_id);
/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", mysqli_error($link));
exit;
}
/* close connection */
mysqli_close($link);
?>
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
CALLstatements for stored procedures can produce multiple result sets. If the stored procedure containsSELECTstatements, 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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
$mysqli->multi_query($query);
do {
/* store the result set in PHP */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
mysqli_multi_query($link, $query);
do {
/* store the result set in PHP */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
ENTITY
my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer
ENTITY
mysqli_query, mysqli_use_result, mysqli_store_result, mysqli_next_result, mysqli_more_results
next-result
mysqli::next_result
mysqli_next_result
Prepare next result from multi_query
ENTITY
ENTITY
public
bool
mysqli::next_result
ENTITY
bool
mysqli_next_result
mysqli
mysql
Prepares next result set from a previous call to mysqli_multi_query which can be retrieved by mysqli_store_result or mysqli_use_result.
ENTITY
ENTITY
ENTITY Also returns ENTITY if the next statement resulted in an error, unlike mysqli_more_results.
ENTITY ENTITY
ENTITY
See mysqli_multi_query.
ENTITY
mysqli_multi_query, mysqli_more_results, mysqli_store_result, mysqli_use_result
options
mysqli::options
mysqli_options
Set options
ENTITY
ENTITY
public
bool
mysqli::options
int
option
string
int
value
ENTITY
bool
mysqli_options
mysqli
mysql
int
option
string
int
value
Used to set extra connect options and affect behavior for a connection.
This function may be called multiple times to set several options.
mysqli_options should be called after mysqli_init and before mysqli_real_connect.
ENTITY
option
The option that you want to set. It can be one of the following values:
| Name | Description |
|---|---|
MYSQLI_OPT_CONNECT_TIMEOUT |
Connection timeout in seconds |
MYSQLI_OPT_READ_TIMEOUT |
Command execution result timeout in seconds. Available as of PHP 7.2.0. |
MYSQLI_OPT_LOCAL_INFILE |
Enable/disable use of LOAD LOCAL INFILE |
MYSQLI_OPT_LOAD_DATA_LOCAL_DIR |
Directory to be used for LOAD DATA LOCAL INFILE. |
MYSQLI_INIT_COMMAND |
Command to execute after establishing a connection to the MySQL server |
MYSQLI_SET_CHARSET_NAME |
The charset to be set as default. |
MYSQLI_READ_DEFAULT_FILE |
Read options from named option file instead of my.cnf Not supported by mysqlnd. |
MYSQLI_READ_DEFAULT_GROUP |
Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. Not supported by mysqlnd. |
MYSQLI_SERVER_PUBLIC_KEY |
RSA public key file used with the SHA-256 based authentication. |
MYSQLI_OPT_NET_CMD_BUFFER_SIZE |
The size of the internal command/network buffer. Only valid for mysqlnd. |
MYSQLI_OPT_NET_READ_BUFFER_SIZE |
Maximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd. |
MYSQLI_OPT_INT_AND_FLOAT_NATIVE |
Convert integer and float columns back to PHP numbers when using non-prepared statements. Only valid for mysqlnd. |
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT |
Whether to verify server certificate or not. |
MYSQLI_OPT_CAN_HANDLE_EXPIRED_PASSWORDS |
Whether the client should accept expired passwords. |
1 |
Whether to use network communication compression. |
Valid options {#mysqli.options.parameters}
value
The value for the option.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
See mysqli_real_connect.
ENTITY ENTITY
ENTITY
mysqli_init, mysqli_real_connect
ping
mysqli::ping
mysqli_ping
Pings a server connection, or tries to reconnect if the connection has gone down
ENTITY
ENTITY
ENTITY
#[\Deprecated(since: '8.4', message: 'because the reconnect feature has been removed in PHP 8.2 and this method is now redundant')]
public
bool
mysqli::ping
ENTITY
#[\Deprecated(since: '8.4', message: 'because the reconnect feature has been removed in PHP 8.2 and this function is now redundant')]
bool
mysqli_ping
mysqli
mysql
Checks whether the connection to the server is working. If it has gone down and global option mysqli.reconnect is enabled, an automatic reconnection is attempted.
[!NOTE] The ENTITY setting mysqli.reconnect is ignored by the mysqlnd driver, so automatic reconnection is never attempted.
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.
ENTITY
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.4.0 | Both mysqli::ping and mysqli_ping are now deprecated. As of PHP 8.2.0, the reconnect feature is no longer available, making this function obsolete. |
ENTITY
mysqli::ping example
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* check if server is alive */
if ($mysqli->ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $mysqli->error);
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* check if server is alive */
if (mysqli_ping($link)) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>
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
<?php
$link1 = mysqli_connect();
$link1->query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
$links = $errors = $reject = array();
foreach ($all_links as $link) {
$links[] = $errors[] = $reject[] = $link;
}
if (!mysqli_poll($links, $errors, $reject, 1)) {
continue;
}
foreach ($links as $link) {
if ($result = $link->reap_async_query()) {
print_r($result->fetch_row());
if (is_object($result))
mysqli_free_result($result);
} else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
$processed++;
}
} while ($processed < count($all_links));
?>
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 anINSERTstatement (to specify column values for a row), or in a comparison with a column in aWHEREclause 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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s is in district %s\n", $city, $district);
ENTITY
Amersfoort is in district Utrecht
ENTITY
mysqli_stmt_execute, mysqli_stmt_fetch, mysqli_stmt_bind_param, mysqli_stmt_bind_result, mysqli_stmt_get_result, mysqli_stmt_close
query
mysqli::query
mysqli_query
Performs a query on the database
ENTITY
ENTITY
public
mysqli_result
bool
mysqli::query
string
query
int
result_mode
MYSQLI_STORE_RESULT
ENTITY
mysqli_result
bool
mysqli_query
mysqli
mysql
string
query
int
result_mode
MYSQLI_STORE_RESULT
Performs a query against the database.
ENTITY
For non-DML queries (not INSERT, UPDATE or DELETE), this function is similar to calling mysqli_real_query followed by either mysqli_use_result or mysqli_store_result.
[!NOTE] In the case where a statement is passed to
mysqli_querythat is longer thanmax_allowed_packetof 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:
mysqlndon Linux returns an error code of 1153. The error message means “got a packet bigger thanmax_allowed_packetbytes”.
mysqlndon Windows returns an error code 2006. This error message means “server has gone away”.
libmysqlclienton all platforms returns an error code 2006. This error message means “server has gone away”.
ENTITY
query
The query string.
result_mode
The result mode can be one of 3 constants indicating how the result will be returned from the MySQL server.
MYSQLI_STORE_RESULT (default) - returns a mysqli_result object with buffered result set.
MYSQLI_USE_RESULT - returns a mysqli_result object with unbuffered result set. As long as there are pending records waiting to be fetched, the connection line will be busy and all subsequent calls will return error Commands out of sync. To avoid the error all records must be fetched from the server or the result set must be discarded by calling mysqli_free_result.
MYSQLI_ASYNC (available with mysqlnd) - the query is performed asynchronously and no result set is immediately returned. mysqli_poll is then used to get results from such queries. Used in combination with either MYSQLI_STORE_RESULT or MYSQLI_USE_RESULT constant.
ENTITY
Returns ENTITY on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN, mysqli_query will return a mysqli_result object. For other successful queries, mysqli_query will return ENTITY.
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.4.0 | When connecting to MySQL 8.0.24 or later, the error code reported for a server wait timeout is now 4031 (ER_CLIENT_INTERACTION_TIMEOUT) instead of 2006 (CR_SERVER_GONE_ERROR). |
ENTITY
mysqli::query example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Create table doesn't return a resultset */
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");
printf("Table myCity successfully created.\n");
/* Select queries return a resultset */
$result = $mysqli->query("SELECT Name FROM City LIMIT 10");
printf("Select returned %d rows.\n", $result->num_rows);
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
$result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT);
/* Note, that we can't execute any functions which interact with the
server until all records have been fully retrieved or the result
set was closed. All calls will return an 'out of sync' error */
$mysqli->query("SET @a:='this will not work'");
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Create table doesn't return a resultset */
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
printf("Table myCity successfully created.\n");
/* Select queries return a resultset */
$result = mysqli_query($link, "SELECT Name FROM City LIMIT 10");
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
$result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT);
/* Note, that we can't execute any functions which interact with the
server until all records have been fully retrieved or the result
set was closed. All calls will return an 'out of sync' error */
mysqli_query($link, "SET @a:='this will not work'");
ENTITY
Table myCity successfully created.
Select returned 10 rows.
Fatal error: Uncaught mysqli_sql_exception: Commands out of sync; you can't run this command now in...
ENTITY
mysqli_execute_query, mysqli_real_query, mysqli_multi_query, mysqli_prepare, mysqli_free_result
quote-string
mysqli::quote_string
mysqli_quote_string
Quotes and escapes a string for use in an SQL statement
ENTITY
ENTITY
public
string
mysqli::quote_string
string
string
ENTITY
string
mysqli_quote_string
mysqli
mysql
string
string
Creates a legal SQL string literal that can be used in an SQL statement. The given string is escaped in the same way as mysqli::real_escape_string, taking into account the current character set of the connection, and the result is wrapped in single quotes. The returned value must therefore be inserted into the query without adding any further quotes around it.
Unlike mysqli::real_escape_string, the result is also safe when the NO_BACKSLASH_ESCAPES SQL mode is enabled on the connection.
[!CAUTION] The character set must be set either at the server level, or with the API function
mysqli_set_charsetfor it to affectmysqli_quote_string. See the concepts section on character sets for more information.
[!NOTE] Quoting is only suitable for string literals. It does not make identifiers, such as table or column names, safe. Whenever possible, use prepared statements instead of building queries manually.
ENTITY
string
The string to be quoted and escaped.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and CTRL+Z. If the NO_BACKSLASH_ESCAPES SQL mode is enabled on the connection, only ' is encoded, by doubling it.
ENTITY
Returns the escaped string enclosed in single quotes.
ENTITY
mysqli::quote_string example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with quoted $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name=%s", $mysqli->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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with quoted $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name=%s", mysqli_quote_string($mysqli, $city));
$result = mysqli_query($mysqli, $query);
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* this query will fail, because we didn't quote and escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = mysqli_query($mysqli, $query);
ENTITY
Select returned 1 rows.
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's-Hertogenbosch'' at line 1 in...
ENTITY
mysqli::real_escape_string
mysqli::set_charset
real-connect
mysqli::real_connect
mysqli_real_connect
Opens a connection to the MySQL server
ENTITY
ENTITY
public
bool
mysqli::real_connect
string
null
hostname
ENTITY
string
null
username
ENTITY
#[\SensitiveParameter]
string
null
password
ENTITY
string
null
database
ENTITY
int
null
port
ENTITY
string
null
socket
ENTITY
int
flags
0
ENTITY
bool
mysqli_real_connect
mysqli
mysql
string
null
hostname
ENTITY
string
null
username
ENTITY
#[\SensitiveParameter]
string
null
password
ENTITY
string
null
database
ENTITY
int
null
port
ENTITY
string
null
socket
ENTITY
int
flags
0
Opens a connection to the MySQL database server with optional connection options.
This function differs from mysqli_connect:
-
mysqli_real_connectneeds a valid object which has to be created bymysqli_init. -
There is a
flagsparameter.
ENTITY
hostname
Can be either a host name or an IP address. When passing ENTITY, the value is retrieved from mysqli.default_host. When possible, pipes will be used instead of the TCP/IP protocol. The TCP/IP protocol is used if a host name and port number are provided together e.g. localhost:3308.
username
The MySQL username or ENTITY to assume the username based on the mysqli.default_user ini option.
password
The MySQL password or ENTITY to assume the password based on the mysqli.default_pw ini option.
database
The default database to be used when performing queries or ENTITY.
port
The port number to attempt to connect to the MySQL server or ENTITY to assume the port based on the mysqli.default_port ini option.
socket
The socket or named pipe that should be used or ENTITY to assume the socket based on the mysqli.default_socket ini option.
[!NOTE] Specifying the
socketparameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by thehostnameparameter.
flags
With the parameter flags you can set different connection options:
| Name | Description |
|---|---|
MYSQLI_CLIENT_COMPRESS |
Use compression protocol |
MYSQLI_CLIENT_FOUND_ROWS |
Return the number of matched rows, not the number of affected rows |
MYSQLI_CLIENT_IGNORE_SPACE |
Allow spaces after function names. Makes all function names reserved words. |
MYSQLI_CLIENT_INTERACTIVE |
Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection |
MYSQLI_CLIENT_SSL |
Use SSL (encryption) |
MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT |
Like MYSQLI_CLIENT_SSL, but disables validation of the provided SSL certificate. This is only for installations using MySQL Native Driver and MySQL 5.6 or later. |
Supported flags {#mysqli.real-connect.flags}
[!NOTE] For security reasons the
MULTI_STATEMENTflag is not supported in PHP. If you want to execute multiple queries use themysqli_multi_queryfunction.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 7.4.0 | All parameters are now nullable. |
ENTITY
mysqli::real_connect example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db', null, null, MYSQLI_CLIENT_COMPRESS|MYSQLI_CLIENT_FOUND_ROWS);
echo 'Success... ' . $mysqli->host_info . "\n";
ENTITY when extending mysqli class
<?php
class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db)
{
parent::__construct();
parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
parent::real_connect($host, $user, $pass, $db, null, null, MYSQLI_CLIENT_COMPRESS|MYSQLI_CLIENT_FOUND_ROWS);
}
}
$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');
echo 'Success... ' . $db->host_info . "\n";
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_init();
mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db', null, null, MYSQLI_CLIENT_COMPRESS|MYSQLI_CLIENT_FOUND_ROWS);
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
ENTITY
Success... MySQL host info: localhost via TCP/IP
ENTITY ENTITY
ENTITY
mysqli_connect, mysqli_init, mysqli_options, mysqli_ssl_set, mysqli_close
real-escape-string
mysqli::real_escape_string
mysqli_real_escape_string
Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
ENTITY
ENTITY
public
string
mysqli::real_escape_string
string
string
ENTITY
string
mysqli_real_escape_string
mysqli
mysql
string
string
This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to produce an escaped SQL string, taking into account the current character set of the connection.
[!CAUTION] The character set must be set either at the server level, or with the API function
mysqli_set_charsetfor it to affectmysqli_real_escape_string. See the concepts section on character sets for more information.
[!WARNING] This function does not add quotes around the result; they must be added by the caller. If the
NO_BACKSLASH_ESCAPESSQL mode is enabled on the connection, only the single quote (') is escaped, so a value placed between double quotes (") can terminate the string and allow SQL injection. Use prepared statements instead. If that is not possible, use mysqli::quote_string, which always wraps the result in single quotes.
ENTITY
string
The string to be escaped.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and CTRL+Z. If the NO_BACKSLASH_ESCAPES SQL mode is enabled on the connection, only ' is encoded, by doubling it.
ENTITY
Returns an escaped string.
ENTITY
mysqli::real_escape_string example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with escaped $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
$mysqli->real_escape_string($city));
$result = $mysqli->query($query);
printf("Select returned %d rows.\n", $result->num_rows);
/* this query will fail, because we didn't escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = $mysqli->query($query);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with escaped $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
mysqli_real_escape_string($mysqli, $city));
$result = mysqli_query($mysqli, $query);
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* this query will fail, because we didn't escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = mysqli_query($mysqli, $query);
ENTITY
Select returned 1 rows.
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's-Hertogenbosch'' at line 1 in...
ENTITY
mysqli_set_charset
mysqli_quote_string
real-query
mysqli::real_query
mysqli_real_query
Execute an SQL query
ENTITY
ENTITY
public
bool
mysqli::real_query
string
query
ENTITY
bool
mysqli_real_query
mysqli
mysql
string
query
Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result or mysqli_use_result functions.
ENTITY
In order to determine if a given query should return a result set or not, see mysqli_field_count.
ENTITY
query
The query string.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
mysqli_query, mysqli_store_result, mysqli_use_result
reap-async-query
mysqli::reap_async_query
mysqli_reap_async_query
Get result from async query
ENTITY
ENTITY
public
mysqli_result
bool
mysqli::reap_async_query
ENTITY
mysqli_result
bool
mysqli_reap_async_query
mysqli
mysql
Get result from async query.
[!NOTE] ENTITY
ENTITY
ENTITY
Returns ENTITY on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN, mysqli_reap_async_query will return a mysqli_result object. For other successful queries, mysqli_reap_async_query will return ENTITY.
ENTITY ENTITY
ENTITY
mysqli_poll
refresh
mysqli::refresh
mysqli_refresh
Refreshes
ENTITY
ENTITY
ENTITY
#[\Deprecated(since: '8.4', message: 'use FLUSH SQL statement instead')]
public
bool
mysqli::refresh
int
flags
ENTITY
#[\Deprecated(since: '8.4', message: 'use FLUSH SQL statement instead')]
bool
mysqli_refresh
mysqli
mysql
int
flags
Flushes tables or caches, or resets the replication server information.
ENTITY
flags
The options to refresh, using the MYSQLI_REFRESH_* constants as documented within the MySQLi constants documentation.
See also the official MySQL Refresh documentation.
ENTITY
ENTITY if the refresh was a success, otherwise ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.4.0 | Both mysqli::refresh and mysqli_refresh are now deprecated. Use FLUSH SQL commands instead. |
ENTITY
mysqli_poll
release-savepoint
mysqli::release_savepoint
mysqli_release_savepoint
Removes the named savepoint from the set of savepoints of the current transaction
ENTITY
ENTITY
public
bool
mysqli::release_savepoint
string
name
ENTITY:
bool
mysqli_release_savepoint
mysqli
mysql
string
name
This function is identical to executing $mysqli-ENTITYquery("RELEASE SAVEPOINT `$name`");. This function does not trigger commit or rollback.
ENTITY
name
The identifier of the savepoint.
ENTITY
ENTITY
ENTITY
mysqli_savepoint
rollback
mysqli::rollback
mysqli_rollback
Rolls back current transaction
ENTITY
ENTITY
public
bool
mysqli::rollback
int
flags
0
string
null
name
ENTITY
ENTITY
bool
mysqli_rollback
mysqli
mysql
int
flags
0
string
null
name
ENTITY
Rolls back the current transaction for the database.
ENTITY
flags
A bitmask of MYSQLI_TRANS_COR_* constants.
name
If provided then ROLLBACK/*name*/ is executed.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | name is now nullable. |
ENTITY
See the mysqli::begin_transaction example.
ENTITY
[!NOTE] This function does not work with non transactional table types (like MyISAM or ISAM).
ENTITY
mysqli_begin_transaction, mysqli_commit, mysqli_autocommit, mysqli_release_savepoint
savepoint
mysqli::savepoint
mysqli_savepoint
Set a named transaction savepoint
ENTITY
ENTITY
public
bool
mysqli::savepoint
string
name
ENTITY:
bool
mysqli_savepoint
mysqli
mysql
string
name
This function is identical to executing $mysqli-ENTITYquery("SAVEPOINT `$name`");
ENTITY
name
The identifier of the savepoint.
ENTITY
ENTITY
ENTITY
mysqli_release_savepoint
select-db
mysqli::select_db
mysqli_select_db
Selects the default database for database queries
ENTITY
ENTITY
public
bool
mysqli::select_db
string
database
ENTITY
bool
mysqli_select_db
mysqli
mysql
string
database
Selects the default database to be used when performing queries against the database connection.
[!NOTE] This function should only be used to change the default database for the connection. You can select the default database with the 4th parameter in
mysqli_connect.
ENTITY
database
The database name.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
mysqli::select_db example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
/* change default database to "world" */
$mysqli->select_db("world");
/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
/* get the name of the current default database */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);
/* change default database to "world" */
mysqli_select_db($link, "world");
/* get the name of the current default database */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);
ENTITY
Default database is test.
Default database is world.
ENTITY
mysqli_connect, mysqli_real_connect
set-charset
mysqli::set_charset
mysqli_set_charset
Sets the client character set
ENTITY
ENTITY
public
bool
mysqli::set_charset
string
charset
ENTITY
bool
mysqli_set_charset
mysqli
mysql
string
charset
Sets the character set to be used when sending data from and to the database server.
ENTITY
charset
The desired character set.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
mysqli::set_charset example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
printf("Initial character set: %s\n", $mysqli->character_set_name());
/* change character set to utf8mb4 */
$mysqli->set_charset("utf8mb4");
printf("Current character set: %s\n", $mysqli->character_set_name());
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');
printf("Initial character set: %s\n", mysqli_character_set_name($link));
/* change character set to utf8mb4 */
mysqli_set_charset($link, "utf8mb4");
printf("Current character set: %s\n", mysqli_character_set_name($link));
ENTITY
Initial character set: latin1
Current character set: utf8mb4
ENTITY
[!NOTE] This is the preferred way to change the charset. Using
mysqli_queryto set it (such asSET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information.
ENTITY
mysqli_character_set_name, mysqli_real_escape_string, MySQL character set concepts, List of character sets that MySQL supports
set-opt
mysqli::set_opt
mysqli_set_opt
ENTITY
mysqli_options
ENTITY
ENTITY mysqli_options.
sqlstate
mysqli::$sqlstate
mysqli_sqlstate
Returns the SQLSTATE error from previous MySQL operation
ENTITY
ENTITY
string
mysqli-ENTITYsqlstate
ENTITY
string
mysqli_sqlstate
mysqli
mysql
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see ENTITY.
[!NOTE] Note that not all MySQL errors are yet mapped to SQLSTATEs. The value
HY000(general error) is used for unmapped errors.
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
$mysqli-ENTITYsqlstate example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Table City already exists, so we should get an error */
try {
$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))");
} catch (mysqli_sql_exception) {
printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* Table City already exists, so we should get an error */
try {
mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))");
} catch (mysqli_sql_exception) {
printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}
ENTITY
Error - SQLSTATE 42S01.
ENTITY
mysqli_errno, mysqli_error
ssl-set
mysqli::ssl_set
mysqli_ssl_set
Used for establishing secure connections using SSL
ENTITY
ENTITY
public
true
mysqli::ssl_set
string
null
key
string
null
certificate
string
null
ca_certificate
string
null
ca_path
string
null
cipher_algos
ENTITY
true
mysqli_ssl_set
mysqli
mysql
string
null
key
string
null
certificate
string
null
ca_certificate
string
null
ca_path
string
null
cipher_algos
Used for establishing secure connections using SSL. It must be called before mysqli_real_connect. This function does nothing unless OpenSSL support is enabled.
ENTITY
key
The path name to the key file.
certificate
The path name to the certificate file.
ca_certificate
The path name to the certificate authority file.
ca_path
The pathname to a directory that contains trusted SSL CA certificates in PEM format.
cipher_algos
A list of allowable ciphers to use for SSL encryption.
ENTITY
ENTITY If SSL setup is incorrect mysqli_real_connect will return an error when you attempt to connect.
ENTITY
mysqli_options, mysqli_real_connect
stat
mysqli::stat
mysqli_stat
Gets the current system status
ENTITY
ENTITY
public
string
false
mysqli::stat
ENTITY
string
false
mysqli_stat
mysqli
mysql
mysqli_stat returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.
ENTITY
ENTITY
A string describing the server status. ENTITY if an error occurred.
ENTITY
mysqli::stat example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
printf("System status: %s\n", $mysqli->stat());
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
printf("System status: %s\n", mysqli_stat($link));
ENTITY
System status: Uptime: 272 Threads: 1 Questions: 5340 Slow queries: 0
Opens: 13 Flush tables: 1 Open tables: 0 Queries per second avg: 19.632
Memory in use: 8496K Max memory used: 8560K
ENTITY
mysqli_get_server_info
stmt-init
mysqli::stmt_init
mysqli_stmt_init
Initializes a statement and returns an object for use with mysqli_stmt_prepare
ENTITY
ENTITY
public
mysqli_stmt
false
mysqli::stmt_init
ENTITY
mysqli_stmt
false
mysqli_stmt_init
mysqli
mysql
Allocates and initializes a statement object suitable for mysqli_stmt_prepare.
[!NOTE] Any subsequent call to any
mysqli_stmtmethod will fail untilmysqli_stmt_prepareis called.
ENTITY
ENTITY
Returns a mysqli_stmt object.
ENTITY
mysqli_stmt_prepare
store-result
mysqli::store_result
mysqli_store_result
Transfers a result set from the last query
ENTITY
ENTITY
public
mysqli_result
false
mysqli::store_result
int
mode
0
ENTITY
mysqli_result
false
mysqli_store_result
mysqli
mysql
int
mode
0
Transfers the result set from the last query on the database connection represented by the mysql parameter to be used with the mysqli_data_seek function.
ENTITY
mode
The option that you want to set. As of PHP 8.1, this parameter has no effect. It can be one of the following values:
| Name | Description |
|---|---|
MYSQLI_STORE_RESULT_COPY_DATA |
Copy results from the internal mysqlnd buffer into the PHP variables fetched. By default, mysqlnd will use a reference logic to avoid copying and duplicating results held in memory. For certain result sets, for example, result sets with many small rows, the copy approach can reduce the overall memory usage because PHP variables holding results may be released earlier (available with mysqlnd only) |
Valid options {#mysqli.store-result.parameters}
ENTITY
Returns a buffered result object or ENTITY if an error occurred.
[!NOTE]
mysqli_store_resultreturns ENTITY in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns ENTITY if the reading of the result set failed. You can check if you have got an error by checking ifmysqli_errordoesn't return an empty string, ifmysqli_errnoreturns a non zero value, or ifmysqli_field_countreturns a non zero value. Also possible reason for this function returning ENTITY after successful call tomysqli_querycan be too large result set (memory for it cannot be allocated). Ifmysqli_field_countreturns a non-zero value, the statement should have produced a non-empty result set.
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.4.0 | Passing the mode parameter is now deprecated. The parameter has had no effect as of PHP 8.1.0. |
ENTITY
See mysqli_multi_query.
ENTITY
[!NOTE] Although it is always good practice to free the memory used by the result of a query using the
mysqli_free_resultfunction, when transferring large result sets using themysqli_store_resultthis becomes particularly important.
ENTITY
mysqli_real_query, mysqli_use_result
thread-id
mysqli::$thread_id
mysqli_thread_id
Returns the thread ID for the current connection
ENTITY
ENTITY
int
mysqli-ENTITYthread_id
ENTITY
int
mysqli_thread_id
mysqli
mysql
The mysqli_thread_id function returns the thread ID for the current connection which can then be killed using the mysqli_kill function. If the connection is lost and you reconnect with mysqli_ping, the thread ID will be different. Therefore you should get the thread ID only when you need it.
[!NOTE] The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.
To kill a running query you can use the SQL command
KILL QUERY processid.
ENTITY
ENTITY
Returns the Thread ID for the current connection.
ENTITY
$mysqli-ENTITYthread_id example
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = $mysqli->thread_id;
/* Kill connection */
$mysqli->kill($thread_id);
/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* determine our thread id */
$thread_id = mysqli_thread_id($link);
/* Kill connection */
mysqli_kill($link, $thread_id);
/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", mysqli_error($link));
exit;
}
/* close connection */
mysqli_close($link);
?>
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_resultfunction does not transfer the entire result set from the database and hence cannot be used with functions such asmysqli_data_seekto move to a particular row within the set. To use this functionality, the result set must be stored usingmysqli_store_result. One should not usemysqli_use_resultif 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
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_use_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}
/* close connection */
mysqli_close($link);
?>
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("SELECT 42/0");
if ($mysqli->warning_count > 0) {
$result = $mysqli->query("SHOW WARNINGS");
$row = $result->fetch_row();
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "SELECT 42/0");
if (mysqli_warning_count($link) > 0) {
$result = mysqli_query($link, "SHOW WARNINGS");
$row = mysqli_fetch_row($result);
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
}
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
<?php
/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this query should report a bad index if the column population doesn't have an index */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}
ENTITY
<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);
try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
/* this query should report an error */
$result = mysqli_query($link, "SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this query should report a bad index if the column population doesn't have an index */
$result = mysqli_query($link, "SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}
Error reporting except bad index errors
<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");
/* this WILL NOT report any errors even if index is not available */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* Select queries return a result set */
$mysqli->real_query("SELECT Name FROM City LIMIT 10");
$result = new mysqli_result($mysqli);
printf("Select returned %d rows.\n", $result->num_rows);
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
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
/* get fieldpointer offset */
$currentfield = $result->current_field;
printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for all fields */
while ($finfo = mysqli_fetch_field($result)) {
/* get fieldpointer offset */
$currentfield = mysqli_field_tell($result);
printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$result = $mysqli->query($query);
/* Seek to row no. 401 */
$result->data_seek(400);
/* Fetch single row */
$row = $result->fetch_row();
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$result = mysqli_query($link, $query);
/* Seek to row no. 401 */
mysqli_data_seek($result, 400);
/* Fetch single row */
$row = mysqli_fetch_row($result);
printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);
ENTITY
City: Benin City Countrycode: NGA
Adjusting the result pointer when iterating
This function can be useful when iterating over the result set to impose a custom order or rewind the result set when iterating multiple times.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 15,4";
$result = $mysqli->query($query);
/* Iterate the result set in reverse order */
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
/* Fetch single row */
$row = $result->fetch_row();
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}
/* Reset pointer to the beginning of the result set */
$result->data_seek(0);
print "\n";
/* Iterate the same result set again */
while ($row = $result->fetch_row()) {
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}
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_queryormysqli_stmt_get_resultfunctions.
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
$rows = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($mysqli, "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($rows as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
ENTITY
Kabul (AFG)
Qandahar (AFG)
Herat (AFG)
ENTITY
mysqli_fetch_array, mysqli_fetch_column, mysqli_query
fetch-array
mysqli_result::fetch_array
mysqli_fetch_array
Fetch the next row of a result set as an associative, a numeric array, or both
ENTITY
ENTITY
public
array
null
false
mysqli_result::fetch_array
int
mode
MYSQLI_BOTH
ENTITY
array
null
false
mysqli_fetch_array
mysqli_result
result
int
mode
MYSQLI_BOTH
Fetches one row of data from the result set and returns it as an array. Each subsequent call to this function will return the next row within the result set, or ENTITY if there are no more rows.
In addition to storing the data in the numeric indices of the result array, this function can also store the data in associative indices by using the field names of the result set as keys.
If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, the numerically indexed version of the row must be used.
ENTITY ENTITY
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.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc, while MYSQLI_NUM will behave identically to the mysqli_fetch_row function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
ENTITY
Returns an array representing the fetched row, ENTITY if there are no more rows in the result set, ENTITY.
ENTITY
mysqli_result::fetch_array example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf("%s (%s)\n", $row[0], $row["CountryCode"]);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($mysqli, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf("%s (%s)\n", $row[0], $row["CountryCode"]);
ENTITY
Kabul (AFG)
Qandahar (AFG)
Herat (AFG)
ENTITY
mysqli_fetch_assoc, mysqli_fetch_column, mysqli_fetch_row, mysqli_fetch_object, mysqli_query, mysqli_data_seek
fetch-assoc
mysqli_result::fetch_assoc
mysqli_fetch_assoc
Fetch the next row of a result set as an associative array
ENTITY
ENTITY
public
array
null
false
mysqli_result::fetch_assoc
ENTITY
array
null
false
mysqli_fetch_assoc
mysqli_result
result
Fetches one row of data from the result set and returns it as an associative array. Each subsequent call to this function will return the next row within the result set, or 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.
ENTITY ENTITY
ENTITY
ENTITY
Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set's columns, ENTITY if there are no more rows in the result set, ENTITY.
ENTITY
mysqli_result::fetch_assoc example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = $mysqli->query($query);
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($mysqli, $query);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
ENTITY
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)
Comparison of mysqli_result iterator and mysqli_result::fetch_assoc usage
mysqli_result can be iterated using ENTITY. The result set will always be iterated from the first row, regardless of the current position.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = 'SELECT Name, CountryCode FROM City ORDER BY ID DESC';
// Using iterators
$result = $mysqli->query($query);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
echo "\n==================\n";
// Not using iterators
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5";
$result = $mysqli->query($query);
/* fetch a single value from the second column */
while ($Name = $result->fetch_column(1)) {
printf("%s\n", $Name);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5";
$result = mysqli_query($mysqli, $query);
/* fetch a single value from the second column */
while ($Name = mysqli_fetch_column($result, 1)) {
printf("%s\n", $Name);
}
ENTITY
Rafah
Nablus
Jabaliya
Hebron
Khan Yunis
ENTITY
mysqli_fetch_all, mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object, mysqli_fetch_row, mysqli_data_seek
fetch-field-direct
mysqli_result::fetch_field_direct
mysqli_fetch_field_direct
Fetch meta-data for a single field
ENTITY
ENTITY
public
object
false
mysqli_result::fetch_field_direct
int
index
ENTITY
object
false
mysqli_fetch_field_direct
mysqli_result
result
int
index
Returns an object which contains field definition information from the specified result set.
ENTITY
index
The field number. This value must be in the range from 0 to number of fields - 1.
ENTITY
Returns an object which contains field definition information or ENTITY if no field information for specified index is available.
ENTITY
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = mysqli_fetch_field_direct($result, 1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for all fields */
while ($finfo = mysqli_fetch_field($result)) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
$mysqli = new mysqli("127.0.0.1", "root", "foofoo", "sakila");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
foreach (array('latin1', 'utf8') as $charset) {
// Set character set, to show its impact on some values (e.g., length in bytes)
$mysqli->set_charset($charset);
$query = "SELECT actor_id, last_name from actor ORDER BY actor_id";
echo "======================\n";
echo "Character Set: $charset\n";
echo "======================\n";
if ($result = $mysqli->query($query)) {
/* Get field information for all columns */
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("Max. Len: %d\n", $val->max_length);
printf("Length: %d\n", $val->length);
printf("charsetnr: %d\n", $val->charsetnr);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
$result->free();
}
}
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach (array('latin1', 'utf8') as $charset) {
// Set character set, to show its impact on some values (e.g., length in bytes)
mysqli_set_charset($link, $charset);
$query = "SELECT actor_id, last_name from actor ORDER BY actor_id";
echo "======================\n";
echo "Character Set: $charset\n";
echo "======================\n";
if ($result = mysqli_query($link, $query)) {
/* Get field information for all columns */
$finfo = mysqli_fetch_fields($result);
foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("Max. Len: %d\n", $val->max_length);
printf("Length: %d\n", $val->length);
printf("charsetnr: %d\n", $val->charsetnr);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
mysqli_free_result($result);
}
}
mysqli_close($link);
?>
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = $mysqli->query($query);
while ($obj = $result->fetch_object()) {
printf("%s (%s)\n", $obj->Name, $obj->CountryCode);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($link, $query);
while ($obj = mysqli_fetch_object($result)) {
printf("%s (%s)\n", $obj->Name, $obj->CountryCode);
}
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = $mysqli->query($query);
/* fetch object array */
while ($row = $result->fetch_row()) {
printf("%s (%s)\n", $row[0], $row[1]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";
$result = mysqli_query($mysqli, $query);
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s)\n", $row[0], $row[1]);
}
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_object, mysqli_query, mysqli_data_seek
field-count
mysqli_result::$field_count
mysqli_num_fields
Gets the number of fields in the result set
ENTITY
ENTITY
int
mysqli_result->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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Name, CountryCode, District, Population FROM City ORDER BY ID LIMIT 1");
/* Get the number of fields in the result set */
$field_cnt = $result->field_count;
printf("Result set has %d fields.\n", $field_cnt);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($link, "SELECT Name, CountryCode, District, Population FROM City ORDER BY ID LIMIT 1");
/* Get the number of fields in the result set */
$field_cnt = mysqli_num_fields($result);
printf("Result set has %d fields.\n", $field_cnt);
ENTITY
Result set has 4 fields.
ENTITY
mysqli_fetch_field
field-seek
mysqli_result::field_seek
mysqli_field_seek
Set result pointer to a specified field offset
ENTITY
ENTITY
public
true
mysqli_result::field_seek
int
index
ENTITY
true
mysqli_field_seek
mysqli_result
result
int
index
Sets the field cursor to the given offset. The next call to mysqli_fetch_field will retrieve the field definition of the column associated with that offset.
[!NOTE] To seek to the beginning of a row, pass an offset value of zero.
ENTITY
index
The field number. This value must be in the range from 0 to number of fields - 1.
ENTITY
ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | This function now always returns ENTITY. Previously it returned ENTITY on failure. |
ENTITY
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for 2nd column */
$result->field_seek(1);
$finfo = $result->fetch_field();
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
/* Get field information for 2nd column */
mysqli_field_seek($result, 1);
$finfo = mysqli_fetch_field($result);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * from Country ORDER BY Code LIMIT 1";
if ($result = $mysqli->query($query)) {
$row = $result->fetch_row();
/* display column lengths */
foreach ($result->lengths as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
$result->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * from Country ORDER BY Code LIMIT 1";
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_row($result);
/* display column lengths */
foreach (mysqli_fetch_lengths($result) as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name");
/* Get the number of rows in the result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name");
/* Get the number of rows in the result set */
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
ENTITY
Result set has 239 rows.
ENTITY
[!NOTE] In contrast to the
mysqli_stmt_num_rowsfunction, this function doesn't have an object-oriented method variant. In the object-oriented style, use the getter property.
ENTITY
mysqli_affected_rows, mysqli_store_result, mysqli_use_result, mysqli_query, mysqli_stmt_num_rows
mysqli_sql_exception
ENTITY
The mysqli exception handling class.
ENTITY
final
mysqli_sql_exception
extends
RuntimeException
ENTITY
protected
string
sqlstate
"00000"
ENTITY
ENTITY
ENTITY
ENTITY
sqlstate
The sql state with the error.
ENTITY
getsqlstate
mysqli_sql_exception::getSqlState
Returns the SQLSTATE error code
ENTITY
public
string
mysqli_sql_exception::getSqlState
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. The values are specified by ANSI SQL and ODBC. For a list of possible values, see ENTITY.
[!NOTE] Note that not all MySQL errors are yet mapped to SQLSTATEs. The value
HY000(general error) is used for unmapped errors.
ENTITY ENTITY
ENTITY
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters.
mysqli_stmt
ENTITY
Represents a prepared statement.
ENTITY
mysqli_stmt
ENTITY
public
readonly
int
string
affected_rows
public
readonly
int
string
insert_id
public
readonly
int
string
num_rows
public
readonly
int
param_count
public
readonly
int
field_count
public
readonly
int
errno
public
readonly
string
error
public
readonly
array
error_list
public
readonly
string
sqlstate
public
int
id
ENTITY
ENTITY
id
Stores the statement ID.
ENTITY
affected-rows
mysqli_stmt::$affected_rows
mysqli_stmt_affected_rows
Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
ENTITY
ENTITY
int
string
mysqli_stmt-ENTITYaffected_rows
ENTITY
int
string
mysqli_stmt_affected_rows
mysqli_stmt
statement
Returns the number of rows affected by the INSERT, UPDATE, or DELETE query. Works like mysqli_stmt_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, for a SELECT query, mysqli_stmt_affected_rows was called prior to calling mysqli_stmt_store_result.
[!NOTE] If the number of affected rows is greater than the maximum PHP int value, the number of affected rows will be returned as a string value.
ENTITY
mysqli_stmt_affected_rows example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
$stmt = $mysqli->prepare($query);
/* Bind variable for placeholder */
$code = 'A%';
$stmt->bind_param("s", $code);
/* execute statement */
$stmt->execute();
printf("Rows inserted: %d\n", $stmt->affected_rows);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
$stmt = mysqli_prepare($link, $query);
/* Bind variable for placeholder */
$code = 'A%';
mysqli_stmt_bind_param($stmt, "s", $code);
/* execute statement */
mysqli_stmt_execute($stmt);
printf("Rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));
ENTITY
Rows inserted: 17
ENTITY
mysqli_stmt_num_rows, mysqli_stmt_store_result
attr-get
mysqli_stmt::attr_get
mysqli_stmt_attr_get
Used to get the current value of a statement attribute
ENTITY
ENTITY
public
int
mysqli_stmt::attr_get
int
attribute
ENTITY
int
mysqli_stmt_attr_get
mysqli_stmt
statement
int
attribute
Gets the current value of a statement attribute.
ENTITY
attribute
The attribute that you want to get.
ENTITY
Returns the value of the attribute.
attr-set
mysqli_stmt::attr_set
mysqli_stmt_attr_set
Used to modify the behavior of a prepared statement
ENTITY
ENTITY
public
bool
mysqli_stmt::attr_set
int
attribute
int
value
ENTITY
bool
mysqli_stmt_attr_set
mysqli_stmt
statement
int
attribute
int
value
Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.
ENTITY
attribute
The attribute that you want to set. It can have one of the following values:
| Character | Description |
|---|---|
| MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH | Setting to ENTITY causes mysqli_stmt_store_result to update the metadata MYSQL_FIELD-ENTITYmax_length value. |
| MYSQLI_STMT_ATTR_CURSOR_TYPE | Type of cursor to open for statement when mysqli_stmt_execute is invoked. value can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY. |
| MYSQLI_STMT_ATTR_PREFETCH_ROWS | Number of rows to fetch from server at a time when using a cursor. value can be in the range from 1 to the maximum value of unsigned long. The default is 1. Removed as of PHP 8.4.0. |
Attribute values {#mysqli-stmt.attr-set.parameters}
If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke mysqli_stmt_execute. If there is already an open cursor from a previous mysqli_stmt_execute call, it closes the cursor before opening a new one. mysqli_stmt_reset also closes any open cursor before preparing the statement for re-execution. mysqli_stmt_free_result closes any open cursor.
If you open a cursor for a prepared statement, mysqli_stmt_store_result is unnecessary.
value
The value to assign to the attribute.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
Connector/MySQL mysql_stmt_attr_set()
bind-param
mysqli_stmt::bind_param
mysqli_stmt_bind_param
Binds variables to a prepared statement as parameters
ENTITY
ENTITY
public
bool
mysqli_stmt::bind_param
string
types
mixed
var
mixed
vars
ENTITY
bool
mysqli_stmt_bind_param
mysqli_stmt
statement
string
types
mixed
var
mixed
vars
Bind variables for the parameter markers in the SQL statement prepared by mysqli_prepare or mysqli_stmt_prepare.
[!NOTE] If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify
bintypesand usemysqli_stmt_send_long_datato send the data in packets.
[!NOTE] Care must be taken when using
mysqli_stmt_bind_paramin conjunction withcall_user_func_array. Note thatmysqli_stmt_bind_paramrequires parameters to be passed by reference, whereascall_user_func_arraycan accept as a parameter a list of variables that can represent references or values.
ENTITY
types
A string that contains one or more characters which specify the types for the corresponding bind variables:
| Character | Description |
|---|---|
| i | corresponding variable has type int |
| d | corresponding variable has type float |
| s | corresponding variable has type string |
| b | corresponding variable is a blob and will be sent in packets |
Type specification chars {#mysqli-stmt.bind-param.parameters}
var; vars
The number of variables and length of string types must match the parameters in the statement.
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
mysqli_stmt::bind_param example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
$stmt->execute();
printf("%d row inserted.\n", $stmt->affected_rows);
/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d row deleted.\n", $mysqli->affected_rows);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
mysqli_stmt_execute($stmt);
printf("%d row inserted.\n", mysqli_stmt_affected_rows($stmt));
/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d row deleted.\n", mysqli_affected_rows($link));
ENTITY
1 row inserted.
1 row deleted.
Using ... to provide arguments
The ... operator can be used to provide variable-length argument list, e.g. in a WHERE IN clause.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("SELECT Language FROM CountryLanguage WHERE CountryCode IN (?, ?)");
/* Using ... to provide arguments */
$stmt->bind_param('ss', ...['DEU', 'POL']);
$stmt->execute();
$stmt->store_result();
printf("%d rows found.\n", $stmt->num_rows());
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_executeand prior to callingmysqli_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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* prepare statement */
$stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5");
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* prepare statement */
$stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5");
mysqli_stmt_execute($stmt);
/* bind variables to prepared statement */
mysqli_stmt_bind_result($stmt, $col1, $col2);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf("%s %s\n", $col1, $col2);
}
ENTITY
AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra
ENTITY
mysqli_stmt_get_result, mysqli_stmt_bind_param, mysqli_stmt_execute, mysqli_stmt_fetch, mysqli_prepare, mysqli_stmt_prepare
close
mysqli_stmt::close
mysqli_stmt_close
Closes a prepared statement
ENTITY
ENTITY
public
true
mysqli_stmt::close
ENTITY
true
mysqli_stmt_close
mysqli_stmt
statement
Closes a prepared statement. mysqli_stmt_close also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
ENTITY
ENTITY
ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | This function now always returns ENTITY. Previously it returned ENTITY on failure. |
ENTITY
mysqli_prepare
construct
mysqli_stmt::__construct
Constructs a new
mysqli_stmt
object
ENTITY
public
mysqli_stmt::__construct
mysqli
mysql
string
null
query
ENTITY
This method constructs a new mysqli_stmt object.
ENTITY
link
A valid mysqli object.
query
The query, as a string. If this parameter is ENTITY, then the constructor behaves identically to mysqli_stmt_init, otherwise it behaves as per mysqli_prepare.
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.0.0 | query is now nullable. |
ENTITY
mysqli_prepare, mysqli_stmt_init
data-seek
mysqli_stmt::data_seek
mysqli_stmt_data_seek
Adjusts the result pointer to an arbitrary row in the buffered result
ENTITY
ENTITY
public
void
mysqli_stmt::data_seek
int
offset
ENTITY
void
mysqli_stmt_data_seek
mysqli_stmt
statement
int
offset
This function moves the result set pointer of the buffered result set to an arbitrary row specified by the offset parameter.
This function works only on the buffered internal result set. mysqli_stmt_store_result must be called prior to mysqli_stmt_data_seek.
ENTITY
offset
Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows - 1).
ENTITY
ENTITY
ENTITY
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($name, $code);
$stmt->store_result();
/* seek to row no. 400 */
$stmt->data_seek(399);
$stmt->fetch();
printf("City: %s Countrycode: %s\n", $name, $code);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name, $code);
mysqli_stmt_store_result($stmt);
/* seek to row no. 400 */
mysqli_stmt_data_seek($stmt, 399);
mysqli_stmt_fetch($stmt);
printf("City: %s Countrycode: %s\n", $name, $code);
ENTITY
City: Benin City Countrycode: NGA
ENTITY
mysqli_prepare, mysqli_stmt_store_result, mysqli_stmt_num_rows, mysqli_data_seek
errno
mysqli_stmt::$errno
mysqli_stmt_errno
Returns the error code for the most recent statement call
ENTITY
ENTITY
int
mysqli_stmt-ENTITYerrno
ENTITY
int
mysqli_stmt_errno
mysqli_stmt
statement
Returns the error code for the most recently invoked statement function that can succeed or fail.
ENTITY
ENTITY
An error code value. Zero means no error occurred.
ENTITY
ENTITY
<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %d.\n", $stmt->errno);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
printf("Error: %d.\n", mysqli_stmt_errno($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
echo "Error:\n";
print_r($stmt->error_list);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
echo "Error:\n";
print_r(mysqli_stmt_error_list($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->error);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", mysqli_stmt_error($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");
/* Prepare an insert statement */
$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");
/* Bind variables to parameters */
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
$stmt->execute();
/* Retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
/* Prepare an insert statement */
$stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");
/* Bind variables to parameters */
mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
mysqli_stmt_execute($stmt);
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
mysqli_stmt_execute($stmt);
/* Retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
ENTITY
Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)
Execute a prepared statement with an array of values
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$mysqli->query('CREATE TEMPORARY TABLE myCity LIKE City');
/* Prepare an insert statement */
$stmt = $mysqli->prepare('INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');
/* Execute the statement */
$stmt->execute(['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);
/* Retrieve all rows from myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
mysqli_query($link, 'CREATE TEMPORARY TABLE myCity LIKE City');
/* Prepare an insert statement */
$stmt = mysqli_prepare($link, 'INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');
/* Execute the statement */
mysqli_stmt_execute($stmt, ['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);
/* Retrieve all rows from myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}
ENTITY
Stuttgart (DEU,Baden-Wuerttemberg)
ENTITY
mysqli_execute_query, mysqli_prepare, mysqli_stmt_bind_param, mysqli_stmt_get_result
fetch
mysqli_stmt::fetch
mysqli_stmt_fetch
Fetch results from a prepared statement into the bound variables
ENTITY
ENTITY
public
bool
null
mysqli_stmt::fetch
ENTITY
bool
null
mysqli_stmt_fetch
mysqli_stmt
statement
Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result.
[!NOTE] Note that all columns must be bound by the application before calling
mysqli_stmt_fetch.
[!NOTE] Data is transferred unbuffered without calling
mysqli_stmt_store_resultwhich can decrease performance (but reduces memory cost).
ENTITY
ENTITY
| Value | Description |
|---|---|
| ENTITY | Success. Data has been fetched |
| ENTITY | Error occurred |
| ENTITY | No more rows/data exists or data truncation occurred |
ENTITY ENTITY
ENTITY
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";
if ($stmt = mysqli_prepare($link, $query)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $name, $code);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$code = 'FR';
$stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Code=?");
$stmt->bind_param('s', $code);
$stmt->execute();
$row = $stmt->get_result()->fetch_row();
for ($i = 0; $i < $stmt->field_count; $i++) {
printf("Value of column number %d is %s", $i, $row[$i]);
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$code = 'FR';
$stmt = mysqli_prepare($mysqli, "SELECT Name FROM Country WHERE Code=?");
mysqli_stmt_bind_param($stmt, 's', $code);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_row($result);
for ($i = 0; $i < mysqli_stmt_field_count($stmt); $i++) {
printf("Value of column number %d is %s", $i, $row[$i]);
}
ENTITY
Value of column number 0 is France
ENTITY
mysqli_stmt_num_rows
free-result
mysqli_stmt::free_result
mysqli_stmt_free_result
Frees stored result memory for the given statement handle
ENTITY
ENTITY
public
void
mysqli_stmt::free_result
ENTITY
void
mysqli_stmt_free_result
mysqli_stmt
statement
Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result.
ENTITY
ENTITY
ENTITY
ENTITY
mysqli_stmt_store_result
get-result
mysqli_stmt::get_result
mysqli_stmt_get_result
Gets a result set from a prepared statement as a
mysqli_result
object
ENTITY
ENTITY
public
mysqli_result
false
mysqli_stmt::get_result
ENTITY
mysqli_result
false
mysqli_stmt_get_result
mysqli_stmt
statement
Retrieves a result set from a prepared statement as a mysqli_result object. The data will be fetched from the MySQL server to PHP. This method should be called only for queries which produce a result set.
[!NOTE] ENTITY
[!NOTE] This function cannot be used together with
mysqli_stmt_store_result. Both of these functions retrieve the full result set from the MySQL server.
ENTITY
ENTITY
Returns ENTITY on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN, mysqli_stmt_get_result will return a mysqli_result object. For other successful queries, mysqli_stmt_get_result will return ENTITY. The mysqli_stmt_errno function can be used to distinguish between the two reasons for ENTITY; due to a bug, prior to PHP 7.4.13, mysqli_errno had to be used for this purpose.
ENTITY ENTITY
ENTITY
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $continent);
$continentList = array('Europe', 'Africa', 'Asia', 'North America');
foreach ($continentList as $continent) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
}
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_bind_param($stmt, "s", $continent);
$continentList= array('Europe', 'Africa', 'Asia', 'North America');
foreach ($continentList as $continent) {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
}
ENTITY
Albania 3401200 Europe
Algeria 31471000 Africa
Afghanistan 22720000 Asia
Anguilla 8000 North America
ENTITY
mysqli_prepare, mysqli_stmt_result_metadata, mysqli_stmt_fetch, mysqli_fetch_array, mysqli_stmt_store_result
get-warnings
mysqli_stmt::get_warnings
mysqli_stmt_get_warnings
Get result of SHOW WARNINGS
ENTITY
ENTITY
public
mysqli_warning
false
mysqli_stmt::get_warnings
ENTITY
mysqli_warning
false
mysqli_stmt_get_warnings
mysqli_stmt
statement
ENTITY
insert-id
mysqli_stmt::$insert_id
mysqli_stmt_insert_id
Returns the value generated for an AUTO_INCREMENT column by the last statement executed
ENTITY
ENTITY
int
string
mysqli_stmt-ENTITYinsert_id
ENTITY
int
string
mysqli_stmt_insert_id
mysqli_stmt
statement
Returns the ID generated by an INSERT or UPDATE statement on a table with a column having the AUTO_INCREMENT attribute. In the case of a multiple-row INSERT statement, it returns the first automatically generated value that was successfully inserted. If LAST_INSERT_ID(expr) is used to set the AUTO_INCREMENT value, or in an UPDATE, the value of expr is returned instead.
Returns 0 if the statement did not change an AUTO_INCREMENT value.
ENTITY
ENTITY
The value of the AUTO_INCREMENT field that was updated by the statement. Returns zero if the statement has not been executed yet or if it did not update an AUTO_INCREMENT value.
The value is specific to the statement object. It is not affected by other statements executed on the same connection after this statement, nor by statements issued using other connections or clients.
[!NOTE] If the number is greater than the maximum int value, it will be returned as a string.
ENTITY
mysqli_stmt::$insert_id example
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");
$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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
$stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District, Population) VALUES (?, ?, ?, ?)");
$name = 'Stuttgart';
$countryCode = 'DEU';
$district = 'Stuttgart';
$population = 617000;
mysqli_stmt_bind_param($stmt, 'sssi', $name, $countryCode, $district, $population);
mysqli_stmt_execute($stmt);
printf("New record has ID %d.\n", mysqli_stmt_insert_id($stmt));
ENTITY
New record has ID 1.
ENTITY
mysqli_insert_id
mysqli_stmt_affected_rows
mysqli_stmt_execute
more-results
mysqli_stmt::more_results
mysqli_stmt_more_results
Check if there are more query results from a multiple query
ENTITY
ENTITY
public
bool
mysqli_stmt::more_results
ENTITY:
bool
mysqli_stmt_more_results
mysqli_stmt
statement
Checks if there are more query results from a multiple query.
[!NOTE] ENTITY
ENTITY
ENTITY
Returns ENTITY if more results exist, otherwise ENTITY.
ENTITY
mysqli_stmt::next_result, mysqli::multi_query
next-result
mysqli_stmt::next_result
mysqli_stmt_next_result
Reads the next result from a multiple query
ENTITY
ENTITY
public
bool
mysqli_stmt::next_result
ENTITY:
bool
mysqli_stmt_next_result
mysqli_stmt
statement
Reads the next result from a multiple query.
[!NOTE] Prior to PHP 8.1.0, available only with mysqlnd.
ENTITY
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.1.0 | Now also available when linking against libmysqlclient. |
ENTITY
mysqli_stmt::more_results, mysqli::multi_query
num-rows
mysqli_stmt::$num_rows
mysqli_stmt::num_rows
mysqli_stmt_num_rows
Returns the number of rows fetched from the server
ENTITY
ENTITY
int
string
mysqli_stmt-ENTITYnum_rows
public
int
string
mysqli_stmt::num_rows
ENTITY
int
string
mysqli_stmt_num_rows
mysqli_stmt
statement
Returns the number of rows buffered in the statement. This function will only work after mysqli_stmt_store_result is called to buffer the entire result set in the statement handle.
This function returns 0 unless all rows have been fetched from the server.
ENTITY
ENTITY
An ENTITY representing the number of buffered rows. Returns 0 in unbuffered mode unless all rows have been fetched from the server.
ENTITY
ENTITY
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = $mysqli->prepare($query);
$stmt->execute();
/* store the result in an internal buffer */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);
/* store the result in an internal buffer */
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));
ENTITY
Number of rows: 20.
ENTITY
mysqli_stmt_store_result, mysqli_stmt_affected_rows, mysqli_prepare
param-count
mysqli_stmt::$param_count
mysqli_stmt_param_count
Returns the number of parameters for the given statement
ENTITY
ENTITY
int
mysqli_stmt-ENTITYparam_count
ENTITY
int
mysqli_stmt_param_count
mysqli_stmt
statement
Returns the number of parameter markers present in the prepared statement.
ENTITY
ENTITY
Returns an integer representing the number of parameters.
ENTITY
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {
$marker = $stmt->param_count;
printf("Statement has %d markers.\n", $marker);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {
$marker = mysqli_stmt_param_count($stmt);
printf("Statement has %d markers.\n", $marker);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
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_preparethat is longer thanmax_allowed_packetof 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:
mysqlndon Linux returns an error code of 1153. The error message means “got a packet bigger thanmax_allowed_packetbytes”.
mysqlndon Windows returns an error code 2006. This error message means “server has gone away”.
libmysqlclienton 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 anINSERTstatement (to specify column values for a row), or in a comparison with a column in aWHEREclause 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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = $mysqli->stmt_init();
$stmt->prepare("SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "Amersfoort";
/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $city);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s is in district %s\n", $city, $district);
ENTITY
Amersfoort is in district Utrecht
ENTITY
mysqli_stmt_init, mysqli_stmt_execute, mysqli_stmt_fetch, mysqli_stmt_bind_param, mysqli_stmt_bind_result, mysqli_stmt_get_result, mysqli_stmt_close
reset
mysqli_stmt::reset
mysqli_stmt_reset
Resets a prepared statement
ENTITY
ENTITY
public
bool
mysqli_stmt::reset
ENTITY
bool
mysqli_stmt_reset
mysqli_stmt
statement
Resets a prepared statement on client and server to the state after prepare.
It resets the statement on the server, data sent using mysqli_stmt_send_long_data, unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it).
To prepare a statement with another query use function mysqli_stmt_prepare.
ENTITY
ENTITY
ENTITY
ENTITY
mysqli_prepare
result-metadata
mysqli_stmt::result_metadata
mysqli_stmt_result_metadata
Returns result set metadata from a prepared statement
ENTITY
ENTITY
public
mysqli_result
false
mysqli_stmt::result_metadata
ENTITY
mysqli_result
false
mysqli_stmt_result_metadata
mysqli_stmt
statement
If a statement passed to mysqli_prepare is one that produces a result set, mysqli_stmt_result_metadata returns the result object that can be used to process the meta information such as total number of fields and individual field information.
This function returns an empty mysqli_result object which can be used to access metadata information from the prepared statement without having to fetch the actual rows of data. There is no need to use this function when using mysqli_stmt_get_result to retrieve the entire result set from a prepared statement as a result object.
[!NOTE] This result set object can be passed as an argument only to the field-based functions that process result set metadata, such as:
mysqli_num_fields
mysqli_fetch_field
mysqli_fetch_field_direct
mysqli_fetch_fields
mysqli_field_count
mysqli_field_seek
mysqli_field_tell
mysqli_free_result
[!NOTE] The result set returned by
mysqli_stmt_result_metadatacontains only metadata. It does not contain any row results. The rows are obtained by callingmysqli_stmt_get_resulton the statement handle or withmysqli_stmt_fetch.
ENTITY
ENTITY
Returns a result object or ENTITY if an error occurred. If the statement does not produce a result set, ENTITY is returned as well.
ENTITY ENTITY
ENTITY
ENTITY
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
$mysqli->query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");
$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();
/* get resultset for metadata */
$result = $stmt->result_metadata();
/* retrieve field information from metadata result set */
$field = $result->fetch_field();
printf("Fieldname: %s\n", $field->name);
?>
ENTITY
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");
mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");
$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);
/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);
/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);
printf("Fieldname: %s\n", $field->name);
?>
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
<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>
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
<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %s.\n", $stmt->sqlstate);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
ENTITY
<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
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_resultfor 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 ifmysqli_stmt_result_metadatareturns ENTITY.
ENTITY
ENTITY
ENTITY
ENTITY ENTITY
ENTITY
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = $mysqli->prepare($query);
$stmt->execute();
/* store the result in an internal buffer */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
ENTITY
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);
/* store the result in an internal buffer */
mysqli_stmt_store_result($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));
ENTITY
Number of rows: 20.
ENTITY
mysqli_prepare, mysqli_stmt_result_metadata, mysqli_stmt_fetch
mysqli_warning
ENTITY
Represents a MySQL warning.
ENTITY
final
mysqli_warning
ENTITY
public
string
message
public
string
sqlstate
public
int
errno
ENTITY
ENTITY
message
Message string
sqlstate
SQL state
errno
Error number
ENTITY
construct
mysqli_warning::__construct
Private constructor to disallow direct instantiation
ENTITY
private
mysqli_warning::__construct
ENTITY ENTITY
next
mysqli_warning::next
Fetch next warning
ENTITY
public
bool
mysqli_warning::next
Change warning information to the next warning if possible.
Once the warning has been set to the next warning, new values of properties message, sqlstate and errno of mysqli_warning are available.
ENTITY ENTITY
ENTITY
Returns ENTITY if next warning was fetched successfully. If there are no more warnings, it will return ENTITY
Overview
This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.
What is an API?
An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.
APIs can be procedural or object-oriented. With a procedural API, you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two, the latter is usually the preferred interface, as it is more modern and leads to better-organized code.
When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.
What is a Connector?
In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.
If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database, and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.
What is a Driver?
A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.
By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.
Sometimes people use the terms connector and driver interchangeably, which can be confusing. In the MySQL-related documentation the term “driver” is reserved for software that provides the database-specific part of a connector package.
What is an Extension?
In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the PDO MySQL driver extension, are implemented using the PHP extension framework.
An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.
The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.
The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.
What are the main PHP API offerings for using MySQL?
There are two main API options when considering connecting to a MySQL database server:
-
PHP's mysqli Extension
-
PHP Data Objects (PDO)
Each has its own advantages and disadvantages. The following discussion aims to give a brief introduction to the key aspects of each API.
What is PHP's mysqli Extension?
The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
-
Object-oriented interface
-
Support for Prepared Statements
-
Support for Multiple Statements
-
Support for Transactions
-
Enhanced debugging capabilities
As well as the object-oriented interface the extension also provides a procedural interface.
The mysqli extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli.
For further information on the mysqli extension, see ???.
What is PDO?
PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. In theory, if you are using the PDO API, you could switch the database server you used, from say Firebird to MySQL, and only need to make minor changes to your PHP code.
Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl.
While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements.
PDO is implemented using the PHP extension framework, its source code is located in the directory ext/pdo.
For further information on PDO, see the ???.
What is the PDO MYSQL driver?
The PDO MYSQL driver is not an API as such, at least from the PHP programmer's perspective. In fact, the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server.
The PDO MYSQL driver is one of several available PDO drivers. Other PDO drivers available include those for the Firebird and PostgreSQL database servers.
The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/pdo_mysql. It does not expose an API to the PHP programmer.
For further information on the PDO MYSQL driver, see ???.
What is PHP's MySQL Native Driver?
In order to communicate with the MySQL database server, mysqli and the PDO MYSQL driver each use a low-level library that implements the required protocol. In the past, the only available library was the MySQL Client Library, otherwise known as libmysqlclient.
However, the interface presented by libmysqlclient was not optimized for communication with PHP applications, as libmysqlclient was originally designed with C applications in mind. For this reason, the MySQL Native Driver, mysqlnd, was developed as an alternative to libmysqlclient for PHP applications.
Both the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysqlclient or mysqlnd. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysqlclient. You are strongly encouraged to take advantage of these improvements.
The MySQL Native Driver is implemented using the PHP extension framework. The source code is located in ext/mysqlnd. It does not expose an API to the PHP programmer.
[!NOTE] There are different internal implementations within
libmysqlclientandmysqlndfor handling columns of typeMYSQL_TYPE_GEOMETRY. Generally speaking,mysqlndwill allocate significantly less memory. For example, if there is aPOINTcolumn in a result set,libmysqlclientmay pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding aPOINTcolumn in memory. Memory allocation is much lower, less than 50 bytes, if usingmysqlnd.
Comparison of Features
The following table compares the functionality of the main methods of connecting to MySQL from PHP:
| PHP's mysqli Extension | PDO (Using PDO MySQL Driver and MySQL Native Driver) | |
|---|---|---|
| PHP version introduced | 5.0 | 5.0 |
| MySQL development status | Active development | Active development |
| API supports Charsets | Yes | Yes |
| API supports server-side Prepared Statements | Yes | Yes |
| API supports client-side Prepared Statements | No | Yes |
| API supports Stored Procedures | Yes | Yes |
| API supports Multiple Statements | Yes | Most |
| Supports all MySQL 4.1+ functionality | Yes | Most |
Comparison of MySQL API options for PHP {#mysqli.overview.option.comparison}
The mysqli Extension and Persistent Connections
The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times. This reduces the overhead of creating fresh connections every time one is required, as unused connections are cached and ready to be reused.
Unlike the mysql extension, mysqli does not provide a separate function for opening persistent connections. To open a persistent connection you must prepend p: to the hostname when connecting.
The problem with persistent connections is that they can be left in unpredictable states by clients. For example, a table lock might be activated before a client terminates unexpectedly. A new client process reusing this persistent connection will get the connection “as is”. Any cleanup would need to be done by the new client process before it could make good use of the persistent connection, increasing the burden on the programmer.
The persistent connection of the mysqli extension however provides built-in cleanup handling code. The cleanup carried out by mysqli includes:
-
Rollback active transactions
-
Close and drop temporary tables
-
Unlock tables
-
Reset session variables
-
Close prepared statements (always happens with PHP)
-
Close handler
-
Release locks acquired with
GET_LOCK
This ensures that persistent connections are in a clean state on return from the connection pool, before the client process uses them.
The mysqli extension does this cleanup by automatically calling the C-API function mysql_change_user().
The automatic cleanup feature has advantages and disadvantages though. The advantage is that the programmer no longer needs to worry about adding cleanup code, as it is called automatically. However, the disadvantage is that the code could potentially be a little slower, as the code to perform the cleanup needs to run each time a connection is returned from the connection pool.
It is possible to switch off the automatic cleanup code, by compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined.
[!NOTE] The
mysqliextension supports persistent connections when using either MySQL Native Driver or MySQL Client Library.
Quick start guide
This quick start guide will help with choosing and gaining familiarity with the PHP MySQL API.
This quick start gives an overview on the mysqli extension. Code examples are provided for all major aspects of the API. Database concepts are explained to the degree needed for presenting concepts specific to MySQL.
Required: A familiarity with the PHP programming language, the SQL language, and basic knowledge of the MySQL server.
Dual procedural and object-oriented interface
The mysqli extension features a dual interface. It supports the procedural and object-oriented programming paradigm.
Users migrating from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the old mysql extension. In many cases, the function names differ only by prefix. Some mysqli functions take a connection handle as their first argument, whereas matching functions in the old mysql interface take it as an optional last argument.
Easy migration from the old mysql extension
<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'Please do not use the deprecated mysql extension for new development. ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo $row['_msg'];
$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$result = mysql_query("SELECT 'Use the mysqli extension instead.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($result);
echo $row['_msg'];
ENTITY
Please do not use the deprecated mysql extension for new development. Use the mysqli extension instead.
The object-oriented interface
In addition to the classical procedural interface, users can choose to use the object-oriented interface. The documentation is organized using the object-oriented interface. The object-oriented interface shows functions grouped by their purpose, making it easier to get started. The reference section gives examples for both syntax variants.
There are no significant performance differences between the two interfaces. Users can base their choice on personal preference.
Object-oriented and procedural interface
<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo $row['_msg'];
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $result->fetch_assoc();
echo $row['_msg'];
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
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");
if ($row = $result->fetch_assoc()) {
echo $row['_msg'];
}
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
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
echo $mysqli->host_info . "\n";
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
Buffered result sets
After statement execution, results can be either retrieved all at once or read row by row from the server. Client-side result set buffering allows the server to free resources associated with the statement's results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli::query combines statement execution and result set buffering.
PHP applications can navigate freely through buffered results. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.
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.
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");
$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");
$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
$label = 'PHP';
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string
$stmt->execute();
Repeated execution
A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.
INSERT prepared once, executed multiple times
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");
/* Prepared statement, stage 2: bind and execute */
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string
$data = [
1 => 'PHP',
2 => 'Java',
3 => 'C++'
];
foreach ($data as $id => $label) {
$stmt->execute();
}
$result = $mysqli->query('SELECT id, label FROM test');
var_dump($result->fetch_all(MYSQLI_ASSOC));
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$values = [1, 2, 3, 4];
$stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?), (?), (?), (?)");
$stmt->bind_param('iiii', ...$values);
$stmt->execute();
Result set values data types
The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. Client libraries receive binary data and try to convert the values into appropriate PHP data types. For example, results from an SQL INT column will be provided as PHP integer variables.
Native datatypes
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$stmt->bind_result($out_id, $out_label);
while ($stmt->fetch()) {
printf("id = %s (%s), label = %s (%s)\n", $out_id, gettype($out_id), $out_label, gettype($out_label));
}
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$result = $stmt->get_result();
var_dump($result->fetch_all(MYSQLI_ASSOC));
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP'), (2, 'Java'), (3, 'C++')");
$stmt = $mysqli->prepare("SELECT id, label FROM test");
$stmt->execute();
$result = $stmt->get_result();
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
var_dump($result->fetch_assoc());
}
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;");
$mysqli->query("CALL p(1)");
$result = $mysqli->query("SELECT id FROM test");
var_dump($result->fetch_assoc());
ENTITY
array(1) {
["id"]=>
string(1) "1"
}
INOUT/OUT parameter
The values of INOUT/OUT parameters are accessed using session variables.
Using session variables
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;');
$mysqli->query("SET @msg = ''");
$mysqli->query("CALL p(@msg)");
$result = $mysqli->query("SELECT @msg as _p_out");
$row = $result->fetch_assoc();
echo $row['_p_out'];
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$mysqli->multi_query("CALL p()");
do {
if ($result = $mysqli->store_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($mysqli->next_result());
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$stmt = $mysqli->prepare("CALL p()");
$stmt->execute();
do {
if ($result = $stmt->get_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($stmt->next_result());
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");
$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');
$stmt = $mysqli->prepare("CALL p()");
$stmt->execute();
do {
if ($stmt->store_result()) {
$stmt->bind_result($id_out);
while ($stmt->fetch()) {
echo "id = $id_out\n";
}
}
} while ($stmt->next_result());
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
do {
if ($result = $mysqli->store_result()) {
var_dump($result->fetch_all(MYSQLI_ASSOC));
$result->free();
}
} while ($mysqli->next_result());
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
?>
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Recommended: using API to control transactional settings */
$mysqli->autocommit(false);
/* Won't be monitored and recognized by the replication and the load balancing plugin */
$mysqli->query('SET AUTOCOMMIT = 0');
Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting autocommit mode, committing or rolling back a transaction.
Commit and rollback
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->autocommit(false);
$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->rollback();
$mysqli->query("INSERT INTO test(id) VALUES (2)");
$mysqli->commit();
Please note, that the MySQL server cannot roll back all statements. Some statements cause an implicit commit.
See also
mysqli::autocommit, mysqli::begin_transaction, mysqli::commit, mysqli::rollback
Metadata
A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the mysqli interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.
Meta data is access through the mysqli_result interface.
Accessing result set meta data
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($result->fetch_fields());
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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$result = $stmt->result_metadata();
var_dump($result->fetch_fields());
See also
mysqli::query, mysqli_result::fetch_fields
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
serializeyour object andunserializeit 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,
resourcevariables cannot be stored in the session.The
phpandphp_binaryserialize 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 thephpserialize handler. Using such a key causes session write failure (and a warning as of PHP 8.5.0).The
php_serializehandler 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
$_SESSIONsuperglobal array. This holds true regardless of if a session has been started using thesession_startfunction.
ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY ENTITY
configure
ENTITY
ENTITY --disable-session
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.
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Unregistering a variable with $_SESSION.
<?php
session_start();
unset($_SESSION['count']);
?>
[!CAUTION] Do NOT unset the whole
$_SESSIONwithunset($_SESSION)as this will disable the registering of session variables through the$_SESSIONsuperglobal.
[!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_startor 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 callingsession_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_closeas 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:
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
<?php
session_start();
if (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
?>
<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>
<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
here</a>.
</p>
The htmlspecialchars may be used when printing the SID in order to prevent XSS related attacks.
Printing the SID, like shown above, is not necessary if --enable-trans-sid was used to compile PHP.
[!NOTE] Non-relative URLs are assumed to point to external sites and hence don't append the
SID, as it would be a security risk to leak theSIDto 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
valueis of value only, ifsession.cache_limiteris set to a value different fromnocache.
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
<?php
/* set the cache limiter to 'private' */
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
/* set the cache expire to 30 minutes */
session_cache_expire(30);
$cache_expire = session_cache_expire();
/* start the session */
session_start();
echo "The cache limiter is now set to $cache_limiter<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>
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.
| Value | Headers sent |
|---|---|
public |
|
private_no_expire |
|
private |
|
nocache |
|
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
<?php
/* set the cache limiter to 'private' */
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
echo "The cache limiter is now set to $cache_limiter<br />";
?>
ENTITY
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
<?php
// My session start function support timestamp management
function my_session_start() {
session_start();
// Do not allow to use too old session ID
if (!empty($_SESSION['deleted_time']) && $_SESSION['deleted_time'] < time() - 180) {
session_destroy();
session_start();
}
}
// My session regenerate id function
function my_session_regenerate_id() {
// Call session_create_id() while session is active to
// make sure collision free.
if (session_status() != PHP_SESSION_ACTIVE) {
session_start();
}
// WARNING: Never use confidential strings for prefix!
$newid = session_create_id('myprefix-');
// Set deleted timestamp. Session data must not be deleted immediately for reasons.
$_SESSION['deleted_time'] = time();
// Finish session
session_commit();
// Make sure to accept user defined session ID
// NOTE: You must enable use_strict_mode for normal operations.
ini_set('session.use_strict_mode', 0);
// Set new custom session ID
session_id($newid);
// Start with custom session ID
session_start();
}
// Make sure use_strict_mode is enabled.
// use_strict_mode is mandatory for security reasons.
ini_set('session.use_strict_mode', 1);
my_session_start();
// Session ID must be regenerated when
// - User logged in
// - User logged out
// - Certain period has passed
my_session_regenerate_id();
// Write useful codes
?>
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_destroyfrom 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_idalso.
ENTITY ENTITY
ENTITY
ENTITY
ENTITY
Destroying a session with $_SESSION
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
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_startbefore usingsession_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_gcfrom 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'sPrivateTmp=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,
1is returned regardless of how many session entries are actually deleted.
ENTITY
session_gc example for task managers like cron
<?php
// Note: This script should be executed by the same user of web server process.
// Need active session to initialize session data storage access.
session_start();
// Executes GC immediately
session_gc();
// Clean up session ID created by session_start()
session_destroy();
?>
session_gc example for user accessible script
<?php
// Note: session_gc() is recommended to be used by a task manager script, but
// it may be used as follows.
// Used for last GC time check
$gc_time = '/tmp/php_session_last_gc';
$gc_period = 1800;
session_start();
// Execute GC only when GC period elapsed.
// i.e. Calling session_gc() every request is waste of resources.
if (file_exists($gc_time)) {
if (filemtime($gc_time) < time() - $gc_period) {
session_gc();
touch($gc_time);
}
} else {
touch($gc_time);
}
?>
ENTITY
session_start
session_destroy
session.gc_probability
session-get-cookie-params
Get the session cookie parameters
ENTITY
array
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-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
idforsession_idwill always send a new cookie whensession_startis 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
<?php
/* set the session name to WebsiteID */
$previous_name = session_name("WebsiteID");
echo "The previous session name was $previous_name<br />";
?>
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
<?php
// NOTE: This code is not fully working code, but an example!
session_start();
// Check destroyed time-stamp
if (isset($_SESSION['destroyed'])
&& $_SESSION['destroyed'] < time() - 300) {
// Should not happen usually. This could be attack or due to unstable network.
// Remove all authentication status of this users session.
remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
throw(new DestroyedSessionAccessException);
}
$old_sessionid = session_id();
// Set destroyed timestamp
$_SESSION['destroyed'] = time(); // session_regenerate_id() saves old session data
// Simply calling session_regenerate_id() may result in lost session, etc.
// See next example.
session_regenerate_id();
// New session does not need destroyed timestamp
unset($_SESSION['destroyed']);
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
?>
Current session module does not handle unstable network well. You should manage session ID to avoid lost session by session_regenerate_id.
Avoiding lost session by session_regenerate_id
<?php
// NOTE: This code is not fully working code, but an example!
// my_session_start() and my_session_regenerate_id() avoid lost sessions by
// unstable network. In addition, this code may prevent exploiting stolen
// session by attackers.
function my_session_start() {
session_start();
if (isset($_SESSION['destroyed'])) {
if ($_SESSION['destroyed'] < time()-300) {
// Should not happen usually. This could be attack or due to unstable network.
// Remove all authentication status of this users session.
remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
throw(new DestroyedSessionAccessException);
}
if (isset($_SESSION['new_session_id'])) {
// Not fully expired yet. Could be lost cookie by unstable network.
// Try again to set proper session ID cookie.
// NOTE: Do not try to set session ID again if you would like to remove
// authentication flag.
session_commit();
session_id($_SESSION['new_session_id']);
// New session ID should exist
session_start();
return;
}
}
}
function my_session_regenerate_id() {
// New session ID is required to set proper session ID
// when session ID is not set due to unstable network.
$new_session_id = session_create_id();
$_SESSION['new_session_id'] = $new_session_id;
// Set destroy timestamp
$_SESSION['destroyed'] = time();
// Write and close current session;
session_commit();
// Start session with new session ID
session_id($new_session_id);
ini_set('session.use_strict_mode', 0);
session_start();
ini_set('session.use_strict_mode', 1);
// New session does not need them
unset($_SESSION['destroyed']);
unset($_SESSION['new_session_id']);
}
?>
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
Set the session cookie parameters
ENTITY
bool
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
array
lifetime_or_options
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.
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-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<open> string``savePath string``sessionName
The open callback works like a constructor in classes and is executed when the session is being opened. It is the first callback function executed when the session is started automatically or manually with session_start. Return value is ENTITY for success, ENTITY for failure.
close
A callable with the following signature: bool<close>
The close callback works like a destructor in classes and is executed after the session write callback has been called. It is also invoked when session_write_close is called. Return value should be ENTITY for success, ENTITY for failure.
read
A callable with the following signature: stringfalse<read> string``sessionId
The read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read. 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<write> string``sessionId string``data
The write callback is called when the session needs to be saved and closed. This callback receives the current session ID a serialized version the $_SESSION superglobal. The serialization method used internally by PHP is specified in the session.serialize_handler ini setting.
The serialized session data passed to this callback should be stored against the passed session ID. When retrieving this data, the read callback must return the exact value that was originally passed to the write callback.
This callback is invoked when PHP shuts down or explicitly when session_write_close is called. Note that after executing this function PHP will internally execute the close callback.
[!NOTE] The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead.
destroy
A callable with the following signature: bool<destroy> 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<gc> 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<create_sid>
This callback is executed when a new session ID is required. No parameters are provided, and the return value should be a string that is a valid session ID for your handler.
validate_sid
A callable with the following signature: bool<validate_sid> 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<update_timestamp> 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.
<?php
class MySessionHandler implements SessionHandlerInterface
{
// implement interfaces here
}
$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
// proceed to set and retrieve values by key from $_SESSION
ENTITY
[!WARNING] The
writeandclosehandlers are called after object destruction and therefore cannot use objects or throw exceptions. Exceptions are not able to be caught since will not be caught nor will any exception trace be displayed and the execution will just cease unexpectedly. The object destructors can however use sessions.It is possible to call
session_write_closefrom the destructor to solve this chicken and egg problem but the most reliable way is to register the shutdown function as described above.
[!WARNING] Current working directory is changed with some SAPIs if session is closed in the script termination. It is possible to close the session earlier with
session_write_close.
ENTITY
The session.save_handler configuration directive, The session.serialize_handler configuration directive., The register_shutdown_function, The session_register_shutdown, Refer to save_handler.inc for a full procedural reference implementation
session-start
session_start
Start new or resume existing session
ENTITY
bool
session_start
array
options
[]
session_start creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
When session_start is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler. The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.
To use a named session, call session_name before calling session_start.
When session.use_trans_sid is enabled, the session_start function will register an internal output handler for URL rewriting.
If a user uses ob_gzhandler or similar with ob_start, the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session.
ENTITY
options
If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix.
In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to ENTITY, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed.
ENTITY
This function returns ENTITY if a session was successfully started, otherwise ENTITY.
ENTITY
As of PHP 8.5.0, throws a ValueError if options has any non-string key.
As of PHP 8.5.0, throws a TypeError if the read_and_close option is not of type string, int or bool, or if its value cannot be interpreted as an int.
ENTITY
| ENTITY | ENTITY |
|---|---|
| 8.5.0 | Now throws a ValueError if the options array has non-string keys, and a TypeError if the read_and_close value is not compatible with int. |
| 7.1.0 | session_start now returns ENTITY and no longer initializes $_SESSION when it failed to start the session. |
ENTITY
A basic session example
page1.php
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';
// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>
After viewing page1.php, the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about.
page2.php
<?php
// page2.php
session_start();
echo 'Welcome to page #2<br />';
echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);
// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>
Providing options to session_start
Overriding the cookie lifetime
<?php
// This sends a persistent cookie that lasts a day.
session_start([
'cookie_lifetime' => 86400,
]);
?>
Reading the session and closing it
<?php
// If we know we don't need to change anything in the
// session, we can just read and close rightaway to avoid
// locking the session file and blocking other pages
session_start([
'cookie_lifetime' => 86400,
'read_and_close' => true,
]);
ENTITY
[!NOTE] To use cookie-based sessions,
session_startmust 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_limiterto 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_DISABLEDif sessions are disabled. -
PHP_SESSION_NONEif sessions are enabled, but none exists. -
PHP_SESSION_ACTIVEif 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
$_SESSIONis used, useunsetto unregister a session variable, i.e.unset($_SESSION['varname']);.
[!CAUTION] Do NOT unset the whole
$_SESSIONwithunset($_SESSION)as this will disable the registering of session variables through the$_SESSIONsuperglobal.
[!NOTE] The use of
session_unsetis identical to$_SESSION = [].
[!CAUTION] This function works only if a session is active. It will not clear the
$_SESSIONarray 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) ** 3directories exist on the filesystem, which can result in a lot of wasted space and inodes.Only use
Ngreater 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_maxlifetimebut 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_checkto 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_filedefaults to/dev/urandomor/dev/arandomif 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_modeis mandatory for general session security. All sites are advised to enable this. Seesession_create_idexample code for more details.
[!WARNING] If a custom session handler registered via
session_set_save_handlerdoes not implement SessionUpdateTimestampHandlerInterface::validateId, nor supplies thevalidate_sidcallback, respectively, strict session ID mode is effectively disabled, regardless of the value of this directive. Particularly note thatSessionHandlerdoes not implement SessionHandler::validateId.
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_cookiesis deprecated as of PHP 8.4.0.
[!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.
If enabled, session.cookie_secure must also be enabled, otherwise the session cookie will not be sent and a warning is raised.
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_sidis 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_tagsfrom 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,
fieldsetis 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_hoststo 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_lengthfrom 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_characterfrom 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_idwith 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, orrandom_bytesand hash functions to generate a new session ID.session_create_idhas collision detection and generates a session ID according to the session's INI settings. Use ofsession_create_idis 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);andsession_destroymust 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_varwith 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.
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
SessionHandlerInterfaceinterface instead of extending fromSessionHandler.
ENTITY
Using SessionHandler to add encryption to internal PHP save handlers.
<?php
/**
* decrypt AES 256
*
* @param data $edata
* @param string $password
* @return decrypted data
*/
function decrypt($edata, $password) {
$data = base64_decode($edata);
$salt = substr($data, 0, 16);
$ct = substr($data, 16);
$rounds = 3; // depends on key length
$data00 = $password.$salt;
$hash = array();
$hash[0] = hash('sha256', $data00, true);
$result = $hash[0];
for ($i = 1; $i < $rounds; $i++) {
$hash[$i] = hash('sha256', $hash[$i - 1].$data00, true);
$result .= $hash[$i];
}
$key = substr($result, 0, 32);
$iv = substr($result, 32,16);
return openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv);
}
/**
* crypt AES 256
*
* @param data $data
* @param string $password
* @return base64 encrypted data
*/
function encrypt($data, $password) {
// Generate a cryptographically secure random salt using random_bytes()
$salt = random_bytes(16);
$salted = '';
$dx = '';
// Salt the key(32) and iv(16) = 48
while (strlen($salted) < 48) {
$dx = hash('sha256', $dx.$password.$salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32,16);
$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv);
return base64_encode($salt . $encrypted_data);
}
class EncryptedSessionHandler extends SessionHandler
{
private $key;
public function __construct($key)
{
$this->key = $key;
}
public function read($id)
{
$data = parent::read($id);
if (!$data) {
return "";
} else {
return decrypt($data, $this->key);
}
}
public function write($id, $data)
{
$data = encrypt($data, $this->key);
return parent::write($id, $data);
}
}
// we'll intercept the native 'files' handler, but will equally work
// with other internal native handlers like 'sqlite', 'memcache' or 'memcached'
// which are provided by PHP extensions.
ini_set('session.save_handler', 'files');
$key = 'secret_string';
$handler = new EncryptedSessionHandler($key);
session_set_save_handler($handler, true);
session_start();
// proceed to set and retrieve values by key from $_SESSION
[!NOTE] Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return 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
$idparameters are actually user supplied values which require proper validation/sanitization to avoid vulnerabilities, such as path traversal issues. So do not use this example unmodified in production environments.
<?php
class MySessionHandler implements SessionHandlerInterface
{
private $savePath;
public function open($savePath, $sessionName): bool
{
$this->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/mdon 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.
<?php
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);
?>
It is also possible to cancel the currently in-progress file upload, by setting the $_SESSION[$key]["cancel_upload"] key to 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.
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
<input type="file" name="file1" />
<input type="file" name="file2" />
<input type="submit" />
</form>
The data stored in the session will look like this:
<?php
$_SESSION["upload_progress_123"] = array(
"start_time" => 1234567890, // The request time
"content_length" => 57343257, // POST content length
"bytes_processed" => 453489, // Amount of bytes received and processed
"done" => false, // true when the POST handler has finished, successfully or not
"files" => array(
0 => array(
"field_name" => "file1", // Name of the <input/> field
// The following 3 elements equals those in $_FILES
"name" => "foo.avi",
"tmp_name" => "/tmp/phpxxxxxx",
"error" => 0,
"done" => true, // True when the POST handler has finished handling this file
"start_time" => 1234567890, // When this file has started to be processed
"bytes_processed" => 57343250, // Number of bytes received and processed for this file
),
// An other file, not finished uploading, in the same request
1 => array(
"field_name" => "file2",
"name" => "bar.avi",
"tmp_name" => NULL,
"error" => 0,
"done" => false,
"start_time" => 1234567899,
"bytes_processed" => 54554,
),
)
);
[!WARNING] The web server's request buffering has to be disabled for this to work properly, else PHP may see the file upload only once fully uploaded. Servers such as Nginx are known to buffer larger requests.
[!CAUTION] The upload progress information is written to the session before any scripts are executed. Therefore changing the session name via
ini_setorsession_namewill 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 callingsession_set_save_handler.