code
stringlengths
2.5k
150k
kind
stringclasses
1 value
php None Class Constants --------------- It is possible to define [constants](language.constants) on a per-class basis remaining the same and unchangeable. The default visibility of class constants is `public`. > > **Note**: > > > Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as [final](language.oop5.final). > > It's also possible for interfaces to have `constants`. Look at the [interface documentation](language.oop5.interfaces) for examples. It's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. `self`, `parent` and `static`). Note that class constants are allocated once per class, and not for each class instance. **Example #1 Defining and using a constant** ``` <?php class MyClass {     const CONSTANT = 'constant value';     function showConstant() {         echo  self::CONSTANT . "\n";     } } echo MyClass::CONSTANT . "\n"; $classname = "MyClass"; echo $classname::CONSTANT . "\n"; $class = new MyClass(); $class->showConstant(); echo $class::CONSTANT."\n"; ?> ``` The special **`::class`** constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes: **Example #2 Namespaced ::class example** ``` <?php namespace foo {     class bar {     }     echo bar::class; // foo\bar } ?> ``` **Example #3 Class constant expression example** ``` <?php const ONE = 1; class foo {     const TWO = ONE * 2;     const THREE = ONE + self::TWO;     const SENTENCE = 'The value of THREE is '.self::THREE; } ?> ``` **Example #4 Class constant visibility modifiers, as of PHP 7.1.0** ``` <?php class Foo {     public const BAR = 'bar';     private const BAZ = 'baz'; } echo Foo::BAR, PHP_EOL; echo Foo::BAZ, PHP_EOL; ?> ``` Output of the above example in PHP 7.1: ``` bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in … ``` > > **Note**: > > > As of PHP 7.1.0 visibility modifiers are allowed for class constants. > > php GearmanWorker::wait GearmanWorker::wait =================== (PECL gearman >= 0.6.0) GearmanWorker::wait — Wait for activity from one of the job servers ### Description ``` public GearmanWorker::wait(): bool ``` Causes the worker to wait for activity from one of the Gearman job servers when operating in non-blocking I/O mode. On failure, issues a **`E_WARNING`** with the last Gearman error encountered. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Running worker in non-blocking mode** ``` <?php echo "Starting\n"; # Create our worker object $worker= new GearmanWorker(); # Make the worker non-blocking $worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);  # Add the default server (localhost, port 4730) $worker->addServer();  # Add our reverse function $worker->addFunction('reverse', 'reverse_fn'); # Try to grab a job while (@$worker->work() ||        $worker->returnCode() == GEARMAN_IO_WAIT ||        $worker->returnCode() == GEARMAN_NO_JOBS) {   if ($worker->returnCode() == GEARMAN_SUCCESS)     continue;   echo "Waiting for next job...\n";   if (!@$worker->wait())    {      if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS)      {        # We are not connected to any servers, so wait a bit before        # trying to reconnect.        sleep(5);        continue;      }      break;    }  }  echo "Worker Error: " . $worker->error() . "\n"; function reverse_fn($job) {   return strrev($job->workload()); } ?> ``` ### See Also * [GearmanWorker::work()](gearmanworker.work) - Wait for and perform jobs php OAuthProvider::generateToken OAuthProvider::generateToken ============================ (PECL OAuth >= 1.0.0) OAuthProvider::generateToken — Generate a random token ### Description ``` final public static OAuthProvider::generateToken(int $size, bool $strong = false): string ``` Generates a string of pseudo-random bytes. ### Parameters `size` The desired token length, in terms of bytes. `strong` Setting to **`true`** means `/dev/random` will be used for entropy, as otherwise the non-blocking `/dev/urandom` is used. This parameter is ignored on Windows. ### Return Values The generated token, as a string of bytes. ### Errors/Exceptions If the `strong` parameter is **`true`**, then an **`E_WARNING`** level error will be emitted when the fallback [rand()](https://www.php.net/manual/en/function.rand.php) implementation is used to fill the remaining random bytes (e.g., when not enough random data was found, initially). ### Examples **Example #1 **OAuthProvider::generateToken()** example** ``` <?php $p = new OAuthProvider(); $t = $p->generateToken(4); echo strlen($t),  PHP_EOL; echo bin2hex($t), PHP_EOL; ?> ``` The above example will output something similar to: ``` 4 b6a82c27 ``` ### Notes > > **Note**: > > > When not enough random data is available to the system, this function will fill the remaining random bytes using the internal PHP [rand()](https://www.php.net/manual/en/function.rand.php) implementation. > > ### See Also * [openssl\_random\_pseudo\_bytes()](function.openssl-random-pseudo-bytes) - Generate a pseudo-random string of bytes * [mcrypt\_create\_iv()](function.mcrypt-create-iv) - Creates an initialization vector (IV) from a random source php krsort krsort ====== (PHP 4, PHP 5, PHP 7, PHP 8) krsort — Sort an array by key in descending order ### Description ``` krsort(array &$array, int $flags = SORT_REGULAR): bool ``` Sorts `array` in place by keys in descending order. > > **Note**: > > > If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. > > > > **Note**: > > > Resets array's internal pointer to the first element. > > ### Parameters `array` The input array. `flags` The optional second parameter `flags` may be used to modify the sorting behavior using these values: Sorting type flags: * **`SORT_REGULAR`** - compare items normally; the details are described in the [comparison operators](language.operators.comparison) section * **`SORT_NUMERIC`** - compare items numerically * **`SORT_STRING`** - compare items as strings * **`SORT_LOCALE_STRING`** - compare items as strings, based on the current locale. It uses the locale, which can be changed using [setlocale()](function.setlocale) * **`SORT_NATURAL`** - compare items as strings using "natural ordering" like [natsort()](function.natsort) * **`SORT_FLAG_CASE`** - can be combined (bitwise OR) with **`SORT_STRING`** or **`SORT_NATURAL`** to sort strings case-insensitively ### Return Values Always returns **`true`**. ### Examples **Example #1 **krsort()** example** ``` <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); krsort($fruits); foreach ($fruits as $key => $val) {     echo "$key = $val\n"; } ?> ``` The above example will output: ``` d = lemon c = apple b = banana a = orange ``` ### See Also * [sort()](function.sort) - Sort an array in ascending order * [ksort()](function.ksort) - Sort an array by key in ascending order * The [comparison of array sorting functions](https://www.php.net/manual/en/array.sorting.php) php runkit7_import runkit7\_import =============== (PECL runkit7 >= Unknown) runkit7\_import — Process a PHP file importing function and class definitions, overwriting where appropriate **Warning** This feature has been *removed* in PECL runkit7 4.0.0. ### Description ``` runkit7_import(string $filename, int $flags = ?): bool ``` Similar to [include](function.include). However, any code residing outside of a function or class is simply ignored. Additionally, depending on the value of `flags`, any functions or classes which already exist in the currently running environment may be automatically overwritten by their new definitions. ### Parameters `filename` Filename to import function and class definitions from `flags` Bitwise OR of the [`RUNKIT7_IMPORT_*` family of constants](https://www.php.net/manual/en/runkit7.constants.php). ### Return Values Returns **`true`** on success or **`false`** on failure. php IntlChar::charMirror IntlChar::charMirror ==================== (PHP 7, PHP 8) IntlChar::charMirror — Get the "mirror-image" character for a code point ### Description ``` public static IntlChar::charMirror(int|string $codepoint): int|string|null ``` Maps the specified character to a "mirror-image" character. For characters with the *Bidi\_Mirrored* property, implementations sometimes need a "poor man's" mapping to another Unicode character (code point) such that the default glyph may serve as the mirror-image of the default glyph of the specified character. This is useful for text conversion to and from codepages with visual order, and for displays without glyph selection capabilities. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns another Unicode code point that may serve as a mirror-image substitute, or `codepoint` itself if there is no such mapping or `codepoint` does not have the *Bidi\_Mirrored* property. The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::charMirror("A")); var_dump(IntlChar::charMirror("<")); var_dump(IntlChar::charMirror("(")); ?> ``` The above example will output: ``` string(1) "A" string(1) ">" string(2) ")" ``` ### See Also * [IntlChar::isMirrored()](intlchar.ismirrored) - Check if code point has the Bidi\_Mirrored property * **`IntlChar::PROPERTY_BIDI_MIRRORED`** php Ds\Deque::apply Ds\Deque::apply =============== (PECL ds >= 1.0.0) Ds\Deque::apply — Updates all values by applying a callback function to each value ### Description ``` public Ds\Deque::apply(callable $callback): void ``` Updates all values by applying a `callback` function to each value in the deque. ### Parameters `callback` ``` callback(mixed $value): mixed ``` A [callable](language.types.callable) to apply to each value in the deque. The callback should return what the value should be replaced by. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Deque::apply()** example** ``` <?php $deque = new \Ds\Deque([1, 2, 3]); $deque->apply(function($value) { return $value * 2; }); print_r($deque); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => 2 [1] => 4 [2] => 6 ) ``` php get_extension_funcs get\_extension\_funcs ===================== (PHP 4, PHP 5, PHP 7, PHP 8) get\_extension\_funcs — Returns an array with the names of the functions of a module ### Description ``` get_extension_funcs(string $extension): array|false ``` This function returns the names of all the functions defined in the module indicated by `extension`. ### Parameters `extension` The module name. > > **Note**: > > > This parameter must be in *lowercase*. > > ### Return Values Returns an array with all the functions, or **`false`** if `extension` is not a valid extension. ### Examples **Example #1 Prints the XML functions** ``` <?php print_r(get_extension_funcs("xml")); ?> ``` The above example will output something similar to: ``` Array ( [0] => xml_parser_create [1] => xml_parser_create_ns [2] => xml_set_object [3] => xml_set_element_handler [4] => xml_set_character_data_handler [5] => xml_set_processing_instruction_handler [6] => xml_set_default_handler [7] => xml_set_unparsed_entity_decl_handler [8] => xml_set_notation_decl_handler [9] => xml_set_external_entity_ref_handler [10] => xml_set_start_namespace_decl_handler [11] => xml_set_end_namespace_decl_handler [12] => xml_parse [13] => xml_parse_into_struct [14] => xml_get_error_code [15] => xml_error_string [16] => xml_get_current_line_number [17] => xml_get_current_column_number [18] => xml_get_current_byte_index [19] => xml_parser_free [20] => xml_parser_set_option [21] => xml_parser_get_option ) ``` ### See Also * [get\_loaded\_extensions()](function.get-loaded-extensions) - Returns an array with the names of all modules compiled and loaded * [ReflectionExtension::getFunctions()](reflectionextension.getfunctions) - Gets extension functions php SplFileInfo::getMTime SplFileInfo::getMTime ===================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getMTime — Gets the last modified time ### Description ``` public SplFileInfo::getMTime(): int|false ``` Returns the time when the contents of the file were changed. The time returned is a Unix timestamp. ### Parameters This function has no parameters. ### Return Values Returns the last modified time for the file, in a Unix timestamp on success, or **`false`** on failure. ### See Also * [filemtime()](function.filemtime) - Gets file modification time php The SysvSemaphore class The SysvSemaphore class ======================= Introduction ------------ (PHP 8) A fully opaque class which replaces a `sysvsem` resource as of PHP 8.0.0. Class synopsis -------------- final class **SysvSemaphore** { } php mysqli_stmt::$error_list mysqli\_stmt::$error\_list ========================== mysqli\_stmt\_error\_list ========================= (PHP 5 >= 5.4.0, PHP 7, PHP 8) mysqli\_stmt::$error\_list -- mysqli\_stmt\_error\_list — Returns a list of errors from the last statement executed ### Description Object-oriented style array [$mysqli\_stmt->error\_list](mysqli-stmt.error-list); Procedural style ``` mysqli_stmt_error_list(mysqli_stmt $statement): array ``` Returns an array of errors for the most recently invoked statement function that can succeed or fail. ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values A list of errors, each as an associative array containing the errno, error, and sqlstate. ### Examples **Example #1 Object-oriented style** ``` <?php /* Open a connection */ $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $mysqli->query("CREATE TABLE myCountry LIKE Country"); $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"); $query = "SELECT Name, Code FROM myCountry ORDER BY Name"; if ($stmt = $mysqli->prepare($query)) {     /* drop table */     $mysqli->query("DROP TABLE myCountry");     /* execute query */     $stmt->execute();          echo "Error:\n";     print_r($stmt->error_list);     /* close statement */     $stmt->close(); } /* close connection */ $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php /* Open a connection */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } mysqli_query($link, "CREATE TABLE myCountry LIKE Country"); mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country"); $query = "SELECT Name, Code FROM myCountry ORDER BY Name"; if ($stmt = mysqli_prepare($link, $query)) {     /* drop table */     mysqli_query($link, "DROP TABLE myCountry");     /* execute query */     mysqli_stmt_execute($stmt);          echo "Error:\n";     print_r(mysql_stmt_error_list($stmt));     /* close statement */     mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Array ( [0] => Array ( [errno] => 1146 [sqlstate] => 42S02 [error] => Table 'world.myCountry' doesn't exist ) ) ``` ### See Also * [mysqli\_stmt\_error()](mysqli-stmt.error) - Returns a string description for last statement error * [mysqli\_stmt\_errno()](mysqli-stmt.errno) - Returns the error code for the most recent statement call * [mysqli\_stmt\_sqlstate()](mysqli-stmt.sqlstate) - Returns SQLSTATE error from previous statement operation php imap_undelete imap\_undelete ============== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_undelete — Unmark the message which is marked deleted ### Description ``` imap_undelete(IMAP\Connection $imap, string $message_nums, int $flags = 0): bool ``` Removes the deletion flag for a specified message, which is set by [imap\_delete()](function.imap-delete) or [imap\_mail\_move()](function.imap-mail-move). ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `message_nums` A string representing one or more messages in IMAP4-style sequence format (`"n"`, `"n:m"`, or combination of these delimited by commas). `flags` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_delete()](function.imap-delete) - Mark a message for deletion from current mailbox * [imap\_mail\_move()](function.imap-mail-move) - Move specified messages to a mailbox php mysqli::$connect_error mysqli::$connect\_error ======================= mysqli\_connect\_error ====================== (PHP 5, PHP 7, PHP 8) mysqli::$connect\_error -- mysqli\_connect\_error — Returns a description of the last connection error ### Description Object-oriented style ?string [$mysqli->connect\_error](mysqli.connect-error); Procedural style ``` mysqli_connect_error(): ?string ``` Returns the error message from the last connection attempt. ### Parameters This function has no parameters. ### Return Values A string that describes the error. **`null`** is returned if no error occurred. ### Examples **Example #1 $mysqli->connect\_error example** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_OFF); /* @ is used to suppress warnings */ $mysqli = @new mysqli('localhost', 'fake_user', 'wrong_password', 'does_not_exist'); if ($mysqli->connect_error) {     /* Use your preferred error logging method here */     error_log('Connection error: ' . $mysqli->connect_error); } ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_OFF); /* @ is used to suppress warnings */ $link = @mysqli_connect('localhost', 'fake_user', 'wrong_password', 'does_not_exist'); if (!$link) {     /* Use your preferred error logging method here */     error_log('Connection error: ' . mysqli_connect_error()); } ``` ### See Also * [mysqli\_connect()](function.mysqli-connect) - Alias of mysqli::\_\_construct * [mysqli\_connect\_errno()](mysqli.connect-errno) - Returns the error code from last connect call * [mysqli\_errno()](mysqli.errno) - Returns the error code for the most recent function call * [mysqli\_error()](mysqli.error) - Returns a string description of the last error * [mysqli\_sqlstate()](mysqli.sqlstate) - Returns the SQLSTATE error from previous MySQL operation
programming_docs
php stats_cdf_noncentral_f stats\_cdf\_noncentral\_f ========================= (PECL stats >= 1.0.0) stats\_cdf\_noncentral\_f — Calculates any one parameter of the non-central F distribution given values for the others ### Description ``` stats_cdf_noncentral_f( float $par1, float $par2, float $par3, float $par4, int $which ): float ``` Returns the cumulative distribution function, its inverse, or one of its parameters, of the non-central F distribution. The kind of the return value and parameters (`par1`, `par2`, `par3`, and `par4`) are determined by `which`. The following table lists the return value and parameters by `which`. CDF, x, nu1, nu2, and lambda denotes cumulative distribution function, the value of the random variable, the degree of freedoms and the non-centrality parameter of the distribution, respectively. **Return value and parameters**| `which` | Return value | `par1` | `par2` | `par3` | `par4` | | --- | --- | --- | --- | --- | --- | | 1 | CDF | x | nu1 | nu2 | lambda | | 2 | x | CDF | nu1 | nu2 | lambda | | 3 | nu1 | x | CDF | nu2 | lambda | | 4 | nu2 | x | CDF | nu1 | lambda | | 5 | lambda | x | CDF | nu1 | nu2 | ### Parameters `par1` The first parameter `par2` The second parameter `par3` The third parameter `par4` The fourth parameter `which` The flag to determine what to be calculated ### Return Values Returns CDF, x, nu1, nu2, or lambda, determined by `which`. php imagefilledrectangle imagefilledrectangle ==================== (PHP 4, PHP 5, PHP 7, PHP 8) imagefilledrectangle — Draw a filled rectangle ### Description ``` imagefilledrectangle( GdImage $image, int $x1, int $y1, int $x2, int $y2, int $color ): bool ``` Creates a rectangle filled with `color` in the given `image` starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `x1` x-coordinate for point 1. `y1` y-coordinate for point 1. `x2` x-coordinate for point 2. `y2` y-coordinate for point 2. `color` The fill color. A color identifier created with [imagecolorallocate()](function.imagecolorallocate). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagefilledrectangle()** usage** ``` <?php // Create a 55x30 image $im = imagecreatetruecolor(55, 30); $white = imagecolorallocate($im, 255, 255, 255); // Draw a white rectangle imagefilledrectangle($im, 4, 4, 50, 25, $white); // Save the image imagepng($im, './imagefilledrectangle.png'); imagedestroy($im); ?> ``` The above example will output something similar to: php Memcached::__construct Memcached::\_\_construct ======================== (PECL memcached >= 0.1.0) Memcached::\_\_construct — Create a Memcached instance ### Description public **Memcached::\_\_construct**(?string `$persistent_id` = null) Creates a Memcached instance representing the connection to the memcache servers. ### Parameters `persistent_id` By default the Memcached instances are destroyed at the end of the request. To create an instance that persists between requests, use `persistent_id` to specify a unique ID for the instance. All instances created with the same `persistent_id` will share the same connection. ### Examples **Example #1 Creating a Memcached object** ``` <?php /* Create a regular instance */ $m = new Memcached(); echo get_class($m); /* Create a persistent instance */ $m2 = new Memcached('story_pool'); $m3 = new Memcached('story_pool'); /* now $m2 and $m3 share the same connection */ ?> ``` php imagewbmp imagewbmp ========= (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) imagewbmp — Output image to browser or file ### Description ``` imagewbmp(GdImage $image, resource|string|null $file = null, ?int $foreground_color = null): bool ``` **imagewbmp()** outputs or save a WBMP version of the given `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `file` The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or **`null`**, the raw image stream will be output directly. `foreground_color` You can set the foreground color with this parameter by setting an identifier obtained from [imagecolorallocate()](function.imagecolorallocate). The default foreground color is black. ### Return Values Returns **`true`** on success or **`false`** on failure. **Caution**However, if libgd fails to output the image, this function returns **`true`**. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | | 8.0.0 | `foreground_color` is nullable now. | ### Examples **Example #1 Outputting a WBMP image** ``` <?php // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color); // Set the content type header - in this case image/vnd.wap.wbmp // Hint: see image_type_to_mime_type() for content-types header('Content-Type: image/vnd.wap.wbmp'); // Output the image imagewbmp($im); // Free up memory imagedestroy($im); ?> ``` **Example #2 Saving the WBMP image** ``` <?php // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color); // Save the image imagewbmp($im, 'simpletext.wbmp'); // Free up memory imagedestroy($im); ?> ``` **Example #3 Outputting the image with a different foreground** ``` <?php // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color); // Set the content type header - in this case image/vnd.wap.wbmp // Hint: see image_type_to_mime_type() for content-types header('Content-Type: image/vnd.wap.wbmp'); // Set a replacement foreground color $foreground_color = imagecolorallocate($im, 255, 0, 0); imagewbmp($im, NULL, $foreground_color); // Free up memory imagedestroy($im); ?> ``` ### See Also * [image2wbmp()](function.image2wbmp) - Output image to browser or file * [imagepng()](function.imagepng) - Output a PNG image to either the browser or a file * [imagegif()](function.imagegif) - Output image to browser or file * [imagejpeg()](function.imagejpeg) - Output image to browser or file * [imagetypes()](function.imagetypes) - Return the image types supported by this PHP build php StompFrame::__construct StompFrame::\_\_construct ========================= (PECL stomp >= 0.1.0) StompFrame::\_\_construct — Constructor ### Description **StompFrame::\_\_construct**(string `$command` = ?, array `$headers` = ?, string `$body` = ?) Constructor. ### Parameters `command` Frame command `headers` Frame headers (array). `body` Frame body. php The PSpell\Dictionary class The PSpell\Dictionary class =========================== Introduction ------------ (PHP 8 >= 8.1.0) A fully opaque class which replaces a `pspell` resource as of PHP 8.1.0. Class synopsis -------------- final class **PSpell\Dictionary** { } php SolrQuery::setFacetDateEnd SolrQuery::setFacetDateEnd ========================== (PECL solr >= 0.9.2) SolrQuery::setFacetDateEnd — Maps to facet.date.end ### Description ``` public SolrQuery::setFacetDateEnd(string $value, string $field_override = ?): SolrQuery ``` Maps to facet.date.end ### Parameters `value` See facet.date.end `field_override` Name of the field ### Return Values Returns the current SolrQuery object, if the return value is used. php EventUtil::sslRandPoll EventUtil::sslRandPoll ====================== (PECL event >= 1.2.6-beta) EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND\_poll() ### Description ``` public static EventUtil::sslRandPoll(): void ``` Generates entropy by means of OpenSSL's `RAND_poll()` (see the system manual). ### Parameters This function has no parameters. ### Return Values No value is returned. php The EventBuffer class The EventBuffer class ===================== Introduction ------------ (PECL event >= 1.5.0) **EventBuffer** represents Libevent's "evbuffer", an utility functionality for buffered I/O. Event buffers are meant to be generally useful for doing the "buffer" part of buffered network I/O. Class synopsis -------------- class **EventBuffer** { /\* Constants \*/ const int [EOL\_ANY](class.eventbuffer#eventbuffer.constants.eol-any) = 0; const int [EOL\_CRLF](class.eventbuffer#eventbuffer.constants.eol-crlf) = 1; const int [EOL\_CRLF\_STRICT](class.eventbuffer#eventbuffer.constants.eol-crlf-strict) = 2; const int [EOL\_LF](class.eventbuffer#eventbuffer.constants.eol-lf) = 3; const int [PTR\_SET](class.eventbuffer#eventbuffer.constants.ptr-set) = 0; const int [PTR\_ADD](class.eventbuffer#eventbuffer.constants.ptr-add) = 1; /\* Properties \*/ public readonly int [$length](class.eventbuffer#eventbuffer.props.length); public readonly int [$contiguous\_space](class.eventbuffer#eventbuffer.props.contiguous-space); /\* Methods \*/ ``` public add( string $data ): bool ``` ``` public addBuffer( EventBuffer $buf ): bool ``` ``` public appendFrom( EventBuffer $buf , int $len ): int ``` ``` public __construct() ``` ``` public copyout( string &$data , int $max_bytes ): int ``` ``` public drain( int $len ): bool ``` ``` public enableLocking(): void ``` ``` public expand( int $len ): bool ``` ``` public freeze( bool $at_front ): bool ``` ``` public lock(): void ``` ``` public prepend( string $data ): bool ``` ``` public prependBuffer( EventBuffer $buf ): bool ``` ``` public pullup( int $size ): string ``` ``` public read( int $max_bytes ): string ``` ``` public read( mixed $fd , int $howmuch ): int ``` ``` public readLine( int $eol_style ): string ``` ``` public search( string $what , int $start = -1 , int $end = -1 ): mixed ``` ``` public searchEol( int $start = -1 , int $eol_style = EventBuffer::EOL_ANY ): mixed ``` ``` public substr( int $start , int $length = ?): string ``` ``` public unfreeze( bool $at_front ): bool ``` ``` public unlock(): bool ``` ``` public write( mixed $fd , int $howmuch = ?): int ``` } Properties ---------- length The number of bytes stored in an event buffer. contiguous\_space The number of bytes stored contiguously at the front of the buffer. The bytes in a buffer may be stored in multiple separate chunks of memory; the property returns the number of bytes currently stored in the first chunk. Predefined Constants -------------------- **`EventBuffer::EOL_ANY`** The end of line is any sequence of any number of carriage return and linefeed characters. This format is not very useful; it exists mainly for backward compatibility. **`EventBuffer::EOL_CRLF`** The end of the line is an optional carriage return, followed by a linefeed. (In other words, it is either a `"\r\n"` or a `"\n"` .) This format is useful in parsing text-based Internet protocols, since the standards generally prescribe a `"\r\n"` line-terminator, but nonconformant clients sometimes say just `"\n"` . **`EventBuffer::EOL_CRLF_STRICT`** The end of a line is a single carriage return, followed by a single linefeed. (This is also known as `"\r\n"` . The ASCII values are **`0x0D`** **`0x0A`** ). **`EventBuffer::EOL_LF`** The end of a line is a single linefeed character. (This is also known as `"\n"` . It is ASCII value is **`0x0A`** .) **`EventBuffer::PTR_SET`** Flag used as argument of **EventBuffer::setPosition()** method. If this flag specified, the position pointer is moved to an absolute position within the buffer. **`EventBuffer::PTR_ADD`** The same as **`EventBuffer::PTR_SET`** , except this flag causes **EventBuffer::setPosition()** method to move position forward up to the specified number of bytes(instead of setting absolute position). Table of Contents ----------------- * [EventBuffer::add](eventbuffer.add) — Append data to the end of an event buffer * [EventBuffer::addBuffer](eventbuffer.addbuffer) — Move all data from a buffer provided to the current instance of EventBuffer * [EventBuffer::appendFrom](eventbuffer.appendfrom) — Moves the specified number of bytes from a source buffer to the end of the current buffer * [EventBuffer::\_\_construct](eventbuffer.construct) — Constructs EventBuffer object * [EventBuffer::copyout](eventbuffer.copyout) — Copies out specified number of bytes from the front of the buffer * [EventBuffer::drain](eventbuffer.drain) — Removes specified number of bytes from the front of the buffer without copying it anywhere * [EventBuffer::enableLocking](eventbuffer.enablelocking) — Description * [EventBuffer::expand](eventbuffer.expand) — Reserves space in buffer * [EventBuffer::freeze](eventbuffer.freeze) — Prevent calls that modify an event buffer from succeeding * [EventBuffer::lock](eventbuffer.lock) — Acquires a lock on buffer * [EventBuffer::prepend](eventbuffer.prepend) — Prepend data to the front of the buffer * [EventBuffer::prependBuffer](eventbuffer.prependbuffer) — Moves all data from source buffer to the front of current buffer * [EventBuffer::pullup](eventbuffer.pullup) — Linearizes data within buffer and returns it's contents as a string * [EventBuffer::read](eventbuffer.read) — Read data from an evbuffer and drain the bytes read * [EventBuffer::readFrom](eventbuffer.readfrom) — Read data from a file onto the end of the buffer * [EventBuffer::readLine](eventbuffer.readline) — Extracts a line from the front of the buffer * [EventBuffer::search](eventbuffer.search) — Scans the buffer for an occurrence of a string * [EventBuffer::searchEol](eventbuffer.searcheol) — Scans the buffer for an occurrence of an end of line * [EventBuffer::substr](eventbuffer.substr) — Substracts a portion of the buffer data * [EventBuffer::unfreeze](eventbuffer.unfreeze) — Re-enable calls that modify an event buffer * [EventBuffer::unlock](eventbuffer.unlock) — Releases lock acquired by EventBuffer::lock * [EventBuffer::write](eventbuffer.write) — Write contents of the buffer to a file or socket php The DOMDocument class The DOMDocument class ===================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Represents an entire HTML or XML document; serves as the root of the document tree. Class synopsis -------------- class **DOMDocument** extends [DOMNode](class.domnode) implements [DOMParentNode](class.domparentnode) { /\* Properties \*/ public readonly ?[DOMDocumentType](class.domdocumenttype) [$doctype](class.domdocument#domdocument.props.doctype); public readonly [DOMImplementation](class.domimplementation) [$implementation](class.domdocument#domdocument.props.implementation); public readonly ?[DOMElement](class.domelement) [$documentElement](class.domdocument#domdocument.props.documentelement); public readonly ?string [$actualEncoding](class.domdocument#domdocument.props.actualencoding); public ?string [$encoding](class.domdocument#domdocument.props.encoding); public readonly ?string [$xmlEncoding](class.domdocument#domdocument.props.xmlencoding); public bool [$standalone](class.domdocument#domdocument.props.standalone); public bool [$xmlStandalone](class.domdocument#domdocument.props.xmlstandalone); public ?string [$version](class.domdocument#domdocument.props.version); public ?string [$xmlVersion](class.domdocument#domdocument.props.xmlversion); public bool [$strictErrorChecking](class.domdocument#domdocument.props.stricterrorchecking); public ?string [$documentURI](class.domdocument#domdocument.props.documenturi); public readonly [mixed](language.types.declarations#language.types.declarations.mixed) [$config](class.domdocument#domdocument.props.config) = null; public bool [$formatOutput](class.domdocument#domdocument.props.formatoutput); public bool [$validateOnParse](class.domdocument#domdocument.props.validateonparse); public bool [$resolveExternals](class.domdocument#domdocument.props.resolveexternals); public bool [$preserveWhiteSpace](class.domdocument#domdocument.props.preservewhitespace); public bool [$recover](class.domdocument#domdocument.props.recover); public bool [$substituteEntities](class.domdocument#domdocument.props.substituteentities); public readonly ?[DOMElement](class.domelement) [$firstElementChild](class.domdocument#domdocument.props.firstelementchild); public readonly ?[DOMElement](class.domelement) [$lastElementChild](class.domdocument#domdocument.props.lastelementchild); public readonly int [$childElementCount](class.domdocument#domdocument.props.childelementcount); /\* Inherited properties \*/ public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domdocument.construct)(string `$version` = "1.0", string `$encoding` = "") ``` public createAttribute(string $localName): DOMAttr|false ``` ``` public createAttributeNS(?string $namespace, string $qualifiedName): DOMAttr|false ``` ``` public createCDATASection(string $data): DOMCdataSection|false ``` ``` public createComment(string $data): DOMComment ``` ``` public createDocumentFragment(): DOMDocumentFragment ``` ``` public createElement(string $localName, string $value = ""): DOMElement|false ``` ``` public createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false ``` ``` public createEntityReference(string $name): DOMEntityReference|false ``` ``` public createProcessingInstruction(string $target, string $data = ""): DOMProcessingInstruction|false ``` ``` public createTextNode(string $data): DOMText ``` ``` public getElementById(string $elementId): ?DOMElement ``` ``` public getElementsByTagName(string $qualifiedName): DOMNodeList ``` ``` public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList ``` ``` public importNode(DOMNode $node, bool $deep = false): DOMNode|false ``` ``` public load(string $filename, int $options = 0): DOMDocument|bool ``` ``` public loadHTML(string $source, int $options = 0): DOMDocument|bool ``` ``` public loadHTMLFile(string $filename, int $options = 0): DOMDocument|bool ``` ``` public loadXML(string $source, int $options = 0): DOMDocument|bool ``` ``` public normalizeDocument(): void ``` ``` public registerNodeClass(string $baseClass, ?string $extendedClass): bool ``` ``` public relaxNGValidate(string $filename): bool ``` ``` public relaxNGValidateSource(string $source): bool ``` ``` public save(string $filename, int $options = 0): int|false ``` ``` public saveHTML(?DOMNode $node = null): string|false ``` ``` public saveHTMLFile(string $filename): int|false ``` ``` public saveXML(?DOMNode $node = null, int $options = 0): string|false ``` ``` public schemaValidate(string $filename, int $flags = 0): bool ``` ``` public schemaValidateSource(string $source, int $flags = 0): bool ``` ``` public validate(): bool ``` ``` public xinclude(int $options = 0): int|false ``` /\* Inherited methods \*/ ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Properties ---------- actualEncoding *Deprecated*. Actual encoding of the document, is a readonly equivalent to encoding. childElementCount The number of child elements. config *Deprecated*. Configuration used when [DOMDocument::normalizeDocument()](domdocument.normalizedocument) is invoked. doctype The Document Type Declaration associated with this document. documentElement The [DOMElement](class.domelement) object that is the first document element. If not found, this evaluates to **`null`**. documentURI The location of the document or **`null`** if undefined. encoding Encoding of the document, as specified by the XML declaration. This attribute is not present in the final DOM Level 3 specification, but is the only way of manipulating XML document encoding in this implementation. firstElementChild First child element or **`null`**. formatOutput Nicely formats output with indentation and extra space. This has no effect if the document was loaded with preserveWhitespace enabled. implementation The [DOMImplementation](class.domimplementation) object that handles this document. lastElementChild Last child element or **`null`**. preserveWhiteSpace Do not remove redundant white space. Default to **`true`**. Setting this to **`false`** has the same effect as passing **`LIBXML_NOBLANKS`** as `option` to [DOMDocument::load()](domdocument.load) etc. recover *Proprietary*. Enables recovery mode, i.e. trying to parse non-well formed documents. This attribute is not part of the DOM specification and is specific to libxml. resolveExternals Set it to **`true`** to load external entities from a doctype declaration. This is useful for including character entities in your XML document. standalone *Deprecated*. Whether or not the document is standalone, as specified by the XML declaration, corresponds to xmlStandalone. strictErrorChecking Throws [DOMException](class.domexception) on errors. Default to **`true`**. substituteEntities *Proprietary*. Whether or not to substitute entities. This attribute is not part of the DOM specification and is specific to libxml. **Caution** Enabling entity substitution may facilitate XML External Entity (XXE) attacks. validateOnParse Loads and validates against the DTD. Default to **`false`**. version *Deprecated*. Version of XML, corresponds to xmlVersion. xmlEncoding An attribute specifying, as part of the XML declaration, the encoding of this document. This is **`null`** when unspecified or when it is not known, such as when the Document was created in memory. xmlStandalone An attribute specifying, as part of the XML declaration, whether this document is standalone. This is **`false`** when unspecified. xmlVersion An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0". Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | **DOMDocument** implements [DOMParentNode](class.domparentnode) now. | | 8.0.0 | The unimplemented method **DOMDocument::renameNode()** has been removed. | Notes ----- > > **Note**: > > > The DOM extension uses UTF-8 encoding. Use [mb\_convert\_encoding()](function.mb-convert-encoding), [UConverter::transcode()](uconverter.transcode), or [iconv()](function.iconv) to handle other encodings. > > > > > **Note**: > > > When using [json\_encode()](function.json-encode) on a **DOMDocument** object the result will be that of encoding an empty object. > > > See Also -------- * [» W3C specification for Document](http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-i-Document) Table of Contents ----------------- * [DOMDocument::\_\_construct](domdocument.construct) — Creates a new DOMDocument object * [DOMDocument::createAttribute](domdocument.createattribute) — Create new attribute * [DOMDocument::createAttributeNS](domdocument.createattributens) — Create new attribute node with an associated namespace * [DOMDocument::createCDATASection](domdocument.createcdatasection) — Create new cdata node * [DOMDocument::createComment](domdocument.createcomment) — Create new comment node * [DOMDocument::createDocumentFragment](domdocument.createdocumentfragment) — Create new document fragment * [DOMDocument::createElement](domdocument.createelement) — Create new element node * [DOMDocument::createElementNS](domdocument.createelementns) — Create new element node with an associated namespace * [DOMDocument::createEntityReference](domdocument.createentityreference) — Create new entity reference node * [DOMDocument::createProcessingInstruction](domdocument.createprocessinginstruction) — Creates new PI node * [DOMDocument::createTextNode](domdocument.createtextnode) — Create new text node * [DOMDocument::getElementById](domdocument.getelementbyid) — Searches for an element with a certain id * [DOMDocument::getElementsByTagName](domdocument.getelementsbytagname) — Searches for all elements with given local tag name * [DOMDocument::getElementsByTagNameNS](domdocument.getelementsbytagnamens) — Searches for all elements with given tag name in specified namespace * [DOMDocument::importNode](domdocument.importnode) — Import node into current document * [DOMDocument::load](domdocument.load) — Load XML from a file * [DOMDocument::loadHTML](domdocument.loadhtml) — Load HTML from a string * [DOMDocument::loadHTMLFile](domdocument.loadhtmlfile) — Load HTML from a file * [DOMDocument::loadXML](domdocument.loadxml) — Load XML from a string * [DOMDocument::normalizeDocument](domdocument.normalizedocument) — Normalizes the document * [DOMDocument::registerNodeClass](domdocument.registernodeclass) — Register extended class used to create base node type * [DOMDocument::relaxNGValidate](domdocument.relaxngvalidate) — Performs relaxNG validation on the document * [DOMDocument::relaxNGValidateSource](domdocument.relaxngvalidatesource) — Performs relaxNG validation on the document * [DOMDocument::save](domdocument.save) — Dumps the internal XML tree back into a file * [DOMDocument::saveHTML](domdocument.savehtml) — Dumps the internal document into a string using HTML formatting * [DOMDocument::saveHTMLFile](domdocument.savehtmlfile) — Dumps the internal document into a file using HTML formatting * [DOMDocument::saveXML](domdocument.savexml) — Dumps the internal XML tree back into a string * [DOMDocument::schemaValidate](domdocument.schemavalidate) — Validates a document based on a schema. Only XML Schema 1.0 is supported. * [DOMDocument::schemaValidateSource](domdocument.schemavalidatesource) — Validates a document based on a schema * [DOMDocument::validate](domdocument.validate) — Validates the document based on its DTD * [DOMDocument::xinclude](domdocument.xinclude) — Substitutes XIncludes in a DOMDocument Object
programming_docs
php SolrDisMaxQuery::setTrigramPhraseSlop SolrDisMaxQuery::setTrigramPhraseSlop ===================================== (No version information available, might only be in Git) SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter) ### Description ``` public SolrDisMaxQuery::setTrigramPhraseSlop(string $slop): SolrDisMaxQuery ``` Sets Trigram Phrase Slop (ps3 parameter) ### Parameters `slop` Phrase slop ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::setTrigramPhraseSlop()** example** ``` <?php $dismaxQuery = new SolrDisMaxQuery('lucene'); $dismaxQuery->setTrigramPhraseSlop(2); echo $dismaxQuery.PHP_EOL; ?> ``` The above example will output something similar to: ``` q=lucene&defType=edismax&ps3=2 ``` ### See Also * [SolrDisMaxQuery::addTrigramPhraseField()](solrdismaxquery.addtrigramphrasefield) - Adds a Trigram Phrase Field (pf3 parameter) * [SolrDisMaxQuery::removeTrigramPhraseField()](solrdismaxquery.removetrigramphrasefield) - Removes a Trigram Phrase Field (pf3 parameter) * [SolrDisMaxQuery::setTrigramPhraseFields()](solrdismaxquery.settrigramphrasefields) - Directly Sets Trigram Phrase Fields (pf3 parameter) php readgzfile readgzfile ========== (PHP 4, PHP 5, PHP 7, PHP 8) readgzfile — Output a gz-file ### Description ``` readgzfile(string $filename, int $use_include_path = 0): int|false ``` Reads a file, decompresses it and writes it to standard output. **readgzfile()** can be used to read a file which is not in gzip format; in this case **readgzfile()** will directly read from the file without decompression. ### Parameters `filename` The file name. This file will be opened from the filesystem and its contents written to standard output. `use_include_path` You can set this optional parameter to `1`, if you want to search for the file in the [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path) too. ### Return Values Returns the number of (uncompressed) bytes read from the file on success, or **`false`** on failure ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### See Also * [gzpassthru()](function.gzpassthru) - Output all remaining data on a gz-file pointer * [gzfile()](function.gzfile) - Read entire gz-file into an array * [gzopen()](function.gzopen) - Open gz-file php htmlentities htmlentities ============ (PHP 4, PHP 5, PHP 7, PHP 8) htmlentities — Convert all applicable characters to HTML entities ### Description ``` htmlentities( string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true ): string ``` This function is identical to [htmlspecialchars()](function.htmlspecialchars) in all ways, except with **htmlentities()**, all characters which have HTML character entity equivalents are translated into these entities. The [get\_html\_translation\_table()](function.get-html-translation-table) function can be used to return the translation table used dependent upon the provided `flags` constants. If you want to decode instead (the reverse) you can use [html\_entity\_decode()](function.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_QUOTES | ENT_SUBSTITUTE | 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](http://unicode.org/reports/tr36/#Deletion_of_Noncharacters). | | **`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, `encoding` defaults to the value of the [default\_charset](https://www.php.net/manual/en/ini.core.php#ini.default-charset) configuration option. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the [default\_charset](https://www.php.net/manual/en/ini.core.php#ini.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](https://www.php.net/manual/en/ini.core.php#ini.default-charset) and current locale (see [nl\_langinfo()](function.nl-langinfo) and [setlocale()](function.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 | | --- | --- | | 8.1.0 | `flags` changed from **`ENT_COMPAT`** to **`ENT_QUOTES`** | **`ENT_SUBSTITUTE`** | **`ENT_HTML401`**. | | 8.0.0 | `encoding` is nullable now. | ### Examples **Example #1 A **htmlentities()** example** ``` <?php $str = "A 'quote' is <b>bold</b>"; // Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt; echo htmlentities($str); // Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt; echo htmlentities($str, ENT_QUOTES); ?> ``` **Example #2 Usage of **`ENT_IGNORE`**** ``` <?php $str = "\x8F!!!"; // Outputs an empty string echo htmlentities($str, ENT_QUOTES, "UTF-8"); // Outputs "!!!" echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8"); ?> ``` ### See Also * [html\_entity\_decode()](function.html-entity-decode) - Convert HTML entities to their corresponding characters * [get\_html\_translation\_table()](function.get-html-translation-table) - Returns the translation table used by htmlspecialchars and htmlentities * [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities * [nl2br()](function.nl2br) - Inserts HTML line breaks before all newlines in a string * [urlencode()](function.urlencode) - URL-encodes string php DOMDocument::createComment DOMDocument::createComment ========================== (PHP 5, PHP 7, PHP 8) DOMDocument::createComment — Create new comment node ### Description ``` public DOMDocument::createComment(string $data): DOMComment ``` This function creates a new instance of class [DOMComment](class.domcomment). This node will not show up in the document unless it is inserted with (e.g.) [DOMNode::appendChild()](domnode.appendchild). ### Parameters `data` The content of the comment. ### Return Values The new [DOMComment](class.domcomment). ### Changelog | Version | Description | | --- | --- | | 8.1.0 | In case of an error, a [DomException](class.domexception) is thrown now. Previously, **`false`** was returned. | ### See Also * [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children * [DOMDocument::createAttribute()](domdocument.createattribute) - Create new attribute * [DOMDocument::createAttributeNS()](domdocument.createattributens) - Create new attribute node with an associated namespace * [DOMDocument::createCDATASection()](domdocument.createcdatasection) - Create new cdata node * [DOMDocument::createDocumentFragment()](domdocument.createdocumentfragment) - Create new document fragment * [DOMDocument::createElement()](domdocument.createelement) - Create new element node * [DOMDocument::createElementNS()](domdocument.createelementns) - Create new element node with an associated namespace * [DOMDocument::createEntityReference()](domdocument.createentityreference) - Create new entity reference node * [DOMDocument::createProcessingInstruction()](domdocument.createprocessinginstruction) - Creates new PI node * [DOMDocument::createTextNode()](domdocument.createtextnode) - Create new text node php The QuickHashStringIntHash class The QuickHashStringIntHash class ================================ Introduction ------------ (No version information available, might only be in Git) This class wraps around a hash containing strings, where the values are integer numbers. Hashes are also available as implementation of the [ArrayAccess](class.arrayaccess) interface. Hashes can also be iterated over with [`foreach`](control-structures.foreach) as the [Iterator](class.iterator) interface is implemented as well. The order of which elements are returned in is not guaranteed. Class synopsis -------------- class **QuickHashStringIntHash** { /\* Constants \*/ const int [CHECK\_FOR\_DUPES](class.quickhashstringinthash#quickhashstringinthash.constants.check-for-dupes) = 1; const int [DO\_NOT\_USE\_ZEND\_ALLOC](class.quickhashstringinthash#quickhashstringinthash.constants.do-not-use-zend-alloc) = 2; /\* Methods \*/ ``` public add(string $key, int $value): bool ``` ``` public __construct(int $size, int $options = 0) ``` ``` public delete(string $key): bool ``` ``` public exists(string $key): bool ``` ``` public get(string $key): mixed ``` ``` public getSize(): int ``` ``` public static loadFromFile(string $filename, int $size = 0, int $options = 0): QuickHashStringIntHash ``` ``` public static loadFromString(string $contents, int $size = 0, int $options = 0): QuickHashStringIntHash ``` ``` public saveToFile(string $filename): void ``` ``` public saveToString(): string ``` ``` public set(string $key, int $value): int ``` ``` public update(string $key, int $value): bool ``` } Predefined Constants -------------------- **`QuickHashStringIntHash::CHECK_FOR_DUPES`** If enabled, adding duplicate elements to a set (through either [QuickHashStringIntHash::add()](quickhashstringinthash.add) or [QuickHashStringIntHash::loadFromFile()](quickhashstringinthash.loadfromfile)) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required. **`QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC`** Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the [memory\_limit](https://www.php.net/manual/en/ini.core.php#ini.memory-limit) settings. Table of Contents ----------------- * [QuickHashStringIntHash::add](quickhashstringinthash.add) — This method adds a new entry to the hash * [QuickHashStringIntHash::\_\_construct](quickhashstringinthash.construct) — Creates a new QuickHashStringIntHash object * [QuickHashStringIntHash::delete](quickhashstringinthash.delete) — This method deletes an entry from the hash * [QuickHashStringIntHash::exists](quickhashstringinthash.exists) — This method checks whether a key is part of the hash * [QuickHashStringIntHash::get](quickhashstringinthash.get) — This method retrieves a value from the hash by its key * [QuickHashStringIntHash::getSize](quickhashstringinthash.getsize) — Returns the number of elements in the hash * [QuickHashStringIntHash::loadFromFile](quickhashstringinthash.loadfromfile) — This factory method creates a hash from a file * [QuickHashStringIntHash::loadFromString](quickhashstringinthash.loadfromstring) — This factory method creates a hash from a string * [QuickHashStringIntHash::saveToFile](quickhashstringinthash.savetofile) — This method stores an in-memory hash to disk * [QuickHashStringIntHash::saveToString](quickhashstringinthash.savetostring) — This method returns a serialized version of the hash * [QuickHashStringIntHash::set](quickhashstringinthash.set) — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist * [QuickHashStringIntHash::update](quickhashstringinthash.update) — This method updates an entry in the hash with a new value php SessionUpdateTimestampHandlerInterface::validateId SessionUpdateTimestampHandlerInterface::validateId ================================================== (PHP 7, PHP 8) SessionUpdateTimestampHandlerInterface::validateId — Validate ID ### Description ``` public SessionUpdateTimestampHandlerInterface::validateId(string $id): bool ``` Validates a given session ID. A session ID is valid, if a session with that ID already exists. This function is automatically executed when a session is to be started, a session ID is supplied and [session.use\_strict\_mode](https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode) is enabled. ### Parameters `id` The session ID. ### Return Values Returns **`true`** for valid ID, **`false`** otherwise. Note that this value is returned internally to PHP for processing. php The EnchantBroker class The EnchantBroker class ======================= Introduction ------------ (PHP 8) A fully opaque class which replaces `enchant_broker` resources as of PHP 8.0.0. Class synopsis -------------- final class **EnchantBroker** { } php Imagick::liquidRescaleImage Imagick::liquidRescaleImage =========================== (PECL imagick 2 >= 2.2.0, PECL imagick 3) Imagick::liquidRescaleImage — Animates an image or images ### Description ``` public Imagick::liquidRescaleImage( int $width, int $height, float $delta_x, float $rigidity ): bool ``` This method scales the images using liquid rescaling method. This method is an implementation of a technique called seam carving. In order for this method to work as expected ImageMagick must be compiled with liblqr support. This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer. ### Parameters `width` The width of the target size `height` The height of the target size `delta_x` How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight. `rigidity` Introduces a bias for non-straight seams. This parameter is typically 0. ### Return Values Returns **`true`** on success. ### See Also * [Imagick::resizeImage()](imagick.resizeimage) - Scales an image php ZipArchive::setExternalAttributesIndex ZipArchive::setExternalAttributesIndex ====================================== (PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4) ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index ### Description ``` public ZipArchive::setExternalAttributesIndex( int $index, int $opsys, int $attr, int $flags = 0 ): bool ``` Set the external attributes of an entry defined by its index. ### Parameters `index` Index of the entry. `opsys` The operating system code defined by one of the ZipArchive::OPSYS\_ constants. `attr` The external attributes. Value depends on operating system. `flags` Optional flags. Currently unused. ### Return Values Returns **`true`** on success or **`false`** on failure. php Yaf_Config_Ini::offsetExists Yaf\_Config\_Ini::offsetExists ============================== (Yaf >=1.0.0) Yaf\_Config\_Ini::offsetExists — The offsetExists purpose ### Description ``` public Yaf_Config_Ini::offsetExists(string $name): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php QuickHashIntHash::getSize QuickHashIntHash::getSize ========================= (PECL quickhash >= Unknown) QuickHashIntHash::getSize — Returns the number of elements in the hash ### Description ``` public QuickHashIntHash::getSize(): int ``` Returns the number of elements in the hash. ### Parameters This function has no parameters. ### Return Values The number of elements in the hash. ### Examples **Example #1 **QuickHashIntHash::getSize()** example** ``` <?php $hash = new QuickHashIntHash( 8 ); var_dump( $hash->add( 2 ) ); var_dump( $hash->add( 3, 5 ) ); var_dump( $hash->getSize() ); ?> ``` The above example will output something similar to: ``` bool(true) bool(true) int(2) ``` php EvLoop::backend EvLoop::backend =============== (PECL ev >= 0.2.0) EvLoop::backend — Returns an integer describing the backend used by libev ### Description ``` public EvLoop::backend(): int ``` The same as [Ev::backend()](ev.backend) , but for the loop instance. ### Parameters This function has no parameters. ### Return Values Returns an integer describing the backend used by libev. See [Ev::backend()](ev.backend) . ### See Also * [Ev::backend()](ev.backend) - Returns an integer describing the backend used by libev php SolrQueryResponse::__destruct SolrQueryResponse::\_\_destruct =============================== (PECL solr >= 0.9.2) SolrQueryResponse::\_\_destruct — Destructor ### Description public **SolrQueryResponse::\_\_destruct**() Destructor. ### Parameters This function has no parameters. ### Return Values None php array_intersect array\_intersect ================ (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) array\_intersect — Computes the intersection of arrays ### Description ``` array_intersect(array $array, array ...$arrays): array ``` **array\_intersect()** returns an array containing all the values of `array` that are present in all the arguments. Note that keys are preserved. ### Parameters `array` The array with master values to check. `arrays` Arrays to compare values against. ### Return Values Returns an array containing all of the values in `array` whose values exist in all of the parameters. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function can now be called with only one parameter. Formerly, at least two parameters have been required. | ### Examples **Example #1 **array\_intersect()** example** ``` <?php $array1 = array("a" => "green", "red", "blue"); $array2 = array("b" => "green", "yellow", "red"); $result = array_intersect($array1, $array2); print_r($result); ?> ``` The above example will output: ``` Array ( [a] => green [0] => red ) ``` ### Notes > **Note**: Two elements are considered equal if and only if `(string) $elem1 === (string) $elem2`. In words: when the string representation is the same. > > ### See Also * [array\_intersect\_assoc()](function.array-intersect-assoc) - Computes the intersection of arrays with additional index check * [array\_diff()](function.array-diff) - Computes the difference of arrays * [array\_diff\_assoc()](function.array-diff-assoc) - Computes the difference of arrays with additional index check
programming_docs
php Gmagick::getimagewidth Gmagick::getimagewidth ====================== (PECL gmagick >= Unknown) Gmagick::getimagewidth — Returns the width of the image ### Description ``` public Gmagick::getimagewidth(): int ``` Returns the width of the image. ### Parameters This function has no parameters. ### Return Values Returns the image width. ### Errors/Exceptions Throws an **GmagickException** on error. php pg_field_is_null pg\_field\_is\_null =================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_field\_is\_null — Test if a field is SQL `NULL` ### Description ``` pg_field_is_null(PgSql\Result $result, int $row, mixed $field): int ``` ``` pg_field_is_null(PgSql\Result $result, mixed $field): int ``` **pg\_field\_is\_null()** tests if a field in an [PgSql\Result](class.pgsql-result) instance is SQL `NULL` or not. > > **Note**: > > > This function used to be called **pg\_fieldisnull()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `row` Row number in result to fetch. Rows are numbered from 0 upwards. If omitted, current row is fetched. `field` Field number (starting from 0) as an int or the field name as a string. ### Return Values Returns `1` if the field in the given row is SQL `NULL`, `0` if not. **`false`** is returned if the row is out of range, or upon any other error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_field\_is\_null()** example** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die ("Could not connect");   $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");   if ($res) {       if (pg_field_is_null($res, 0, "year") == 1) {           echo "The value of the field year is null.\n";       }       if (pg_field_is_null($res, 0, "year") == 0) {           echo "The value of the field year is not null.\n";     }  } ?> ``` php Fiber::start Fiber::start ============ (PHP 8 >= 8.1.0) Fiber::start — Start execution of the fiber ### Description ``` public Fiber::start(mixed ...$args): mixed ``` A variadic list of arguments to provide to the callable used when constructing the fiber. If the fiber has already been started when this method is called, a [FiberError](class.fibererror) will be thrown. ### Parameters `args` The arguments to use when invoking the callable given to the fiber constructor. ### Return Values The value provided to the first call to [Fiber::suspend()](fiber.suspend) or **`null`** if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method. php IntlCalendar::getActualMinimum IntlCalendar::getActualMinimum ============================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getActualMinimum — The minimum value for a field, considering the objectʼs current time ### Description Object-oriented style ``` public IntlCalendar::getActualMinimum(int $field): int|false ``` Procedural style ``` intlcal_get_actual_minimum(IntlCalendar $calendar, int $field): int|false ``` Returns a fieldʼs relative minimum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the [greatest relative minimum](intlcalendar.getgreatestminimum) for the field and would decrement it until reaching the [global minimum](intlcalendar.getminimum) or the field value wraps around, in which the value returned would be the global minimum or the value before the wrapping, respectively. For the Gregorian calendar, this is always the same as [IntlCalendar::getMinimum()](intlcalendar.getminimum). ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `field` One of the [IntlCalendar](class.intlcalendar) date/time [field constants](class.intlcalendar#intlcalendar.constants). These are integer values between `0` and **`IntlCalendar::FIELD_COUNT`**. ### Return Values An int representing the minimum value in the fieldʼs unit or **`false`** on failure. ### See Also * [IntlCalendar::getMinimum()](intlcalendar.getminimum) - Get the global minimum value for a field * [IntlCalendar::getGreatestMinimum()](intlcalendar.getgreatestminimum) - Get the largest local minimum value for a field * [IntlCalendar::getActualMaximum()](intlcalendar.getactualmaximum) - The maximum value for a field, considering the objectʼs current time php OAuth::setToken OAuth::setToken =============== (PECL OAuth >= 0.99.1) OAuth::setToken — Sets the token and secret ### Description ``` public OAuth::setToken(string $token, string $token_secret): bool ``` Set the token and secret for subsequent requests. ### Parameters `token` The OAuth token. `token_secret` The OAuth token secret. ### Return Values **`true`** ### Examples **Example #1 **OAuth::setToken()** example** ``` <?php $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET); $oauth->setToken("token","token-secret"); ?> ``` php Imagick::levelImage Imagick::levelImage =================== (PECL imagick 2, PECL imagick 3) Imagick::levelImage — Adjusts the levels of an image ### Description ``` public Imagick::levelImage( float $blackPoint, float $gamma, float $whitePoint, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value. ### Parameters `blackPoint` The image black point `gamma` The gamma value `whitePoint` The image white point `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel). ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::levelImage()**** ``` <?php function levelImage($blackPoint, $gamma, $whitePoint) {     $imagick = new \Imagick();     $imagick->newPseudoimage(500, 500, 'gradient:black-white');     $imagick->setFormat('png');     $quantum = $imagick->getQuantum();     $imagick->levelImage($blackPoint / 100 , $gamma, $quantum * $whitePoint / 100);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php XMLReader::moveToAttributeNs XMLReader::moveToAttributeNs ============================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::moveToAttributeNs — Move cursor to a named attribute ### Description ``` public XMLReader::moveToAttributeNs(string $name, string $namespace): bool ``` Positions cursor on the named attribute in specified namespace. ### Parameters `name` The local name. `namespace` The namespace URI. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [XMLReader::moveToElement()](xmlreader.movetoelement) - Position cursor on the parent Element of current Attribute * [XMLReader::moveToAttribute()](xmlreader.movetoattribute) - Move cursor to a named attribute * [XMLReader::moveToAttributeNo()](xmlreader.movetoattributeno) - Move cursor to an attribute by index * [XMLReader::moveToFirstAttribute()](xmlreader.movetofirstattribute) - Position cursor on the first Attribute php ErrorException::getSeverity ErrorException::getSeverity =========================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) ErrorException::getSeverity — Gets the exception severity ### Description ``` final public ErrorException::getSeverity(): int ``` Returns the severity of the exception. ### Parameters This function has no parameters. ### Return Values Returns the severity level of the exception. ### Examples **Example #1 **ErrorException::getSeverity()** example** ``` <?php try {     throw new ErrorException("Exception message", 0, E_USER_ERROR); } catch(ErrorException $e) {     echo "This exception severity is: " . $e->getSeverity();     var_dump($e->getSeverity() === E_USER_ERROR); } ?> ``` The above example will output something similar to: ``` This exception severity is: 256 bool(true) ``` php strtotime strtotime ========= (PHP 4, PHP 5, PHP 7, PHP 8) strtotime — Parse about any English textual datetime description into a Unix timestamp ### Description ``` strtotime(string $datetime, ?int $baseTimestamp = null): int|false ``` The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in `baseTimestamp`, or the current time if `baseTimestamp` is not supplied. The date string parsing is defined in [Date and Time Formats](https://www.php.net/manual/en/datetime.formats.php), and has several subtle considerations. Reviewing the full details there is strongly recommended. **Warning** The Unix timestamp that this function returns does not contain information about time zones. In order to do calculations with date/time information, you should use the more capable [DateTimeImmutable](class.datetimeimmutable). Each parameter of this function uses the default time zone unless a time zone is specified in that parameter. Be careful not to use different time zones in each parameter unless that is intended. See [date\_default\_timezone\_get()](function.date-default-timezone-get) on the various ways to define the default time zone. ### Parameters `datetime` A date/time string. Valid formats are explained in [Date and Time Formats](https://www.php.net/manual/en/datetime.formats.php). `baseTimestamp` The timestamp which is used as a base for the calculation of relative dates. ### Return Values Returns a timestamp on success, **`false`** otherwise. ### Errors/Exceptions Every call to a date/time function will generate a **`E_WARNING`** if the time zone is not valid. See also [date\_default\_timezone\_set()](function.date-default-timezone-set) ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `baseTimestamp` is nullable now. | ### Examples **Example #1 A **strtotime()** example** ``` <?php echo strtotime("now"), "\n"; echo strtotime("10 September 2000"), "\n"; echo strtotime("+1 day"), "\n"; echo strtotime("+1 week"), "\n"; echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n"; echo strtotime("next Thursday"), "\n"; echo strtotime("last Monday"), "\n"; ?> ``` **Example #2 Checking for failure** ``` <?php $str = 'Not Good'; if (($timestamp = strtotime($str)) === false) {     echo "The string ($str) is bogus"; } else {     echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp); } ?> ``` ### Notes > > **Note**: > > > "Relative" date in this case also means that if a particular component of the date/time stamp is not provided, it will be taken verbatim from the `baseTimestamp`. That is, `strtotime('February')`, if run on the 31st of May 2022, will be interpreted as `31 February 2022`, which will overflow into a timestamp on `3 March`. (In a leap year, it would be `2 March`.) Using `strtotime('1 February')` or `strtotime('first day of February')` would avoid that problem. > > > > **Note**: > > > If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07). > > > > **Note**: > > > The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) > > For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction. > > > > **Note**: > > > Using this function for mathematical operations is not advisable. It is better to use [DateTime::add()](datetime.add) and [DateTime::sub()](datetime.sub). > > ### See Also * [DateTimeImmutable](class.datetimeimmutable) * [DateTimeImmutable::createFromFormat()](datetimeimmutable.createfromformat) - Parses a time string according to a specified format * [Date and Time Formats](https://www.php.net/manual/en/datetime.formats.php) * [checkdate()](function.checkdate) - Validate a Gregorian date * [strptime()](function.strptime) - Parse a time/date generated with strftime php IntlCalendar::isEquivalentTo IntlCalendar::isEquivalentTo ============================ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time ### Description Object-oriented style ``` public IntlCalendar::isEquivalentTo(IntlCalendar $other): bool ``` Procedural style ``` intlcal_is_equivalent_to(IntlCalendar $calendar, IntlCalendar $other): bool ``` Returns whether this and the given object are equivalent for all purposes except as to the time they have set. The locales do not have to match, as long as no change in behavior results from such mismatch. This includes the [timezone](intlcalendar.gettimezone), whether the [lenient mode](intlcalendar.islenient) is set, the [repeated](intlcalendar.getrepeatedwalltimeoption) and [skipped](intlcalendar.getskippedwalltimeoption) wall time settings, the [days of the week when the weekend starts and ceases](intlcalendar.getdayofweektype) and the [times where such transitions occur](intlcalendar.getweekendtransition). It may also include other calendar specific settings, such as the Gregorian/Julian transition instant. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `other` The other calendar against which the comparison is to be made. ### Return Values Assuming there are no argument errors, returns **`true`** if the calendars are equivalent except possibly for their set time. ### Examples **Example #1 **IntlCalendar::isEquivalentTo()**** ``` <?php $cal1 = IntlCalendar::createInstance('Europe/Lisbon', 'pt_PT'); $cal2 = IntlCalendar::createInstance('Europe/Lisbon', 'es_ES'); $cal2->clear(); var_dump($cal1->isEquivalentTo($cal2)); // true $cal3 = IntlCalendar::createInstance('Europe/Lisbon', 'en_US'); var_dump($cal1->isEquivalentTo($cal3)); // false var_dump($cal1->getFirstDayOfWeek(),    // 2 (Monday) $cal3->getFirstDayOfWeek());            // 1 (Sunday) ``` The above example will output: ``` bool(true) bool(false) int(2) int(1) ``` ### See Also * [IntlCalendar::equals()](intlcalendar.equals) - Compare time of two IntlCalendar objects for equality php is_object is\_object ========== (PHP 4, PHP 5, PHP 7, PHP 8) is\_object — Finds whether a variable is an object ### Description ``` is_object(mixed $value): bool ``` Finds whether the given variable is an object. ### Parameters `value` The variable being evaluated. ### Return Values Returns **`true`** if `value` is an object, **`false`** otherwise. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | **is\_object()** now returns **`true`** for unserialized objects without a class definition (class of **\_\_PHP\_Incomplete\_Class**). Previously **`false`** was returned. | ### Examples **Example #1 **is\_object()** example** ``` <?php // Declare a simple function to return an  // array from our object function get_students($obj) {     if (!is_object($obj)) {         return false;     }     return $obj->students; } // Declare a new class instance and fill up  // some values $obj = new stdClass(); $obj->students = array('Kalle', 'Ross', 'Felipe'); var_dump(get_students(null)); var_dump(get_students($obj)); ?> ``` ### See Also * [is\_bool()](function.is-bool) - Finds out whether a variable is a boolean * [is\_int()](function.is-int) - Find whether the type of a variable is integer * [is\_float()](function.is-float) - Finds whether the type of a variable is float * [is\_string()](function.is-string) - Find whether the type of a variable is string * [is\_array()](function.is-array) - Finds whether a variable is an array php NoRewindIterator::valid NoRewindIterator::valid ======================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) NoRewindIterator::valid — Validates the iterator ### Description ``` public NoRewindIterator::valid(): bool ``` Checks whether the iterator is valid. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [NoRewindIterator::getInnerIterator()](norewinditerator.getinneriterator) - Get the inner iterator php Ds\Vector::clear Ds\Vector::clear ================ (PECL ds >= 1.0.0) Ds\Vector::clear — Removes all values ### Description ``` public Ds\Vector::clear(): void ``` Removes all values from the vector. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Vector::clear()** example** ``` <?php $vector = new \Ds\Vector([1, 2, 3]); print_r($vector); $vector->clear(); print_r($vector); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 ) Ds\Vector Object ( ) ``` php APCUIterator::getTotalCount APCUIterator::getTotalCount =========================== (PECL apcu >= 5.0.0) APCUIterator::getTotalCount — Get total count ### Description ``` public APCUIterator::getTotalCount(): int ``` Get the total count. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The total count. ### See Also * [APCUIterator::getTotalHits()](apcuiterator.gettotalhits) - Get total cache hits * [APCUIterator::getTotalSize()](apcuiterator.gettotalsize) - Get total cache size * [apcu\_cache\_info()](function.apcu-cache-info) - Retrieves cached information from APCu's data store php uopz_extend uopz\_extend ============ (PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7 < 7.1.0) uopz\_extend — Extend a class at runtime ### Description ``` uopz_extend(string $class, string $parent): bool ``` Makes `class` extend `parent` ### Parameters `class` The name of the class to extend `parent` The name of the class to inherit ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions As of PHP 7.4.0, **uopz\_extends()** throws a [RuntimeException](class.runtimeexception), if [OPcache](https://www.php.net/manual/en/book.opcache.php) is enabled, and the class entry of either `class` or `parent` (if it is a trait) is immutable. ### Examples **Example #1 **uopz\_extend()** example** ``` <?php class A {} class B {} uopz_extend(A::class, B::class); var_dump(class_parents(A::class)); ?> ``` The above example will output: ``` array(1) { ["B"]=> string(1) "B" } ```
programming_docs
php ImagickDraw::popDefs ImagickDraw::popDefs ==================== (PECL imagick 2, PECL imagick 3) ImagickDraw::popDefs — Terminates a definition list ### Description ``` public ImagickDraw::popDefs(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Terminates a definition list. ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::popDefs()** example** ``` <?php function popDefs($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setstrokeOpacity(1);     $draw->setStrokeWidth(2);     $draw->setFontSize(72);     $draw->pushDefs();     $draw->setStrokeColor('white');     $draw->rectangle(50, 50, 200, 200);     $draw->popDefs();     $draw->rectangle(300, 50, 450, 200);     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php mysqli_execute mysqli\_execute =============== (PHP 5, PHP 7, PHP 8) mysqli\_execute — Alias of [mysqli\_stmt\_execute()](mysqli-stmt.execute) ### Description This function is an alias of: [mysqli\_stmt\_execute()](mysqli-stmt.execute). ### Notes > > **Note**: > > > **mysqli\_execute()** is deprecated and will be removed. > > ### See Also * [mysqli\_stmt\_execute()](mysqli-stmt.execute) - Executes a prepared statement php ReflectionEnumUnitCase::getValue ReflectionEnumUnitCase::getValue ================================ (PHP 8 >= 8.1.0) ReflectionEnumUnitCase::getValue — Gets the enum case object described by this reflection object ### Description ``` public ReflectionEnumUnitCase::getValue(): UnitEnum ``` Returns the enum case object described by this reflection object. ### Parameters This function has no parameters. ### Return Values The enum case object described by this reflection object. ### Examples **Example #1 **ReflectionEnum::getValue()** example** ``` <?php enum Suit {     case Hearts;     case Diamonds;     case Clubs;     case Spades; } $rEnum = new ReflectionEnum(Suit::class); $rCase = $rEnum->getCase('Diamonds'); var_dump($rCase->getValue()); ?> ``` The above example will output: ``` enum(Suit::Diamonds) ``` ### See Also * [Enumerations](https://www.php.net/manual/en/language.enumerations.php) php mysqli_stmt::store_result mysqli\_stmt::store\_result =========================== mysqli\_stmt\_store\_result =========================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::store\_result -- mysqli\_stmt\_store\_result — Stores a result set in an internal buffer ### Description Object-oriented style ``` public mysqli_stmt::store_result(): bool ``` Procedural style ``` mysqli_stmt_store_result(mysqli_stmt $statement): bool ``` This function should be called for queries that successfully produce a result set (e.g. `SELECT, SHOW, DESCRIBE, EXPLAIN`) only if the complete result set needs to be buffered in PHP. Each subsequent [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) call will return buffered data. > > **Note**: > > > It is unnecessary to call **mysqli\_stmt\_store\_result()** for other queries, but if you do, it will not harm or cause any notable performance loss in all cases. You can detect whether the query produced a result set by checking if [mysqli\_stmt\_result\_metadata()](mysqli-stmt.result-metadata) returns **`false`**. > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Object-oriented style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; $stmt = $mysqli->prepare($query); $stmt->execute(); /* store the result in an internal buffer */ $stmt->store_result(); printf("Number of rows: %d.\n", $stmt->num_rows); ``` **Example #2 Procedural style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); $query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; $stmt = mysqli_prepare($link, $query); mysqli_stmt_execute($stmt); /* store the result in an internal buffer */ mysqli_stmt_store_result($stmt); printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt)); ``` The above examples will output: ``` Number of rows: 20. ``` ### See Also * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_stmt\_result\_metadata()](mysqli-stmt.result-metadata) - Returns result set metadata from a prepared statement * [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) - Fetch results from a prepared statement into the bound variables php OuterIterator::getInnerIterator OuterIterator::getInnerIterator =============================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) OuterIterator::getInnerIterator — Returns the inner iterator for the current entry ### Description ``` public OuterIterator::getInnerIterator(): ?Iterator ``` Returns the inner iterator for the current iterator entry. ### Parameters This function has no parameters. ### Return Values Returns the inner iterator for the current entry if it exists, or **`null`** otherwise. php sodium_crypto_core_ristretto255_scalar_mul sodium\_crypto\_core\_ristretto255\_scalar\_mul =============================================== (PHP 8 >= 8.1.0) sodium\_crypto\_core\_ristretto255\_scalar\_mul — Multiplies a scalar value ### Description ``` sodium_crypto_core_ristretto255_scalar_mul(string $x, string $y): string ``` Multiplies a scalar value. Available as of libsodium 1.0.18. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `x` Scalar, representing the X coordinate. `y` Scalar, representing the Y coordinate. ### Return Values Returns a 32-byte random string. ### See Also * [sodium\_crypto\_core\_ristretto255\_scalar\_random()](function.sodium-crypto-core-ristretto255-scalar-random) - Generates a random key php None Back references --------------- Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (i.e. to its left) in the pattern, provided there have been that many previous capturing left parentheses. However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. A "forward back reference" can make sense when a repetition is involved and the subpattern to the right has participated in an earlier iteration. See the section [escape sequences](regexp.reference.escape) for further details of the handling of digits following a backslash. A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself. So the pattern `(sens|respons)e and \1ibility` matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If case-sensitive (caseful) matching is in force at the time of the back reference, then the case of letters is relevant. For example, `((?i)rah)\s+\1` matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched case-insensitively (caselessly). There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, then any back references to it always fail. For example, the pattern `(a|(bc))\2` always fails if it starts to match "a" rather than "bc". Because there may be up to 99 back references, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, then some delimiter must be used to terminate the back reference. If the [PCRE\_EXTENDED](reference.pcre.pattern.modifiers) option is set, this can be whitespace. Otherwise an empty comment can be used. A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern `(a|b\1)+` matches any number of "a"s and also "aba", "ababba" etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero. The `\g` escape sequence can be used for absolute and relative referencing of subpatterns. This escape sequence must be followed by an unsigned number or a negative number, optionally enclosed in braces. The sequences `\1`, `\g1` and `\g{1}` are synonymous with one another. The use of this pattern with an unsigned number can help remove the ambiguity inherent when using digits following a backslash. The sequence helps to distinguish back references from octal characters and also makes it easier to have a back reference followed by a literal number, e.g. `\g{2}1`. The use of the `\g` sequence with a negative number signifies a relative reference. For example, `(foo)(bar)\g{-1}` would match the sequence "foobarbar" and `(foo)(bar)\g{-2}` matches "foobarfoo". This can be useful in long patterns as an alternative to keeping track of the number of subpatterns in order to reference a specific previous subpattern. Back references to the named subpatterns can be achieved by `(?P=name)`, `\k<name>`, `\k'name'`, `\k{name}`, `\g{name}`, `\g<name>` or `\g'name'`. php The GmagickPixel class The GmagickPixel class ====================== Introduction ------------ (PECL gmagick >= Unknown) Class synopsis -------------- class **GmagickPixel** { /\* Methods \*/ public [\_\_construct](gmagickpixel.construct)(string `$color` = ?) ``` public getcolor(bool $as_array = false, bool $normalize_array = false): mixed ``` ``` public getcolorcount(): int ``` ``` public getcolorvalue(int $color): float ``` ``` public setcolor(string $color): GmagickPixel ``` ``` public setcolorvalue(int $color, float $value): GmagickPixel ``` } Table of Contents ----------------- * [GmagickPixel::\_\_construct](gmagickpixel.construct) — The GmagickPixel constructor * [GmagickPixel::getcolor](gmagickpixel.getcolor) — Returns the color * [GmagickPixel::getcolorcount](gmagickpixel.getcolorcount) — Returns the color count associated with this color * [GmagickPixel::getcolorvalue](gmagickpixel.getcolorvalue) — Gets the normalized value of the provided color channel * [GmagickPixel::setcolor](gmagickpixel.setcolor) — Sets the color * [GmagickPixel::setcolorvalue](gmagickpixel.setcolorvalue) — Sets the normalized value of one of the channels php mb_convert_variables mb\_convert\_variables ====================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_convert\_variables — Convert character code in variable(s) ### Description ``` mb_convert_variables( string $to_encoding, array|string $from_encoding, mixed &$var, mixed &...$vars ): string|false ``` Converts character encoding of variables `var` and `vars` in encoding `from_encoding` to encoding `to_encoding`. **mb\_convert\_variables()** join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object. ### Parameters `to_encoding` The encoding that the string is being converted to. `from_encoding` `from_encoding` is specified as an array or comma separated string, it tries to detect encoding from `from-coding`. When `from_encoding` is omitted, `detect_order` is used. `var` `var` is the reference to the variable being converted. String, Array and Object are accepted. **mb\_convert\_variables()** assumes all parameters have the same encoding. `vars` Additional `var`s. ### Return Values The character encoding before conversion for success, or **`false`** for failure. ### Examples **Example #1 **mb\_convert\_variables()** example** ``` <?php /* Convert variables $post1, $post2 to internal encoding */ $interenc = mb_internal_encoding(); $inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2); ?> ``` php pspell_config_mode pspell\_config\_mode ==================== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) pspell\_config\_mode — Change the mode number of suggestions returned ### Description ``` pspell_config_mode(PSpell\Config $config, int $mode): bool ``` **pspell\_config\_mode()** should be used on a config before calling [pspell\_new\_config()](function.pspell-new-config). This function determines how many suggestions will be returned by [pspell\_suggest()](function.pspell-suggest). ### Parameters `config` An [PSpell\Config](class.pspell-config) instance. `mode` The mode parameter is the mode in which spellchecker will work. There are several modes available: * **`PSPELL_FAST`** - Fast mode (least number of suggestions) * **`PSPELL_NORMAL`** - Normal mode (more suggestions) * **`PSPELL_BAD_SPELLERS`** - Slow mode (a lot of suggestions) ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `config` parameter expects an [PSpell\Config](class.pspell-config) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pspell\_config\_mode()** Example** ``` <?php $pspell_config = pspell_config_create("en"); pspell_config_mode($pspell_config, PSPELL_FAST); $pspell = pspell_new_config($pspell_config); pspell_check($pspell, "thecat"); ?> ``` php dba_replace dba\_replace ============ (PHP 4, PHP 5, PHP 7, PHP 8) dba\_replace — Replace or insert entry ### Description ``` dba_replace(string|array $key, string $value, resource $dba): bool ``` **dba\_replace()** replaces or inserts the entry described with `key` and `value` into the database specified by `dba`. ### Parameters `key` The key of the entry to be replaced. `value` The value to be replaced. `dba` The database handler, returned by [dba\_open()](function.dba-open) or [dba\_popen()](function.dba-popen). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [dba\_exists()](function.dba-exists) - Check whether key exists * [dba\_delete()](function.dba-delete) - Delete DBA entry specified by key * [dba\_fetch()](function.dba-fetch) - Fetch data specified by key * [dba\_insert()](function.dba-insert) - Insert entry php XMLWriter::writeCdata XMLWriter::writeCdata ===================== xmlwriter\_write\_cdata ======================= (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::writeCdata -- xmlwriter\_write\_cdata — Write full CDATA tag ### Description Object-oriented style ``` public XMLWriter::writeCdata(string $content): bool ``` Procedural style ``` xmlwriter_write_cdata(XMLWriter $writer, string $content): bool ``` Writes a full CDATA. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `content` The contents of the CDATA. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### Examples **Example #1 Basic **xmlwriter\_write\_cdata()** Usage** ``` <?php // set up the document $xml = new XmlWriter(); $xml->openMemory(); $xml->setIndent(true); $xml->startDocument('1.0', 'UTF-8'); $xml->startElement('mydoc'); $xml->startElement('myele'); // CData output $xml->startElement('mycdataelement'); $xml->writeCData("text for inclusion as CData"); $xml->endElement(); // end the document and output $xml->endElement(); $xml->endElement(); echo $xml->outputMemory(true); ?> ``` The above example will output: ``` <mydoc> <myele> <mycdataelement><![CDATA[text for inclusion as CData]​]></mycdataelement> </myele> </mydoc> ``` ### See Also * [XMLWriter::startCdata()](xmlwriter.startcdata) - Create start CDATA tag * [XMLWriter::endCdata()](xmlwriter.endcdata) - End current CDATA php pi pi == (PHP 4, PHP 5, PHP 7, PHP 8) pi — Get value of pi ### Description ``` pi(): float ``` Returns an approximation of pi. Also, you can use the **`M_PI`** constant which yields identical results to **pi()**. ### Parameters This function has no parameters. ### Return Values The value of pi as float. ### Examples **Example #1 **pi()** example** ``` <?php echo pi(); // 3.1415926535898 echo M_PI; // 3.1415926535898 ?> ``` php pow pow === (PHP 4, PHP 5, PHP 7, PHP 8) pow — Exponential expression ### Description ``` pow(mixed $num, mixed $exponent): int|float|object ``` Returns `num` raised to the power of `exponent`. > > **Note**: > > > It is possible to use the [\*\*](language.operators.arithmetic) operator instead. > > ### Parameters `num` The base to use `exponent` The exponent ### Return Values `num` raised to the power of `exponent`. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with int type, otherwise it will be returned as a float. ### Examples **Example #1 Some examples of **pow()**** ``` <?php var_dump(pow(2, 8)); // int(256) echo pow(-1, 20); // 1 echo pow(0, 0); // 1 echo pow(10, -1); // 0.1 echo pow(-1, 5.5); // NAN ?> ``` ### Notes > > **Note**: > > > This function will convert all input to a number, even non-scalar values, which could lead to `weird` results. > > ### See Also * [exp()](function.exp) - Calculates the exponent of e * [sqrt()](function.sqrt) - Square root * [bcpow()](function.bcpow) - Raise an arbitrary precision number to another * [gmp\_pow()](function.gmp-pow) - Raise number into power php recode recode ====== (PHP 4, PHP 5, PHP 7 < 7.4.0) recode — Alias of [recode\_string()](function.recode-string) ### Description This function is an alias of: [recode\_string()](function.recode-string). php The ArrayAccess interface The ArrayAccess interface ========================= Introduction ------------ (PHP 5, PHP 7, PHP 8) Interface to provide accessing objects as arrays. Interface synopsis ------------------ interface **ArrayAccess** { /\* Methods \*/ ``` public offsetExists(mixed $offset): bool ``` ``` public offsetGet(mixed $offset): mixed ``` ``` public offsetSet(mixed $offset, mixed $value): void ``` ``` public offsetUnset(mixed $offset): void ``` } **Example #1 Basic usage** ``` <?php class Obj implements ArrayAccess {     private $container = array();     public function __construct() {         $this->container = array(             "one"   => 1,             "two"   => 2,             "three" => 3,         );     }     public function offsetSet($offset, $value) {         if (is_null($offset)) {             $this->container[] = $value;         } else {             $this->container[$offset] = $value;         }     }     public function offsetExists($offset) {         return isset($this->container[$offset]);     }     public function offsetUnset($offset) {         unset($this->container[$offset]);     }     public function offsetGet($offset) {         return isset($this->container[$offset]) ? $this->container[$offset] : null;     } } $obj = new Obj; var_dump(isset($obj["two"])); var_dump($obj["two"]); unset($obj["two"]); var_dump(isset($obj["two"])); $obj["two"] = "A value"; var_dump($obj["two"]); $obj[] = 'Append 1'; $obj[] = 'Append 2'; $obj[] = 'Append 3'; print_r($obj); ?> ``` The above example will output something similar to: ``` bool(true) int(2) bool(false) string(7) "A value" obj Object ( [container:obj:private] => Array ( [one] => 1 [three] => 3 [two] => A value [0] => Append 1 [1] => Append 2 [2] => Append 3 ) ) ``` Table of Contents ----------------- * [ArrayAccess::offsetExists](arrayaccess.offsetexists) — Whether an offset exists * [ArrayAccess::offsetGet](arrayaccess.offsetget) — Offset to retrieve * [ArrayAccess::offsetSet](arrayaccess.offsetset) — Assign a value to the specified offset * [ArrayAccess::offsetUnset](arrayaccess.offsetunset) — Unset an offset
programming_docs
php PharData::offsetSet PharData::offsetSet =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) PharData::offsetSet — Set the contents of a file within the tar/zip to those of an external file or string ### Description ``` public PharData::offsetSet(string $localName, resource|string $value): void ``` This is an implementation of the [ArrayAccess](class.arrayaccess) interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a tar/zip archive. ### Parameters `localName` The filename (relative path) to modify in a tar or zip archive. `value` Content of the file. ### Return Values No return values. ### Errors/Exceptions Throws [PharException](class.pharexception) if there are any problems flushing changes made to the tar/zip archive to disk. ### Examples **Example #1 A **PharData::offsetSet()** example** offsetSet should not be accessed directly, but instead used via array access with the `[]` operator. ``` <?php $p = new PharData('/path/to/my.tar'); try {     // calls offsetSet     $p['file.txt'] = 'Hi there'; } catch (Exception $e) {     echo 'Could not modify file.txt:', $e; } ?> ``` ### Notes > **Note**: [PharData::addFile()](phardata.addfile), [PharData::addFromString()](phardata.addfromstring) and **PharData::offsetSet()** save a new phar archive each time they are called. If performance is a concern, [PharData::buildFromDirectory()](phardata.buildfromdirectory) or [PharData::buildFromIterator()](phardata.buildfromiterator) should be used instead. > > ### See Also * [Phar::offsetSet()](phar.offsetset) - Set the contents of an internal file to those of an external file php OAuthProvider::timestampNonceHandler OAuthProvider::timestampNonceHandler ==================================== (PECL OAuth >= 1.0.0) OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback ### Description ``` public OAuthProvider::timestampNonceHandler(callable $callback_function): void ``` Sets the timestamp nonce handler callback, which will later be called with [OAuthProvider::callTimestampNonceHandler()](oauthprovider.calltimestampnoncehandler). Errors related to timestamp/nonce are thrown to this callback. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `callback_function` The [callable](language.types.callable) functions name. ### Return Values No value is returned. ### Examples **Example #1 Example **OAuthProvider::timestampNonceHandler()** callback** ``` <?php function timestampNonceChecker($provider) {     if ($provider->nonce === 'bad') {         return OAUTH_BAD_NONCE;     } elseif ($provider->timestamp == '0') {         return OAUTH_BAD_TIMESTAMP;     }          return OAUTH_OK; } ?> ``` ### See Also * [OAuthProvider::callTimestampNonceHandler()](oauthprovider.calltimestampnoncehandler) - Calls the timestampNonceHandler callback php ImagickPixelIterator::destroy ImagickPixelIterator::destroy ============================= (PECL imagick 2, PECL imagick 3) ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator ### Description ``` public ImagickPixelIterator::destroy(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Deallocates resources associated with a PixelIterator. ### Return Values Returns **`true`** on success. php FilesystemIterator::key FilesystemIterator::key ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) FilesystemIterator::key — Retrieve the key for the current file ### Description ``` public FilesystemIterator::key(): string ``` ### Parameters This function has no parameters. ### Return Values Returns the pathname or filename depending on the set flags. See the [FilesystemIterator constants](class.filesystemiterator#filesystemiterator.constants). ### Examples **Example #1 **FilesystemIterator::key()** example** This example will list the contents of the directory containing the script. ``` <?php $iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME); foreach ($iterator as $fileinfo) {     echo $iterator->key() . "\n"; } ?> ``` Output of the above example in PHP 8.2 is similar to: ``` . .. apple.jpg banana.jpg example.php ``` ### See Also * [FilesystemIterator constants](class.filesystemiterator#filesystemiterator.constants) * [DirectoryIterator::key()](directoryiterator.key) - Return the key for the current DirectoryIterator item * [DirectoryIterator::getFilename()](directoryiterator.getfilename) - Return file name of current DirectoryIterator item * [DirectoryIterator::getPathname()](directoryiterator.getpathname) - Return path and file name of current DirectoryIterator item php zend_version zend\_version ============= (PHP 4, PHP 5, PHP 7, PHP 8) zend\_version — Gets the version of the current Zend engine ### Description ``` zend_version(): string ``` Returns a string containing the version of the currently running Zend Engine. ### Parameters This function has no parameters. ### Return Values Returns the Zend Engine version number, as a string. ### Examples **Example #1 **zend\_version()** example** ``` <?php echo "Zend engine version: " . zend_version(); ?> ``` The above example will output something similar to: ``` Zend engine version: 2.2.0 ``` ### See Also * [phpinfo()](function.phpinfo) - Outputs information about PHP's configuration * [phpcredits()](function.phpcredits) - Prints out the credits for PHP * [phpversion()](function.phpversion) - Gets the current PHP version php idate idate ===== (PHP 5, PHP 7, PHP 8) idate — Format a local time/date part as integer ### Description ``` idate(string $format, ?int $timestamp = null): int|false ``` Returns a number formatted according to the given format string using the given integer `timestamp` or the current local time if no timestamp is given. In other words, `timestamp` is optional and defaults to the value of [time()](function.time). Unlike the function [date()](function.date), **idate()** accepts just one char in the `format` parameter. ### Parameters `format` **The following characters are recognized in the `format` parameter string**| `format` character | Description | | --- | --- | | `B` | Swatch Beat/Internet Time | | `d` | Day of the month | | `h` | Hour (12 hour format) | | `H` | Hour (24 hour format) | | `i` | Minutes | | `I` (uppercase i) | returns `1` if DST is activated, `0` otherwise | | `L` (uppercase l) | returns `1` for leap year, `0` otherwise | | `m` | Month number | | `N` | ISO-8601 day of the week (`1` for Monday through `7` for Sunday) | | `o` | ISO-8601 year (4 digits) | | `s` | Seconds | | `t` | Days in current month | | `U` | Seconds since the Unix Epoch - January 1 1970 00:00:00 UTC - this is the same as [time()](function.time) | | `w` | Day of the week (`0` on Sunday) | | `W` | ISO-8601 week number of year, weeks starting on Monday | | `y` | Year (1 or 2 digits - check note below) | | `Y` | Year (4 digits) | | `z` | Day of the year | | `Z` | Timezone offset in seconds | `timestamp` The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or **`null`**. In other words, it defaults to the value of [time()](function.time). ### Return Values Returns an int on success, or **`false`** on failure. As **idate()** always returns an int and as they can't start with a "0", **idate()** may return fewer digits than you would expect. See the example below. ### Errors/Exceptions Every call to a date/time function will generate a **`E_WARNING`** if the time zone is not valid. See also [date\_default\_timezone\_set()](function.date-default-timezone-set) ### Changelog | Version | Description | | --- | --- | | 8.2.0 | Adds the `N` (ISO-8601 day of the week) and `o` (ISO-8601 year) format characters. | | 8.0.0 | `timestamp` is nullable now. | ### Examples **Example #1 **idate()** example** ``` <?php $timestamp = strtotime('1st January 2004'); //1072915200 // this prints the year in a two digit format // however, as this would start with a "0", it // only prints "4" echo idate('y', $timestamp); ?> ``` ### See Also * [DateTimeInterface::format()](datetime.format) - Returns date formatted according to given format * [date()](function.date) - Format a Unix timestamp * [getdate()](function.getdate) - Get date/time information * [time()](function.time) - Return current Unix timestamp php SolrQuery::setEchoParams SolrQuery::setEchoParams ======================== (PECL solr >= 0.9.2) SolrQuery::setEchoParams — Determines what kind of parameters to include in the response ### Description ``` public SolrQuery::setEchoParams(string $type): SolrQuery ``` Instructs Solr what kinds of Request parameters should be included in the response for debugging purposes, legal values include: ``` - none - don't include any request parameters for debugging - explicit - include the parameters explicitly specified by the client in the request - all - include all parameters involved in this request, either specified explicitly by the client, or implicit because of the request handler configuration. ``` ### Parameters `type` The type of parameters to include ### Return Values Returns the current SolrQuery object, if the return value is used. php openssl_cms_read openssl\_cms\_read ================== (PHP 8) openssl\_cms\_read — Export the CMS file to an array of PEM certificates ### Description ``` openssl_cms_read(string $input_filename, array &$certificates): bool ``` Performs the exact analog to [openssl\_pkcs7\_read()](function.openssl-pkcs7-read). **Warning**This function is currently not documented; only its argument list is available. ### Parameters `input_filename` `certificates` ### Return Values Returns **`true`** on success or **`false`** on failure. php sodium_crypto_aead_xchacha20poly1305_ietf_keygen sodium\_crypto\_aead\_xchacha20poly1305\_ietf\_keygen ===================================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_aead\_xchacha20poly1305\_ietf\_keygen — Generate a random XChaCha20-Poly1305 key. ### Description ``` sodium_crypto_aead_xchacha20poly1305_ietf_keygen(): string ``` Generate a random key for use with [sodium\_crypto\_aead\_xchacha20poly1305\_ietf\_encrypt()](function.sodium-crypto-aead-xchacha20poly1305-ietf-encrypt) and [sodium\_crypto\_aead\_xchacha20poly1305\_ietf\_decrypt()](function.sodium-crypto-aead-xchacha20poly1305-ietf-decrypt). ### Parameters This function has no parameters. ### Return Values Returns a 256-bit random key. php ZipArchive::setMtimeName ZipArchive::setMtimeName ======================== (PHP >= 8.0.0, PECL zip >= 1.16.0) ZipArchive::setMtimeName — Set the modification time of an entry defined by its name ### Description ``` public ZipArchive::setMtimeName(string $name, int $timestamp, int $flags = 0): bool ``` Set the modification time of an entry defined by its name. ### Parameters `name` Name of the entry. `timestamp` The modification time (unix timestamp) of the file. `flags` Optional flags, unused for now. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples This example creates a ZIP file archive test.zip and add the file test.txt with its modification date. **Example #1 Archive a file** ``` <?php $zip = new ZipArchive(); if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {     $zip->addFile('text.txt');     $zip->setMtimeName('text.txt', mktime(0,0,0,12,25,2019));     $zip->close();     echo "Ok\n"; } else {     echo "KO\n"; } ?> ``` ### Notes > > **Note**: > > > This function is only available if built against libzip ≥ 1.0.0. > > ### See Also * [ZipArchive::setMtimeIndex()](ziparchive.setmtimeindex) - Set the modification time of an entry defined by its index php stats_stat_correlation stats\_stat\_correlation ======================== (PECL stats >= 1.0.0) stats\_stat\_correlation — Returns the Pearson correlation coefficient of two data sets ### Description ``` stats_stat_correlation(array $arr1, array $arr2): float ``` Returns the Pearson correlation coefficient between `arr1` and `arr2`. ### Parameters `arr1` The first array `arr2` The second array ### Return Values Returns the Pearson correlation coefficient between `arr1` and `arr2`, or **`false`** on failure. php exp exp === (PHP 4, PHP 5, PHP 7, PHP 8) exp — Calculates the exponent of **`e`** ### Description ``` exp(float $num): float ``` Returns **`e`** raised to the power of `num`. > > **Note**: > > > '**`e`**' is the base of the natural system of logarithms, or approximately 2.718282. > > ### Parameters `num` The argument to process ### Return Values 'e' raised to the power of `num` ### Examples **Example #1 **exp()** example** ``` <?php echo exp(12) . "\n"; echo exp(5.7); ?> ``` The above example will output: ``` 1.6275E+005 298.87 ``` ### See Also * [log()](function.log) - Natural logarithm * [pow()](function.pow) - Exponential expression php IntlTimeZone::getErrorCode IntlTimeZone::getErrorCode ========================== intltz\_get\_error\_code ======================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::getErrorCode -- intltz\_get\_error\_code — Get last error code on the object ### Description Object-oriented style (method): ``` public IntlTimeZone::getErrorCode(): int|false ``` Procedural style: ``` intltz_get_error_code(IntlTimeZone $timezone): int|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php imap_headers imap\_headers ============= (PHP 4, PHP 5, PHP 7, PHP 8) imap\_headers — Returns headers for all messages in a mailbox ### Description ``` imap_headers(IMAP\Connection $imap): array|false ``` Returns headers for all messages in a mailbox. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. ### Return Values Returns an array of string formatted with header info. One element per mail message. Returns **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | php VarnishAdmin::getPanic VarnishAdmin::getPanic ====================== (PECL varnish >= 0.4) VarnishAdmin::getPanic — Get the last panic message on a varnish instance ### Description ``` public VarnishAdmin::getPanic(): string ``` ### Parameters This function has no parameters. ### Return Values Returns the last panic message on the current varnish instance. php Imagick::clear Imagick::clear ============== (PECL imagick 2, PECL imagick 3) Imagick::clear — Clears all resources associated to Imagick object ### Description ``` public Imagick::clear(): bool ``` Clears all resources associated to Imagick object ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. php svn_fs_node_created_rev svn\_fs\_node\_created\_rev =========================== (PECL svn >= 0.1.0) svn\_fs\_node\_created\_rev — Returns the revision in which path under fsroot was created ### Description ``` svn_fs_node_created_rev(resource $fsroot, string $path): int ``` **Warning**This function is currently not documented; only its argument list is available. Returns the revision in which path under fsroot was created ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php mb_substr_count mb\_substr\_count ================= (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) mb\_substr\_count — Count the number of substring occurrences ### Description ``` mb_substr_count(string $haystack, string $needle, ?string $encoding = null): int ``` Counts the number of times the `needle` substring occurs in the `haystack` string. ### Parameters `haystack` The string being checked. `needle` The string being found. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values The number of times the `needle` substring occurs in the `haystack` string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | ### Examples **Example #1 **mb\_substr\_count()** example** ``` <?php echo mb_substr_count("This is a test", "is"); // prints out 2 ?> ``` ### See Also * [mb\_strpos()](function.mb-strpos) - Find position of first occurrence of string in a string * [mb\_substr()](function.mb-substr) - Get part of string * [substr\_count()](function.substr-count) - Count the number of substring occurrences php None Scope Resolution Operator (::) ------------------------------ The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to [static](language.oop5.static), [constant](language.oop5.constants), and overridden properties or methods of a class. When referencing these items from outside the class definition, use the name of the class. It's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. `self`, `parent` and `static`). Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew! **Example #1 :: from outside the class definition** ``` <?php class MyClass {     const CONST_VALUE = 'A constant value'; } $classname = 'MyClass'; echo $classname::CONST_VALUE; echo MyClass::CONST_VALUE; ?> ``` Three special keywords self, parent and static are used to access properties or methods from inside the class definition. **Example #2 :: from inside the class definition** ``` <?php class OtherClass extends MyClass {     public static $my_static = 'static var';     public static function doubleColon() {         echo parent::CONST_VALUE . "\n";         echo self::$my_static . "\n";     } } $classname = 'OtherClass'; $classname::doubleColon(); OtherClass::doubleColon(); ?> ``` When an extending class overrides the parent's definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to [Constructors and Destructors](language.oop5.decon), [Overloading](language.oop5.overloading), and [Magic](language.oop5.magic) method definitions. **Example #3 Calling a parent's method** ``` <?php class MyClass {     protected function myFunc() {         echo "MyClass::myFunc()\n";     } } class OtherClass extends MyClass {     // Override parent's definition     public function myFunc()     {         // But still call the parent function         parent::myFunc();         echo "OtherClass::myFunc()\n";     } } $class = new OtherClass(); $class->myFunc(); ?> ``` See also [some examples of static call trickery](language.oop5.basic#language.oop5.basic.class.this).
programming_docs
php Ev::suspend Ev::suspend =========== (PECL ev >= 0.2.0) Ev::suspend — Suspend the default event loop ### Description ``` final public static Ev::suspend(): void ``` **Ev::suspend()** and [Ev::resume()](ev.resume) methods suspend and resume the default loop correspondingly. All timer watchers will be delayed by the time spend between *suspend* and *resume* , and all *periodic* watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended). After calling **Ev::suspend()** it is not allowed to call any function on the given loop other than [Ev::resume()](ev.resume) . Also it is not allowed to call [Ev::resume()](ev.resume) without a previous call to **Ev::suspend()** . ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [Ev::resume()](ev.resume) - Resume previously suspended default event loop php imagefilter imagefilter =========== (PHP 5, PHP 7, PHP 8) imagefilter — Applies a filter to an image ### Description ``` imagefilter(GdImage $image, int $filter, array|int|float|bool ...$args): bool ``` **imagefilter()** applies the given filter `filter` on the `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `filter` `filter` can be one of the following: * **`IMG_FILTER_NEGATE`**: Reverses all colors of the image. * **`IMG_FILTER_GRAYSCALE`**: Converts the image into grayscale by changing the red, green and blue components to their weighted sum using the same coefficients as the REC.601 luma (Y') calculation. The alpha components are retained. For palette images the result may differ due to palette limitations. * **`IMG_FILTER_BRIGHTNESS`**: Changes the brightness of the image. Use `args` to set the level of brightness. The range for the brightness is -255 to 255. * **`IMG_FILTER_CONTRAST`**: Changes the contrast of the image. Use `args` to set the level of contrast. * **`IMG_FILTER_COLORIZE`**: Like **`IMG_FILTER_GRAYSCALE`**, except you can specify the color. Use `args`, `arg2` and `arg3` in the form of `red`, `green`, `blue` and `arg4` for the `alpha` channel. The range for each color is 0 to 255. * **`IMG_FILTER_EDGEDETECT`**: Uses edge detection to highlight the edges in the image. * **`IMG_FILTER_EMBOSS`**: Embosses the image. * **`IMG_FILTER_GAUSSIAN_BLUR`**: Blurs the image using the Gaussian method. * **`IMG_FILTER_SELECTIVE_BLUR`**: Blurs the image. * **`IMG_FILTER_MEAN_REMOVAL`**: Uses mean removal to achieve a "sketchy" effect. * **`IMG_FILTER_SMOOTH`**: Makes the image smoother. Use `args` to set the level of smoothness. * **`IMG_FILTER_PIXELATE`**: Applies pixelation effect to the image, use `args` to set the block size and `arg2` to set the pixelation effect mode. * **`IMG_FILTER_SCATTER`**: Applies scatter effect to the image, use `args` and `arg2` to define the effect strength and additionally `arg3` to only apply the on select pixel colors. `args` * **`IMG_FILTER_BRIGHTNESS`**: Brightness level. * **`IMG_FILTER_CONTRAST`**: Contrast level. * **`IMG_FILTER_COLORIZE`**: Value of red component. * **`IMG_FILTER_SMOOTH`**: Smoothness level. * **`IMG_FILTER_PIXELATE`**: Block size in pixels. * **`IMG_FILTER_SCATTER`**: Effect substraction level. This must not be higher or equal to the addition level set with `arg2`. `arg2` * **`IMG_FILTER_COLORIZE`**: Value of green component. * **`IMG_FILTER_PIXELATE`**: Whether to use advanced pixelation effect or not (defaults to **`false`**). * **`IMG_FILTER_SCATTER`**: Effect addition level. `arg3` * **`IMG_FILTER_COLORIZE`**: Value of blue component. * **`IMG_FILTER_SCATTER`**: Optional array indexed color values to apply effect at. `arg4` * **`IMG_FILTER_COLORIZE`**: Alpha channel, A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | | 7.4.0 | Scatter support (**`IMG_FILTER_SCATTER`**) was added. | ### Examples **Example #1 **imagefilter()** grayscale example** ``` <?php $im = imagecreatefrompng('dave.png'); if($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) {     echo 'Image converted to grayscale.';     imagepng($im, 'dave.png'); } else {     echo 'Conversion to grayscale failed.'; } imagedestroy($im); ?> ``` **Example #2 **imagefilter()** brightness example** ``` <?php $im = imagecreatefrompng('sean.png'); if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {     echo 'Image brightness changed.';     imagepng($im, 'sean.png');     imagedestroy($im); } else {     echo 'Image brightness change failed.'; } ?> ``` **Example #3 **imagefilter()** colorize example** ``` <?php $im = imagecreatefrompng('philip.png'); /* R, G, B, so 0, 255, 0 is green */ if($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {     echo 'Image successfully shaded green.';     imagepng($im, 'philip.png');     imagedestroy($im); } else {     echo 'Green shading failed.'; } ?> ``` **Example #4 **imagefilter()** negate example** ``` <?php // Define our negate function so its portable for  // php versions without imagefilter() function negate($im) {     if(function_exists('imagefilter'))     {         return imagefilter($im, IMG_FILTER_NEGATE);     }     for($x = 0; $x < imagesx($im); ++$x)     {         for($y = 0; $y < imagesy($im); ++$y)         {             $index = imagecolorat($im, $x, $y);             $rgb = imagecolorsforindex($index);             $color = imagecolorallocate($im, 255 - $rgb['red'], 255 - $rgb['green'], 255 - $rgb['blue']);             imagesetpixel($im, $x, $y, $color);         }     }     return(true); } $im = imagecreatefromjpeg('kalle.jpg'); if($im && negate($im)) {     echo 'Image successfully converted to negative colors.';     imagejpeg($im, 'kalle.jpg', 100);     imagedestroy($im); } else {     echo 'Converting to negative colors failed.'; } ?> ``` **Example #5 **imagefilter()** pixelate example** ``` <?php // Load the PHP logo, we need to create two instances  // to show the differences $logo1 = imagecreatefrompng('./php.png'); $logo2 = imagecreatefrompng('./php.png'); // Create the image instance we want to show the  // differences on $output = imagecreatetruecolor(imagesx($logo1) * 2, imagesy($logo1)); // Apply pixelation to each instance, with a block  // size of 3 imagefilter($logo1, IMG_FILTER_PIXELATE, 3); imagefilter($logo2, IMG_FILTER_PIXELATE, 3, true); // Merge the differences onto the output image imagecopy($output, $logo1, 0, 0, 0, 0, imagesx($logo1) - 1, imagesy($logo1) - 1); imagecopy($output, $logo2, imagesx($logo2), 0, 0, 0, imagesx($logo2) - 1, imagesy($logo2) - 1); imagedestroy($logo1); imagedestroy($logo2); // Output the differences header('Content-Type: image/png'); imagepng($output); imagedestroy($output); ?> ``` The above example will output something similar to: **Example #6 **imagefilter()** scatter example** ``` <?php // Load the image $logo = imagecreatefrompng('./php.png'); // Apply a very soft scatter effect to the image imagefilter($logo, IMG_FILTER_SCATTER, 3, 5); // Output the image with the scatter effect header('Content-Type: image/png'); imagepng($logo); imagedestroy($logo); ?> ``` The above example will output something similar to: ### Notes > **Note**: The result of **`IMG_FILTER_SCATTER`** is always random. > > ### See Also * [imageconvolution()](function.imageconvolution) - Apply a 3x3 convolution matrix, using coefficient and offset php SoapServer::setClass SoapServer::setClass ==================== (PHP 5, PHP 7, PHP 8) SoapServer::setClass — Sets the class which handles SOAP requests ### Description ``` public SoapServer::setClass(string $class, mixed ...$args): void ``` Exports all methods from specified class. The object can be made persistent across request for a given PHP session with the [SoapServer::setPersistence()](soapserver.setpersistence) method. ### Parameters `class` The name of the exported class. `args` These optional parameters will be passed to the default class constructor during object creation. ### Return Values No value is returned. ### See Also * [SoapServer::\_\_construct()](soapserver.construct) - SoapServer constructor * [SoapServer::addFunction()](soapserver.addfunction) - Adds one or more functions to handle SOAP requests * [SoapServer::setPersistence()](soapserver.setpersistence) - Sets SoapServer persistence mode php ZipArchive::unchangeAll ZipArchive::unchangeAll ======================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0) ZipArchive::unchangeAll — Undo all changes done in the archive ### Description ``` public ZipArchive::unchangeAll(): bool ``` Undo all changes done in the archive. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. php Yaf_Response_Abstract::setAllHeaders Yaf\_Response\_Abstract::setAllHeaders ====================================== (Yaf >=1.0.0) Yaf\_Response\_Abstract::setAllHeaders — The setAllHeaders purpose ### Description ``` protected Yaf_Response_Abstract::setAllHeaders(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php SessionUpdateTimestampHandlerInterface::updateTimestamp SessionUpdateTimestampHandlerInterface::updateTimestamp ======================================================= (PHP 7, PHP 8) SessionUpdateTimestampHandlerInterface::updateTimestamp — Update timestamp ### Description ``` public SessionUpdateTimestampHandlerInterface::updateTimestamp(string $id, string $data): bool ``` Updates the last modification timestamp of the session. This function is automatically executed when a session is updated. ### Parameters `id` The session ID. `data` The session data. ### Return Values Returns **`true`** if the timestamp was updated, **`false`** otherwise. Note that this value is returned internally to PHP for processing. php The OpenSSLAsymmetricKey class The OpenSSLAsymmetricKey class ============================== Introduction ------------ (PHP 8) A fully opaque class which replaces `OpenSSL key` resources as of PHP 8.0.0. Class synopsis -------------- final class **OpenSSLAsymmetricKey** { } php ReflectionProperty::export ReflectionProperty::export ========================== (PHP 5, PHP 7) ReflectionProperty::export — Export **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public static ReflectionProperty::export(mixed $class, string $name, bool $return = ?): string ``` Exports a reflection. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `argument` The reflection to export. `name` The property name. `return` Setting to **`true`** will return the export, as opposed to emitting it. Setting to **`false`** (the default) will do the opposite. ### Return Values ### See Also * [ReflectionProperty::\_\_toString()](reflectionproperty.tostring) - To string php openssl_spki_export_challenge openssl\_spki\_export\_challenge ================================ (PHP 5 >= 5.6.0, PHP 7, PHP 8) openssl\_spki\_export\_challenge — Exports the challenge associated with a signed public key and challenge ### Description ``` openssl_spki_export_challenge(string $spki): string|false ``` Exports challenge from encoded signed public key and challenge ### Parameters `spki` Expects a valid signed public key and challenge ### Return Values Returns the associated challenge string or **`false`** on failure. ### Errors/Exceptions Emits an **`E_WARNING`** level error if an invalid argument is passed via the `spki` parameter. ### Examples **Example #1 **openssl\_spki\_export\_challenge()** example** Extracts the associated challenge string or NULL on failure. ``` <?php $pkey = openssl_pkey_new('secret password'); $spkac = openssl_spki_new($pkey, 'challenge string'); $challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $spkac)); ?> ``` **Example #2 **openssl\_spki\_export\_challenge()** example from <keygen>** Extracts the associated challenge string issued from the <keygen> element ``` <?php $challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $_POST['spkac'])); ?> <keygen name="spkac" challenge="challenge string" keytype="RSA"> ``` ### See Also * [openssl\_spki\_new()](function.openssl-spki-new) - Generate a new signed public key and challenge * [openssl\_spki\_verify()](function.openssl-spki-verify) - Verifies a signed public key and challenge * [openssl\_spki\_export()](function.openssl-spki-export) - Exports a valid PEM formatted public key signed public key and challenge * [openssl\_get\_md\_methods()](function.openssl-get-md-methods) - Gets available digest methods * [openssl\_csr\_new()](function.openssl-csr-new) - Generates a CSR * [openssl\_csr\_sign()](function.openssl-csr-sign) - Sign a CSR with another certificate (or itself) and generate a certificate php GearmanTask::isKnown GearmanTask::isKnown ==================== (PECL gearman >= 0.5.0) GearmanTask::isKnown — Determine if task is known ### Description ``` public GearmanTask::isKnown(): bool ``` Gets the status information for whether or not this task is known to the job server. ### Parameters This function has no parameters. ### Return Values **`true`** if the task is known, **`false`** otherwise. php readline_read_history readline\_read\_history ======================= (PHP 4, PHP 5, PHP 7, PHP 8) readline\_read\_history — Reads the history ### Description ``` readline_read_history(?string $filename = null): bool ``` This function reads a command history from a file. ### Parameters `filename` Path to the filename containing the command history. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `filename` is nullable now. | php None Visibility ---------- The visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by prefixing the declaration with the keywords `public`, `protected` or `private`. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inheriting and parent classes. Members declared as private may only be accessed by the class that defines the member. ### Property Visibility Class properties may be defined as public, private, or protected. Properties declared without any explicit visibility keyword are defined as public. **Example #1 Property declaration** ``` <?php /**  * Define MyClass  */ class MyClass {     public $public = 'Public';     protected $protected = 'Protected';     private $private = 'Private';     function printHello()     {         echo $this->public;         echo $this->protected;         echo $this->private;     } } $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private /**  * Define MyClass2  */ class MyClass2 extends MyClass {     // We can redeclare the public and protected properties, but not private     public $public = 'Public2';     protected $protected = 'Protected2';     function printHello()     {         echo $this->public;         echo $this->protected;         echo $this->private;     } } $obj2 = new MyClass2(); echo $obj2->public; // Works echo $obj2->protected; // Fatal Error echo $obj2->private; // Undefined $obj2->printHello(); // Shows Public2, Protected2, Undefined ?> ``` ### Method Visibility Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public. **Example #2 Method Declaration** ``` <?php /**  * Define MyClass  */ class MyClass {     // Declare a public constructor     public function __construct() { }     // Declare a public method     public function MyPublic() { }     // Declare a protected method     protected function MyProtected() { }     // Declare a private method     private function MyPrivate() { }     // This is public     function Foo()     {         $this->MyPublic();         $this->MyProtected();         $this->MyPrivate();     } } $myclass = new MyClass; $myclass->MyPublic(); // Works $myclass->MyProtected(); // Fatal Error $myclass->MyPrivate(); // Fatal Error $myclass->Foo(); // Public, Protected and Private work /**  * Define MyClass2  */ class MyClass2 extends MyClass {     // This is public     function Foo2()     {         $this->MyPublic();         $this->MyProtected();         $this->MyPrivate(); // Fatal Error     } } $myclass2 = new MyClass2; $myclass2->MyPublic(); // Works $myclass2->Foo2(); // Public and Protected work, not Private class Bar  {     public function test() {         $this->testPrivate();         $this->testPublic();     }     public function testPublic() {         echo "Bar::testPublic\n";     }          private function testPrivate() {         echo "Bar::testPrivate\n";     } } class Foo extends Bar  {     public function testPublic() {         echo "Foo::testPublic\n";     }          private function testPrivate() {         echo "Foo::testPrivate\n";     } } $myFoo = new Foo(); $myFoo->test(); // Bar::testPrivate                  // Foo::testPublic ?> ``` ### Constant Visibility As of PHP 7.1.0, class constants may be defined as public, private, or protected. Constants declared without any explicit visibility keyword are defined as public. **Example #3 Constant Declaration as of PHP 7.1.0** ``` <?php /**  * Define MyClass  */ class MyClass {     // Declare a public constant     public const MY_PUBLIC = 'public';     // Declare a protected constant     protected const MY_PROTECTED = 'protected';     // Declare a private constant     private const MY_PRIVATE = 'private';     public function foo()     {         echo self::MY_PUBLIC;         echo self::MY_PROTECTED;         echo self::MY_PRIVATE;     } } $myclass = new MyClass(); MyClass::MY_PUBLIC; // Works MyClass::MY_PROTECTED; // Fatal Error MyClass::MY_PRIVATE; // Fatal Error $myclass->foo(); // Public, Protected and Private work /**  * Define MyClass2  */ class MyClass2 extends MyClass {     // This is public     function foo2()     {         echo self::MY_PUBLIC;         echo self::MY_PROTECTED;         echo self::MY_PRIVATE; // Fatal Error     } } $myclass2 = new MyClass2; echo MyClass2::MY_PUBLIC; // Works $myclass2->foo2(); // Public and Protected work, not Private ?> ``` ### Visibility from other objects Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects. **Example #4 Accessing private members of the same object type** ``` <?php class Test {     private $foo;     public function __construct($foo)     {         $this->foo = $foo;     }     private function bar()     {         echo 'Accessed the private method.';     }     public function baz(Test $other)     {         // We can change the private property:         $other->foo = 'hello';         var_dump($other->foo);         // We can also call the private method:         $other->bar();     } } $test = new Test('test'); $test->baz(new Test('other')); ?> ``` The above example will output: ``` string(5) "hello" Accessed the private method. ```
programming_docs
php PharData::addFromString PharData::addFromString ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) PharData::addFromString — Add a file from the filesystem to the tar/zip archive ### Description ``` public PharData::addFromString(string $localName, string $contents): void ``` With this method, any string can be added to the tar/zip archive. The file will be stored in the archive with `localname` as its path. This method is similar to [ZipArchive::addFromString()](ziparchive.addfromstring). ### Parameters `localName` Path that the file will be stored in the archive. `contents` The file contents to store ### Return Values no return value, exception is thrown on failure. ### Examples **Example #1 A **PharData::addFromString()** example** ``` <?php try {     $a = new PharData('/path/to/my.tar');     $a->addFromString('path/to/file.txt', 'my simple file');     $b = $a['path/to/file.txt']->getContent();     // to add contents from a stream handle for large files, use offsetSet()     $c = fopen('/path/to/hugefile.bin');     $a['largefile.bin'] = $c;     fclose($c); } catch (Exception $e) {     // handle errors here } ?> ``` ### Notes > **Note**: [PharData::addFile()](phardata.addfile), **PharData::addFromString()** and [PharData::offsetSet()](phardata.offsetset) save a new phar archive each time they are called. If performance is a concern, [PharData::buildFromDirectory()](phardata.buildfromdirectory) or [PharData::buildFromIterator()](phardata.buildfromiterator) should be used instead. > > ### See Also * [PharData::offsetSet()](phardata.offsetset) - Set the contents of a file within the tar/zip to those of an external file or string * [Phar::addFromString()](phar.addfromstring) - Add a file from a string to the phar archive * [PharData::addFile()](phardata.addfile) - Add a file from the filesystem to the tar/zip archive * [PharData::addEmptyDir()](phardata.addemptydir) - Add an empty directory to the tar/zip archive php The Spoofchecker class The Spoofchecker class ====================== Introduction ------------ (PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0) This class is provided because Unicode contains large number of characters and incorporates the varied writing systems of the world and their incorrect usage can expose programs or systems to possible security attacks using characters similarity. Provided methods allow to check whether an individual string is likely an attempt at confusing the reader (`spoof detection`), such as "pаypаl" spelled with Cyrillic 'а' characters. Class synopsis -------------- class **Spoofchecker** { /\* Constants \*/ public const int [SINGLE\_SCRIPT\_CONFUSABLE](class.spoofchecker#spoofchecker.constants.single-script-confusable); public const int [MIXED\_SCRIPT\_CONFUSABLE](class.spoofchecker#spoofchecker.constants.mixed-script-confusable); public const int [WHOLE\_SCRIPT\_CONFUSABLE](class.spoofchecker#spoofchecker.constants.whole-script-confusable); public const int [ANY\_CASE](class.spoofchecker#spoofchecker.constants.any-case); public const int [SINGLE\_SCRIPT](class.spoofchecker#spoofchecker.constants.single-script); public const int [INVISIBLE](class.spoofchecker#spoofchecker.constants.invisible); public const int [CHAR\_LIMIT](class.spoofchecker#spoofchecker.constants.char-limit); public const int [ASCII](class.spoofchecker#spoofchecker.constants.ascii); public const int [HIGHLY\_RESTRICTIVE](class.spoofchecker#spoofchecker.constants.highly-restrictive); public const int [MODERATELY\_RESTRICTIVE](class.spoofchecker#spoofchecker.constants.moderately-restrictive); public const int [MINIMALLY\_RESTRICTIVE](class.spoofchecker#spoofchecker.constants.minimally-restrictive); public const int [UNRESTRICTIVE](class.spoofchecker#spoofchecker.constants.unrestrictive); public const int [SINGLE\_SCRIPT\_RESTRICTIVE](class.spoofchecker#spoofchecker.constants.single-script-restrictive); /\* Methods \*/ public [\_\_construct](spoofchecker.construct)() ``` public areConfusable(string $string1, string $string2, int &$errorCode = null): bool ``` ``` public isSuspicious(string $string, int &$errorCode = null): bool ``` ``` public setAllowedLocales(string $locales): void ``` ``` public setChecks(int $checks): void ``` } Predefined Constants -------------------- **`Spoofchecker::ASCII`** **`Spoofchecker::HIGHLY_RESTRICTIVE`** **`Spoofchecker::MODERATELY_RESTRICTIVE`** **`Spoofchecker::MINIMALLY_RESTRICTIVE`** **`Spoofchecker::UNRESTRICTIVE`** **`Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE`** **`Spoofchecker::SINGLE_SCRIPT_CONFUSABLE`** **`Spoofchecker::MIXED_SCRIPT_CONFUSABLE`** **`Spoofchecker::WHOLE_SCRIPT_CONFUSABLE`** **`Spoofchecker::ANY_CASE`** **`Spoofchecker::SINGLE_SCRIPT`** **`Spoofchecker::INVISIBLE`** **`Spoofchecker::CHAR_LIMIT`** Changelog --------- | Version | Description | | --- | --- | | 7.3.0 | Class constants used by **Spoofchecker::setRestrictionLevel()** such as **`Spoofchecker::ASCII`**, **`Spoofchecker::HIGHLY_RESTRICTIVE`**, **`Spoofchecker::MODERATELY_RESTRICTIVE`**, **`Spoofchecker::MINIMALLY_RESTRICTIVE`**, **`Spoofchecker::UNRESTRICTIVE`**, **`Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE`** has been added. | Table of Contents ----------------- * [Spoofchecker::areConfusable](spoofchecker.areconfusable) — Checks if given strings can be confused * [Spoofchecker::\_\_construct](spoofchecker.construct) — Constructor * [Spoofchecker::isSuspicious](spoofchecker.issuspicious) — Checks if a given text contains any suspicious characters * [Spoofchecker::setAllowedLocales](spoofchecker.setallowedlocales) — Locales to use when running checks * [Spoofchecker::setChecks](spoofchecker.setchecks) — Set the checks to run php RegexIterator::setFlags RegexIterator::setFlags ======================= (PHP 5 >= 5.2.0, PHP 7, PHP 8) RegexIterator::setFlags — Sets the flags ### Description ``` public RegexIterator::setFlags(int $flags): void ``` Sets the flags. ### Parameters `flags` The flags to set, a bitmask of class constants. The available flags are listed below. The actual meanings of these flags are described in the [predefined constants](class.regexiterator#regexiterator.constants). **[RegexIterator](class.regexiterator) flags**| value | constant | | --- | --- | | 1 | [RegexIterator::USE\_KEY](class.regexiterator#regexiterator.constants.use-key) | ### Return Values No value is returned. ### Examples **Example #1 **RegexIterator::setFlags()** example** Creates a new RegexIterator that filters all entries whose key starts with '`test`'. ``` <?php $test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123'); $arrayIterator = new ArrayIterator($test); $regexIterator = new RegexIterator($arrayIterator, '/^test/'); $regexIterator->setFlags(RegexIterator::USE_KEY); foreach ($regexIterator as $key => $value) {     echo $key . ' => ' . $value . "\n"; } ?> ``` The above example will output: ``` teststr2 => another test ``` ### See Also * [RegexIterator::getFlags()](regexiterator.getflags) - Get flags php Yaf_Controller_Abstract::getRequest Yaf\_Controller\_Abstract::getRequest ===================================== (Yaf >=1.0.0) Yaf\_Controller\_Abstract::getRequest — Retrieve current request object ### Description ``` public Yaf_Controller_Abstract::getRequest(): Yaf_Request_Abstract ``` retrieve current request object ### Parameters This function has no parameters. ### Return Values [Yaf\_Request\_Abstract](class.yaf-request-abstract) instance php ImagickDraw::roundRectangle ImagickDraw::roundRectangle =========================== (PECL imagick 2, PECL imagick 3) ImagickDraw::roundRectangle — Draws a rounded rectangle ### Description ``` public ImagickDraw::roundRectangle( float $x1, float $y1, float $x2, float $y2, float $rx, float $ry ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a rounded rectangle given two coordinates, x & y corner radiuses and using the current stroke, stroke width, and fill settings. ### Parameters `x1` x coordinate of the top left corner `y1` y coordinate of the top left corner `x2` x coordinate of the bottom right `y2` y coordinate of the bottom right `rx` x rounding `ry` y rounding ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::roundRectangle()** example** ``` <?php function roundRectangle($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $roundX, $roundY) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeOpacity(1);     $draw->setStrokeWidth(2);     $draw->roundRectangle($startX, $startY, $endX, $endY, $roundX, $roundY);     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php None Object Inheritance ------------------ Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another. For example, when extending a class, the subclass inherits all of the public and protected methods, properties and constants from the parent class. Unless a class overrides those methods, they will retain their original functionality. This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality. Private methods of a parent class are not accessible to a child class. As a result, child classes may reimplement a private method themselves without regard for normal inheritance rules. Prior to PHP 8.0.0, however, `final` and `static` restrictions were applied to private methods. As of PHP 8.0.0, the only private method restriction that is enforced is `private final` constructors, as that is a common way to "disable" the constructor when using static factory methods instead. The [visibility](language.oop5.visibility) of methods, properties and constants can be relaxed, e.g. a `protected` method can be marked as `public`, but they cannot be restricted, e.g. marking a `public` property as `private`. > > **Note**: > > > Unless autoloading is used, the classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces. > > > > **Note**: > > > It is not allowed to override a read-write property with a [readonly property](language.oop5.properties#language.oop5.properties.readonly-properties) or vice versa. > > > > ``` > <?php > > class A { >     public int $prop; > } > class B extends A { >     // Illegal: read-write -> readonly >     public readonly int $prop; > } > ?> > ``` > **Example #1 Inheritance Example** ``` <?php class Foo {     public function printItem($string)     {         echo 'Foo: ' . $string . PHP_EOL;     }          public function printPHP()     {         echo 'PHP is great.' . PHP_EOL;     } } class Bar extends Foo {     public function printItem($string)     {         echo 'Bar: ' . $string . PHP_EOL;     } } $foo = new Foo(); $bar = new Bar(); $foo->printItem('baz'); // Output: 'Foo: baz' $foo->printPHP();       // Output: 'PHP is great'  $bar->printItem('baz'); // Output: 'Bar: baz' $bar->printPHP();       // Output: 'PHP is great' ?> ``` ### Return Type Compatibility with Internal Classes Prior to PHP 8.1, most internal classes or methods didn't declare their return types, and any return type was allowed when extending them. As of PHP 8.1.0, most internal methods started to "tentatively" declare their return type, in that case the return type of methods should be compatible with the parent being extended; otherwise, a deprecation notice is emitted. Note that lack of an explicit return declaration is also considered a signature mismatch, and thus results in the deprecation notice. If the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a `#[ReturnTypeWillChange]` attribute can be added to silence the deprecation notice. **Example #2 The overriding method does not declare any return type** ``` <?php class MyDateTime extends DateTime {     public function modify(string $modifier) { return false; } }   // "Deprecated: Return type of MyDateTime::modify(string $modifier) should either be compatible with DateTime::modify(string $modifier): DateTime|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice" as of PHP 8.1.0 ?> ``` **Example #3 The overriding method declares a wrong return type** ``` <?php class MyDateTime extends DateTime {     public function modify(string $modifier): ?DateTime { return null; } }   // "Deprecated: Return type of MyDateTime::modify(string $modifier): ?DateTime should either be compatible with DateTime::modify(string $modifier): DateTime|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice" as of PHP 8.1.0 ?> ``` **Example #4 The overriding method declares a wrong return type without a deprecation notice** ``` <?php class MyDateTime extends DateTime {     /**      * @return DateTime|false      */     #[ReturnTypeWillChange]     public function modify(string $modifier) { return false; } }   // No notice is triggered  ?> ``` php Phar::hasMetadata Phar::hasMetadata ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0) Phar::hasMetadata — Returns whether phar has global meta-data ### Description ``` public Phar::hasMetadata(): bool ``` Returns whether phar has global meta-data set. ### Parameters No parameters. ### Return Values Returns **`true`** if meta-data has been set, and **`false`** if not. ### Examples **Example #1 A **Phar::hasMetadata()** example** ``` <?php try {     $phar = new Phar('myphar.phar');     var_dump($phar->hasMetadata());     $phar->setMetadata(array('thing' => 'hi'));     var_dump($phar->hasMetadata());     $phar->delMetadata();     var_dump($phar->hasMetadata()); } catch (Exception $e) {     // handle error } ?> ``` The above example will output: ``` bool(false) bool(true) bool(false) ``` ### See Also * [Phar::getMetadata()](phar.getmetadata) - Returns phar archive meta-data * [Phar::setMetadata()](phar.setmetadata) - Sets phar archive meta-data * [Phar::delMetadata()](phar.delmetadata) - Deletes the global metadata of the phar php SolrQuery::setHighlightFragmenter SolrQuery::setHighlightFragmenter ================================= (PECL solr >= 0.9.2) SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text ### Description ``` public SolrQuery::setHighlightFragmenter(string $fragmenter, string $field_override = ?): SolrQuery ``` Specify a text snippet generator for highlighted text. ### Parameters `fragmenter` The standard fragmenter is gap. Another option is regex, which tries to create fragments that resembles a certain regular expression `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php eio_get_event_stream eio\_get\_event\_stream ======================= (PECL eio >= 0.3.1b) eio\_get\_event\_stream — Get stream representing a variable used in internal communications with libeio ### Description ``` eio_get_event_stream(): mixed ``` **eio\_get\_event\_stream()** acquires stream representing a variable used in internal communications with libeio. Could be used to bind with some event loop provided by other PECL extension, for example libevent. ### Parameters This function has no parameters. ### Return Values **eio\_get\_event\_stream()** returns stream on success; otherwise, **`null`** ### Examples **Example #1 Using eio with libevent** ``` <?php function my_eio_poll($fd, $events, $arg) {     /* Some libevent regulation might go here .. */     if (eio_nreqs()) {         eio_poll();     }     /* .. and here */ } function my_res_cb($d, $r) {     var_dump($r); var_dump($d); } $base = event_base_new(); $event = event_new(); $fd = eio_get_event_stream(); var_dump($fd); eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data"); eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data"); /* some other eio_* calls here ... */ // set event flags event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base)); // set event base  event_base_set($event, $base); // enable event event_add($event); // start event loop event_base_loop($base); /* The same will be available via buffered libevent interface */ ?> ``` The above example will output something similar to: ``` int(3) int(0) string(8) "nop data" int(0) string(10) "mkdir data" ``` php IntlCalendar::getLeastMaximum IntlCalendar::getLeastMaximum ============================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field ### Description Object-oriented style ``` public IntlCalendar::getLeastMaximum(int $field): int|false ``` Procedural style ``` intlcal_get_least_maximum(IntlCalendar $calendar, int $field): int|false ``` Returns the smallest local maximumw for a field. This should be a value smaller or equal to that returned by **IntlCalendar::getActualMaxmimum()**, which is in its turn smaller or equal to that returned by [IntlCalendar::getMaximum()](intlcalendar.getmaximum). ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `field` One of the [IntlCalendar](class.intlcalendar) date/time [field constants](class.intlcalendar#intlcalendar.constants). These are integer values between `0` and **`IntlCalendar::FIELD_COUNT`**. ### Return Values An int representing a field value in the fieldʼs unit or **`false`** on failure. ### Examples **Example #1 Maxima examples** ``` <?php ini_set('date.timezone', 'UTC'); ini_set('intl.default_locale', 'it_IT'); $cal = new IntlGregorianCalendar(2013, 3 /* April */, 6); var_dump(     $cal->getLeastMaximum(IntlCalendar::FIELD_DAY_OF_MONTH),  // 28     $cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH), // 30     $cal->getMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)        // 31 ); ``` The above example will output: ``` int(28) int(30) int(31) ``` ### See Also * [IntlCalendar::getActualMaximum()](intlcalendar.getactualmaximum) - The maximum value for a field, considering the objectʼs current time * [IntlCalendar::getMaximum()](intlcalendar.getmaximum) - Get the global maximum value for a field * [IntlCalendar::getGreatestMinimum()](intlcalendar.getgreatestminimum) - Get the largest local minimum value for a field php SplFixedArray::current SplFixedArray::current ====================== (PHP 5 >= 5.3.0, PHP 7) SplFixedArray::current — Return current array entry ### Description ``` public SplFixedArray::current(): mixed ``` Get the current array element. ### Parameters This function has no parameters. ### Return Values The current element value. ### Errors/Exceptions Throws [RuntimeException](class.runtimeexception) when the internal array pointer points to an invalid index or is out of bounds.
programming_docs
php SplFileInfo::getRealPath SplFileInfo::getRealPath ======================== (PHP 5 >= 5.2.2, PHP 7, PHP 8) SplFileInfo::getRealPath — Gets absolute path to file ### Description ``` public SplFileInfo::getRealPath(): string|false ``` This method expands all symbolic links, resolves relative references and returns the real path to the file. ### Parameters This function has no parameters. ### Return Values Returns the path to the file, or **`false`** if the file does not exist. ### Examples **Example #1 **SplFileInfo::getRealPath()** example** ``` <?php $info = new SplFileInfo('/..//./../../'.__FILE__); var_dump($info->getRealPath()); $info = new SplFileInfo('/tmp'); var_dump($info->getRealPath()); $info = new SplFileInfo('/I/Do/Not/Exist'); var_dump($info->getRealPath()); $info = new SplFileInfo('php://output'); var_dump($info->getRealPath()); $info = new SplFileInfo(""); var_dump($info->getRealPath()); ?> ``` The above example will output something similar to: ``` string(28) "/private/tmp/phptempfile.php" string(12) "/private/tmp" bool(false) bool(false) string(12) "/private/tmp" ``` ### See Also * [SplFileInfo::isLink()](splfileinfo.islink) - Tells if the file is a link * [realpath()](function.realpath) - Returns canonicalized absolute pathname php Locale::filterMatches Locale::filterMatches ===================== locale\_filter\_matches ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Locale::filterMatches -- locale\_filter\_matches — Checks if a language tag filter matches with locale ### Description Object-oriented style ``` public static Locale::filterMatches(string $languageTag, string $locale, bool $canonicalize = false): ?bool ``` Procedural style ``` locale_filter_matches(string $languageTag, string $locale, bool $canonicalize = false): ?bool ``` Checks if a `languageTag` filter matches with `locale` according to RFC 4647's basic filtering algorithm ### Parameters `languageTag` The language tag to check `locale` The language range to check against `canonicalize` If true, the arguments will be converted to canonical form before matching. ### Return Values **`true`** if `locale` matches `languageTag` **`false`** otherwise. Returns **`null`** when the length of `locale` exceeds **`INTL_MAX_LOCALE_LEN`**. ### Examples **Example #1 **locale\_filter\_matches()** example** ``` <?php echo (locale_filter_matches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match"; echo '; '; echo (locale_filter_matches('de-DE_1996','de-DE', false)) ? "Matches" : "Does not match"; ?> ``` **Example #2 OO example** ``` <?php echo (Locale::filterMatches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match"; echo '; '; echo (Locale::filterMatches('de-DE-1996','de-DE', false)) ? "Matches" : "Does not match"; ?> ``` The above example will output: ``` Does not match; Matches ``` ### See Also * [locale\_lookup()](locale.lookup) - Searches the language tag list for the best match to the language php headers_sent headers\_sent ============= (PHP 4, PHP 5, PHP 7, PHP 8) headers\_sent — Checks if or where headers have been sent ### Description ``` headers_sent(string &$filename = null, int &$line = null): bool ``` Checks if or where headers have been sent. You can't add any more header lines using the [header()](function.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](https://www.php.net/manual/en/ref.outcontrol.php). ### Parameters `filename` If the optional `filename` and `line` parameters are set, **headers\_sent()** will put the PHP source file name and line number where output started in the `filename` and `line` variables. `line` The line number where the output started. ### Return Values **headers\_sent()** will return **`false`** if no HTTP headers have already been sent or **`true`** otherwise. ### Examples **Example #1 Examples using **headers\_sent()**** ``` <?php // If no headers are sent, send one if (!headers_sent()) {     header('Location: http://www.example.com/');     exit; } // An example using the optional file and line parameters // Note that $filename and $linenum are passed in for later use. // Do not assign them values beforehand. if (!headers_sent($filename, $linenum)) {     header('Location: http://www.example.com/');     exit; // You would most likely trigger an error here. } else {     echo "Headers already sent in $filename on line $linenum\n" .           "Cannot redirect, for now please click this <a " .           "href=\"http://www.example.com\">link</a> instead\n";     exit; } ?> ``` ### Notes > > **Note**: > > > Headers will only be accessible and output when a SAPI that supports them is in use. > > ### See Also * [ob\_start()](function.ob-start) - Turn on output buffering * [trigger\_error()](function.trigger-error) - Generates a user-level error/warning/notice message * [headers\_list()](function.headers-list) - Returns a list of response headers sent (or ready to send) * [header()](function.header) - Send a raw HTTP header for a more detailed discussion of the matters involved. php fdatasync fdatasync ========= (PHP 8 >= 8.1.0) fdatasync — Synchronizes data (but not meta-data) to the file ### Description ``` fdatasync(resource $stream): bool ``` This function synchronizes `stream` contents to storage media, just like [fsync()](function.fsync) does, but it does not synchronize file meta-data. Note that this function is only effectively different in POSIX systems. In Windows, this function is aliased to [fsync()](function.fsync). ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen) (and not yet closed by [fclose()](function.fclose)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **fdatasync()** example** ``` <?php $file = 'test.txt'; $stream = fopen($file, 'w'); fwrite($stream, 'test data'); fwrite($stream, "\r\n"); fwrite($stream, 'additional data'); fdatasync($stream); fclose($stream); ?> ``` ### See Also * [fflush()](function.fflush) - Flushes the output to a file * [fsync()](function.fsync) - Synchronizes changes to the file (including meta-data) php ReflectionFiber::getFiber ReflectionFiber::getFiber ========================= (PHP 8 >= 8.1.0) ReflectionFiber::getFiber — Get the reflected Fiber instance ### Description ``` public ReflectionFiber::getFiber(): Fiber ``` Returns the [Fiber](class.fiber) instance being reflected. ### Parameters This function has no parameters. ### Return Values The [Fiber](class.fiber) instance being reflected. php snmp_set_oid_numeric_print snmp\_set\_oid\_numeric\_print ============================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) snmp\_set\_oid\_numeric\_print — Alias of [snmp\_set\_oid\_output\_format()](function.snmp-set-oid-output-format) ### Description This function is an alias of: [snmp\_set\_oid\_output\_format()](function.snmp-set-oid-output-format). ### See Also * [snmp\_set\_oid\_output\_format()](function.snmp-set-oid-output-format) - Set the OID output format php IntlCodePointBreakIterator::getLastCodePoint IntlCodePointBreakIterator::getLastCodePoint ============================================ (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator ### Description ``` public IntlCodePointBreakIterator::getLastCodePoint(): int ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php AppendIterator::getInnerIterator AppendIterator::getInnerIterator ================================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) AppendIterator::getInnerIterator — Gets the inner iterator ### Description ``` public AppendIterator::getInnerIterator(): Iterator ``` This method returns the current inner iterator. ### Parameters This function has no parameters. ### Return Values The current inner iterator, or **`null`** if there is not one. ### Examples **Example #1 **AppendIterator::getInnerIterator()** example** ``` <?php $array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara')); $array_b = new RegexIterator($array_a, '/^[ac]/'); $iterator = new AppendIterator; $iterator->append($array_a); $iterator->append($array_b); foreach ($iterator as $current) {     $inner = $iterator->getInnerIterator();     if ($inner instanceOf RegexIterator) {         echo 'Filtered: ';     } else {         echo 'Original: ';     }     echo $current . PHP_EOL; } ?> ``` The above example will output: ``` Original: aardwolf Original: bear Original: capybara Filtered: aardwolf Filtered: capybara ``` ### See Also * [AppendIterator::getIteratorIndex()](appenditerator.getiteratorindex) - Gets an index of iterators php DateTimeImmutable::setDate DateTimeImmutable::setDate ========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) DateTimeImmutable::setDate — Sets the date ### Description ``` public DateTimeImmutable::setDate(int $year, int $month, int $day): DateTimeImmutable ``` Returns a new DateTimeImmutable object with the current date of the DateTimeImmutable object set to the given date. ### Parameters `object` Procedural style only: A [DateTime](class.datetime) object returned by [date\_create()](function.date-create). The function modifies this object. `year` Year of the date. `month` Month of the date. `day` Day of the date. ### Return Values Returns a new [DateTimeImmutable](class.datetimeimmutable) object with the modified data. ### Examples **Example #1 **DateTimeImmutable::setDate()** example** Object-oriented style ``` <?php $date = new DateTimeImmutable(); $newDate = $date->setDate(2001, 2, 3); echo $newDate->format('Y-m-d'); ?> ``` The above examples will output: ``` 2001-02-03 ``` **Example #2 Values exceeding ranges are added to their parent values** ``` <?php $date = new DateTimeImmutable(); $newDate = $date->setDate(2001, 2, 28); echo $newDate->format('Y-m-d') . "\n"; $newDate = $date->setDate(2001, 2, 29); echo $newDate->format('Y-m-d') . "\n"; $newDate = $date->setDate(2001, 14, 3); echo $newDate->format('Y-m-d') . "\n"; ?> ``` The above example will output: ``` 2001-02-28 2001-03-01 2002-02-03 ``` ### See Also * [DateTimeImmutable::setISODate()](datetimeimmutable.setisodate) - Sets the ISO date * [DateTimeImmutable::setTime()](datetimeimmutable.settime) - Sets the time php get_html_translation_table get\_html\_translation\_table ============================= (PHP 4, PHP 5, PHP 7, PHP 8) get\_html\_translation\_table — Returns the translation table used by [htmlspecialchars()](function.htmlspecialchars) and [htmlentities()](function.htmlentities) ### Description ``` get_html_translation_table(int $table = HTML_SPECIALCHARS, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = "UTF-8"): array ``` **get\_html\_translation\_table()** will return the translation table that is used internally for [htmlspecialchars()](function.htmlspecialchars) and [htmlentities()](function.htmlentities). > > **Note**: > > > Special characters can be encoded in several ways. E.g. `"` can be encoded as `&quot;`, `&#34;` or `&#x22`. **get\_html\_translation\_table()** returns only the form used by [htmlspecialchars()](function.htmlspecialchars) and [htmlentities()](function.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_QUOTES | ENT_SUBSTITUTE | 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_SUBSTITUTE`** | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of returning an empty string. | | **`ENT_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 UTF-8. 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](https://www.php.net/manual/en/ini.core.php#ini.default-charset) and current locale (see [nl\_langinfo()](function.nl-langinfo) and [setlocale()](function.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 | | --- | --- | | 8.1.0 | `flags` changed from **`ENT_COMPAT`** to **`ENT_QUOTES`** | **`ENT_SUBSTITUTE`** | **`ENT_HTML401`**. | ### Examples **Example #1 Translation Table Example** ``` <?php var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5)); ?> ``` The above example will output something similar to: ``` array(1510) { [" "]=> string(9) "&NewLine;" ["!"]=> string(6) "&excl;" ["""]=> string(6) "&quot;" ["#"]=> string(5) "&num;" ["$"]=> string(8) "&dollar;" ["%"]=> string(8) "&percnt;" ["&"]=> string(5) "&amp;" ["'"]=> string(6) "&apos;" // ... } ``` ### See Also * [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities * [htmlentities()](function.htmlentities) - Convert all applicable characters to HTML entities * [html\_entity\_decode()](function.html-entity-decode) - Convert HTML entities to their corresponding characters php Yaf_Session::getInstance Yaf\_Session::getInstance ========================= (Yaf >=1.0.0) Yaf\_Session::getInstance — The getInstance purpose ### Description ``` public static Yaf_Session::getInstance(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php PDOStatement::execute PDOStatement::execute ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0) PDOStatement::execute — Executes a prepared statement ### Description ``` public PDOStatement::execute(?array $params = null): bool ``` Execute the [prepared statement](https://www.php.net/manual/en/pdo.prepared-statements.php). If the prepared statement included parameter markers, either: * [PDOStatement::bindParam()](pdostatement.bindparam) and/or [PDOStatement::bindValue()](pdostatement.bindvalue) has to be called to bind either variables or values (respectively) to the parameter markers. Bound variables pass their value as input and receive the output value, if any, of their associated parameter markers * or an array of input-only parameter values has to be passed ### Parameters `params` An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as **`PDO::PARAM_STR`**. Multiple values cannot be bound to a single parameter; for example, it is not allowed to bind two values to a single named parameter in an IN() clause. Binding more values than specified is not possible; if more keys exist in `params` than in the SQL specified in the [PDO::prepare()](pdo.prepare), then the statement will fail and an error is emitted. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Execute a prepared statement with a bound variable and value** ``` <?php /* Execute a prepared statement by binding a variable and value */ $calories = 150; $colour = 'gre'; $sth = $dbh->prepare('SELECT name, colour, calories     FROM fruit     WHERE calories < :calories AND colour LIKE :colour'); $sth->bindParam('calories', $calories, PDO::PARAM_INT); /* Names can be prefixed with colons ":" too (optional) */ $sth->bindValue(':colour', "%$colour%"); $sth->execute(); ?> ``` **Example #2 Execute a prepared statement with an array of named values** ``` <?php /* Execute a prepared statement by passing an array of insert values */ $calories = 150; $colour = 'red'; $sth = $dbh->prepare('SELECT name, colour, calories     FROM fruit     WHERE calories < :calories AND colour = :colour'); $sth->execute(array('calories' => $calories, 'colour' => $colour)); /* Array keys can be prefixed with colons ":" too (optional) */ $sth->execute(array(':calories' => $calories, ':colour' => $colour)); ?> ``` **Example #3 Execute a prepared statement with an array of positional values** ``` <?php /* Execute a prepared statement by passing an array of insert values */ $calories = 150; $colour = 'red'; $sth = $dbh->prepare('SELECT name, colour, calories     FROM fruit     WHERE calories < ? AND colour = ?'); $sth->execute(array($calories, $colour)); ?> ``` **Example #4 Execute a prepared statement with variables bound to positional placeholders** ``` <?php /* Execute a prepared statement by binding PHP variables */ $calories = 150; $colour = 'red'; $sth = $dbh->prepare('SELECT name, colour, calories     FROM fruit     WHERE calories < ? AND colour = ?'); $sth->bindParam(1, $calories, PDO::PARAM_INT); $sth->bindParam(2, $colour, PDO::PARAM_STR, 12); $sth->execute(); ?> ``` **Example #5 Execute a prepared statement using array for IN clause** ``` <?php /* Execute a prepared statement using an array of values for an IN clause */ $params = array(1, 21, 63, 171); /* Create a string for the parameter placeholders filled to the number of params */ $place_holders = implode(',', array_fill(0, count($params), '?')); /*     This prepares the statement with enough unnamed placeholders for every value     in our $params array. The values of the $params array are then bound to the     placeholders in the prepared statement when the statement is executed.     This is not the same thing as using PDOStatement::bindParam() since this     requires a reference to the variable. PDOStatement::execute() only binds     by value instead. */ $sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)"); $sth->execute($params); ?> ``` ### Notes > > **Note**: > > > Some drivers require to [close cursor](pdostatement.closecursor) before executing next statement. > > ### See Also * [PDO::prepare()](pdo.prepare) - Prepares a statement for execution and returns a statement object * [PDOStatement::bindParam()](pdostatement.bindparam) - Binds a parameter to the specified variable name * [PDOStatement::fetch()](pdostatement.fetch) - Fetches the next row from a result set * [PDOStatement::fetchAll()](pdostatement.fetchall) - Fetches the remaining rows from a result set * [PDOStatement::fetchColumn()](pdostatement.fetchcolumn) - Returns a single column from the next row of a result set
programming_docs
php fdf_save fdf\_save ========= (PHP 4, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_save — Save a FDF document ### Description ``` fdf_save(resource $fdf_document, string $filename = ?): bool ``` Saves a FDF document. ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). `filename` If provided, the resulting FDF will be written in this parameter. Otherwise, this function will write the FDF to the default PHP output stream. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [fdf\_close()](function.fdf-close) - Close an FDF document * [fdf\_create()](function.fdf-create) - Create a new FDF document * [fdf\_save\_string()](function.fdf-save-string) - Returns the FDF document as a string php enchant_dict_is_in_session enchant\_dict\_is\_in\_session ============================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 ) enchant\_dict\_is\_in\_session — Alias of [enchant\_dict\_is\_added()](function.enchant-dict-is-added) **Warning**This alias is *DEPRECATED* as of PHP 8.0.0. ### Description This function is an alias of: [enchant\_dict\_is\_added()](function.enchant-dict-is-added). php Yar_Server::__construct Yar\_Server::\_\_construct ========================== (PECL yar >= 1.0.0) Yar\_Server::\_\_construct — Register a server ### Description ``` final public Yar_Server::__construct(Object $obj) ``` Set up a Yar HTTP RPC Server, All the public methods of $obj will be register as a RPC service. ### Parameters `obj` An Object, all public methods of its will be registered as RPC services. ### Return Values An instance of [Yar\_Server](class.yar-server). ### Examples **Example #1 **Yar\_Server::\_\_construct()** example** ``` <?php class API {     /**      * the doc info will be generated automatically into service info page.      * @params       * @return      */     public function some_method($parameter, $option = "foo") {          return "some_method";     }     protected function client_can_not_see() {     } } $service = new Yar_Server(new API()); $service->handle(); ?> ``` The above example will output something similar to: ### See Also * [Yar\_Server::handle()](yar-server.handle) - Start RPC Server php ldap_read ldap\_read ========== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_read — Read an entry ### Description ``` ldap_read( LDAP\Connection|array $ldap, array|string $base, array|string $filter, array $attributes = [], int $attributes_only = 0, int $sizelimit = -1, int $timelimit = -1, int $deref = LDAP_DEREF_NEVER, ?array $controls = null ): LDAP\Result|array|false ``` Performs the search for a specified `filter` on the directory with the scope **`LDAP_SCOPE_BASE`**. So it is equivalent to reading an entry from the directory. It is also possible to perform parallel searches. In this case, the first argument should be an array of [LDAP\Connection](class.ldap-connection) instances, rather than a single one. If the searches should not all use the same base DN and filter, an array of base DNs and/or an array of filters can be passed as arguments instead. These arrays must be of the same size as the [LDAP\Connection](class.ldap-connection) instances array, since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of [LDAP\Result](class.ldap-result) instances is returned, except in case of error, when the return value will be **`false`**. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `base` The base DN for the directory. `filter` An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of `objectClass=*`. If you know which entry types are used on the directory server, you might use an appropriate filter such as `objectClass=inetOrgPerson`. `attributes` An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested. Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice. `attributes_only` Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour. `sizelimit` Enables you to limit the count of entries fetched. Setting this to 0 means no limit. > > **Note**: > > > This parameter can NOT override server-side preset sizelimit. You can set it lower though. > > Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries. > > `timelimit` Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. > > **Note**: > > > This parameter can NOT override server-side preset timelimit. You can set it lower though. > > `deref` Specifies how aliases should be handled during the search. It can be one of the following: * **`LDAP_DEREF_NEVER`** - (default) aliases are never dereferenced. * **`LDAP_DEREF_SEARCHING`** - aliases should be dereferenced during the search but not when locating the base object of the search. * **`LDAP_DEREF_FINDING`** - aliases should be dereferenced when locating the base object but not during the search. * **`LDAP_DEREF_ALWAYS`** - aliases should be dereferenced always. `controls` Array of [LDAP Controls](https://www.php.net/manual/en/ldap.controls.php) to send with the request. ### Return Values Returns an [LDAP\Result](class.ldap-result) instance, an array of [LDAP\Result](class.ldap-result) instances, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | Returns an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was returned. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | | 4.0.5 | Parallel searches support was added. See [ldap\_search()](function.ldap-search) for details. | | 7.3.0 | Support for `controls` added | php Error::__construct Error::\_\_construct ==================== (PHP 7, PHP 8) Error::\_\_construct — Construct the error object ### Description public **Error::\_\_construct**(string `$message` = "", int `$code` = 0, ?[Throwable](class.throwable) `$previous` = **`null`**) Constructs the Error. ### Parameters `message` The error message. `code` The error code. `previous` The previous throwable used for the exception chaining. ### Notes > > **Note**: > > > The `message` is *NOT* binary safe. > > php xattr_remove xattr\_remove ============= (PECL xattr >= 0.9.0) xattr\_remove — Remove an extended attribute ### Description ``` xattr_remove(string $filename, string $name, int $flags = 0): bool ``` This function removes an extended attribute of a file. Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter. ### Parameters `filename` The file from which we remove the attribute. `name` The name of the attribute to remove. `flags` **Supported xattr flags**| **`XATTR_DONTFOLLOW`** | Do not follow the symbolic link but operate on symbolic link itself. | | **`XATTR_ROOT`** | Set attribute in root (trusted) namespace. Requires root privileges. | ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Removes all extended attributes of a file** ``` <?php $file = 'some_file'; $attributes = xattr_list($file); foreach ($attributes as $attr_name) {     xattr_remove($file, $attr_name); } ?> ``` ### See Also * [xattr\_list()](function.xattr-list) - Get a list of extended attributes * [xattr\_set()](function.xattr-set) - Set an extended attribute * [xattr\_get()](function.xattr-get) - Get an extended attribute php FilterIterator::rewind FilterIterator::rewind ====================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) FilterIterator::rewind — Rewind the iterator ### Description ``` public FilterIterator::rewind(): void ``` **Warning**This function is currently not documented; only its argument list is available. Rewind the iterator. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [FilterIterator::current()](filteriterator.current) - Get the current element value * [FilterIterator::key()](filteriterator.key) - Get the current key * [FilterIterator::next()](filteriterator.next) - Move the iterator forward php preg_split preg\_split =========== (PHP 4, PHP 5, PHP 7, PHP 8) preg\_split — Split string by a regular expression ### Description ``` preg_split( string $pattern, string $subject, int $limit = -1, int $flags = 0 ): array|false ``` Split the given string by a regular expression. ### Parameters `pattern` The pattern to search for, as a string. `subject` The input string. `limit` If specified, then only substrings up to `limit` are returned with the rest of the string being placed in the last substring. A `limit` of -1 or 0 means "no limit". `flags` `flags` can be any combination of the following flags (combined with the `|` bitwise operator): **`PREG_SPLIT_NO_EMPTY`** If this flag is set, only non-empty pieces will be returned by **preg\_split()**. **`PREG_SPLIT_DELIM_CAPTURE`** If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. **`PREG_SPLIT_OFFSET_CAPTURE`** If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset `0` and its string offset into `subject` at offset `1`. ### Return Values Returns an array containing substrings of `subject` split along boundaries matched by `pattern`, or **`false`** on failure. ### Errors/Exceptions If the regex pattern passed does not compile to a valid regex, an **`E_WARNING`** is emitted. ### Examples **Example #1 **preg\_split()** example : Get the parts of a search string** ``` <?php // split the phrase by any number of commas or space characters, // which include " ", \r, \t, \n and \f $keywords = preg_split("/[\s,]+/", "hypertext language, programming"); print_r($keywords); ?> ``` The above example will output: ``` Array ( [0] => hypertext [1] => language [2] => programming ) ``` **Example #2 Splitting a string into component characters** ``` <?php $str = 'string'; $chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); print_r($chars); ?> ``` The above example will output: ``` Array ( [0] => s [1] => t [2] => r [3] => i [4] => n [5] => g ) ``` **Example #3 Splitting a string into matches and their offsets** ``` <?php $str = 'hypertext language programming'; $chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); print_r($chars); ?> ``` The above example will output: ``` Array ( [0] => Array ( [0] => hypertext [1] => 0 ) [1] => Array ( [0] => language [1] => 10 ) [2] => Array ( [0] => programming [1] => 19 ) ) ``` ### Notes **Tip** If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like [explode()](function.explode) or [str\_split()](function.str-split). **Tip** If matching fails, an array with a single element containing the input string will be returned. ### See Also * [PCRE Patterns](https://www.php.net/manual/en/pcre.pattern.php) * [preg\_quote()](function.preg-quote) - Quote regular expression characters * [implode()](function.implode) - Join array elements with a string * [preg\_match()](function.preg-match) - Perform a regular expression match * [preg\_match\_all()](function.preg-match-all) - Perform a global regular expression match * [preg\_replace()](function.preg-replace) - Perform a regular expression search and replace * [preg\_last\_error()](function.preg-last-error) - Returns the error code of the last PCRE regex execution php sodium_crypto_secretstream_xchacha20poly1305_keygen sodium\_crypto\_secretstream\_xchacha20poly1305\_keygen ======================================================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_secretstream\_xchacha20poly1305\_keygen — Generate a random secretstream key. ### Description ``` sodium_crypto_secretstream_xchacha20poly1305_keygen(): string ``` Generate a random secretstream key. ### Parameters This function has no parameters. ### Return Values Returns a string of random bytes. php SolrCollapseFunction::getNullPolicy SolrCollapseFunction::getNullPolicy =================================== (PECL solr >= 2.2.0) SolrCollapseFunction::getNullPolicy — Returns null policy ### Description ``` public SolrCollapseFunction::getNullPolicy(): string ``` Returns null policy used or null ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrCollapseFunction::setNullPolicy()](solrcollapsefunction.setnullpolicy) - Sets the NULL Policy php Imagick::getImageDistortion Imagick::getImageDistortion =========================== (PECL imagick 2, PECL imagick 3) Imagick::getImageDistortion — Compares an image to a reconstructed image ### Description ``` public Imagick::getImageDistortion(MagickWand $reference, int $metric): float ``` Compares an image to a reconstructed image and returns the specified distortion metric. ### Parameters `reference` Imagick object to compare to. `metric` One of the [metric type constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.metric). ### Return Values Returns the distortion metric used on the image (or the best guess thereof). ### Errors/Exceptions Throws ImagickException on error. php msg_send msg\_send ========= (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) msg\_send — Send a message to a message queue ### Description ``` msg_send( SysvMessageQueue $queue, int $message_type, string|int|float|bool $message, bool $serialize = true, bool $blocking = true, int &$error_code = null ): bool ``` **msg\_send()** sends a `message` of type `message_type` (which MUST be greater than 0) to the message queue specified by `queue`. ### Parameters `queue` The message queue. `message_type` The type of the message (MUST be greater than 0) `message` The body of the message. > > **Note**: > > > If `serialize` set to **`false`** is supplied, MUST be of type: string, int, float or bool. In other case a warning will be issued. > > `serialize` The optional `serialize` controls how the `message` is sent. `serialize` defaults to **`true`** which means that the `message` is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client. `blocking` If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional `blocking` parameter to **`false`**, in which case **msg\_send()** will immediately return **`false`** if the message is too big for the queue, and set the optional `error_code` to **`MSG_EAGAIN`**, indicating that you should try to send your message again a little later on. `error_code` If the function fails, the optional errorcode will be set to the value of the system errno variable. ### Return Values Returns **`true`** on success or **`false`** on failure. Upon successful completion the message queue data structure is updated as follows: `msg_lspid` is set to the process-ID of the calling process, `msg_qnum` is incremented by 1 and `msg_stime` is set to the current time. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `queue` expects a [SysvMessageQueue](class.sysvmessagequeue) instance now; previously, a resource was expected. | ### See Also * [msg\_remove\_queue()](function.msg-remove-queue) - Destroy a message queue * [msg\_receive()](function.msg-receive) - Receive a message from a message queue * [msg\_stat\_queue()](function.msg-stat-queue) - Returns information from the message queue data structure * [msg\_set\_queue()](function.msg-set-queue) - Set information in the message queue data structure php gnupg_clearencryptkeys gnupg\_clearencryptkeys ======================= (PECL gnupg >= 0.5) gnupg\_clearencryptkeys — Removes all keys which were set for encryption before ### Description ``` gnupg_clearencryptkeys(resource $identifier): bool ``` ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Procedural **gnupg\_clearencryptkeys()** example** ``` <?php $res = gnupg_init(); gnupg_clearencryptkeys($res); ?> ``` **Example #2 OO **gnupg\_clearencryptkeys()** example** ``` <?php $gpg = new gnupg(); $gpg->clearencryptkeys(); ?> ``` php posix_isatty posix\_isatty ============= (PHP 4, PHP 5, PHP 7, PHP 8) posix\_isatty — Determine if a file descriptor is an interactive terminal ### Description ``` posix_isatty(resource|int $file_descriptor): bool ``` Determines if the file descriptor `file_descriptor` refers to a valid terminal type device. ### Parameters `fd` The file descriptor, which is expected to be either a file resource or an int. An int will be assumed to be a file descriptor that can be passed directly to the underlying system call. In almost all cases, you will want to provide a file resource. ### Return Values Returns **`true`** if `file_descriptor` is an open descriptor connected to a terminal and **`false`** otherwise. ### See Also * [posix\_ttyname()](function.posix-ttyname) - Determine terminal device name * [stream\_isatty()](function.stream-isatty) - Check if a stream is a TTY php DOMDocument::getElementsByTagName DOMDocument::getElementsByTagName ================================= (PHP 5, PHP 7, PHP 8) DOMDocument::getElementsByTagName — Searches for all elements with given local tag name ### Description ``` public DOMDocument::getElementsByTagName(string $qualifiedName): DOMNodeList ``` This function returns a new instance of class [DOMNodeList](class.domnodelist) containing all the elements with a given local tag name. ### Parameters `qualifiedName` The local name (without namespace) of the tag to match on. The special value `*` matches all tags. ### Return Values A new [DOMNodeList](class.domnodelist) object containing all the matched elements. ### Examples **Example #1 Basic Usage Example** ``` <?php $xml = <<< XML <?xml version="1.0" encoding="utf-8"?> <books>  <book>Patterns of Enterprise Application Architecture</book>  <book>Design Patterns: Elements of Reusable Software Design</book>  <book>Clean Code</book> </books> XML; $dom = new DOMDocument; $dom->loadXML($xml); $books = $dom->getElementsByTagName('book'); foreach ($books as $book) {     echo $book->nodeValue, PHP_EOL; } ?> ``` The above example will output: ``` Patterns of Enterprise Application Architecture Design Patterns: Elements of Reusable Software Design Clean Code ``` ### See Also * [DOMDocument::getElementsByTagNameNS()](domdocument.getelementsbytagnamens) - Searches for all elements with given tag name in specified namespace
programming_docs
php Yaf_Session::offsetExists Yaf\_Session::offsetExists ========================== (Yaf >=1.0.0) Yaf\_Session::offsetExists — The offsetExists purpose ### Description ``` public Yaf_Session::offsetExists(string $name): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php IntlChar::isUWhiteSpace IntlChar::isUWhiteSpace ======================= (PHP 7, PHP 8) IntlChar::isUWhiteSpace — Check if code point has the White\_Space Unicode property ### Description ``` public static IntlChar::isUWhiteSpace(int|string $codepoint): ?bool ``` Check if a code point has the White\_Space Unicode property. This is the same as `IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_WHITE_SPACE)` > > **Note**: > > > This is different from both [IntlChar::isspace()](intlchar.isspace) and [IntlChar::isWhitespace()](intlchar.iswhitespace). > > ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` has the White\_Space Unicode property, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isUWhiteSpace("A")); var_dump(IntlChar::isUWhiteSpace(" ")); var_dump(IntlChar::isUWhiteSpace("\n")); var_dump(IntlChar::isUWhiteSpace("\t")); var_dump(IntlChar::isUWhiteSpace("\u{00A0}")); ?> ``` The above example will output: ``` bool(false) bool(true) bool(true) bool(true) bool(true) ``` ### See Also * [IntlChar::isspace()](intlchar.isspace) - Check if code point is a space character * [IntlChar::isWhitespace()](intlchar.iswhitespace) - Check if code point is a whitespace character according to ICU * [IntlChar::isJavaSpaceChar()](intlchar.isjavaspacechar) - Check if code point is a space character according to Java * [IntlChar::hasBinaryProperty()](intlchar.hasbinaryproperty) - Check a binary Unicode property for a code point * **`IntlChar::PROPERTY_WHITE_SPACE`** php ctype_upper ctype\_upper ============ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ctype\_upper — Check for uppercase character(s) ### Description ``` ctype_upper(mixed $text): bool ``` Checks if all of the characters in the provided string, `text`, are uppercase characters. ### Parameters `text` The tested string. > > **Note**: > > > If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer. > > > **Warning** As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to [chr()](function.chr) should be made. ### Return Values Returns **`true`** if every character in `text` is an uppercase letter in the current locale. When called with an empty string the result will always be **`false`**. ### Examples **Example #1 A **ctype\_upper()** example (using the default locale)** ``` <?php $strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm'); foreach ($strings as $testcase) {     if (ctype_upper($testcase)) {         echo "The string $testcase consists of all uppercase letters.\n";     } else {         echo "The string $testcase does not consist of all uppercase letters.\n";     } } ?> ``` The above example will output: ``` The string AKLWC139 does not consist of all uppercase letters. The string LMNSDO consists of all uppercase letters. The string akwSKWsm does not consist of all uppercase letters. ``` ### See Also * [ctype\_alpha()](function.ctype-alpha) - Check for alphabetic character(s) * [ctype\_lower()](function.ctype-lower) - Check for lowercase character(s) * [setlocale()](function.setlocale) - Set locale information php ibase_query ibase\_query ============ (PHP 5, PHP 7 < 7.4.0) ibase\_query — Execute a query on an InterBase database ### Description ``` ibase_query(resource $link_identifier = ?, string $query, int $bind_args = ?): resource ``` Performs a query on an InterBase database. ### Parameters `link_identifier` An InterBase link identifier. If omitted, the last opened link is assumed. `query` An InterBase query. `bind_args` ### Return Values If the query raises an error, returns **`false`**. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns **`true`**. > > **Note**: > > > In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return **`true`** for these statements if the query succeeded without affecting any rows. > > ### Errors/Exceptions If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after **ibase\_query()** you must set the character set (i.e. ISO8859\_1 or your current character set). ### Examples **Example #1 **ibase\_query()** example** ``` <?php $host = 'localhost:/path/to/your.gdb'; $dbh = ibase_connect($host, $username, $password); $stmt = 'SELECT * FROM tblname'; $sth = ibase_query($dbh, $stmt) or die(ibase_errmsg()); ?> ``` ### See Also * [ibase\_errmsg()](function.ibase-errmsg) - Return error messages * [ibase\_fetch\_row()](function.ibase-fetch-row) - Fetch a row from an InterBase database * [ibase\_fetch\_object()](function.ibase-fetch-object) - Get an object from a InterBase database * [ibase\_free\_result()](function.ibase-free-result) - Free a result set php Ds\Vector::reduce Ds\Vector::reduce ================= (PECL ds >= 1.0.0) Ds\Vector::reduce — Reduces the vector to a single value using a callback function ### Description ``` public Ds\Vector::reduce(callable $callback, mixed $initial = ?): mixed ``` Reduces the vector to a single value using a callback function. ### Parameters `callback` ``` callback(mixed $carry, mixed $value): mixed ``` `carry` The return value of the previous callback, or `initial` if it's the first iteration. `value` The value of the current iteration. `initial` The initial value of the carry value. Can be **`null`**. ### Return Values The return value of the final callback. ### Examples **Example #1 **Ds\Vector::reduce()** with initial value example** ``` <?php $vector = new \Ds\Vector([1, 2, 3]); $callback = function($carry, $value) {     return $carry * $value; }; var_dump($vector->reduce($callback, 5)); // Iterations: // // $carry = $initial = 5 // // $carry = $carry * 1 =  5 // $carry = $carry * 2 = 10 // $carry = $carry * 3 = 30 ?> ``` The above example will output something similar to: ``` int(30) ``` **Example #2 **Ds\Vector::reduce()** without an initial value example** ``` <?php $vector = new \Ds\Vector([1, 2, 3]); var_dump($vector->reduce(function($carry, $value) {     return $carry + $value + 5; })); // Iterations: // // $carry = $initial = null // // $carry = $carry + 1 + 5 =  6 // $carry = $carry + 2 + 5 = 13 // $carry = $carry + 3 + 5 = 21 ?> ``` The above example will output something similar to: ``` int(21) ``` php array_uintersect_uassoc array\_uintersect\_uassoc ========================= (PHP 5, PHP 7, PHP 8) array\_uintersect\_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions ### Description ``` array_uintersect_uassoc( array $array1, array ...$arrays, callable $value_compare_func, callable $key_compare_func ): array ``` Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions. ### Parameters `array1` The first array. `arrays` Further arrays. `value_compare_func` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` `key_compare_func` Key comparison callback function. ### Return Values Returns an array containing all the values of `array1` that are present in all the arguments. ### Examples **Example #1 **array\_uintersect\_uassoc()** example** ``` <?php $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp")); ?> ``` The above example will output: ``` Array ( [a] => green [b] => brown ) ``` ### See Also * [array\_uintersect()](function.array-uintersect) - Computes the intersection of arrays, compares data by a callback function * [array\_intersect\_assoc()](function.array-intersect-assoc) - Computes the intersection of arrays with additional index check * [array\_intersect\_uassoc()](function.array-intersect-uassoc) - Computes the intersection of arrays with additional index check, compares indexes by a callback function * [array\_uintersect\_assoc()](function.array-uintersect-assoc) - Computes the intersection of arrays with additional index check, compares data by a callback function php imap_qprint imap\_qprint ============ (PHP 4, PHP 5, PHP 7, PHP 8) imap\_qprint — Convert a quoted-printable string to an 8 bit string ### Description ``` imap_qprint(string $string): string|false ``` Convert a quoted-printable string to an 8 bit string according to [» RFC2045](http://www.faqs.org/rfcs/rfc2045), section 6.7. ### Parameters `string` A quoted-printable string ### Return Values Returns an 8 bits string, or **`false`** on failure. ### See Also * [imap\_8bit()](function.imap-8bit) - Convert an 8bit string to a quoted-printable string php EventBuffer::lock EventBuffer::lock ================= (PECL event >= 1.2.6-beta) EventBuffer::lock — Acquires a lock on buffer ### Description ``` public EventBuffer::lock(): void ``` Acquires a lock on buffer. Can be used in pair with [EventBuffer::unlock()](eventbuffer.unlock) to make a set of operations atomic, i.e. thread-safe. Note, it is not needed to lock buffers for *individual* operations. When locking is enabled(see [EventBuffer::enableLocking()](eventbuffer.enablelocking) ), individual operations on event buffers are already atomic. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [EventBuffer::unlock()](eventbuffer.unlock) - Releases lock acquired by EventBuffer::lock php ceil ceil ==== (PHP 4, PHP 5, PHP 7, PHP 8) ceil — Round fractions up ### Description ``` ceil(int|float $num): float ``` Returns the next highest integer value by rounding up `num` if necessary. ### Parameters `num` The value to round ### Return Values `num` rounded up to the next highest integer. The return value of **ceil()** is still of type float as the value range of float is usually bigger than that of int. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `num` no longer accepts internal objects which support numeric conversion. | ### Examples **Example #1 **ceil()** example** ``` <?php echo ceil(4.3);    // 5 echo ceil(9.999);  // 10 echo ceil(-3.14);  // -3 ?> ``` ### See Also * [floor()](function.floor) - Round fractions down * [round()](function.round) - Rounds a float php imagefilledarc imagefilledarc ============== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) imagefilledarc — Draw a partial arc and fill it ### Description ``` imagefilledarc( GdImage $image, int $center_x, int $center_y, int $width, int $height, int $start_angle, int $end_angle, int $color, int $style ): bool ``` Draws a partial arc centered at the specified coordinate in the given `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `center_x` x-coordinate of the center. `center_y` y-coordinate of the center. `width` The arc width. `height` The arc height. `start_angle` The arc start angle, in degrees. `end_angle` The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise. `color` A color identifier created with [imagecolorallocate()](function.imagecolorallocate). `style` A bitwise OR of the following possibilities: 1. **`IMG_ARC_PIE`** 2. **`IMG_ARC_CHORD`** 3. **`IMG_ARC_NOFILL`** 4. **`IMG_ARC_EDGED`** **`IMG_ARC_PIE`** and **`IMG_ARC_CHORD`** are mutually exclusive; **`IMG_ARC_CHORD`** just connects the starting and ending angles with a straight line, while **`IMG_ARC_PIE`** produces a rounded edge. **`IMG_ARC_NOFILL`** indicates that the arc or chord should be outlined, not filled. **`IMG_ARC_EDGED`**, used together with **`IMG_ARC_NOFILL`**, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Creating a 3D looking pie** ``` <?php // create image $image = imagecreatetruecolor(100, 100); // allocate some colors $white    = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); $gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0); $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90); $navy     = imagecolorallocate($image, 0x00, 0x00, 0x80); $darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50); $red      = imagecolorallocate($image, 0xFF, 0x00, 0x00); $darkred  = imagecolorallocate($image, 0x90, 0x00, 0x00); // make the 3D effect for ($i = 60; $i > 50; $i--) {    imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);    imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);    imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE); } imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE); imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE); imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE); // flush image header('Content-type: image/png'); imagepng($image); imagedestroy($image); ?> ``` The above example will output something similar to: php fgets fgets ===== (PHP 4, PHP 5, PHP 7, PHP 8) fgets — Gets line from file pointer ### Description ``` fgets(resource $stream, ?int $length = null): string|false ``` Gets a line from file pointer. ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen) (and not yet closed by [fclose()](function.fclose)). `length` Reading ends when `length` - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line. ### Return Values Returns a string of up to `length` - 1 bytes read from the file pointed to by `stream`. If there is no more data to read in the file pointer, then **`false`** is returned. If an error occurs, **`false`** is returned. ### Examples **Example #1 Reading a file line by line** ``` <?php $fp = @fopen("/tmp/inputfile.txt", "r"); if ($fp) {     while (($buffer = fgets($fp, 4096)) !== false) {         echo $buffer;     }     if (!feof($fp)) {         echo "Error: unexpected fgets() fail\n";     }     fclose($fp); } ?> ``` ### Notes > **Note**: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the [auto\_detect\_line\_endings](https://www.php.net/manual/en/filesystem.configuration.php#ini.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()](function.fgetss) - Gets line from file pointer and strip HTML tags * [fread()](function.fread) - Binary-safe file read * [fgetc()](function.fgetc) - Gets character from file pointer * [stream\_get\_line()](function.stream-get-line) - Gets line from stream resource up to a given delimiter * [fopen()](function.fopen) - Opens file or URL * [popen()](function.popen) - Opens process file pointer * [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection * [stream\_set\_timeout()](function.stream-set-timeout) - Set timeout period on a stream php ReflectionFunctionAbstract::getNumberOfParameters ReflectionFunctionAbstract::getNumberOfParameters ================================================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters ### Description ``` public ReflectionFunctionAbstract::getNumberOfParameters(): int ``` Get the number of parameters that a function defines, both optional and required. ### Parameters This function has no parameters. ### Return Values The number of parameters. ### See Also * [ReflectionFunctionAbstract::getNumberOfRequiredParameters()](reflectionfunctionabstract.getnumberofrequiredparameters) - Gets number of required parameters * [func\_num\_args()](function.func-num-args) - Returns the number of arguments passed to the function php ImagickDraw::getStrokeMiterLimit ImagickDraw::getStrokeMiterLimit ================================ (PECL imagick 2, PECL imagick 3) ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit ### Description ``` public ImagickDraw::getStrokeMiterLimit(): int ``` **Warning**This function is currently not documented; only its argument list is available. Returns the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The 'miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'. ### Return Values Returns an int describing the miter limit and 0 if no miter limit is set. php odbc_execute odbc\_execute ============= (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_execute — Execute a prepared statement ### Description ``` odbc_execute(resource $statement, array $params = []): bool ``` Executes a statement prepared with [odbc\_prepare()](function.odbc-prepare). ### Parameters `statement` The result id resource, from [odbc\_prepare()](function.odbc-prepare). `params` Parameters in `params` will be substituted for placeholders in the prepared statement in order. Elements of this array will be converted to strings by calling this function. Any parameters in `params` which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder. If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with [odbc\_exec()](function.odbc-exec)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **odbc\_execute()** and [odbc\_prepare()](function.odbc-prepare) example** In the following code, $success will only be **`true`** if all three parameters to myproc are IN parameters: ``` <?php $a = 1; $b = 2; $c = 3; $stmt    = odbc_prepare($conn, 'CALL myproc(?,?,?)'); $success = odbc_execute($stmt, array($a, $b, $c)); ?> ``` If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, [oci8](https://www.php.net/manual/en/ref.oci8.php) for Oracle). ### See Also * [odbc\_prepare()](function.odbc-prepare) - Prepares a statement for execution
programming_docs
php htmlspecialchars htmlspecialchars ================ (PHP 4, PHP 5, PHP 7, PHP 8) htmlspecialchars — Convert special characters to HTML entities ### Description ``` htmlspecialchars( string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true ): string ``` Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use [htmlentities()](function.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()](function.htmlentities) (which only encodes substrings that have named entity equivalents) may be insufficient. You may have to use [mb\_encode\_numericentity()](function.mb-encode-numericentity) instead. **Performed translations**| Character | Replacement | | --- | --- | | `&` (ampersand) | `&amp;` | | `"` (double quote) | `&quot;`, unless **`ENT_NOQUOTES`** is set | | `'` (single quote) | `&#039;` (for **`ENT_HTML401`**) or `&apos;` (for **`ENT_XML1`**, **`ENT_XHTML`** or **`ENT_HTML5`**), but only when **`ENT_QUOTES`** is set | | `<` (less than) | `&lt;` | | `>` (greater than) | `&gt;` | ### Parameters `string` The string being converted. `flags` A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is `ENT_QUOTES | ENT_SUBSTITUTE | 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](http://unicode.org/reports/tr36/#Deletion_of_Noncharacters). | | **`ENT_SUBSTITUTE`** | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of returning an empty string. | | **`ENT_DISALLOWED`** | Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content. | | **`ENT_HTML401`** | Handle code as HTML 4.01. | | **`ENT_XML1`** | Handle code as XML 1. | | **`ENT_XHTML`** | Handle code as XHTML. | | **`ENT_HTML5`** | Handle code as HTML 5. | `encoding` An optional argument defining the encoding used when converting characters. If omitted, `encoding` defaults to the value of the [default\_charset](https://www.php.net/manual/en/ini.core.php#ini.default-charset) configuration option. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the [default\_charset](https://www.php.net/manual/en/ini.core.php#ini.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](https://www.php.net/manual/en/ini.core.php#ini.default-charset) and current locale (see [nl\_langinfo()](function.nl-langinfo) and [setlocale()](function.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 | | --- | --- | | 8.1.0 | `flags` changed from **`ENT_COMPAT`** to **`ENT_QUOTES`** | **`ENT_SUBSTITUTE`** | **`ENT_HTML401`**. | ### Examples **Example #1 **htmlspecialchars()** example** ``` <?php $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt; ?> ``` ### Notes > > **Note**: > > > Note that this function does not translate anything beyond what is listed above. For full entity translation, see [htmlentities()](function.htmlentities). > > > > **Note**: > > > In case of an ambiguous `flags` value, the following rules apply: > > > * When neither of **`ENT_COMPAT`**, **`ENT_QUOTES`**, **`ENT_NOQUOTES`** is present, the default is **`ENT_NOQUOTES`**. > * When more than one of **`ENT_COMPAT`**, **`ENT_QUOTES`**, **`ENT_NOQUOTES`** is present, **`ENT_QUOTES`** takes the highest precedence, followed by **`ENT_COMPAT`**. > * When neither of **`ENT_HTML401`**, **`ENT_HTML5`**, **`ENT_XHTML`**, **`ENT_XML1`** is present, the default is **`ENT_HTML401`**. > * When more than one of **`ENT_HTML401`**, **`ENT_HTML5`**, **`ENT_XHTML`**, **`ENT_XML1`** is present, **`ENT_HTML5`** takes the highest precedence, followed by **`ENT_XHTML`**, **`ENT_XML1`** and **`ENT_HTML401`**. > * When more than one of **`ENT_DISALLOWED`**, **`ENT_IGNORE`**, **`ENT_SUBSTITUTE`** are present, **`ENT_IGNORE`** takes the highest precedence, followed by **`ENT_SUBSTITUTE`**. > > ### See Also * [get\_html\_translation\_table()](function.get-html-translation-table) - Returns the translation table used by htmlspecialchars and htmlentities * [htmlspecialchars\_decode()](function.htmlspecialchars-decode) - Convert special HTML entities back to characters * [strip\_tags()](function.strip-tags) - Strip HTML and PHP tags from a string * [htmlentities()](function.htmlentities) - Convert all applicable characters to HTML entities * [nl2br()](function.nl2br) - Inserts HTML line breaks before all newlines in a string php None Traits ------ Enumerations may leverage traits, which will behave the same as on classes. The caveat is that traits `use`d in an enum must not contain properties. They may only include methods and static methods. A trait with properties will result in a fatal error. ``` <?php interface Colorful {     public function color(): string; } trait Rectangle {     public function shape(): string {         return "Rectangle";     } } enum Suit implements Colorful {     use Rectangle;     case Hearts;     case Diamonds;     case Clubs;     case Spades;     public function color(): string     {         return match($this) {             Suit::Hearts, Suit::Diamonds => 'Red',             Suit::Clubs, Suit::Spades => 'Black',         };     } } ?> ``` php ReflectionParameter::isPassedByReference ReflectionParameter::isPassedByReference ======================================== (PHP 5, PHP 7, PHP 8) ReflectionParameter::isPassedByReference — Checks if passed by reference ### Description ``` public ReflectionParameter::isPassedByReference(): bool ``` Checks if the parameter is passed in by reference. ### Parameters This function has no parameters. ### Return Values **`true`** if the parameter is passed in by reference, otherwise **`false`** ### See Also * [ReflectionParameter::getName()](reflectionparameter.getname) - Gets parameter name php imap_expunge imap\_expunge ============= (PHP 4, PHP 5, PHP 7, PHP 8) imap\_expunge — Delete all messages marked for deletion ### Description ``` imap_expunge(IMAP\Connection $imap): bool ``` Deletes all the messages marked for deletion by [imap\_delete()](function.imap-delete), [imap\_mail\_move()](function.imap-mail-move), or [imap\_setflag\_full()](function.imap-setflag-full). ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. ### Return Values Returns **`true`**. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | php sodium_crypto_pwhash sodium\_crypto\_pwhash ====================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_pwhash — Derive a key from a password, using Argon2 ### Description ``` sodium_crypto_pwhash( int $length, string $password, string $salt, int $opslimit, int $memlimit, int $algo = SODIUM_CRYPTO_PWHASH_ALG_DEFAULT ): string ``` This function provides low-level access to libsodium's crypto\_pwhash key derivation function. Unless you have specific reason to use this function, you should use [sodium\_crypto\_pwhash\_str()](function.sodium-crypto-pwhash-str) or [password\_hash()](function.password-hash) functions instead. A common reason to use this particular function is to derive the seeds for cryptographic keys from a password and salt, and then use these seeds to generate the actual keys needed for some purpose (e.g. [sodium\_crypto\_sign\_detached()](function.sodium-crypto-sign-detached)). ### Parameters `length` int; The length of the password hash to generate, in bytes. `password` string; The password to generate a hash for. `salt` A salt to add to the password before hashing. The salt should be unpredictable, ideally generated from a good random number source such as [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php), and have a length of at least **`SODIUM_CRYPTO_PWHASH_SALTBYTES`** bytes. `opslimit` Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are some constants available to set the operations limit to appropriate values depending on intended use, in order of strength: **`SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE`**, **`SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE`** and **`SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE`**. `memlimit` The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: **`SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE`**, **`SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE`**, and **`SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE`**. Typically these should be paired with the matching `opslimit` values. `algo` int A number indicating the hash algorithm to use. By default **`SODIUM_CRYPTO_PWHASH_ALG_DEFAULT`** (the currently recommended algorithm, which can change from one version of libsodium to another), or explicitly using **`SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13`**, representing the Argon2id algorithm version 1.3. ### Return Values Returns the derived key. The return value is a binary string of the hash, not an ASCII-encoded representation, and does not contain additional information about the parameters used to create the hash, so you will need to keep that information if you are ever going to verify the password in future. Use [sodium\_crypto\_pwhash\_str()](function.sodium-crypto-pwhash-str) to avoid needing to do all that. ### Examples **Example #1 **sodium\_crypto\_pwhash()** example** ``` <?php //Need to keep the salt if we're ever going to be able to check this password $salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES); //Using bin2hex to keep output readable echo bin2hex(     sodium_crypto_pwhash(         16, // == 128 bits         'password',         $salt,         SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,         SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE,         SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13     ) ); ?> ``` The above example will output something similar to: ``` a18f346ba57992eb7e4ae6abf3fd30ee ``` php Yaf_Request_Abstract::clearParams Yaf\_Request\_Abstract::clearParams =================================== (No version information available, might only be in Git) Yaf\_Request\_Abstract::clearParams — Remove all params ### Description ``` public Yaf_Request_Abstract::clearParams(): bool ``` Remove all params set by router, or [Yaf\_Request\_Abstract::setParam()](yaf-request-abstract.setparam) ### Parameters This function has no parameters. ### Return Values bool ### See Also * [Yaf\_Request\_Abstract::isHead()](yaf-request-abstract.ishead) - Determine if request is HEAD request * [Yaf\_Request\_Abstract::isGet()](yaf-request-abstract.isget) - Determine if request is GET request * [Yaf\_Request\_Abstract::isPost()](yaf-request-abstract.ispost) - Determine if request is POST request * [Yaf\_Request\_Abstract::isPut()](yaf-request-abstract.isput) - Determine if request is PUT request * [Yaf\_Request\_Abstract::isOptions()](yaf-request-abstract.isoptions) - Determine if request is OPTIONS request * [Yaf\_Request\_Abstract::isXmlHTTPRequest()](yaf-request-abstract.isxmlhttprequest) - Determine if request is AJAX request php curl_multi_remove_handle curl\_multi\_remove\_handle =========================== (PHP 5, PHP 7, PHP 8) curl\_multi\_remove\_handle — Remove a multi handle from a set of cURL handles ### Description ``` curl_multi_remove_handle(CurlMultiHandle $multi_handle, CurlHandle $handle): int ``` Removes a given `handle` handle from the given `multi_handle` handle. When the `handle` handle has been removed, it is again perfectly legal to run [curl\_exec()](function.curl-exec) on this handle. Removing the `handle` handle while being used, will effectively halt the transfer in progress involving that handle. ### Parameters `multi_handle` A cURL multi handle returned by [curl\_multi\_init()](function.curl-multi-init). `handle` A cURL handle returned by [curl\_init()](function.curl-init). ### Return Values Returns 0 on success, or one of the **`CURLM_XXX`** error codes. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `multi_handle` expects a [CurlMultiHandle](class.curlmultihandle) instance now; previously, a resource was expected. | | 8.0.0 | `handle` expects a [CurlHandle](class.curlhandle) instance now; previously, a resource was expected. | ### See Also * [curl\_init()](function.curl-init) - Initialize a cURL session * [curl\_multi\_init()](function.curl-multi-init) - Returns a new cURL multi handle * [curl\_multi\_add\_handle()](function.curl-multi-add-handle) - Add a normal cURL handle to a cURL multi handle php is_string is\_string ========== (PHP 4, PHP 5, PHP 7, PHP 8) is\_string — Find whether the type of a variable is string ### Description ``` is_string(mixed $value): bool ``` Finds whether the type of the given variable is string. ### Parameters `value` The variable being evaluated. ### Return Values Returns **`true`** if `value` is of type string, **`false`** otherwise. ### Examples **Example #1 **is\_string()** example** ``` <?php $values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0); foreach ($values as $value) {     echo "is_string(";     var_export($value);     echo ") = ";     echo var_dump(is_string($value)); } ?> ``` The above example will output: ``` is_string(false) = bool(false) is_string(true) = bool(false) is_string(NULL) = bool(false) is_string('abc') = bool(true) is_string('23') = bool(true) is_string(23) = bool(false) is_string('23.5') = bool(true) is_string(23.5) = bool(false) is_string('') = bool(true) is_string(' ') = bool(true) is_string('0') = bool(true) is_string(0) = bool(false) ``` ### See Also * [is\_float()](function.is-float) - Finds whether the type of a variable is float * [is\_int()](function.is-int) - Find whether the type of a variable is integer * [is\_bool()](function.is-bool) - Finds out whether a variable is a boolean * [is\_object()](function.is-object) - Finds whether a variable is an object * [is\_array()](function.is-array) - Finds whether a variable is an array php Gmagick::queryformats Gmagick::queryformats ===================== (PECL gmagick >= Unknown) Gmagick::queryformats — Returns formats supported by Gmagick ### Description ``` public Gmagick::queryformats(string $pattern = "*"): array ``` Returns formats supported by [Gmagick](class.gmagick). ### Parameters `pattern` Specifies a string containing a pattern. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php Ds\PriorityQueue::allocate Ds\PriorityQueue::allocate ========================== (PECL ds >= 1.0.0) Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity ### Description ``` public Ds\PriorityQueue::allocate(int $capacity): void ``` Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added. ### Parameters `capacity` The number of values for which capacity should be allocated. > > **Note**: > > > Capacity will stay the same if this value is less than or equal to the current capacity. > > > > **Note**: > > > Capacity will always be rounded up to the nearest power of 2. > > ### Return Values No value is returned. ### Examples **Example #1 **Ds\PriorityQueue::allocate()** example** ``` <?php $queue = new \Ds\PriorityQueue(); var_dump($queue->capacity()); $queue->allocate(100); var_dump($queue->capacity()); ?> ``` The above example will output something similar to: ``` int(8) int(128) ``` php EvPeriodic::createStopped EvPeriodic::createStopped ========================= (PECL ev >= 0.2.0) EvPeriodic::createStopped — Create a stopped EvPeriodic watcher ### Description ``` final public static EvPeriodic::createStopped( float $offset , float $interval , callable $reschedule_cb , callable $callback , mixed $data = null , int $priority = 0 ): EvPeriodic ``` Create EvPeriodic object. Unlike [EvPeriodic::\_\_construct()](evperiodic.construct) this method doesn't start the watcher automatically. ### Parameters `offset` See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) `interval` See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) `reschedule_cb` Reschedule callback. You can pass **`null`**. See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### Return Values Returns EvPeriodic watcher object on success. ### See Also * [EvPeriodic::\_\_construct()](evperiodic.construct) - Constructs EvPeriodic watcher object * [EvTimer::createStopped()](evtimer.createstopped) - Creates EvTimer stopped watcher object
programming_docs
php SolrClient::deleteByQuery SolrClient::deleteByQuery ========================= (PECL solr >= 0.9.2) SolrClient::deleteByQuery — Deletes all documents matching the given query ### Description ``` public SolrClient::deleteByQuery(string $query): SolrUpdateResponse ``` Deletes all documents matching the given query. ### Parameters `query` The query ### Return Values Returns a [SolrUpdateResponse](class.solrupdateresponse) on success and throws an exception on failure. ### Errors/Exceptions Throws [SolrClientException](class.solrclientexception) if the client had failed, or there was a connection issue. Throws [SolrServerException](class.solrserverexception) if the Solr Server had failed to process the request. ### Examples **Example #1 **SolrQuery::deleteByQuery()** example** ``` <?php $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT, ); $client = new SolrClient($options); //This will erase the entire index $client->deleteByQuery("*:*"); $client->commit(); ?> ``` ### See Also * [SolrClient::deleteById()](solrclient.deletebyid) - Delete by Id * [SolrClient::deleteByIds()](solrclient.deletebyids) - Deletes by Ids * [SolrClient::deleteByQueries()](solrclient.deletebyqueries) - Removes all documents matching any of the queries php SimpleXMLIterator::getChildren SimpleXMLIterator::getChildren ============================== (PHP 5, PHP 7, PHP 8) SimpleXMLIterator::getChildren — Returns the sub-elements of the current element ### Description ``` public SimpleXMLIterator::getChildren(): SimpleXMLIterator ``` This method returns a [SimpleXMLIterator](class.simplexmliterator) object containing sub-elements of the current [SimpleXMLIterator](class.simplexmliterator) element. ### Parameters This function has no parameters. ### Return Values Returns a [SimpleXMLIterator](class.simplexmliterator) object containing the sub-elements of the current element. ### Examples **Example #1 Return the sub-elements of the current element** ``` <?php $xml = <<<XML <books>     <book>         <title>PHP Basics</title>         <author>Jim Smith</author>     </book>     <book>XML basics</book> </books> XML; $xmlIterator = new SimpleXMLIterator($xml); for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {     foreach($xmlIterator->getChildren() as $name => $data) {     echo "The $name is '$data' from the class " . get_class($data) . "\n";     } } ?> ``` The above example will output: ``` The title is 'PHP Basics' from the class SimpleXMLIterator The author is 'Jim Smith' from the class SimpleXMLIterator ``` php imageline imageline ========= (PHP 4, PHP 5, PHP 7, PHP 8) imageline — Draw a line ### Description ``` imageline( GdImage $image, int $x1, int $y1, int $x2, int $y2, int $color ): bool ``` Draws a line between the two given points. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `x1` x-coordinate for first point. `y1` y-coordinate for first point. `x2` x-coordinate for second point. `y2` y-coordinate for second point. `color` The line color. A color identifier created with [imagecolorallocate()](function.imagecolorallocate). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Drawing a thick line** ``` <?php function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1) {     /* this way it works well only for orthogonal lines     imagesetthickness($image, $thick);     return imageline($image, $x1, $y1, $x2, $y2, $color);     */     if ($thick == 1) {         return imageline($image, $x1, $y1, $x2, $y2, $color);     }     $t = $thick / 2 - 0.5;     if ($x1 == $x2 || $y1 == $y2) {         return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);     }     $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q     $a = $t / sqrt(1 + pow($k, 2));     $points = array(         round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),         round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),         round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),         round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),     );     imagefilledpolygon($image, $points, 4, $color);     return imagepolygon($image, $points, 4, $color); } ?> ``` ### See Also * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image * [imagecolorallocate()](function.imagecolorallocate) - Allocate a color for an image php QuickHashStringIntHash::loadFromString QuickHashStringIntHash::loadFromString ====================================== (No version information available, might only be in Git) QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string ### Description ``` public static QuickHashStringIntHash::loadFromString(string $contents, int $size = 0, int $options = 0): QuickHashStringIntHash ``` This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile". ### Parameters `contents` The string containing a serialized format of the hash. `size` The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304. `options` The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304. ### Return Values Returns a new QuickHashStringIntHash. ### Examples **Example #1 **QuickHashStringIntHash::loadFromString()** example** ``` <?php $contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash.string" ); $hash = QuickHashStringIntHash::loadFromString(     $contents,     QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC ); foreach( range( 0, 0x0f ) as $key ) {     $i = 48712 + $key * 1631;     $k = base_convert( $i, 10, 36 );     echo $k, ' => ', $hash->get( $k ), "\n"; } ?> ``` The above example will output something similar to: ``` 11l4 => 48712 12uf => 50343 143q => 51974 15d1 => 53605 16mc => 55236 17vn => 56867 194y => 58498 1ae9 => 60129 1bnk => 61760 1cwv => 63391 1e66 => 65022 1ffh => 66653 1gos => 68284 1hy3 => 69915 1j7e => 71546 1kgp => 73177 ``` php EvLoop::embed EvLoop::embed ============= (PECL ev >= 0.2.0) EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object ### Description ``` final public EvLoop::embed( string $other , string $callback = ?, string $data = ?, string $priority = ? ): EvEmbed ``` Creates an instance of [EvEmbed](class.evembed) watcher associated with the current [EvLoop](class.evloop) object. ### Parameters All parameters have the same meaning as for [EvEmbed::\_\_construct()](evembed.construct) . ### Return Values Returns EvEmbed object on success. ### See Also * [EvEmbed::\_\_construct()](evembed.construct) - Constructs the EvEmbed object php None Final Keyword ------------- The final keyword prevents child classes from overriding a method or constant by prefixing the definition with `final`. If the class itself is being defined final then it cannot be extended. **Example #1 Final methods example** ``` <?php class BaseClass {    public function test() {        echo "BaseClass::test() called\n";    }        final public function moreTesting() {        echo "BaseClass::moreTesting() called\n";    } } class ChildClass extends BaseClass {    public function moreTesting() {        echo "ChildClass::moreTesting() called\n";    } } // Results in Fatal error: Cannot override final method BaseClass::moreTesting() ?> ``` **Example #2 Final class example** ``` <?php final class BaseClass {    public function test() {        echo "BaseClass::test() called\n";    }    // As the class is already final, the final keyword is redundant    final public function moreTesting() {        echo "BaseClass::moreTesting() called\n";    } } class ChildClass extends BaseClass { } // Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass) ?> ``` **Example #3 Final constants example as of PHP 8.1.0** ``` <?php class Foo {     final public const X = "foo"; } class Bar extends Foo {     public const X = "bar"; } // Fatal error: Bar::X cannot override final constant Foo::X ?> ``` > **Note**: Properties cannot be declared final: only classes, methods, and constants (as of PHP 8.1.0) may be declared as final. As of PHP 8.0.0, private methods may not be declared final except for the constructor. > > php None Late Static Bindings -------------------- PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the [`::`](language.oop5.paamayim-nekudotayim) operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by `self::`, `parent::`, `static::`, or, if going up in the class hierarchy, [forward\_static\_call()](function.forward-static-call). The function [get\_called\_class()](function.get-called-class) can be used to retrieve a string with the name of the called class and `static::` introduces its scope. This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that `static::` will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls. ### Limitations of `self::` Static references to the current class like `self::` or `__CLASS__` are resolved using the class in which the function belongs, as in where it was defined: **Example #1 `self::` usage** ``` <?php class A {     public static function who() {         echo __CLASS__;     }     public static function test() {         self::who();     } } class B extends A {     public static function who() {         echo __CLASS__;     } } B::test(); ?> ``` The above example will output: ``` A ``` ### Late Static Bindings' usage Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow referencing `B` from `test()` in the previous example. It was decided not to introduce a new keyword but rather use `static` that was already reserved. **Example #2 `static::` simple usage** ``` <?php class A {     public static function who() {         echo __CLASS__;     }     public static function test() {         static::who(); // Here comes Late Static Bindings     } } class B extends A {     public static function who() {         echo __CLASS__;     } } B::test(); ?> ``` The above example will output: ``` B ``` > > **Note**: > > > In non-static contexts, the called class will be the class of the object instance. Since `$this->` will try to call private methods from the same scope, using `static::` may give different results. Another difference is that `static::` can only refer to static properties. > > **Example #3 `static::` usage in a non-static context** ``` <?php class A {     private function foo() {         echo "success!\n";     }     public function test() {         $this->foo();         static::foo();     } } class B extends A {    /* foo() will be copied to B, hence its scope will still be A and     * the call be successful */ } class C extends A {     private function foo() {         /* original method is replaced; the scope of the new one is C */     } } $b = new B(); $b->test(); $c = new C(); $c->test();   //fails ?> ``` The above example will output: ``` success! success! success! Fatal error: Call to private method C::foo() from context 'A' in /tmp/test.php on line 9 ``` > > **Note**: > > > Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like `parent::` or `self::` will forward the calling information. > > **Example #4 Forwarding and non-forwarding calls** > > > ``` > <?php > class A { >     public static function foo() { >         static::who(); >     } > >     public static function who() { >         echo __CLASS__."\n"; >     } > } > > class B extends A { >     public static function test() { >         A::foo(); >         parent::foo(); >         self::foo(); >     } > >     public static function who() { >         echo __CLASS__."\n"; >     } > } > class C extends B { >     public static function who() { >         echo __CLASS__."\n"; >     } > } > > C::test(); > ?> > ``` > The above example will output: > > > ``` > > A > C > C > > ``` > php socket_create socket\_create ============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_create — Create a socket (endpoint for communication) ### Description ``` socket_create(int $domain, int $type, int $protocol): Socket|false ``` Creates and returns a [Socket](class.socket) instance, also referred to as an endpoint of communication. A typical network connection is made up of 2 sockets, one performing the role of the client, and another performing the role of the server. ### Parameters `domain` The `domain` parameter specifies the protocol family to be used by the socket. **Available address/protocol families**| Domain | Description | | --- | --- | | **`AF_INET`** | IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family. | | **`AF_INET6`** | IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family. | | **`AF_UNIX`** | Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication). | `type` The `type` parameter selects the type of communication to be used by the socket. **Available socket types**| Type | Description | | --- | --- | | **`SOCK_STREAM`** | Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type. | | **`SOCK_DGRAM`** | Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type. | | **`SOCK_SEQPACKET`** | Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call. | | **`SOCK_RAW`** | Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping). | | **`SOCK_RDM`** | Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system. | `protocol` The `protocol` parameter sets the specific protocol within the specified `domain` to be used when communicating on the returned socket. The proper value can be retrieved by name by using [getprotobyname()](function.getprotobyname). If the desired protocol is TCP, or UDP the corresponding constants **`SOL_TCP`**, and **`SOL_UDP`** can also be used. **Common protocols**| Name | Description | | --- | --- | | icmp | The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP. | | udp | The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead. | | tcp | The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission. | ### Return Values **socket\_create()** returns a [Socket](class.socket) instance on success, or **`false`** on error. The actual error code can be retrieved by calling [socket\_last\_error()](function.socket-last-error). This error code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual explanation of the error. ### Errors/Exceptions If an invalid `domain` or `type` is given, **socket\_create()** defaults to **`AF_INET`** and **`SOCK_STREAM`** respectively and additionally emits an **`E_WARNING`** message. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [Socket](class.socket) instance now; previously, a resource was returned. | ### See Also * [socket\_accept()](function.socket-accept) - Accepts a connection on a socket * [socket\_bind()](function.socket-bind) - Binds a name to a socket * [socket\_connect()](function.socket-connect) - Initiates a connection on a socket * [socket\_listen()](function.socket-listen) - Listens for a connection on a socket * [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error php mysqli::poll mysqli::poll ============ mysqli\_poll ============ (PHP 5 >= 5.3.0, PHP 7, PHP 8) mysqli::poll -- mysqli\_poll — Poll connections ### Description Object-oriented style ``` public static mysqli::poll( ?array &$read, ?array &$error, array &$reject, int $seconds, int $microseconds = 0 ): int|false ``` Procedural style ``` mysqli_poll( ?array &$read, ?array &$error, array &$reject, int $seconds, int $microseconds = 0 ): int|false ``` Poll connections. The method can be used as [static](language.oop5.static). > > **Note**: > > > Available only with [mysqlnd](https://www.php.net/manual/en/book.mysqlnd.php). > > ### Parameters `read` List of connections to check for outstanding results that can be read. `error` List of connections on which an error occurred, for example, query failure or lost connection. `reject` List of connections rejected because no asynchronous query has been run on for which the function could poll results. `seconds` Maximum number of seconds to wait, must be non-negative. `microseconds` Maximum number of microseconds to wait, must be non-negative. ### Return Values Returns number of ready connections upon success, **`false`** otherwise. ### Examples **Example #1 A **mysqli\_poll()** example** ``` <?php $link1 = mysqli_connect(); $link1->query("SELECT 'test'", MYSQLI_ASYNC); $all_links = array($link1); $processed = 0; do {     $links = $errors = $reject = array();     foreach ($all_links as $link) {         $links[] = $errors[] = $reject[] = $link;     }     if (!mysqli_poll($links, $errors, $reject, 1)) {         continue;     }     foreach ($links as $link) {         if ($result = $link->reap_async_query()) {             print_r($result->fetch_row());             if (is_object($result))                 mysqli_free_result($result);         } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));         $processed++;     } } while ($processed < count($all_links)); ?> ``` The above example will output: ``` Array ( [0] => test ) ``` ### See Also * [mysqli\_query()](mysqli.query) - Performs a query on the database * [mysqli\_reap\_async\_query()](mysqli.reap-async-query) - Get result from async query
programming_docs
php ArrayIterator::seek ArrayIterator::seek =================== (PHP 5, PHP 7, PHP 8) ArrayIterator::seek — Seek to position ### Description ``` public ArrayIterator::seek(int $offset): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `offset` The position to seek to. ### Return Values No value is returned. php DOMNode::isSupported DOMNode::isSupported ==================== (PHP 5, PHP 7, PHP 8) DOMNode::isSupported — Checks if feature is supported for specified version ### Description ``` public DOMNode::isSupported(string $feature, string $version): bool ``` Checks if the asked `feature` is supported for the specified `version`. ### Parameters `feature` The feature to test. See the example of [DOMImplementation::hasFeature()](domimplementation.hasfeature) for a list of features. `version` The version number of the `feature` to test. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [DOMImplementation::hasFeature()](domimplementation.hasfeature) - Test if the DOM implementation implements a specific feature php EventConfig::setFlags EventConfig::setFlags ===================== (PECL event >= 2.0.2-alpha) EventConfig::setFlags — Sets one or more flags to configure the eventual EventBase will be initialized ### Description ``` public EventConfig::setFlags( int $flags ): bool ``` Sets one or more flags to configure what parts of the eventual EventBase will be initialized, and how they'll work. ### Parameters `flags` One of `EventBase::LOOP_*` constants. See [EventBase constants](class.eventbase#eventbase.constants). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventBase::getFeatures()](eventbase.getfeatures) - Returns bitmask of features supported php mysqli_stmt::result_metadata mysqli\_stmt::result\_metadata ============================== mysqli\_stmt\_result\_metadata ============================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::result\_metadata -- mysqli\_stmt\_result\_metadata — Returns result set metadata from a prepared statement ### Description Object-oriented style ``` public mysqli_stmt::result_metadata(): mysqli_result|false ``` Procedural style ``` mysqli_stmt_result_metadata(mysqli_stmt $statement): mysqli_result|false ``` If a statement passed to [mysqli\_prepare()](mysqli.prepare) is one that produces a result set, **mysqli\_stmt\_result\_metadata()** returns the result object that can be used to process the meta information such as total number of fields and individual field information. > > **Note**: > > > This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as: > > > * [mysqli\_num\_fields()](mysqli-result.field-count) > * [mysqli\_fetch\_field()](mysqli-result.fetch-field) > * [mysqli\_fetch\_field\_direct()](mysqli-result.fetch-field-direct) > * [mysqli\_fetch\_fields()](mysqli-result.fetch-fields) > * [mysqli\_field\_count()](mysqli.field-count) > * [mysqli\_field\_seek()](mysqli-result.field-seek) > * [mysqli\_field\_tell()](mysqli-result.current-field) > * [mysqli\_free\_result()](mysqli-result.free) > > The result set structure should be freed when you are done with it, which you can do by passing it to [mysqli\_free\_result()](mysqli-result.free) > > **Note**: > > > The result set returned by **mysqli\_stmt\_result\_metadata()** contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with [mysqli\_stmt\_fetch()](mysqli-stmt.fetch). > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values Returns a result object or **`false`** if an error occurred. ### Examples **Example #1 Object-oriented style** ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "test"); $mysqli->query("DROP TABLE IF EXISTS friends"); $mysqli->query("CREATE TABLE friends (id int, name varchar(20))"); $mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')"); $stmt = $mysqli->prepare("SELECT id, name FROM friends"); $stmt->execute(); /* get resultset for metadata */ $result = $stmt->result_metadata(); /* retrieve field information from metadata result set */ $field = $result->fetch_field(); printf("Fieldname: %s\n", $field->name); /* close resultset */ $result->close(); /* close connection */ $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "test"); mysqli_query($link, "DROP TABLE IF EXISTS friends"); mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))"); mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')"); $stmt = mysqli_prepare($link, "SELECT id, name FROM friends"); mysqli_stmt_execute($stmt); /* get resultset for metadata */ $result = mysqli_stmt_result_metadata($stmt); /* retrieve field information from metadata result set */ $field = mysqli_fetch_field($result); printf("Fieldname: %s\n", $field->name); /* close resultset */ mysqli_free_result($result); /* close connection */ mysqli_close($link); ?> ``` ### See Also * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_free\_result()](mysqli-result.free) - Frees the memory associated with a result php ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute ===================================================== (PECL imagick 2, PECL imagick 3) ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve ### Description ``` public ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute(float $x, float $y): bool ``` Draws a quadratic Bezier curve (using absolute coordinates) from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point.). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. This function cannot be used to continue a cubic Bezier curve smoothly. It can only continue from a quadratic curve smoothly. ### Parameters `x` ending x coordinate `y` ending y coordinate ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute()** example** ``` <?php $draw = new \ImagickDraw(); $draw->setStrokeOpacity(1); $draw->setStrokeColor("black"); $draw->setFillColor("blue"); $draw->setStrokeWidth(2); $draw->setFontSize(72); $draw->pathStart(); $draw->pathMoveToAbsolute(50,250); // This specifies a quadratic bezier curve with the current position as the start // point, the control point is the first two params, and the end point is the last two params. $draw->pathCurveToQuadraticBezierAbsolute(     150,50,      250,250 ); // This specifies a quadratic bezier curve with the current position as the start // point, the control point is mirrored from the previous curves control point // and the end point is defined by the x, y values. $draw->pathCurveToQuadraticBezierSmoothAbsolute(     450,250 ); // This specifies a quadratic bezier curve with the current position as the start // point, the control point is mirrored from the previous curves control point // and the end point is defined relative from the current position by the x, y values. $draw->pathCurveToQuadraticBezierSmoothRelative(     200,-100 ); $draw->pathFinish(); $imagick = new \Imagick(); $imagick->newImage(700, 500, $backgroundColor); $imagick->setImageFormat("png"); $imagick->drawImage($draw); header("Content-Type: image/png"); echo $imagick->getImageBlob(); ?> ``` php AppendIterator::getIteratorIndex AppendIterator::getIteratorIndex ================================ (PHP 5 >= 5.2.0, PHP 7, PHP 8) AppendIterator::getIteratorIndex — Gets an index of iterators ### Description ``` public AppendIterator::getIteratorIndex(): ?int ``` Gets the index of the current inner iterator. ### Parameters This function has no parameters. ### Return Values Returns the zero-based, integer index of the current inner iterator if it exists, or **`null`** otherwise. ### Examples **Example #1 **AppendIterator.getIteratorIndex()** basic example** ``` <?php $array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara')); $array_b = new ArrayIterator(array('apple', 'orange', 'lemon')); $iterator = new AppendIterator; $iterator->append($array_a); $iterator->append($array_b); foreach ($iterator as $key => $current) {     echo $iterator->getIteratorIndex() . '  ' . $key . ' ' . $current . PHP_EOL; } ?> ``` The above example will output: ``` 0 a aardwolf 0 b bear 0 c capybara 1 0 apple 1 1 orange 1 2 lemon ``` ### See Also * [AppendIterator::getInnerIterator()](appenditerator.getinneriterator) - Gets the inner iterator * [AppendIterator::getArrayIterator()](appenditerator.getarrayiterator) - Gets the ArrayIterator php Ds\Queue::push Ds\Queue::push ============== (PECL ds >= 1.0.0) Ds\Queue::push — Pushes values into the queue ### Description ``` public Ds\Queue::push(mixed ...$values): void ``` Pushes `values` into the queue. ### Parameters `values` The values to push into the queue. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Queue::push()** example** ``` <?php $queue = new \Ds\Queue(); $queue->push("a"); $queue->push("b"); $queue->push("c", "d"); $queue->push(...["e", "f"]); print_r($queue); ?> ``` The above example will output something similar to: ``` Ds\Queue Object ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f ) ``` php SolrQuery::getMltMaxWordLength SolrQuery::getMltMaxWordLength ============================== (PECL solr >= 0.9.2) SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored ### Description ``` public SolrQuery::getMltMaxWordLength(): int ``` Returns the maximum word length above which words will be ignored ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php ImagickDraw::setStrokeColor ImagickDraw::setStrokeColor =========================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines ### Description ``` public ImagickDraw::setStrokeColor(ImagickPixel $stroke_pixel): bool ``` **Warning**This function is currently not documented; only its argument list is available. Sets the color used for stroking object outlines. ### Parameters `stroke_pixel` the stroke color ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setStrokeColor()** example** ``` <?php function setStrokeColor($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(5);     $draw->line(100, 100, 400, 145);     $draw->rectangle(100, 200, 225, 350);     $draw->setStrokeOpacity(0.1);     $draw->line(100, 120, 400, 165);     $draw->rectangle(275, 200, 400, 350);     $image = new \Imagick();     $image->newImage(500, 400, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php EventHttpRequest::clearHeaders EventHttpRequest::clearHeaders ============================== (PECL event >= 1.4.0-beta) EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request ### Description ``` public EventHttpRequest::clearHeaders(): void ``` Removes all output headers from the header list of the request. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [EventHttpRequest::addHeader()](eventhttprequest.addheader) - Adds an HTTP header to the headers of the request php DOMElement::setIdAttribute DOMElement::setIdAttribute ========================== (PHP 5, PHP 7, PHP 8) DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID ### Description ``` public DOMElement::setIdAttribute(string $qualifiedName, bool $isId): void ``` Declares the attribute `qualifiedName` to be of type ID. ### Parameters `qualifiedName` The name of the attribute. `isId` Set it to **`true`** if you want `qualifiedName` to be of type ID, **`false`** otherwise. ### Return Values No value is returned. ### Errors/Exceptions **`DOM_NO_MODIFICATION_ALLOWED_ERR`** Raised if the node is readonly. **`DOM_NOT_FOUND`** Raised if `qualifiedName` is not an attribute of this element. ### See Also * [DOMDocument::getElementById()](domdocument.getelementbyid) - Searches for an element with a certain id * [DOMElement::setIdAttributeNode()](domelement.setidattributenode) - Declares the attribute specified by node to be of type ID * [DOMElement::setIdAttributeNS()](domelement.setidattributens) - Declares the attribute specified by local name and namespace URI to be of type ID php IntlDateFormatter::getTimeZoneId IntlDateFormatter::getTimeZoneId ================================ datefmt\_get\_timezone\_id ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) IntlDateFormatter::getTimeZoneId -- datefmt\_get\_timezone\_id — Get the timezone-id used for the IntlDateFormatter ### Description Object-oriented style ``` public IntlDateFormatter::getTimeZoneId(): string|false ``` Procedural style ``` datefmt_get_timezone_id(IntlDateFormatter $formatter): string|false ``` Get the timezone-id used for the IntlDateFormatter. ### Parameters `formatter` The formatter resource. ### Return Values ID string for the time zone used by this formatter, or **`false`** on failure. ### Examples **Example #1 **datefmt\_get\_timezone\_id()** example** ``` <?php $fmt = datefmt_create(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'timezone_id of the formatter is: ' . datefmt_get_timezone_id($fmt) . "\n"; datefmt_set_timezone($fmt, 'Europe/Madrid'); echo 'Now timezone_id of the formatter is: ' . datefmt_get_timezone_id($fmt); ?> ``` **Example #2 OO example** ``` <?php $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'timezone_id of the formatter is: ' . $fmt->getTimezoneId() . "\n"; $fmt->setTimezone('Europe/Madrid'); echo 'Now timezone_id of the formatter is: ' . $fmt->getTimezoneId(); ?> ``` The above example will output: ``` timezone_id of the formatter is: America/Los_Angeles Now timezone_id of the formatter is: Europe/Madrid ``` ### See Also * [datefmt\_set\_timezone()](intldateformatter.settimezone) - Sets formatterʼs timezone * [datefmt\_create()](intldateformatter.create) - Create a date formatter php SolrInputDocument::sort SolrInputDocument::sort ======================= (PECL solr >= 0.9.2) SolrInputDocument::sort — Sorts the fields within the document ### Description ``` public SolrInputDocument::sort(int $sortOrderBy, int $sortDirection = SolrInputDocument::SORT_ASC): bool ``` ``` The fields are rearranged according to the specified criteria and sort direction Fields can be sorted by boost values, field names and number of values. The $order_by parameter must be one of : * SolrInputDocument::SORT_FIELD_NAME * SolrInputDocument::SORT_FIELD_BOOST_VALUE * SolrInputDocument::SORT_FIELD_VALUE_COUNT The sort direction can be one of : * SolrInputDocument::SORT_DEFAULT * SolrInputDocument::SORT_ASC * SolrInputDocument::SORT_DESC ``` ### Parameters `sortOrderBy` The sort criteria `sortDirection` The sort direction ### Return Values Returns **`true`** on success or **`false`** on failure. php uopz_copy uopz\_copy ========== (PECL uopz 1 >= 1.0.4, PECL uopz 2) uopz\_copy — Copy a function **Warning**This function has been *REMOVED* in PECL uopz 5.0.0. ### Description ``` uopz_copy(string $function): Closure ``` ``` uopz_copy(string $class, string $function): Closure ``` Copy a function by name ### Parameters `class` The name of the class containing the function to copy `function` The name of the function ### Return Values A Closure for the specified function ### Examples **Example #1 **uopz\_copy()** example** ``` <?php $strtotime = uopz_copy('strtotime'); uopz_function("strtotime", function($arg1, $arg2) use($strtotime) {     /* can call original strtotime from here */     var_dump($arg1); }); var_dump(strtotime('dummy')); ?> ``` The above example will output: ``` string(5) "dummy" ``` php imap_num_recent imap\_num\_recent ================= (PHP 4, PHP 5, PHP 7, PHP 8) imap\_num\_recent — Gets the number of recent messages in current mailbox ### Description ``` imap_num_recent(IMAP\Connection $imap): int ``` Gets the number of recent messages in the current mailbox. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. ### Return Values Returns the number of recent messages in the current mailbox, as an integer. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_num\_msg()](function.imap-num-msg) - Gets the number of messages in the current mailbox * [imap\_status()](function.imap-status) - Returns status information on a mailbox php IntlDateFormatter::getDateType IntlDateFormatter::getDateType ============================== datefmt\_get\_datetype ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) IntlDateFormatter::getDateType -- datefmt\_get\_datetype — Get the datetype used for the IntlDateFormatter ### Description Object-oriented style ``` public IntlDateFormatter::getDateType(): int|false ``` Procedural style ``` datefmt_get_datetype(IntlDateFormatter $formatter): int|false ``` Returns date type used by the formatter. ### Parameters `formatter` The formatter resource. ### Return Values The current [date type](class.intldateformatter#intl.intldateformatter-constants) value of the formatter, or **`false`** on failure. ### Examples **Example #1 **datefmt\_get\_datetype()** example** ``` <?php $fmt = datefmt_create(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'datetype of the formatter is : ' . datefmt_get_datetype($fmt); echo 'First Formatted output with datetype is ' . datefmt_format($fmt, 0); $fmt = datefmt_create(     'en_US',     IntlDateFormatter::SHORT,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'Now datetype of the formatter is : ' . datefmt_get_datetype($fmt); echo 'Second Formatted output with datetype is ' . datefmt_format($fmt, 0); ?> ``` **Example #2 OO example** ``` <?php $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'datetype of the formatter is : ' . $fmt->getDateType(); echo 'First Formatted output is ' . $fmt->format(0); $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::SHORT,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'Now datetype of the formatter is : ' . $fmt->getDateType(); echo 'Second Formatted output is ' . $fmt->format(0); ?> ``` The above example will output: ``` datetype of the formatter is : 0 First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT Now datetype of the formatter is : 2 Second Formatted output is 12/31/69 4:00:00 PM PT ``` ### See Also * [datefmt\_get\_timetype()](intldateformatter.gettimetype) - Get the timetype used for the IntlDateFormatter * [datefmt\_create()](intldateformatter.create) - Create a date formatter
programming_docs
php chroot chroot ====== (PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8) chroot — Change the root directory ### Description ``` chroot(string $directory): bool ``` Changes the root directory of the current process to `directory`, and changes the current working directory to "/". This function is only available to GNU and BSD systems, and only when using the CLI, CGI or Embed SAPI. Also, this function requires root privileges. Calling this function does not change the values of the `__DIR__` and `__FILE__` magic constants. ### Parameters `directory` The path to change the root directory to. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **chroot()** example** ``` <?php chroot("/path/to/your/chroot/"); echo getcwd(); ?> ``` The above example will output: ``` / ``` ### Notes > **Note**: This function is not implemented on Windows platforms. > > > **Note**: This function is not available in PHP interpreters built with ZTS (Zend Thread Safety) enabled. To check whether your copy of PHP was built with ZTS enabled, use **php -i** or test the built-in constant **`PHP_ZTS`**. > > php PDO::commit PDO::commit =========== (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0) PDO::commit — Commits a transaction ### Description ``` public PDO::commit(): bool ``` Commits a transaction, returning the database connection to autocommit mode until the next call to [PDO::beginTransaction()](pdo.begintransaction) starts a new transaction. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Throws a [PDOException](class.pdoexception) if there is no active transaction. > **Note**: An exception is raised even when the **`PDO::ATTR_ERRMODE`** attribute is not **`PDO::ERRMODE_EXCEPTION`**. > > ### Examples **Example #1 Committing a basic transaction** ``` <?php /* Begin a transaction, turning off autocommit */ $dbh->beginTransaction(); /* Insert multiple records on an all-or-nothing basis */ $sql = 'INSERT INTO fruit     (name, colour, calories)     VALUES (?, ?, ?)'; $sth = $dbh->prepare($sql); foreach ($fruits as $fruit) {     $sth->execute(array(         $fruit->name,         $fruit->colour,         $fruit->calories,     )); } /* Commit the changes */ $dbh->commit(); /* Database connection is now back in autocommit mode */ ?> ``` **Example #2 Committing a DDL transaction** ``` <?php /* Begin a transaction, turning off autocommit */ $dbh->beginTransaction(); /* Change the database schema */ $sth = $dbh->exec("DROP TABLE fruit"); /* Commit the changes */ $dbh->commit(); /* Database connection is now back in autocommit mode */ ?> ``` > **Note**: Not all databases will allow transactions to operate on DDL statements: some will generate errors, whereas others (including MySQL) will automatically commit the transaction after the first DDL statement has been encountered. > > ### See Also * [PDO::beginTransaction()](pdo.begintransaction) - Initiates a transaction * [PDO::rollBack()](pdo.rollback) - Rolls back a transaction * [Transactions and auto-commit](https://www.php.net/manual/en/pdo.transactions.php) php IntlCalendar::setFirstDayOfWeek IntlCalendar::setFirstDayOfWeek =============================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start ### Description Object-oriented style ``` public IntlCalendar::setFirstDayOfWeek(int $dayOfWeek): bool ``` Procedural style ``` intlcal_set_first_day_of_week(IntlCalendar $calendar, int $dayOfWeek): bool ``` Defines the day of week deemed to start the week. This affects the behavior of fields that depend on the concept of week start and end such as **`IntlCalendar::FIELD_WEEK_OF_YEAR`** and **`IntlCalendar::FIELD_YEAR_WOY`**. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `dayOfWeek` One of the constants **`IntlCalendar::DOW_SUNDAY`**, **`IntlCalendar::DOW_MONDAY`**, …, **`IntlCalendar::DOW_SATURDAY`**. ### Return Values Always returns **`true`**. ### Examples **Example #1 **IntlCalendar::setFirstDayOfWeek()**** ``` <?php ini_set('date.timezone', 'Europe/Lisbon'); ini_set('intl.default_locale', 'es_ES'); $cal = IntlCalendar::createInstance(); $cal->set(2013, 5 /* June */, 30); // A Sunday var_dump($cal->getFirstDayOfWeek()); // 2 (Monday) echo IntlDateFormatter::formatObject($cal, <<<EOD 'local day of week: 'cc' week of month    : 'W' week of year     : 'ww EOD ), "\n"; $cal->setFirstDayOfWeek(IntlCalendar::DOW_SUNDAY); echo IntlDateFormatter::formatObject($cal, <<<EOD 'local day of week: 'cc' week of month    : 'W' week of year     : 'ww EOD ), "\n"; ``` The above example will output: ``` int(2) local day of week: 7 week of month : 4 week of year : 26 local day of week: 1 week of month : 5 week of year : 27 ``` php timezone_name_from_abbr timezone\_name\_from\_abbr ========================== (PHP 5 >= 5.1.3, PHP 7, PHP 8) timezone\_name\_from\_abbr — Returns a timezone name by guessing from abbreviation and UTC offset ### Description ``` timezone_name_from_abbr(string $abbr, int $utcOffset = -1, int $isDST = -1): string|false ``` ### Parameters `abbr` Time zone abbreviation. `utcOffset` Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to `abbr` is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned. `isDST` Daylight saving time indicator. Defaults to -1, which means that whether the time zone has daylight saving or not is not taken into consideration when searching. If this is set to 1, then the `utcOffset` is assumed to be an offset with daylight saving in effect; if 0, then `utcOffset` is assumed to be an offset without daylight saving in effect. If `abbr` doesn't exist then the time zone is searched solely by the `utcOffset` and `isDST`. ### Return Values Returns time zone name on success or **`false`** on failure. ### Examples **Example #1 A **timezone\_name\_from\_abbr()** example** ``` <?php echo timezone_name_from_abbr("CET") . "\n"; echo timezone_name_from_abbr("", 3600, 0) . "\n"; ?> ``` The above example will output something similar to: ``` Europe/Berlin Europe/Paris ``` ### See Also * [timezone\_abbreviations\_list()](function.timezone-abbreviations-list) - Alias of DateTimeZone::listAbbreviations php SoapHeader::__construct SoapHeader::\_\_construct ========================= (PHP 5, PHP 7, PHP 8) SoapHeader::\_\_construct — SoapHeader constructor ### Description public **SoapHeader::\_\_construct**( string `$namespace`, string `$name`, [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = ?, bool `$mustunderstand` = ?, string `$actor` = ? ) Constructs a new SoapHeader object. ### Parameters `namespace` The namespace of the SOAP header element. `name` The name of the SoapHeader object. `data` A SOAP header's content. It can be a PHP value or a [SoapVar](class.soapvar) object. `mustUnderstand` Value of the `mustUnderstand` attribute of the SOAP header element. `actor` Value of the `actor` attribute of the SOAP header element. ### Examples **Example #1 **SoapHeader::\_\_construct()** example** ``` <?php $client = new SoapClient(null, array('location' => "http://localhost/soap.php",                                      'uri'      => "http://test-uri/")); $client->__soapCall("echoVoid", null, null,                 new SoapHeader('http://soapinterop.org/echoheader/',                                'echoMeStringRequest',                                'hello world')); ?> ``` ### See Also * [SoapClient::\_\_soapCall()](soapclient.soapcall) - Calls a SOAP function * [SoapVar::\_\_construct()](soapvar.construct) - SoapVar constructor * [SoapParam::\_\_construct()](soapparam.construct) - SoapParam constructor * [SoapServer::addSoapHeader()](soapserver.addsoapheader) - Add a SOAP header to the response php curl_multi_info_read curl\_multi\_info\_read ======================= (PHP 5, PHP 7, PHP 8) curl\_multi\_info\_read — Get information about the current transfers ### Description ``` curl_multi_info_read(CurlMultiHandle $multi_handle, int &$queued_messages = null): array|false ``` Ask the multi handle if there are any messages or information from the individual transfers. Messages may include information such as an error code from the transfer or just the fact that a transfer is completed. Repeated calls to this function will return a new result each time, until a **`false`** is returned as a signal that there is no more to get at this point. The integer pointed to with `queued_messages` will contain the number of remaining messages after this function was called. **Warning** The data the returned resource points to will not survive calling [curl\_multi\_remove\_handle()](function.curl-multi-remove-handle). ### Parameters `multi_handle` A cURL multi handle returned by [curl\_multi\_init()](function.curl-multi-init). `queued_messages` Number of messages that are still in the queue ### Return Values On success, returns an associative array for the message, **`false`** on failure. **Contents of the returned array**| Key: | Value: | | --- | --- | | `msg` | The **`CURLMSG_DONE`** constant. Other return values are currently not available. | | `result` | One of the **`CURLE_*`** constants. If everything is OK, the **`CURLE_OK`** will be the result. | | `handle` | Resource of type curl indicates the handle which it concerns. | ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `multi_handle` expects a [CurlMultiHandle](class.curlmultihandle) instance now; previously, a resource was expected. | ### Examples **Example #1 A **curl\_multi\_info\_read()** example** ``` <?php $urls = array(    "http://www.cnn.com/",    "http://www.bbc.co.uk/",    "http://www.yahoo.com/" ); $mh = curl_multi_init(); foreach ($urls as $i => $url) {     $conn[$i] = curl_init($url);     curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);     curl_multi_add_handle($mh, $conn[$i]); } do {     $status = curl_multi_exec($mh, $active);     if ($active) {         curl_multi_select($mh);     }     while (false !== ($info = curl_multi_info_read($mh))) {         var_dump($info);     } } while ($active && $status == CURLM_OK); foreach ($urls as $i => $url) {     $res[$i] = curl_multi_getcontent($conn[$i]);     curl_close($conn[$i]); } var_dump(curl_multi_info_read($mh)); ?> ``` The above example will output something similar to: ``` array(3) { ["msg"]=> int(1) ["result"]=> int(0) ["handle"]=> resource(5) of type (curl) } array(3) { ["msg"]=> int(1) ["result"]=> int(0) ["handle"]=> resource(7) of type (curl) } array(3) { ["msg"]=> int(1) ["result"]=> int(0) ["handle"]=> resource(6) of type (curl) } bool(false) ``` ### See Also * [curl\_multi\_init()](function.curl-multi-init) - Returns a new cURL multi handle php Yaf_Response_Abstract::clearBody Yaf\_Response\_Abstract::clearBody ================================== (Yaf >=1.0.0) Yaf\_Response\_Abstract::clearBody — Discard all exists response body ### Description ``` public Yaf_Response_Abstract::clearBody(string $key = ?): bool ``` Clear existsed content ### Parameters `key` the content key, if you don't specific, then all contents will be cleared. > > **Note**: > > > this parameter is introduced as of 2.2.0 > > ### Return Values ### See Also * [Yaf\_Response\_Abstract::setBody()](yaf-response-abstract.setbody) - Set content to response * [Yaf\_Response\_Abstract::appendBody()](yaf-response-abstract.appendbody) - Append to response body * [Yaf\_Response\_Abstract::prependBody()](yaf-response-abstract.prependbody) - The prependBody purpose * [Yaf\_Response\_Abstract::getBody()](yaf-response-abstract.getbody) - Retrieve a exists content php wincache_ucache_set wincache\_ucache\_set ===================== (PECL wincache >= 1.1.0) wincache\_ucache\_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache ### Description ``` wincache_ucache_set(mixed $key, mixed $value, int $ttl = 0): bool ``` ``` wincache_ucache_set(array $values, mixed $unused = NULL, int $ttl = 0): bool ``` Adds a variable in user cache. Overwrites a variable if it already exists in the cache. The added or updated variable remains in the user cache unless its time to live expires or it is deleted by using [wincache\_ucache\_delete()](function.wincache-ucache-delete) or [wincache\_ucache\_clear()](function.wincache-ucache-clear) functions. ### Parameters `key` Store the variable using this `key` name. If a variable with same `key` is already present the function will overwrite the previous value with the new one. `key` is case sensitive. `key` can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition. `value` Value of a variable to store. `Value` supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass **`null`** as `value` while using array as `key`. If `value` is an object, or an array containing objects, then the objects will be serialized. See [\_\_sleep()](language.oop5.magic#object.sleep) for details on serializing objects. `values` Associative array of keys and values. `ttl` Time for the variable to live in the cache in seconds. After the value specified in `ttl` has passed the stored variable will be deleted from the cache. This parameter takes a default value of `0` which means the variable will stay in the cache unless explicitly deleted by using [wincache\_ucache\_delete()](function.wincache-ucache-delete) or [wincache\_ucache\_clear()](function.wincache-ucache-clear) functions. ### Return Values If `key` is string, the function returns **`true`** on success and **`false`** on failure. If `key` is an array, the function returns: * If all the name => value pairs in the array can be set, function returns an empty array; * If all the name => value pairs in the array cannot be set, function returns **`false`**; * If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache. ### Examples **Example #1 **wincache\_ucache\_set()** with `key` as a string** ``` <?php $bar = 'BAR'; var_dump(wincache_ucache_set('foo', $bar)); var_dump(wincache_ucache_get('foo')); $bar1 = 'BAR1'; var_dump(wincache_ucache_set('foo', $bar1)); var_dump(wincache_ucache_get('foo')); ?> ``` The above example will output: ``` bool(true) string(3) "BAR" bool(true) string(3) "BAR1" ``` **Example #2 **wincache\_ucache\_set()** with `key` as an array** ``` <?php $colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8'); var_dump(wincache_ucache_set($colors_array)); var_dump(wincache_ucache_set($colors_array)); var_dump(wincache_ucache_get('Blue')); ?> ``` The above example will output: ``` array(0) {} array(0) {} string(1) "6" ``` ### See Also * [wincache\_ucache\_add()](function.wincache-ucache-add) - Adds a variable in user cache only if variable does not already exist in the cache * [wincache\_ucache\_get()](function.wincache-ucache-get) - Gets a variable stored in the user cache * [wincache\_ucache\_delete()](function.wincache-ucache-delete) - Deletes variables from the user cache * [wincache\_ucache\_clear()](function.wincache-ucache-clear) - Deletes entire content of the user cache * [wincache\_ucache\_exists()](function.wincache-ucache-exists) - Checks if a variable exists in the user cache * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache * [\_\_sleep()](language.oop5.magic#object.sleep) php date_create_from_format date\_create\_from\_format ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) date\_create\_from\_format — Alias of [DateTime::createFromFormat()](datetime.createfromformat) ### Description This function is an alias of: [DateTime::createFromFormat()](datetime.createfromformat) php SolrQuery::setTermsSort SolrQuery::setTermsSort ======================= (PECL solr >= 0.9.2) SolrQuery::setTermsSort — Specifies how to sort the returned terms ### Description ``` public SolrQuery::setTermsSort(int $sortType): SolrQuery ``` If SolrQuery::TERMS\_SORT\_COUNT, sorts the terms by the term frequency (highest count first). If SolrQuery::TERMS\_SORT\_INDEX, returns the terms in index order ### Parameters `sortType` SolrQuery::TERMS\_SORT\_INDEX or SolrQuery::TERMS\_SORT\_COUNT ### Return Values Returns the current SolrQuery object, if the return value is used. php EmptyIterator::valid EmptyIterator::valid ==================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) EmptyIterator::valid — The valid() method ### Description ``` public EmptyIterator::valid(): false ``` The EmptyIterator valid() method. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values **`false`** php stream_socket_enable_crypto stream\_socket\_enable\_crypto ============================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) stream\_socket\_enable\_crypto — Turns encryption on/off on an already connected socket ### Description ``` stream_socket_enable_crypto( resource $stream, bool $enable, ?int $crypto_method = null, ?resource $session_stream = null ): int|bool ``` Enable or disable encryption on the stream. Once the crypto settings are established, cryptography can be turned on and off dynamically by passing **`true`** or **`false`** in the `enable` parameter. ### Parameters `stream` The stream resource. `enable` Enable/disable cryptography on the stream. `crypto_method` Setup encryption on the stream. Valid methods are * **`STREAM_CRYPTO_METHOD_SSLv2_CLIENT`** * **`STREAM_CRYPTO_METHOD_SSLv3_CLIENT`** * **`STREAM_CRYPTO_METHOD_SSLv23_CLIENT`** * **`STREAM_CRYPTO_METHOD_ANY_CLIENT`** * **`STREAM_CRYPTO_METHOD_TLS_CLIENT`** * **`STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT`** * **`STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT`** * **`STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT`** * **`STREAM_CRYPTO_METHOD_SSLv2_SERVER`** * **`STREAM_CRYPTO_METHOD_SSLv3_SERVER`** * **`STREAM_CRYPTO_METHOD_SSLv23_SERVER`** * **`STREAM_CRYPTO_METHOD_ANY_SERVER`** * **`STREAM_CRYPTO_METHOD_TLS_SERVER`** * **`STREAM_CRYPTO_METHOD_TLSv1_0_SERVER`** * **`STREAM_CRYPTO_METHOD_TLSv1_1_SERVER`** * **`STREAM_CRYPTO_METHOD_TLSv1_2_SERVER`** If omitted, the `crypto_method` context option on the stream's SSL context will be used instead. `session_stream` Seed the stream with settings from `session_stream`. ### Return Values Returns **`true`** on success, **`false`** if negotiation has failed or `0` if there isn't enough data and you should try again (only for non-blocking sockets). ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `session_stream` is now nullable. | ### Examples **Example #1 **stream\_socket\_enable\_crypto()** example** ``` <?php $fp = stream_socket_client("tcp://myproto.example.com:31337", $errno, $errstr, 30); if (!$fp) {     die("Unable to connect: $errstr ($errno)"); } /* Turn on encryption for login phase */ stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); fwrite($fp, "USER god\r\n"); fwrite($fp, "PASS secret\r\n"); /* Turn off encryption for the rest */ stream_socket_enable_crypto($fp, false); while ($motd = fgets($fp)) {     echo $motd; } fclose($fp); ?> ``` The above example will output something similar to: ### See Also * [OpenSSL Functions](https://www.php.net/manual/en/ref.openssl.php) * [List of Supported Socket Transports](https://www.php.net/manual/en/transports.php)
programming_docs
php mb_send_mail mb\_send\_mail ============== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_send\_mail — Send encoded mail ### Description ``` mb_send_mail( string $to, string $subject, string $message, array|string $additional_headers = [], ?string $additional_params = null ): bool ``` Sends email. Headers and messages are converted and encoded according to the [mb\_language()](function.mb-language) setting. It's a wrapper function for [mail()](function.mail), so see also [mail()](function.mail) for details. ### Parameters `to` The mail addresses being sent to. Multiple recipients may be specified by putting a comma between each address in `to`. This parameter is not automatically encoded. `subject` The subject of the mail. `message` The message of the mail. `additional_headers` (optional) String or array to be inserted at the end of the email header. This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). Validate parameter not to be injected unwanted headers by attackers. If an array is passed, its keys are the header names and its values are the respective header values. > > **Note**: > > > When sending mail, the mail *must* contain a `From` header. This can be set with the `additional_headers` parameter, or a default can be set in php.ini. > > Failing to do this will result in an error message similar to `Warning: mail(): "sendmail_from" not > set in php.ini or custom "From:" header missing`. The `From` header sets also `Return-Path` under Windows. > > > > **Note**: > > > If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably [» qmail](http://cr.yp.to/qmail.html)) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with [» RFC 2822](http://www.faqs.org/rfcs/rfc2822). > > `additional_params` `additional_params` is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail. This parameter is escaped by [escapeshellcmd()](function.escapeshellcmd) internally to prevent command execution. [escapeshellcmd()](function.escapeshellcmd) prevents command execution, but allows to add additional parameters. For security reason, this parameter should be validated. Since [escapeshellcmd()](function.escapeshellcmd) is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. Programs that are required to use these characters [mail()](function.mail) cannot be used. The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `additional_params` is nullable now. | | 7.2.0 | The `additional_headers` parameter now also accepts an array. | ### See Also * [mail()](function.mail) - Send mail * [mb\_encode\_mimeheader()](function.mb-encode-mimeheader) - Encode string for MIME header * [mb\_language()](function.mb-language) - Set/Get current language php EventBufferEvent::sslSocket EventBufferEvent::sslSocket =========================== (PECL event >= 1.2.6-beta) EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket ### Description ``` public static EventBufferEvent::sslSocket( EventBase $base , mixed $socket , EventSslContext $ctx , int $state , int $options = ? ): EventBufferEvent ``` Creates a new SSL buffer event to send its data over an SSL on a socket. ### Parameters `base` Associated event base. `socket` Socket to use for this SSL. Can be stream or socket resource, numeric file descriptor, or **`null`**. If `socket` is **`null`**, it is assumed that the file descriptor for the socket will be assigned later, for instance, by means of [EventBufferEvent::connectHost()](eventbufferevent.connecthost) method. `ctx` Object of [EventSslContext](class.eventsslcontext) class. `state` The current state of SSL connection: **`EventBufferEvent::SSL_OPEN`** , **`EventBufferEvent::SSL_ACCEPTING`** or **`EventBufferEvent::SSL_CONNECTING`** . `options` The buffer event options. ### Return Values Returns [EventBufferEvent](class.eventbufferevent) object. ### See Also * [EventBufferEvent::sslFilter()](eventbufferevent.sslfilter) - Create a new SSL buffer event to send its data over another buffer event php openssl_csr_export openssl\_csr\_export ==================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) openssl\_csr\_export — Exports a CSR as a string ### Description ``` openssl_csr_export(OpenSSLCertificateSigningRequest|string $csr, string &$output, bool $no_text = true): bool ``` **openssl\_csr\_export()** takes the Certificate Signing Request represented by `csr` and stores it in PEM format in `output`, which is passed by reference. ### Parameters `csr` See [CSR parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values. `output` on success, this string will contain the PEM encoded CSR `no_text` The optional parameter `notext` affects the verbosity of the output; if it is **`false`**, then additional human-readable information is included in the output. The default value of `notext` is **`true`**. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `csr` accepts an [OpenSSLCertificateSigningRequest](class.opensslcertificatesigningrequest) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509 CSR` was accepted. | ### Examples **Example #1 openssl\_csr\_export() example** ``` <?php $subject = array(     "commonName" => "example.com", ); $private_key = openssl_pkey_new(array(     "private_key_bits" => 2048,     "private_key_type" => OPENSSL_KEYTYPE_RSA, )); $configargs = array(     'digest_alg' => 'sha256WithRSAEncryption' ); $csr = openssl_csr_new($subject, $private_key, $configargs); openssl_csr_export($csr, $csr_string); echo $csr_string; ?> ``` ### See Also * [openssl\_csr\_export\_to\_file()](function.openssl-csr-export-to-file) - Exports a CSR to a file * [openssl\_csr\_new()](function.openssl-csr-new) - Generates a CSR * [openssl\_csr\_sign()](function.openssl-csr-sign) - Sign a CSR with another certificate (or itself) and generate a certificate php mysqli_get_client_stats mysqli\_get\_client\_stats ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) mysqli\_get\_client\_stats — Returns client per-process statistics ### Description ``` mysqli_get_client_stats(): array ``` Returns client per-process statistics. > > **Note**: > > > Available only with [mysqlnd](https://www.php.net/manual/en/book.mysqlnd.php). > > ### Parameters ### Return Values Returns an array with client stats. ### Examples **Example #1 A **mysqli\_get\_client\_stats()** example** ``` <?php $link = mysqli_connect(); print_r(mysqli_get_client_stats()); ?> ``` The above example will output something similar to: ``` Array ( [bytes_sent] => 43 [bytes_received] => 80 [packets_sent] => 1 [packets_received] => 2 [protocol_overhead_in] => 8 [protocol_overhead_out] => 4 [bytes_received_ok_packet] => 11 [bytes_received_eof_packet] => 0 [bytes_received_rset_header_packet] => 0 [bytes_received_rset_field_meta_packet] => 0 [bytes_received_rset_row_packet] => 0 [bytes_received_prepare_response_packet] => 0 [bytes_received_change_user_packet] => 0 [packets_sent_command] => 0 [packets_received_ok] => 1 [packets_received_eof] => 0 [packets_received_rset_header] => 0 [packets_received_rset_field_meta] => 0 [packets_received_rset_row] => 0 [packets_received_prepare_response] => 0 [packets_received_change_user] => 0 [result_set_queries] => 0 [non_result_set_queries] => 0 [no_index_used] => 0 [bad_index_used] => 0 [slow_queries] => 0 [buffered_sets] => 0 [unbuffered_sets] => 0 [ps_buffered_sets] => 0 [ps_unbuffered_sets] => 0 [flushed_normal_sets] => 0 [flushed_ps_sets] => 0 [ps_prepared_never_executed] => 0 [ps_prepared_once_executed] => 0 [rows_fetched_from_server_normal] => 0 [rows_fetched_from_server_ps] => 0 [rows_buffered_from_client_normal] => 0 [rows_buffered_from_client_ps] => 0 [rows_fetched_from_client_normal_buffered] => 0 [rows_fetched_from_client_normal_unbuffered] => 0 [rows_fetched_from_client_ps_buffered] => 0 [rows_fetched_from_client_ps_unbuffered] => 0 [rows_fetched_from_client_ps_cursor] => 0 [rows_skipped_normal] => 0 [rows_skipped_ps] => 0 [copy_on_write_saved] => 0 [copy_on_write_performed] => 0 [command_buffer_too_small] => 0 [connect_success] => 1 [connect_failure] => 0 [connection_reused] => 0 [reconnect] => 0 [pconnect_success] => 0 [active_connections] => 1 [active_persistent_connections] => 0 [explicit_close] => 0 [implicit_close] => 0 [disconnect_close] => 0 [in_middle_of_command_close] => 0 [explicit_free_result] => 0 [implicit_free_result] => 0 [explicit_stmt_close] => 0 [implicit_stmt_close] => 0 [mem_emalloc_count] => 0 [mem_emalloc_ammount] => 0 [mem_ecalloc_count] => 0 [mem_ecalloc_ammount] => 0 [mem_erealloc_count] => 0 [mem_erealloc_ammount] => 0 [mem_efree_count] => 0 [mem_malloc_count] => 0 [mem_malloc_ammount] => 0 [mem_calloc_count] => 0 [mem_calloc_ammount] => 0 [mem_realloc_count] => 0 [mem_realloc_ammount] => 0 [mem_free_count] => 0 [proto_text_fetched_null] => 0 [proto_text_fetched_bit] => 0 [proto_text_fetched_tinyint] => 0 [proto_text_fetched_short] => 0 [proto_text_fetched_int24] => 0 [proto_text_fetched_int] => 0 [proto_text_fetched_bigint] => 0 [proto_text_fetched_decimal] => 0 [proto_text_fetched_float] => 0 [proto_text_fetched_double] => 0 [proto_text_fetched_date] => 0 [proto_text_fetched_year] => 0 [proto_text_fetched_time] => 0 [proto_text_fetched_datetime] => 0 [proto_text_fetched_timestamp] => 0 [proto_text_fetched_string] => 0 [proto_text_fetched_blob] => 0 [proto_text_fetched_enum] => 0 [proto_text_fetched_set] => 0 [proto_text_fetched_geometry] => 0 [proto_text_fetched_other] => 0 [proto_binary_fetched_null] => 0 [proto_binary_fetched_bit] => 0 [proto_binary_fetched_tinyint] => 0 [proto_binary_fetched_short] => 0 [proto_binary_fetched_int24] => 0 [proto_binary_fetched_int] => 0 [proto_binary_fetched_bigint] => 0 [proto_binary_fetched_decimal] => 0 [proto_binary_fetched_float] => 0 [proto_binary_fetched_double] => 0 [proto_binary_fetched_date] => 0 [proto_binary_fetched_year] => 0 [proto_binary_fetched_time] => 0 [proto_binary_fetched_datetime] => 0 [proto_binary_fetched_timestamp] => 0 [proto_binary_fetched_string] => 0 [proto_binary_fetched_blob] => 0 [proto_binary_fetched_enum] => 0 [proto_binary_fetched_set] => 0 [proto_binary_fetched_geometry] => 0 [proto_binary_fetched_other] => 0 ) ``` ### See Also * [Stats description](https://www.php.net/manual/en/mysqlnd.stats.php) php EventDnsBase::loadHosts EventDnsBase::loadHosts ======================= (PECL event >= 1.2.6-beta) EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file ### Description ``` public EventDnsBase::loadHosts( string $hosts ): bool ``` Loads a hosts file (in the same format as `/etc/hosts` ) from hosts file. ### Parameters `hosts` Path to the hosts' file. ### Return Values Returns **`true`** on success or **`false`** on failure. php Ds\Deque::unshift Ds\Deque::unshift ================= (PECL ds >= 1.0.0) Ds\Deque::unshift — Adds values to the front of the deque ### Description ``` public Ds\Deque::unshift(mixed $values = ?): void ``` Adds values to the front of the deque, moving all the current values forward to make room for the new values. ### Parameters `values` The values to add to the front of the deque. > > **Note**: > > > Multiple values will be added in the same order that they are passed. > > ### Return Values No value is returned. ### Examples **Example #1 **Ds\Deque::unshift()** example** ``` <?php $deque = new \Ds\Deque([1, 2, 3]); $deque->unshift("a"); $deque->unshift("b", "c"); print_r($deque); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => b [1] => c [2] => a [3] => 1 [4] => 2 [5] => 3 ) ``` php ob_clean ob\_clean ========= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) ob\_clean — Clean (erase) the output buffer ### Description ``` ob_clean(): bool ``` This function discards the contents of the output buffer. This function does not destroy the output buffer like [ob\_end\_clean()](function.ob-end-clean) does. The output buffer must be started by [ob\_start()](function.ob-start) with [PHP\_OUTPUT\_HANDLER\_CLEANABLE](https://www.php.net/manual/en/outcontrol.constants.php#constant.php-output-handler-cleanable) flag. Otherwise **ob\_clean()** will not work. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [ob\_flush()](function.ob-flush) - Flush (send) the output buffer * [ob\_end\_flush()](function.ob-end-flush) - Flush (send) the output buffer and turn off output buffering * [ob\_end\_clean()](function.ob-end-clean) - Clean (erase) the output buffer and turn off output buffering php EventHttpRequest::getOutputHeaders EventHttpRequest::getOutputHeaders ================================== (PECL event >= 1.4.0-beta) EventHttpRequest::getOutputHeaders — Returns associative array of the output headers ### Description ``` public EventHttpRequest::getOutputHeaders(): void ``` Returns associative array of the output headers. ### Parameters This function has no parameters. ### Return Values ### See Also * [EventHttpRequest::getInputHeaders()](eventhttprequest.getinputheaders) - Returns associative array of the input headers php pg_dbname pg\_dbname ========== (PHP 4, PHP 5, PHP 7, PHP 8) pg\_dbname — Get the database name ### Description ``` pg_dbname(?PgSql\Connection $connection = null): string ``` **pg\_dbname()** returns the name of the database that the given PostgreSQL `connection` instance. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is **`null`**, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. ### Return Values A string containing the name of the database the `connection` is to. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `connection` is now nullable. | ### Examples **Example #1 **pg\_dbname()** example** ``` <?php   error_reporting(E_ALL);   pg_connect("host=localhost port=5432 dbname=mary");   echo pg_dbname(); // mary ?> ``` php Ds\Collection::clear Ds\Collection::clear ==================== (PECL ds >= 1.0.0) Ds\Collection::clear — Removes all values ### Description ``` abstract public Ds\Collection::clear(): void ``` Removes all values from the collection. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Collection::clear()** example** ``` <?php $collection = new \Ds\Vector([1, 2, 3]); print_r($collection); $collection->clear(); print_r($collection); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 ) Ds\Vector Object ( ) ``` php The Yaf_Request_Simple class The Yaf\_Request\_Simple class ============================== Introduction ------------ (Yaf >=1.0.0) **Yaf\_Request\_Simple** is particularlly used for test puporse. ie. simulate some espacial request under CLI mode. Class synopsis -------------- class **Yaf\_Request\_Simple** extends [Yaf\_Request\_Abstract](class.yaf-request-abstract) { /\* Constants \*/ const string [SCHEME\_HTTP](class.yaf-request-simple#yaf-request-simple.constants.scheme-http) = http; const string [SCHEME\_HTTPS](class.yaf-request-simple#yaf-request-simple.constants.scheme-https) = https; /\* Properties \*/ /\* Methods \*/ public [\_\_construct](yaf-request-simple.construct)( string `$method` = ?, string `$module` = ?, string `$controller` = ?, string `$action` = ?, array `$params` = ? ) ``` public get(): void ``` ``` public getCookie(): void ``` ``` public getFiles(): void ``` ``` public getPost(): void ``` ``` public getQuery(): void ``` ``` public getRequest(): void ``` ``` public isXmlHttpRequest(): void ``` /\* Inherited methods \*/ ``` public Yaf_Request_Abstract::clearParams(): bool ``` ``` public Yaf_Request_Abstract::getActionName(): void ``` ``` public Yaf_Request_Abstract::getBaseUri(): void ``` ``` public Yaf_Request_Abstract::getControllerName(): void ``` ``` public Yaf_Request_Abstract::getEnv(string $name, string $default = ?): void ``` ``` public Yaf_Request_Abstract::getException(): void ``` ``` public Yaf_Request_Abstract::getLanguage(): void ``` ``` public Yaf_Request_Abstract::getMethod(): string ``` ``` public Yaf_Request_Abstract::getModuleName(): void ``` ``` public Yaf_Request_Abstract::getParam(string $name, string $default = ?): mixed ``` ``` public Yaf_Request_Abstract::getParams(): array ``` ``` public Yaf_Request_Abstract::getRequestUri(): void ``` ``` public Yaf_Request_Abstract::getServer(string $name, string $default = ?): void ``` ``` public Yaf_Request_Abstract::isCli(): bool ``` ``` public Yaf_Request_Abstract::isDispatched(): bool ``` ``` public Yaf_Request_Abstract::isGet(): bool ``` ``` public Yaf_Request_Abstract::isHead(): bool ``` ``` public Yaf_Request_Abstract::isOptions(): bool ``` ``` public Yaf_Request_Abstract::isPost(): bool ``` ``` public Yaf_Request_Abstract::isPut(): bool ``` ``` public Yaf_Request_Abstract::isRouted(): bool ``` ``` public Yaf_Request_Abstract::isXmlHttpRequest(): bool ``` ``` public Yaf_Request_Abstract::setActionName(string $action, bool $format_name = true): void ``` ``` public Yaf_Request_Abstract::setBaseUri(string $uir): bool ``` ``` public Yaf_Request_Abstract::setControllerName(string $controller, bool $format_name = true): void ``` ``` public Yaf_Request_Abstract::setDispatched(): void ``` ``` public Yaf_Request_Abstract::setModuleName(string $module, bool $format_name = true): void ``` ``` public Yaf_Request_Abstract::setParam(string $name, string $value = ?): bool ``` ``` public Yaf_Request_Abstract::setRequestUri(string $uir): void ``` ``` public Yaf_Request_Abstract::setRouted(string $flag = ?): void ``` } Properties ---------- module controller action method params language \_exception \_base\_uri uri dispatched routed Predefined Constants -------------------- **`Yaf_Request_Simple::SCHEME_HTTP`** **`Yaf_Request_Simple::SCHEME_HTTPS`** Table of Contents ----------------- * [Yaf\_Request\_Simple::\_\_construct](yaf-request-simple.construct) — Constructor of Yaf\_Request\_Simple * [Yaf\_Request\_Simple::get](yaf-request-simple.get) — The get purpose * [Yaf\_Request\_Simple::getCookie](yaf-request-simple.getcookie) — The getCookie purpose * [Yaf\_Request\_Simple::getFiles](yaf-request-simple.getfiles) — The getFiles purpose * [Yaf\_Request\_Simple::getPost](yaf-request-simple.getpost) — The getPost purpose * [Yaf\_Request\_Simple::getQuery](yaf-request-simple.getquery) — The getQuery purpose * [Yaf\_Request\_Simple::getRequest](yaf-request-simple.getrequest) — The getRequest purpose * [Yaf\_Request\_Simple::isXmlHttpRequest](yaf-request-simple.isxmlhttprequest) — Determin if request is AJAX request
programming_docs
php fdf_get_status fdf\_get\_status ================ (PHP 4, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_get\_status — Get the value of the /STATUS key ### Description ``` fdf_get_status(resource $fdf_document): string ``` Gets the value of the `/STATUS` key. ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). ### Return Values Returns the key value, as a string. ### See Also * [fdf\_set\_status()](function.fdf-set-status) - Set the value of the /STATUS key php openssl_pkcs7_verify openssl\_pkcs7\_verify ====================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) openssl\_pkcs7\_verify — Verifies the signature of an S/MIME signed message ### Description ``` openssl_pkcs7_verify( string $input_filename, int $flags, ?string $signers_certificates_filename = null, array $ca_info = [], ?string $untrusted_certificates_filename = null, ?string $content = null, ?string $output_filename = null ): bool|int ``` **openssl\_pkcs7\_verify()** reads the S/MIME message contained in the given file and examines the digital signature. ### Parameters `input_filename` Path to the message. `flags` `flags` can be used to affect how the signature is verified - see [PKCS7 constants](https://www.php.net/manual/en/openssl.pkcs7.flags.php) for more information. `signers_certificates_filename` If the `signers_certificates_filename` is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format. `ca_info` If the `ca_info` is specified, it should hold information about the trusted CA certificates to use in the verification process - see [certificate verification](https://www.php.net/manual/en/openssl.cert.verification.php) for more information about this parameter. `untrusted_certificates_filename` If the `untrusted_certificates_filename` is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs. `content` You can specify a filename with `content` that will be filled with the verified data, but with the signature information stripped. `output_filename` ### Return Values Returns **`true`** if the signature is verified, **`false`** if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `signers_certificates_filename`, `untrusted_certificates_filename`, `content` and `output_filename` are nullable now. | | 7.2.0 | The `output_filename` parameter was added. | ### Notes > **Note**: As specified in RFC 2045, lines may not be longer than 76 characters in the `input_filename` parameter. > > php mysqli_warning::next mysqli\_warning::next ===================== (PHP 5, PHP 7, PHP 8) mysqli\_warning::next — Fetch next warning ### Description ``` public mysqli_warning::next(): bool ``` Change warning information to the next warning if possible. Once the warning has been set to the next warning, new values of properties `message`, `sqlstate` and `errno` of [mysqli\_warning](class.mysqli-warning) are available. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if next warning was fetched successfully. If there are no more warnings, it will return **`false`** php net_get_interfaces net\_get\_interfaces ==================== (PHP 7 >= 7.3, PHP 8) net\_get\_interfaces — Get network interfaces ### Description ``` net_get_interfaces(): array|false ``` Returns an enumeration of network interfaces (adapters) on the local machine. ### Parameters This function has no parameters. ### Return Values Returns an associative array where the key is the name of the interface and the value an associative array of interface attributes, or **`false`** on failure. Each interface associative array contains: **Interface attributes**| Name | Description | | --- | --- | | description | Optional string value for description of the interface. Windows only. | | mac | Optional string value for MAC address of the interface. Windows only. | | mtu | Integer value for Maximum transmission unit (MTU) of the interface. Windows only. | | unicast | Array of associative arrays, see Unicast attributes below. | | up | Boolean status (on/off) for interface. | **Unicast attributes**| Name | Description | | --- | --- | | flags | Integer value. | | family | Integer value. | | address | String value for address in either IPv4 or IPv6. | | netmask | String value for netmask in either IPv4 or IPv6. | ### Errors/Exceptions Emits an **`E_WARNING`** on failure to get interface information. php stream_set_write_buffer stream\_set\_write\_buffer ========================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) stream\_set\_write\_buffer — Sets write file buffering on the given stream ### Description ``` stream_set_write_buffer(resource $stream, int $size): int ``` Sets the buffering for write operations on the given `stream` to `size` bytes. ### Parameters `stream` The file pointer. `size` The number of bytes to buffer. If `size` is 0 then write operations are unbuffered. This ensures that all writes with [fwrite()](function.fwrite) are completed before other processes are allowed to write to that output stream. ### Return Values Returns 0 on success, or another value if the request cannot be honored. ### Examples **Example #1 **stream\_set\_write\_buffer()** example** The following example demonstrates how to use **stream\_set\_write\_buffer()** to create an unbuffered stream. ``` <?php $fp = fopen($file, "w"); if ($fp) {   if (stream_set_write_buffer($fp, 0) !== 0) {       // changing the buffering failed   }   fwrite($fp, $output);   fclose($fp); } ?> ``` ### See Also * [fopen()](function.fopen) - Opens file or URL * [fwrite()](function.fwrite) - Binary-safe file write php date_create_immutable_from_format date\_create\_immutable\_from\_format ===================================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) date\_create\_immutable\_from\_format — Alias of [DateTimeImmutable::createFromFormat()](datetimeimmutable.createfromformat) ### Description This function is an alias of: [DateTimeImmutable::createFromFormat()](datetimeimmutable.createfromformat) php SolrQuery::getMltBoost SolrQuery::getMltBoost ====================== (PECL solr >= 0.9.2) SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance ### Description ``` public SolrQuery::getMltBoost(): bool ``` Returns whether or not the query will be boosted by the interesting term relevance ### Parameters This function has no parameters. ### Return Values Returns a boolean on success and **`null`** if not set. php SessionHandler::destroy SessionHandler::destroy ======================= (PHP 5 >= 5.4.0, PHP 7, PHP 8) SessionHandler::destroy — Destroy a session ### Description ``` public SessionHandler::destroy(string $id): bool ``` Destroys a session. Called internally by PHP with [session\_regenerate\_id()](function.session-regenerate-id) (assuming the `$destroy` is set to **`true`**, by [session\_destroy()](function.session-destroy) or when [session\_decode()](function.session-decode) fails. This method wraps the internal PHP save handler defined in the [session.save\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.save-handler) ini setting that was set before this handler was set by [session\_set\_save\_handler()](function.session-set-save-handler). If this class is extended by inheritance, calling the parent `destroy` method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered. For more information on what this method is expected to do, please refer to the documentation at [SessionHandlerInterface::destroy()](sessionhandlerinterface.destroy). ### Parameters `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. php ldap_start_tls ldap\_start\_tls ================ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) ldap\_start\_tls — Start TLS ### Description ``` ldap_start_tls(LDAP\Connection $ldap): bool ``` **Warning**This function is currently not documented; only its argument list is available. php eio_realpath eio\_realpath ============= (PECL eio >= 0.0.1dev) eio\_realpath — Get the canonicalized absolute pathname ### Description ``` eio_realpath( string $path, int $pri, callable $callback, string $data = NULL ): resource ``` **eio\_realpath()** returns the canonicalized absolute pathname in `result` argument of `callback` function. ### Parameters `path` Short pathname `pri` `callback` `data` ### Return Values ### Examples **Example #1 **eio\_realpath()** example** ``` <?php var_dump(getcwd()); function my_realpath_allback($data, $result) {     var_dump($result); } eio_realpath("../", EIO_PRI_DEFAULT, "my_realpath_allback"); eio_event_loop(); ?> ``` The above example will output something similar to: ``` string(12) "/home/ruslan" string(5) "/home" ``` php RecursiveTreeIterator::callGetChildren RecursiveTreeIterator::callGetChildren ====================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::callGetChildren — Get children ### Description ``` public RecursiveTreeIterator::callGetChildren(): RecursiveIterator ``` Gets children of the current element. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values A [RecursiveIterator](class.recursiveiterator). php rsort rsort ===== (PHP 4, PHP 5, PHP 7, PHP 8) rsort — Sort an array in descending order ### Description ``` rsort(array &$array, int $flags = SORT_REGULAR): bool ``` Sorts `array` in place by values in descending order. > > **Note**: > > > If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. > > > **Note**: This function assigns new keys to the elements in `array`. It will remove any existing keys that may have been assigned, rather than just reordering the keys. > > > > **Note**: > > > Resets array's internal pointer to the first element. > > ### Parameters `array` The input array. `flags` The optional second parameter `flags` may be used to modify the sorting behavior using these values: Sorting type flags: * **`SORT_REGULAR`** - compare items normally; the details are described in the [comparison operators](language.operators.comparison) section * **`SORT_NUMERIC`** - compare items numerically * **`SORT_STRING`** - compare items as strings * **`SORT_LOCALE_STRING`** - compare items as strings, based on the current locale. It uses the locale, which can be changed using [setlocale()](function.setlocale) * **`SORT_NATURAL`** - compare items as strings using "natural ordering" like [natsort()](function.natsort) * **`SORT_FLAG_CASE`** - can be combined (bitwise OR) with **`SORT_STRING`** or **`SORT_NATURAL`** to sort strings case-insensitively ### Return Values Always returns **`true`**. ### Examples **Example #1 **rsort()** example** ``` <?php $fruits = array("lemon", "orange", "banana", "apple"); rsort($fruits); foreach ($fruits as $key => $val) {     echo "$key = $val\n"; } ?> ``` The above example will output: ``` 0 = orange 1 = lemon 2 = banana 3 = apple ``` The fruits have been sorted in reverse alphabetical order. ### See Also * [sort()](function.sort) - Sort an array in ascending order * [arsort()](function.arsort) - Sort an array in descending order and maintain index association * [krsort()](function.krsort) - Sort an array by key in descending order * The [comparison of array sorting functions](https://www.php.net/manual/en/array.sorting.php) php Yaf_Controller_Abstract::display Yaf\_Controller\_Abstract::display ================================== (Yaf >=1.0.0) Yaf\_Controller\_Abstract::display — The display purpose ### Description ``` protected Yaf_Controller_Abstract::display(string $tpl, array $parameters = ?): bool ``` ### Parameters `tpl` `parameters` ### Return Values php file_put_contents file\_put\_contents =================== (PHP 5, PHP 7, PHP 8) file\_put\_contents — Write data to a file ### Description ``` file_put_contents( string $filename, mixed $data, int $flags = 0, ?resource $context = null ): int|false ``` This function is identical to calling [fopen()](function.fopen), [fwrite()](function.fwrite) and [fclose()](function.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()](function.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](https://www.php.net/manual/en/ini.core.php#ini.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()](function.flock) call happens between the [fopen()](function.fopen) call and the [fwrite()](function.fwrite) call. This is not identical to an [fopen()](function.fopen) call with mode "x". | `context` A valid context resource created with [stream\_context\_create()](function.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](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Examples **Example #1 Simple usage example** ``` <?php $file = 'people.txt'; // Open the file to get existing content $current = file_get_contents($file); // Append a new person to the file $current .= "John Smith\n"; // Write the contents back to the file file_put_contents($file, $current); ?> ``` **Example #2 Using flags** ``` <?php $file = 'people.txt'; // The new person to add to the file $person = "John Smith\n"; // Write the contents to the file,  // using the FILE_APPEND flag to append the content to the end of the file // and the LOCK_EX flag to prevent anyone else writing to the file at the same time file_put_contents($file, $person, FILE_APPEND | LOCK_EX); ?> ``` ### Notes > **Note**: This function is binary-safe. > > **Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) 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()](function.fopen) - Opens file or URL * [fwrite()](function.fwrite) - Binary-safe file write * [file\_get\_contents()](function.file-get-contents) - Reads entire file into a string * [stream\_context\_create()](function.stream-context-create) - Creates a stream context php realpath_cache_get realpath\_cache\_get ==================== (PHP 5 >= 5.3.2, PHP 7, PHP 8) realpath\_cache\_get — Get realpath cache entries ### Description ``` realpath_cache_get(): array ``` Get the contents of the realpath cache. ### Parameters This function has no parameters. ### Return Values Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache. ### Examples **Example #1 **realpath\_cache\_get()** example** ``` <?php var_dump(realpath_cache_get()); ?> ``` The above example will output something similar to: ``` array(2) { ["/test"]=> array(4) { ["key"]=> int(123456789) ["is_dir"]=> bool(true) ["realpath"]=> string(5) "/test" ["expires"]=> int(1260318939) } ["/test/test.php"]=> array(4) { ["key"]=> int(987654321) ["is_dir"]=> bool(false) ["realpath"]=> string(12) "/root/test.php" ["expires"]=> int(1260318939) } } ``` ### See Also * [realpath\_cache\_size()](function.realpath-cache-size) - Get realpath cache size php Yaf_Application::getModules Yaf\_Application::getModules ============================ (Yaf >=1.0.0) Yaf\_Application::getModules — Get defined module names ### Description ``` public Yaf_Application::getModules(): array ``` Get the modules list defined in config, if no one defined, there will always be a module named "Index". ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 **Yaf\_Application::getModules()**example** ``` <?php $config = array(     "application" => array(         "directory" => realpath(dirname(__FILE__)) . "/application",     ), ); /** Yaf_Application */ $application = new Yaf_Application($config); print_r($application->getModules()); ?> ``` The above example will output something similar to: ``` Array ( [0] => Index ) ``` php NoRewindIterator::current NoRewindIterator::current ========================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) NoRewindIterator::current — Get the current value ### Description ``` public NoRewindIterator::current(): mixed ``` Gets the current value. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The current value. ### See Also * [NoRewindIterator::key()](norewinditerator.key) - Get the current key php SplObjectStorage::removeAllExcept SplObjectStorage::removeAllExcept ================================= (PHP 5 >= 5.3.6, PHP 7, PHP 8) SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage ### Description ``` public SplObjectStorage::removeAllExcept(SplObjectStorage $storage): int ``` Removes all objects except for those contained in another storage from the current storage. ### Parameters `storage` The storage containing the elements to retain in the current storage. ### Return Values Returns the number of remaining objects. ### Examples **Example #1 **SplObjectStorage::removeAllExcept()** example** ``` <?php $a = (object) 'a';  $b = (object) 'b';  $c = (object) 'c';  $foo = new SplObjectStorage; $foo->attach($a); $foo->attach($b); $bar = new SplObjectStorage; $bar->attach($b); $bar->attach($c); $foo->removeAllExcept($bar); var_dump($foo->contains($a)); var_dump($foo->contains($b)); ?> ``` The above example will output something similar to: ``` bool(false) bool(true) ```
programming_docs
php mb_regex_encoding mb\_regex\_encoding =================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) mb\_regex\_encoding — Set/Get character encoding for multibyte regex ### Description ``` mb_regex_encoding(?string $encoding = null): string|bool ``` Set/Get character encoding for a multibyte regex. ### Parameters `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values If `encoding` is set, then Returns **`true`** on success or **`false`** on failure. In this case, the internal character encoding is NOT changed. If `encoding` is omitted, then the current character encoding name for a multibyte regex is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | ### See Also * [mb\_internal\_encoding()](function.mb-internal-encoding) - Set/Get internal character encoding * [mb\_ereg()](function.mb-ereg) - Regular expression match with multibyte support php Memcached::deleteByKey Memcached::deleteByKey ====================== (PECL memcached >= 0.1.0) Memcached::deleteByKey — Delete an item from a specific server ### Description ``` public Memcached::deleteByKey(string $server_key, string $key, int $time = 0): bool ``` **Memcached::deleteByKey()** is functionally equivalent to [Memcached::delete()](memcached.delete), except that the free-form `server_key` can be used to map the `key` to a specific server. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `key` The key to be deleted. `time` The amount of time the server will wait to delete the item. > **Note**: As of memcached 1.3.0 (released 2009) this feature is no longer supported. Passing a non-zero `time` will cause the deletion to fail. [Memcached::getResultCode()](memcached.getresultcode) will return **`MEMCACHED_INVALID_ARGUMENTS`**. > > ### Return Values Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTFOUND`** if the key does not exist. ### See Also * [Memcached::delete()](memcached.delete) - Delete an item * [Memcached::deleteMulti()](memcached.deletemulti) - Delete multiple items * [Memcached::deleteMultiByKey()](memcached.deletemultibykey) - Delete multiple items from a specific server php sodium_base642bin sodium\_base642bin ================== (PHP 7 >= 7.2.0, PHP 8) sodium\_base642bin — Decodes a base64-encoded string into raw binary. ### Description ``` sodium_base642bin(string $string, int $id, string $ignore = ""): string ``` Converts a base64 encoded string into raw binary. Unlike [base64\_decode()](function.base64-decode), **sodium\_base642bin()** is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys) and supports multiple character sets. ### Parameters `string` string; Encoded string. `id` * **`SODIUM_BASE64_VARIANT_ORIGINAL`** for standard (`A-Za-z0-9/\+`) Base64 encoding. * **`SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING`** for standard (`A-Za-z0-9/\+`) Base64 encoding, without `=` padding characters. * **`SODIUM_BASE64_VARIANT_URLSAFE`** for URL-safe (`A-Za-z0-9\-_`) Base64 encoding. * **`SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING`** for URL-safe (`A-Za-z0-9\-_`) Base64 encoding, without `=` padding characters. `ignore` Characters to ignore when decoding (e.g. whitespace characters). ### Return Values Decoded string. php Zookeeper::create Zookeeper::create ================= (PECL zookeeper >= 0.1.0) Zookeeper::create — Create a node synchronously ### Description ``` public Zookeeper::create( string $path, string $value, array $acls, int $flags = null ): string ``` This method will create a node in ZooKeeper. A node can only be created if it does not already exists. The Create Flags affect the creation of nodes. If ZOO\_EPHEMERAL flag is set, the node will automatically get removed if the client session goes away. If the ZOO\_SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name. ### Parameters `path` The name of the node. Expressed as a file name with slashes separating ancestors of the node. `value` The data to be stored in the node. `acls` The initial ACL of the node. The ACL must not be null or empty. `flags` this parameter can be set to 0 for normal create or an OR of the Create Flags ### Return Values Returns the path of the new node (this might be different than the supplied path because of the ZOO\_SEQUENCE flag) on success, and false on failure. ### Errors/Exceptions This method emits PHP error/warning when parameters count or types are wrong or fail to create node. **Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives. ### Examples **Example #1 **Zookeeper::create()** example** Create a new node. ``` <?php $zookeeper = new Zookeeper('locahost:2181'); $aclArray = array(   array(     'perms'  => Zookeeper::PERM_ALL,     'scheme' => 'world',     'id'     => 'anyone',   ) ); $path = '/path/to/newnode'; $realPath = $zookeeper->create($path, null, $aclArray); if ($realPath)   echo $realPath; else   echo 'ERR'; ?> ``` The above example will output: ``` /path/to/newnode ``` ### See Also * [Zookeeper::delete()](zookeeper.delete) - Delete a node in zookeeper synchronously * [Zookeeper::getChildren()](zookeeper.getchildren) - Lists the children of a node synchronously * [ZooKeeper Permissions](class.zookeeper#zookeeper.class.constants.perms) * [ZookeeperException](class.zookeeperexception) php ldap_rename_ext ldap\_rename\_ext ================= (PHP 7 >= 7.3.0, PHP 8) ldap\_rename\_ext — Modify the name of an entry ### Description ``` ldap_rename_ext( LDAP\Connection $ldap, string $dn, string $new_rdn, string $new_parent, bool $delete_old_rdn, ?array $controls = null ): LDAP\Result|false ``` Does the same thing as [ldap\_rename()](function.ldap-rename) but returns an [LDAP\Result](class.ldap-result) instance to be parsed with [ldap\_parse\_result()](function.ldap-parse-result). ### Parameters See [ldap\_rename()](function.ldap-rename) ### Return Values Returns an [LDAP\Result](class.ldap-result) instance, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | Returns an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was returned. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | | 7.3.0 | Support for `controls` added | ### See Also * [ldap\_rename()](function.ldap-rename) - Modify the name of an entry * [ldap\_parse\_result()](function.ldap-parse-result) - Extract information from result php openal_device_close openal\_device\_close ===================== (PECL openal >= 0.1.0) openal\_device\_close — Close an OpenAL device ### Description ``` openal_device_close(resource $device): bool ``` ### Parameters `device` An [Open AL(Device)](https://www.php.net/manual/en/openal.resources.php) resource (previously created by [openal\_device\_open()](function.openal-device-open)) to be closed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [openal\_device\_open()](function.openal-device-open) - Initialize the OpenAL audio layer php DOMChildNode::after DOMChildNode::after =================== (PHP 8) DOMChildNode::after — Adds nodes after the node ### Description ``` public DOMChildNode::after(DOMNode|string ...$nodes): void ``` Adds the passed `nodes` after the node. ### Parameters `nodes` Nodes to be added after the node. ### Return Values No value is returned. ### See Also * [DOMChildNode::before()](domchildnode.before) - Adds nodes before the node * [DOMChildNode::remove()](domchildnode.remove) - Removes the node * [DOMChildNode::replaceWith()](domchildnode.replacewith) - Replaces the node with new nodes * [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children php InfiniteIterator::next InfiniteIterator::next ====================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) InfiniteIterator::next — Moves the inner Iterator forward or rewinds it ### Description ``` public InfiniteIterator::next(): void ``` Moves the inner [Iterator](class.iterator) forward to its next element if there is one, otherwise rewinds the inner [Iterator](class.iterator) back to the beginning. > > **Note**: > > > Even an [InfiniteIterator](class.infiniteiterator) stops if its inner [Iterator](class.iterator) is empty. > > ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [InfiniteIterator::\_\_construct()](infiniteiterator.construct) - Constructs an InfiniteIterator php DOMDocument::relaxNGValidate DOMDocument::relaxNGValidate ============================ (PHP 5, PHP 7, PHP 8) DOMDocument::relaxNGValidate — Performs relaxNG validation on the document ### Description ``` public DOMDocument::relaxNGValidate(string $filename): bool ``` Performs [» relaxNG](http://www.relaxng.org/) validation on the document based on the given RNG schema. ### Parameters `filename` The RNG file. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [DOMDocument::relaxNGValidateSource()](domdocument.relaxngvalidatesource) - Performs relaxNG validation on the document * [DOMDocument::schemaValidate()](domdocument.schemavalidate) - Validates a document based on a schema. Only XML Schema 1.0 is supported. * [DOMDocument::schemaValidateSource()](domdocument.schemavalidatesource) - Validates a document based on a schema * [DOMDocument::validate()](domdocument.validate) - Validates the document based on its DTD php The Countable interface The Countable interface ======================= Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Classes implementing **Countable** can be used with the [count()](function.count) function. Interface synopsis ------------------ interface **Countable** { /\* Methods \*/ ``` public count(): int ``` } Table of Contents ----------------- * [Countable::count](countable.count) — Count elements of an object php EventHttp::setDefaultCallback EventHttp::setDefaultCallback ============================= (PECL event >= 1.4.0-beta) EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks ### Description ``` public EventHttp::setDefaultCallback( string $cb , string $arg = ?): void ``` Sets default callback to handle requests that are not caught by specific callbacks ### Parameters `cb` The callback [callable](language.types.callable) . It should match the following prototype: ``` callback( EventHttpRequest $req = NULL , mixed $arg = NULL ): void ``` `req` [EventHttpRequest](class.eventhttprequest) object. `arg` Custom data. `arg` User custom data passed to the callback. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **EventHttp::setDefaultCallback()** example** ``` <?php $base = new EventBase(); $http = new EventHttp($base); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$http->bind("127.0.0.1", 8088)) {     exit("bind(1) failed\n"); }; $http->setDefaultCallback(function($req) {     echo "URI: ", $req->getUri(), PHP_EOL;     $req->sendReply(200, "OK"); }); $base->dispatch(); ?> ``` ### See Also * [EventHttp::setCallback()](eventhttp.setcallback) - Sets a callback for specified URI php Yaf_Request_Abstract::setRequestUri Yaf\_Request\_Abstract::setRequestUri ===================================== (Yaf >=2.1.0) Yaf\_Request\_Abstract::setRequestUri — The setRequestUri purpose ### Description ``` public Yaf_Request_Abstract::setRequestUri(string $uir): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `uir` ### Return Values php imagesetthickness imagesetthickness ================= (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) imagesetthickness — Set the thickness for line drawing ### Description ``` imagesetthickness(GdImage $image, int $thickness): bool ``` **imagesetthickness()** sets the thickness of the lines drawn when drawing rectangles, polygons, arcs etc. to `thickness` pixels. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `thickness` Thickness, in pixels. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagesetthickness()** example** ``` <?php // Create a 200x100 image $im = imagecreatetruecolor(200, 100); $white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF); $black = imagecolorallocate($im, 0x00, 0x00, 0x00); // Set the background to be white imagefilledrectangle($im, 0, 0, 299, 99, $white); // Set the line thickness to 5 imagesetthickness($im, 5); // Draw the rectangle imagerectangle($im, 14, 14, 185, 85, $black); // Output image to the browser header('Content-Type: image/png'); imagepng($im); imagedestroy($im); ?> ``` The above example will output something similar to: php SolrQuery::addGroupQuery SolrQuery::addGroupQuery ======================== (PECL solr >= 2.2.0) SolrQuery::addGroupQuery — Allows grouping of documents that match the given query ### Description ``` public SolrQuery::addGroupQuery(string $value): SolrQuery ``` Allows grouping of documents that match the given query. Adds query to the group.query parameter ### Parameters `value` ### Return Values [SolrQuery](class.solrquery) ### See Also * [SolrQuery::setGroup()](solrquery.setgroup) - Enable/Disable result grouping (group parameter) * [SolrQuery::addGroupField()](solrquery.addgroupfield) - Add a field to be used to group results * [SolrQuery::addGroupFunction()](solrquery.addgroupfunction) - Allows grouping results based on the unique values of a function query (group.func parameter) * [SolrQuery::addGroupSortField()](solrquery.addgroupsortfield) - Add a group sort field (group.sort parameter) * [SolrQuery::setGroupFacet()](solrquery.setgroupfacet) - Sets group.facet parameter * [SolrQuery::setGroupOffset()](solrquery.setgroupoffset) - Sets the group.offset parameter * [SolrQuery::setGroupLimit()](solrquery.setgrouplimit) - Specifies the number of results to return for each group. The server default value is 1 * [SolrQuery::setGroupMain()](solrquery.setgroupmain) - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple * [SolrQuery::setGroupNGroups()](solrquery.setgroupngroups) - If true, Solr includes the number of groups that have matched the query in the results * [SolrQuery::setGroupTruncate()](solrquery.setgrouptruncate) - If true, facet counts are based on the most relevant document of each group matching the query * [SolrQuery::setGroupFormat()](solrquery.setgroupformat) - Sets the group format, result structure (group.format parameter) * [SolrQuery::setGroupCachePercent()](solrquery.setgroupcachepercent) - Enables caching for result grouping php mb_preferred_mime_name mb\_preferred\_mime\_name ========================= (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_preferred\_mime\_name — Get MIME charset string ### Description ``` mb_preferred_mime_name(string $encoding): string|false ``` Get a MIME charset string for a specific encoding. ### Parameters `encoding` The encoding being checked. ### Return Values The MIME `charset` string for character encoding `encoding`, or **`false`** if no charset is preferred for the given `encoding`. ### Examples **Example #1 **mb\_preferred\_mime\_name()** example** ``` <?php $outputenc = "sjis-win"; mb_http_output($outputenc); ob_start("mb_output_handler"); header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc)); ?> ``` php apcu_cache_info apcu\_cache\_info ================= (PECL apcu >= 4.0.0) apcu\_cache\_info — Retrieves cached information from APCu's data store ### Description ``` apcu_cache_info(bool $limited = false): array|false ``` Retrieves cached information and meta-data from APC's data store. ### Parameters `limited` If `limited` is **`true`**, the return value will exclude the individual list of cache entries. This is useful when trying to optimize calls for statistics gathering. ### Return Values Array of cached data (and meta-data) or **`false`** on failure > **Note**: **apcu\_cache\_info()** will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled. > > ### Changelog | Version | Description | | --- | --- | | PECL apcu 3.0.11 | The `limited` parameter was introduced. | | PECL apcu 3.0.16 | The "`filehits`" option for the `cache_type` parameter was introduced. | ### Examples **Example #1 A **apcu\_cache\_info()** example** ``` <?php print_r(apcu_cache_info()); ?> ``` The above example will output something similar to: ``` Array ( [num_slots] => 2000 [ttl] => 0 [num_hits] => 9 [num_misses] => 3 [start_time] => 1123958803 [cache_list] => Array ( [0] => Array ( [filename] => /path/to/apcu_test.php [device] => 29954 [inode] => 1130511 [type] => file [num_hits] => 1 [mtime] => 1123960686 [creation_time] => 1123960696 [deletion_time] => 0 [access_time] => 1123962864 [ref_count] => 1 [mem_size] => 677 ) [1] => Array (...iterates for each cached file) ) ``` ### See Also * [APCu configuration directives](https://www.php.net/manual/en/apcu.configuration.php) * [APCUIterator::getTotalSize()](apcuiterator.gettotalsize) - Get total cache size * [APCUIterator::getTotalHits()](apcuiterator.gettotalhits) - Get total cache hits * [APCUIterator::getTotalCount()](apcuiterator.gettotalcount) - Get total count php EventHttpRequest::cancel EventHttpRequest::cancel ======================== (PECL event >= 1.4.0-beta) EventHttpRequest::cancel — Cancels a pending HTTP request ### Description ``` public EventHttpRequest::cancel(): void ``` Cancels a pending HTTP request. Cancels an ongoing HTTP request. The callback associated with this request is not executed and the request object is freed. If the request is currently being processed, e.g. it is ongoing, the corresponding [EventHttpConnection](class.eventhttpconnection) object is going to get reset. A request cannot be canceled if its callback has executed already. A request may be canceled reentrantly from its chunked callback. ### Parameters This function has no parameters. ### Return Values No value is returned.
programming_docs
php SplFixedArray::getSize SplFixedArray::getSize ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplFixedArray::getSize — Gets the size of the array ### Description ``` public SplFixedArray::getSize(): int ``` Gets the size of the array. ### Parameters This function has no parameters. ### Return Values Returns the size of the array, as an int. ### Examples **Example #1 **SplFixedArray::getSize()** example** ``` <?php $array = new SplFixedArray(5); echo $array->getSize()."\n"; $array->setSize(10); echo $array->getSize()."\n"; ?> ``` The above example will output: ``` 5 10 ``` ### Notes > > **Note**: > > > This method is functionally equivalent to [SplFixedArray::count()](splfixedarray.count) > > ### See Also * [SplFixedArray::count()](splfixedarray.count) - Returns the size of the array php ReflectionClass::__toString ReflectionClass::\_\_toString ============================= (PHP 5, PHP 7, PHP 8) ReflectionClass::\_\_toString — Returns the string representation of the ReflectionClass object ### Description ``` public ReflectionClass::__toString(): string ``` Returns the string representation of the ReflectionClass object. ### Parameters This function has no parameters. ### Return Values A string representation of this [ReflectionClass](class.reflectionclass) instance. ### Examples **Example #1 **ReflectionClass::\_\_toString()** example** ``` <?php $reflectionClass = new ReflectionClass('Exception'); echo $reflectionClass->__toString(); ?> ``` The above example will output: ``` Class [ <internal:Core> class Exception ] { - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [7] { Property [ <default> protected $message ] Property [ <default> private $string ] Property [ <default> protected $code ] Property [ <default> protected $file ] Property [ <default> protected $line ] Property [ <default> private $trace ] Property [ <default> private $previous ] } - Methods [10] { Method [ <internal:Core> final private method __clone ] { } Method [ <internal:Core, ctor> public method __construct ] { - Parameters [3] { Parameter #0 [ <optional> $message ] Parameter #1 [ <optional> $code ] Parameter #2 [ <optional> $previous ] } } Method [ <internal:Core> final public method getMessage ] { } Method [ <internal:Core> final public method getCode ] { } Method [ <internal:Core> final public method getFile ] { } Method [ <internal:Core> final public method getLine ] { } Method [ <internal:Core> final public method getTrace ] { } Method [ <internal:Core> final public method getPrevious ] { } Method [ <internal:Core> final public method getTraceAsString ] { } Method [ <internal:Core> public method __toString ] { } } } ``` ### See Also * [ReflectionClass::export()](reflectionclass.export) - Exports a class * [\_\_toString()](language.oop5.magic#object.tostring) php ReflectionClass::getParentClass ReflectionClass::getParentClass =============================== (PHP 5, PHP 7, PHP 8) ReflectionClass::getParentClass — Gets parent class ### Description ``` public ReflectionClass::getParentClass(): ReflectionClass|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values A [ReflectionClass](class.reflectionclass) or **`false`** if there's no parent. ### See Also * [ReflectionClass::\_\_construct()](reflectionclass.construct) - Constructs a ReflectionClass php sqlsrv_server_info sqlsrv\_server\_info ==================== (No version information available, might only be in Git) sqlsrv\_server\_info — Returns information about the server ### Description ``` sqlsrv_server_info(resource $conn): array ``` Returns information about the server. ### Parameters `conn` The connection resource that connects the client and the server. ### Return Values Returns an array as described in the following table: **Returned Array**| CurrentDatabase | The connected-to database. | | --- | --- | | SQLServerVersion | The SQL Server version. | | SQLServerName | The name of the server. | ### Examples **Example #1 **sqlsrv\_server\_info()** example** ``` <?php $serverName = "serverName\sqlexpress"; $conn = sqlsrv_connect( $serverName); if( $conn === false ) {      die( print_r( sqlsrv_errors(), true)); } $server_info = sqlsrv_server_info( $conn); if( $server_info ) {     foreach( $server_info as $key => $value) {        echo $key.": ".$value."<br />";     } } else {       die( print_r( sqlsrv_errors(), true)); } ?> ``` ### See Also * [sqlsrv\_client\_info()](function.sqlsrv-client-info) - Returns information about the client and specified connection php ReflectionClassConstant::getDocComment ReflectionClassConstant::getDocComment ====================================== (PHP 7 >= 7.1.0, PHP 8) ReflectionClassConstant::getDocComment — Gets doc comments ### Description ``` public ReflectionClassConstant::getDocComment(): string|false ``` Gets doc comments from a class constant. ### Parameters This function has no parameters. ### Return Values The doc comment if it exists, otherwise **`false`** php The LDAP\Result class The LDAP\Result class ===================== Introduction ------------ (PHP 8 >= 8.1.0) A fully opaque class which replaces a `ldap result` resource as of PHP 8.1.0. Class synopsis -------------- final class **LDAP\Result** { } php XMLReader::close XMLReader::close ================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::close — Close the XMLReader input ### Description ``` public XMLReader::close(): bool ``` Closes the input the XMLReader object is currently parsing. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [XMLReader::open()](xmlreader.open) - Set the URI containing the XML to parse * [XMLReader::xml()](xmlreader.xml) - Set the data containing the XML to parse php get_declared_interfaces get\_declared\_interfaces ========================= (PHP 5, PHP 7, PHP 8) get\_declared\_interfaces — Returns an array of all declared interfaces ### Description ``` get_declared_interfaces(): array ``` Gets the declared interfaces. ### Parameters This function has no parameters. ### Return Values Returns an array of the names of the declared interfaces in the current script. ### Examples **Example #1 **get\_declared\_interfaces()** example** ``` <?php print_r(get_declared_interfaces()); ?> ``` The above example will output something similar to: ``` Array ( [0] => Traversable [1] => IteratorAggregate [2] => Iterator [3] => ArrayAccess [4] => reflector [5] => RecursiveIterator [6] => SeekableIterator ) ``` ### See Also * [interface\_exists()](function.interface-exists) - Checks if the interface has been defined * [get\_declared\_classes()](function.get-declared-classes) - Returns an array with the name of the defined classes * [class\_implements()](function.class-implements) - Return the interfaces which are implemented by the given class or interface php odbc_setoption odbc\_setoption =============== (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_setoption — Adjust ODBC settings ### Description ``` odbc_setoption( resource $odbc, int $which, int $option, int $value ): bool ``` This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work around to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options. Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters. ### Parameters `odbc` Is a connection id or result id on which to change the settings. For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id. `which` Is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption(). `option` The option to set. `value` The value for the given `option`. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **odbc\_setoption()** examples** ``` <?php // 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT. //    Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON. //    This example has the same effect as //    odbc_autocommit($conn, true); odbc_setoption($conn, 1, 102, 1); // 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT. //    This example sets the query to timeout after 30 seconds. $result = odbc_prepare($conn, $sql); odbc_setoption($result, 2, 0, 30); odbc_execute($result); ?> ``` php array_merge_recursive array\_merge\_recursive ======================= (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) array\_merge\_recursive — Merge one or more arrays recursively ### Description ``` array_merge_recursive(array ...$arrays): array ``` **array\_merge\_recursive()** merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended. ### Parameters `arrays` Variable list of arrays to recursively merge. ### Return Values An array of values resulted from merging the arguments together. If called without any arguments, returns an empty array. ### Changelog | Version | Description | | --- | --- | | 7.4.0 | This function can now be called without any parameter. Formerly, at least one parameter has been required. | ### Examples **Example #1 **array\_merge\_recursive()** example** ``` <?php $ar1 = array("color" => array("favorite" => "red"), 5); $ar2 = array(10, "color" => array("favorite" => "green", "blue")); $result = array_merge_recursive($ar1, $ar2); print_r($result); ?> ``` The above example will output: ``` Array ( [color] => Array ( [favorite] => Array ( [0] => red [1] => green ) [0] => blue ) [0] => 5 [1] => 10 ) ``` ### See Also * [array\_merge()](function.array-merge) - Merge one or more arrays * [array\_replace\_recursive()](function.array-replace-recursive) - Replaces elements from passed arrays into the first array recursively php EventHttp::bind EventHttp::bind =============== (PECL event >= 1.2.6-beta) EventHttp::bind — Binds an HTTP server on the specified address and port ### Description ``` public EventHttp::bind( string $address , int $port ): void ``` Binds an HTTP server on the specified address and port. Can be called multiple times to bind the same HTTP server to multiple different ports. ### Parameters `address` A string containing the IP address to `listen(2)` on. `port` The port number to listen on. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **EventHttp::bind()** example** ``` <?php $base = new EventBase(); $http = new EventHttp($base); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$http->bind("127.0.0.1", 8088)) {     exit("bind(1) failed\n"); }; if (!$http->bind("127.0.0.1", 8089)) {     exit("bind(2) failed\n"); }; $http->setCallback("/about", function($req) {     echo "URI: ", $req->getUri(), PHP_EOL;     $req->sendReply(200, "OK");     echo "OK\n"; }); $base->dispatch(); ?> ``` The above example will output something similar to: ``` Client: $ nc 127.0.0.1 8088 GET /about HTTP/1.0 Connection: close HTTP/1.0 200 OK Content-Type: text/html; charset=ISO-8859-1 Connection: close $ nc 127.0.0.1 8089 GET /unknown HTTP/1.0 Connection: close HTTP/1.1 404 Not Found Content-Type: text/html Date: Wed, 13 Mar 2013 04:14:41 GMT Content-Length: 149 Connection: close <html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /unknown was not found on this server.</p></body></html> Server: URI: /about OK ``` ### See Also * [EventHttp::accept()](eventhttp.accept) - Makes an HTTP server accept connections on the specified socket stream or resource php imagecopymerge imagecopymerge ============== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) imagecopymerge — Copy and merge part of an image ### Description ``` imagecopymerge( GdImage $dst_image, GdImage $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $src_width, int $src_height, int $pct ): bool ``` Copy a part of `src_image` onto `dst_image` starting at the x,y coordinates `src_x`, `src_y` with a width of `src_width` and a height of `src_height`. The portion defined will be copied onto the x,y coordinates, `dst_x` and `dst_y`. ### Parameters `dst_image` Destination image resource. `src_image` Source image resource. `dst_x` x-coordinate of destination point. `dst_y` y-coordinate of destination point. `src_x` x-coordinate of source point. `src_y` y-coordinate of source point. `src_width` Source width. `src_height` Source height. `pct` The two images will be merged according to `pct` which can range from 0 to 100. When `pct` = 0, no action is taken, when 100 this function behaves identically to [imagecopy()](function.imagecopy) for pallete images, except for ignoring alpha components, while it implements alpha transparency for true colour images. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `dst_image` and `src_image` expect [GdImage](class.gdimage) instances now; previously, resources were expected. | ### Examples **Example #1 Merging two copies of the PHP.net logo with 75% transparency** ``` <?php // Create image instances $dest = imagecreatefromgif('php.gif'); $src = imagecreatefromgif('php.gif'); // Copy and merge imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75); // Output and free from memory header('Content-Type: image/gif'); imagegif($dest); imagedestroy($dest); imagedestroy($src); ?> ``` php imap_set_quota imap\_set\_quota ================ (PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8) imap\_set\_quota — Sets a quota for a given mailbox ### Description ``` imap_set_quota(IMAP\Connection $imap, string $quota_root, int $mailbox_size): bool ``` Sets an upper limit quota on a per mailbox basis. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `quota_root` The mailbox to have a quota set. This should follow the IMAP standard format for a mailbox: `user.name`. `mailbox_size` The maximum size (in KB) for the `quota_root` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_set\_quota()** example** ``` <?php $mbox = imap_open("{imap.example.org:143}", "mailadmin", "password"); if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {     echo "Error in setting quota\n";     return; } imap_close($mbox); ?> ``` ### Notes This function is currently only available to users of the c-client2000 or greater library. The given `imap` must be opened as the mail administrator, other wise this function will fail. ### See Also * [imap\_open()](function.imap-open) - Open an IMAP stream to a mailbox * [imap\_get\_quota()](function.imap-get-quota) - Retrieve the quota level settings, and usage statics per mailbox php date_isodate_set date\_isodate\_set ================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) date\_isodate\_set — Alias of [DateTime::setISODate()](datetime.setisodate) ### Description This function is an alias of: [DateTime::setISODate()](datetime.setisodate) php Yaf_Request_Abstract::setDispatched Yaf\_Request\_Abstract::setDispatched ===================================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::setDispatched — The setDispatched purpose ### Description ``` public Yaf_Request_Abstract::setDispatched(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php The VarnishAdmin class The VarnishAdmin class ====================== Introduction ------------ (PECL varnish >= 0.3) Class synopsis -------------- class **VarnishAdmin** { /\* Methods \*/ ``` public auth(): bool ``` ``` public ban(string $vcl_regex): int ``` ``` public banUrl(string $vcl_regex): int ``` ``` public clearPanic(): int ``` ``` public connect(): bool ``` ``` public __construct(array $args = ?) ``` ``` public disconnect(): bool ``` ``` public getPanic(): string ``` ``` public getParams(): array ``` ``` public isRunning(): bool ``` ``` public setCompat(int $compat): void ``` ``` public setHost(string $host): void ``` ``` public setIdent(string $ident): void ``` ``` public setParam(string $name, string|int $value): int ``` ``` public setPort(int $port): void ``` ``` public setSecret(string $secret): void ``` ``` public setTimeout(int $timeout): void ``` ``` public start(): int ``` ``` public stop(): int ``` } Table of Contents ----------------- * [VarnishAdmin::auth](varnishadmin.auth) — Authenticate on a varnish instance * [VarnishAdmin::ban](varnishadmin.ban) — Ban URLs using a VCL expression * [VarnishAdmin::banUrl](varnishadmin.banurl) — Ban an URL using a VCL expression * [VarnishAdmin::clearPanic](varnishadmin.clearpanic) — Clear varnish instance panic messages * [VarnishAdmin::connect](varnishadmin.connect) — Connect to a varnish instance administration interface * [VarnishAdmin::\_\_construct](varnishadmin.construct) — VarnishAdmin constructor * [VarnishAdmin::disconnect](varnishadmin.disconnect) — Disconnect from a varnish instance administration interface * [VarnishAdmin::getPanic](varnishadmin.getpanic) — Get the last panic message on a varnish instance * [VarnishAdmin::getParams](varnishadmin.getparams) — Fetch current varnish instance configuration parameters * [VarnishAdmin::isRunning](varnishadmin.isrunning) — Check if the varnish slave process is currently running * [VarnishAdmin::setCompat](varnishadmin.setcompat) — Set the class compat configuration param * [VarnishAdmin::setHost](varnishadmin.sethost) — Set the class host configuration param * [VarnishAdmin::setIdent](varnishadmin.setident) — Set the class ident configuration param * [VarnishAdmin::setParam](varnishadmin.setparam) — Set configuration param on the current varnish instance * [VarnishAdmin::setPort](varnishadmin.setport) — Set the class port configuration param * [VarnishAdmin::setSecret](varnishadmin.setsecret) — Set the class secret configuration param * [VarnishAdmin::setTimeout](varnishadmin.settimeout) — Set the class timeout configuration param * [VarnishAdmin::start](varnishadmin.start) — Start varnish worker process * [VarnishAdmin::stop](varnishadmin.stop) — Stop varnish worker process
programming_docs
php Gmagick::reducenoiseimage Gmagick::reducenoiseimage ========================= (PECL gmagick >= Unknown) Gmagick::reducenoiseimage — Smooths the contours of an image ### Description ``` public Gmagick::reducenoiseimage(float $radius): Gmagick ``` Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and **Gmagick::reducenoiseimage()** selects a suitable radius for you. ### Parameters `radius` The radius of the pixel neighborhood. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php ReflectionClass::implementsInterface ReflectionClass::implementsInterface ==================================== (PHP 5, PHP 7, PHP 8) ReflectionClass::implementsInterface — Implements interface ### Description ``` public ReflectionClass::implementsInterface(ReflectionClass|string $interface): bool ``` Checks whether it implements an interface. ### Parameters `interface` The interface name. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions **ReflectionClass::implementsInterface()** throws an [ReflectionException](class.reflectionexception) if `interface` is not an interface. ### See Also * [ReflectionClass::isInterface()](reflectionclass.isinterface) - Checks if the class is an interface * [ReflectionClass::isSubclassOf()](reflectionclass.issubclassof) - Checks if a subclass * [interface\_exists()](function.interface-exists) - Checks if the interface has been defined * [Object Interfaces](language.oop5.interfaces) php Memcached::touchByKey Memcached::touchByKey ===================== (PECL memcached >= 2.0.0) Memcached::touchByKey — Set a new expiration on an item on a specific server ### Description ``` public Memcached::touchByKey(string $server_key, string $key, int $expiration): bool ``` **Memcached::touchByKey()** is functionally equivalent to [Memcached::touch()](memcached.touch), except that the free-form `server_key` can be used to map the `key` to a specific server. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `key` The key under which to store the value. `expiration` The expiration time, defaults to 0. See [Expiration Times](https://www.php.net/manual/en/memcached.expiration.php) for more info. ### Return Values Returns **`true`** on success or **`false`** on failure. Use [Memcached::getResultCode()](memcached.getresultcode) if necessary. ### See Also * [Memcached::touch()](memcached.touch) - Set a new expiration on an item php Yaf_Loader::autoload Yaf\_Loader::autoload ===================== (Yaf >=1.0.0) Yaf\_Loader::autoload — The autoload purpose ### Description ``` public Yaf_Loader::autoload(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php ctype_cntrl ctype\_cntrl ============ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ctype\_cntrl — Check for control character(s) ### Description ``` ctype_cntrl(mixed $text): bool ``` Checks if all of the characters in the provided string, `text`, are control characters. Control characters are e.g. line feed, tab, escape. ### Parameters `text` The tested string. > > **Note**: > > > If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer. > > > **Warning** As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to [chr()](function.chr) should be made. ### Return Values Returns **`true`** if every character in `text` is a control character from the current locale, **`false`** otherwise. When called with an empty string the result will always be **`false`**. ### Examples **Example #1 A **ctype\_cntrl()** example** ``` <?php $strings = array('string1' => "\n\r\t", 'string2' => 'arf12'); foreach ($strings as $name => $testcase) {     if (ctype_cntrl($testcase)) {         echo "The string '$name' consists of all control characters.\n";     } else {         echo "The string '$name' does not consist of all control characters.\n";     } } ?> ``` The above example will output: ``` The string 'string1' consists of all control characters. The string 'string2' does not consist of all control characters. ``` ### See Also * [ctype\_print()](function.ctype-print) - Check for printable character(s) php is_iterable is\_iterable ============ (PHP 7 >= 7.1.0, PHP 8) is\_iterable — Verify that the contents of a variable is an iterable value ### Description ``` is_iterable(mixed $value): bool ``` Verify that the contents of a variable is accepted by the [iterable](language.types.iterable) pseudo-type, i.e. that it is either an array or an object implementing [Traversable](class.traversable) ### Parameters `value` The value to check ### Return Values Returns **`true`** if `value` is iterable, **`false`** otherwise. ### Examples **Example #1 **is\_iterable()** examples** ``` <?php var_dump(is_iterable([1, 2, 3]));  // bool(true) var_dump(is_iterable(new ArrayIterator([1, 2, 3])));  // bool(true) var_dump(is_iterable((function () { yield 1; })()));  // bool(true) var_dump(is_iterable(1));  // bool(false) var_dump(is_iterable(new stdClass()));  // bool(false) ?> ``` ### See Also * [is\_array()](function.is-array) - Finds whether a variable is an array php Gmagick::commentimage Gmagick::commentimage ===================== (PECL gmagick >= Unknown) Gmagick::commentimage — Adds a comment to your image ### Description ``` public Gmagick::commentimage(string $comment): Gmagick ``` Adds a comment to your image. ### Parameters `comment` The comment to add. ### Return Values The [Gmagick](class.gmagick) object with comment added. ### Errors/Exceptions Throws an **GmagickException** on error. php Lua::assign Lua::assign =========== (PECL lua >=0.9.0) Lua::assign — Assign a PHP variable to Lua ### Description ``` public Lua::assign(string $name, string $value): mixed ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` `value` ### Return Values Returns $this or **`null`** on failure. ### Examples **Example #1 **Lua::assign()**example** ``` <?php $lua = new Lua(); $lua->assign("php_var", array(1=>1, 2, 3)); //lua table index begin with 1 $lua->eval(<<<CODE     print(php_var); CODE ); ?> ``` The above example will output: ``` Array ( [1] => 1 [2] => 2 [3] => 3 ) ``` php SolrQuery::setGroupMain SolrQuery::setGroupMain ======================= (PECL solr >= 2.2.0) SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple ### Description ``` public SolrQuery::setGroupMain(string $value): SolrQuery ``` If **`true`**, the result of the first field grouping command is used as the main result list in the response, using `group.format=simple`. ### Parameters `value` If **`true`**, the result of the first field grouping command is used as the main result list in the response. ### Return Values Returns an instance of [SolrQuery](class.solrquery). ### See Also * [SolrQuery::setGroup()](solrquery.setgroup) - Enable/Disable result grouping (group parameter) * [SolrQuery::addGroupField()](solrquery.addgroupfield) - Add a field to be used to group results * [SolrQuery::addGroupFunction()](solrquery.addgroupfunction) - Allows grouping results based on the unique values of a function query (group.func parameter) * [SolrQuery::addGroupQuery()](solrquery.addgroupquery) - Allows grouping of documents that match the given query * [SolrQuery::addGroupSortField()](solrquery.addgroupsortfield) - Add a group sort field (group.sort parameter) * [SolrQuery::setGroupFacet()](solrquery.setgroupfacet) - Sets group.facet parameter * [SolrQuery::setGroupOffset()](solrquery.setgroupoffset) - Sets the group.offset parameter * **SolrQuery::setGroupMain()** * [SolrQuery::setGroupNGroups()](solrquery.setgroupngroups) - If true, Solr includes the number of groups that have matched the query in the results * [SolrQuery::setGroupTruncate()](solrquery.setgrouptruncate) - If true, facet counts are based on the most relevant document of each group matching the query * [SolrQuery::setGroupFormat()](solrquery.setgroupformat) - Sets the group format, result structure (group.format parameter) * [SolrQuery::setGroupCachePercent()](solrquery.setgroupcachepercent) - Enables caching for result grouping php Stomp::ack Stomp::ack ========== stomp\_ack ========== (PECL stomp >= 0.1.0) Stomp::ack -- stomp\_ack — Acknowledges consumption of a message ### Description Object-oriented style (method): ``` public Stomp::ack(mixed $msg, array $headers = ?): bool ``` Procedural style: ``` stomp_ack(resource $link, mixed $msg, array $headers = ?): bool ``` Acknowledges consumption of a message from a subscription using client acknowledgment. ### Parameters `link` Procedural style only: The stomp link identifier returned by [stomp\_connect()](stomp.construct). `msg` The message/messageId to be acknowledged. `headers` Associative array containing the additional headers (example: receipt). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Object-oriented style** ``` <?php $queue  = '/queue/foo'; $msg    = 'bar'; /* connection */ try {     $stomp = new Stomp('tcp://localhost:61613'); } catch(StompException $e) {     die('Connection failed: ' . $e->getMessage()); } /* send a message to the queue 'foo' */ $stomp->send($queue, $msg); /* subscribe to messages from the queue 'foo' */ $stomp->subscribe($queue); /* read a frame */ $frame = $stomp->readFrame(); if ($frame->body === $msg) {     /* acknowledge that the frame was received */     $stomp->ack($frame); } /* remove the subscription */ $stomp->unsubscribe($queue); /* close connection */ unset($stomp); ?> ``` **Example #2 Procedural style** ``` <?php $queue  = '/queue/foo'; $msg    = 'bar'; /* connection */ $link = stomp_connect('ssl://localhost:61612'); /* check connection */ if (!$link) {     die('Connection failed: ' . stomp_connect_error()); } /* begin a transaction */ stomp_begin($link, 't1'); /* send a message to the queue 'foo' */ stomp_send($link, $queue, $msg, array('transaction' => 't1')); /* commit a transaction */ stomp_commit($link, 't1'); /* subscribe to messages from the queue 'foo' */ stomp_subscribe($link, $queue); /* read a frame */ $frame = stomp_read_frame($link); if ($frame['body'] === $msg) {     /* acknowledge that the frame was received */     stomp_ack($link, $frame['headers']['message-id']); } /* remove the subscription */ stomp_unsubscribe($link, $queue); /* close connection */ stomp_close($link); ?> ``` ### Notes > > **Note**: > > > A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction. > > > **Tip**Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached. php ImagickDraw::getStrokeAntialias ImagickDraw::getStrokeAntialias =============================== (PECL imagick 2, PECL imagick 3) ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting ### Description ``` public ImagickDraw::getStrokeAntialias(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Returns the current stroke antialias setting. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used. ### Return Values Returns **`true`** if antialiasing is on and **`false`** if it is off. php pg_get_pid pg\_get\_pid ============ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_get\_pid — Gets the backend's process ID ### Description ``` pg_get_pid(PgSql\Connection $connection): int ``` **pg\_get\_pid()** gets the backend's (database server process) PID. The PID is useful to determine whether or not a `NOTIFY` message received via [pg\_get\_notify()](function.pg-get-notify) is sent from another process or not. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. ### Return Values The backend database process ID. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 PostgreSQL backend PID** ``` <?php  $conn = pg_pconnect("dbname=publisher"); if (!$conn) {   echo "An error occurred.\n";   exit; } // Backend process PID. Use PID with pg_get_notify() $pid = pg_get_pid($conn); ?> ``` ### See Also * [pg\_get\_notify()](function.pg-get-notify) - Gets SQL NOTIFY message php XMLWriter::openUri XMLWriter::openUri ================== xmlwriter\_open\_uri ==================== (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::openUri -- xmlwriter\_open\_uri — Create new xmlwriter using source uri for output ### Description Object-oriented style ``` public XMLWriter::openUri(string $uri): bool ``` Procedural style ``` xmlwriter_open_uri(string $uri): XMLWriter|false ``` Creates a new [XMLWriter](class.xmlwriter) using `uri` for the output. ### Parameters `uri` The URI of the resource for the output. ### Return Values Object-oriented style: Returns **`true`** on success or **`false`** on failure. Procedural style: Returns a new [XMLWriter](class.xmlwriter) instance for later use with the xmlwriter functions on success, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function returns now an [XMLWriter](class.xmlwriter) instance on success. Previouly, a [resource](language.types.resource) has been returned in this case. | ### Examples **Example #1 Direct output of XML** It is possible to directly output XML by using the [php://output stream wrapper](https://www.php.net/manual/en/wrappers.php.php#wrappers.php.output). ``` <?php $out =new XMLWriter(); $out->openURI('php://output'); ?> ``` ### Notes > > **Note**: > > > On Windows, files opened with this function are locked until the writer is released. > > ### See Also * [XMLWriter::openMemory()](xmlwriter.openmemory) - Create new xmlwriter using memory for string output php None Function arguments ------------------ Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right, before the function is actually called (*eager* evaluation). PHP supports passing arguments by value (the default), [passing by reference](functions.arguments#functions.arguments.by-reference), and [default argument values](functions.arguments#functions.arguments.default). [Variable-length argument lists](functions.arguments#functions.variable-arg-list) and [Named Arguments](functions.arguments#functions.named-arguments) are also supported. **Example #1 Passing arrays to functions** ``` <?php function takes_array($input) {     echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } ?> ``` As of PHP 8.0.0, the list of function arguments may include a trailing comma, which will be ignored. That is particularly useful in cases where the list of arguments is long or contains long variable names, making it convenient to list arguments vertically. **Example #2 Function Argument List with trailing Comma** ``` <?php function takes_many_args(     $first_arg,     $second_arg,     $a_very_long_argument_name,     $arg_with_default = 5,     $again = 'a default string', // This trailing comma was not permitted before 8.0.0. ) {     // ... } ?> ``` ### Passing arguments by reference By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition: **Example #3 Passing function parameters by reference** ``` <?php function add_some_extra(&$string) {     $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str;    // outputs 'This is a string, and something extra.' ?> ``` It is an error to pass a value as argument which is supposed to be passed by reference. ### Default argument values A function may define default values for arguments using syntax similar to assigning a variable. The default is used only when the parameter is not specified; in particular, note that passing **`null`** does *not* assign the default value. **Example #4 Use of default parameters in functions** ``` <?php function makecoffee($type = "cappuccino") {     return "Making a cup of $type.\n"; } echo makecoffee(); echo makecoffee(null); echo makecoffee("espresso"); ?> ``` The above example will output: ``` Making a cup of cappuccino. Making a cup of . Making a cup of espresso. ``` Default parameter values may be scalar values, arrays, the special type **`null`**, and as of PHP 8.1.0, objects using the [new ClassName()](language.oop5.basic#language.oop5.basic.new) syntax. **Example #5 Using non-scalar types as default values** ``` <?php function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) {     $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;     return "Making a cup of ".join(", ", $types)." with $device.\n"; } echo makecoffee(); echo makecoffee(array("cappuccino", "lavazza"), "teapot");?> ``` **Example #6 Using objects as default values (as of PHP 8.1.0)** ``` <?php class DefaultCoffeeMaker {     public function brew() {         return 'Making coffee.';     } } class FancyCoffeeMaker {     public function brew() {         return 'Crafting a beautiful coffee just for you.';     } } function makecoffee($coffeeMaker = new DefaultCoffeeMaker) {     return $coffeeMaker->brew(); } echo makecoffee(); echo makecoffee(new FancyCoffeeMaker); ?> ``` The default value must be a constant expression, not (for example) a variable, a class member or a function call. Note that any optional arguments should be specified after any required arguments, otherwise they cannot be omitted from calls. Consider the following example: **Example #7 Incorrect usage of default function arguments** ``` <?php function makeyogurt($container = "bowl", $flavour) {     return "Making a $container of $flavour yogurt.\n"; }   echo makeyogurt("raspberry"); // "raspberry" is $container, not $flavour ?> ``` The above example will output: ``` Fatal error: Uncaught ArgumentCountError: Too few arguments to function makeyogurt(), 1 passed in example.php on line 42 ``` Now, compare the above with this: **Example #8 Correct usage of default function arguments** ``` <?php function makeyogurt($flavour, $container = "bowl") {     return "Making a $container of $flavour yogurt.\n"; }   echo makeyogurt("raspberry"); // "raspberry" is $flavour ?> ``` The above example will output: ``` Making a bowl of raspberry yogurt. ``` As of PHP 8.0.0, [named arguments](functions.arguments#functions.named-arguments) can be used to skip over multiple optional parameters. **Example #9 Correct usage of default function arguments** ``` <?php function makeyogurt($container = "bowl", $flavour = "raspberry", $style = "Greek") {     return "Making a $container of $flavour $style yogurt.\n"; } echo makeyogurt(style: "natural"); ?> ``` The above example will output: ``` Making a bowl of raspberry natural yogurt. ``` As of PHP 8.0.0, declaring mandatory arguments after optional arguments is *deprecated*. This can generally be resolved by dropping the default value, since it will never be used. One exception to this rule are arguments of the form `Type $param = null`, where the **`null`** default makes the type implicitly nullable. This usage remains allowed, though it is recommended to use an explicit [nullable type](language.types.declarations#language.types.declarations.nullable) instead. **Example #10 Declaring optional arguments after mandatory arguments** ``` <?php  function foo($a = [], $b) {} // Default not used; deprecated as of PHP 8.0.0  function foo($a, $b) {}      // Functionally equivalent, no deprecation notice  function bar(A $a = null, $b) {} // Still allowed; $a is required but nullable  function bar(?A $a, $b) {}       // Recommended  ?> ``` > **Note**: As of PHP 7.1.0, omitting a parameter which does not specify a default throws an [ArgumentCountError](class.argumentcounterror); in previous versions it raised a Warning. > > > **Note**: Arguments that are passed by reference may have a default value. > > ### Variable-length argument lists PHP has support for variable-length argument lists in user-defined functions by using the `...` token. > **Note**: It is also possible to achieve variable-length arguments by using [func\_num\_args()](function.func-num-args), [func\_get\_arg()](function.func-get-arg), and [func\_get\_args()](function.func-get-args) functions. This technique is not recommended as it was used prior to the introduction of the `...` token. > > Argument lists may include the `...` token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example: **Example #11 Using `...` to access variable arguments** ``` <?php function sum(...$numbers) {     $acc = 0;     foreach ($numbers as $n) {         $acc += $n;     }     return $acc; } echo sum(1, 2, 3, 4); ?> ``` The above example will output: ``` 10 ``` `...` can also be used when calling functions to unpack an array or [Traversable](class.traversable) variable or literal into the argument list: **Example #12 Using `...` to provide arguments** ``` <?php function add($a, $b) {     return $a + $b; } echo add(...[1, 2])."\n"; $a = [1, 2]; echo add(...$a); ?> ``` The above example will output: ``` 3 3 ``` You may specify normal positional arguments before the `...` token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by `...`. It is also possible to add a [type declaration](language.types.declarations) before the `...` token. If this is present, then all arguments captured by `...` must match that parameter type. **Example #13 Type declared variable arguments** ``` <?php function total_intervals($unit, DateInterval ...$intervals) {     $time = 0;     foreach ($intervals as $interval) {         $time += $interval->$unit;     }     return $time; } $a = new DateInterval('P1D'); $b = new DateInterval('P2D'); echo total_intervals('d', $a, $b).' days'; // This will fail, since null isn't a DateInterval object. echo total_intervals('d', null); ?> ``` The above example will output: ``` 3 days Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2 ``` Finally, variable arguments can also be passed [by reference](functions.arguments#functions.arguments.by-reference) by prefixing the `...` with an ampersand (`&`). #### Older versions of PHP No special syntax is required to note that a function is variadic; however access to the function's arguments must use [func\_num\_args()](function.func-num-args), [func\_get\_arg()](function.func-get-arg) and [func\_get\_args()](function.func-get-args). The first example above would be implemented as follows in old versions of PHP: **Example #14 Accessing variable arguments in old PHP versions** ``` <?php function sum() {     $acc = 0;     foreach (func_get_args() as $n) {         $acc += $n;     }     return $acc; } echo sum(1, 2, 3, 4); ?> ``` The above example will output: ``` 10 ``` ### Named Arguments PHP 8.0.0 introduced named arguments as an extension of the existing positional parameters. Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position. This makes the meaning of the argument self-documenting, makes the arguments order-independent and allows skipping default values arbitrarily. Named arguments are passed by prefixing the value with the parameter name followed by a colon. Using reserved keywords as parameter names is allowed. The parameter name must be an identifier, specifying dynamically is not allowed. **Example #15 Named argument syntax** ``` <?php myFunction(paramName: $value); array_foobar(array: $value); // NOT supported. function_name($variableStoringParamName: $value); ?> ``` **Example #16 Positional arguments versus named arguments** ``` <?php // Using positional arguments: array_fill(0, 100, 50); // Using named arguments: array_fill(start_index: 0, count: 100, value: 50); ?> ``` The order in which the named arguments are passed does not matter. **Example #17 Same example as above with a different order of parameters** ``` <?php array_fill(value: 50, count: 100, start_index: 0); ?> ``` Named arguments can be combined with positional arguments. In this case, the named arguments must come after the positional arguments. It is also possible to specify only some of the optional arguments of a function, regardless of their order. **Example #18 Combining named arguments with positional arguments** ``` <?php htmlspecialchars($string, double_encode: false); // Same as htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false); ?> ``` Passing the same parameter multiple times results in an Error exception. **Example #19 Error thrown when passing the same parameter multiple times** ``` <?php function foo($param) { ... } foo(param: 1, param: 2); // Error: Named parameter $param overwrites previous argument foo(1, param: 2); // Error: Named parameter $param overwrites previous argument ?> ``` As of PHP 8.1.0, it is possible to use named arguments after unpacking the arguments. A named argument *must not* override an already unpacked arguments. **Example #20 Use named arguments after unpacking** ``` <?php function foo($a, $b, $c = 3, $d = 4) {   return $a + $b + $c + $d; } var_dump(foo(...[1, 2], d: 40)); // 46 var_dump(foo(...['b' => 2, 'a' => 1], d: 40)); // 46 var_dump(foo(...[1, 2], b: 20)); // Fatal error. Named parameter $b overwrites previous argument ?> ```
programming_docs
php SolrClient::rollback SolrClient::rollback ==================== (PECL solr >= 0.9.2) SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit ### Description ``` public SolrClient::rollback(): SolrUpdateResponse ``` Rollbacks all add/deletes made to the index since the last commit. It neither calls any event listeners nor creates a new searcher. ### Parameters This function has no parameters. ### Return Values Returns a SolrUpdateResponse on success or throws a SolrClientException on failure. ### See Also * [SolrClient::commit()](solrclient.commit) - Finalizes all add/deletes made to the index * [SolrClient::optimize()](solrclient.optimize) - Defragments the index php iconv_mime_encode iconv\_mime\_encode =================== (PHP 5, PHP 7, PHP 8) iconv\_mime\_encode — Composes a `MIME` header field ### Description ``` iconv_mime_encode(string $field_name, string $field_value, array $options = []): string|false ``` Composes and returns a string that represents a valid `MIME` header field, which looks like the following: ``` Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile ``` In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value. ### Parameters `field_name` The field name. `field_value` The field value. `options` You can control the behaviour of **iconv\_mime\_encode()** by specifying an associative array that contains configuration items to the optional third parameter `options`. The items supported by **iconv\_mime\_encode()** are listed below. Note that item names are treated case-sensitive. **Configuration items supported by **iconv\_mime\_encode()****| Item | Type | Description | Default value | Example | | --- | --- | --- | --- | --- | | scheme | string | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for `base64` encoding scheme and "Q" stands for `quoted-printable` encoding scheme. | B | B | | input-charset | string | Specifies the character set in which the first parameter `field_name` and the second parameter `field_value` are presented. If not given, **iconv\_mime\_encode()** assumes those parameters are presented to it in the [iconv.internal\_encoding](https://www.php.net/manual/en/iconv.configuration.php) ini setting. | [iconv.internal\_encoding](https://www.php.net/manual/en/iconv.configuration.php) | ISO-8859-1 | | output-charset | string | Specifies the character set to use to compose the `MIME` header. | [iconv.internal\_encoding](https://www.php.net/manual/en/iconv.configuration.php) | UTF-8 | | line-length | int | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to [» RFC2822 - Internet Message Format](http://www.faqs.org/rfcs/rfc2822). If not given, the length will be limited to 76 characters. | 76 | 996 | | line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (`CR` `LF`). Note that this parameter is always treated as an ASCII string regardless of the value of `input-charset`. | \r\n | \n | ### Return Values Returns an encoded `MIME` field on success, or **`false`** if an error occurs during the encoding. ### Examples **Example #1 **iconv\_mime\_encode()** example** ``` <?php $preferences = array(     "input-charset" => "ISO-8859-1",     "output-charset" => "UTF-8",     "line-length" => 76,     "line-break-chars" => "\n" ); $preferences["scheme"] = "Q"; // This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?=" echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences); $preferences["scheme"] = "B"; // This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=" echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences); ?> ``` ### See Also * [imap\_binary()](function.imap-binary) - Convert an 8bit string to a base64 string * [mb\_encode\_mimeheader()](function.mb-encode-mimeheader) - Encode string for MIME header * [imap\_8bit()](function.imap-8bit) - Convert an 8bit string to a quoted-printable string * [quoted\_printable\_encode()](function.quoted-printable-encode) - Convert a 8 bit string to a quoted-printable string php odbc_cursor odbc\_cursor ============ (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_cursor — Get cursorname ### Description ``` odbc_cursor(resource $statement): string|false ``` Gets the cursorname for the given result\_id. ### Parameters `statement` The result identifier. ### Return Values Returns the cursor name, as a string, or **`false`** on failure. php GearmanTask::function GearmanTask::function ===================== (PECL gearman <= 0.5.0) GearmanTask::function — Get associated function name (deprecated) ### Description ``` public GearmanTask::function(): string ``` Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls. > > **Note**: > > > This method has been replaced by [GearmanTask::functionName()](gearmantask.functionname) in the 0.6.0 release of the Gearman extension. > > ### Parameters This function has no parameters. ### Return Values A function name. php EventBufferEvent::connect EventBufferEvent::connect ========================= (PECL event >= 1.2.6-beta) EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket ### Description ``` public EventBufferEvent::connect( string $addr ): bool ``` Connect buffer event's file descriptor to given address(optionally with port), or a UNIX domain socket. If socket is not assigned to the buffer event, this function allocates a new socket and makes it non-blocking internally. To resolve DNS names(asyncronously), use [EventBufferEvent::connectHost()](eventbufferevent.connecthost) method. ### Parameters `addr` Should contain an IP address with optional port number, or a path to UNIX domain socket. Recognized formats are: ``` [IPv6Address]:port [IPv6Address] IPv6Address IPv4Address:port IPv4Address unix:path ``` Note, `'unix:'` prefix is currently not case sensitive. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **EventBufferEvent::connect()** example** ``` <?php /*  * 1. Connect to 127.0.0.1 at port 80  * by means of EventBufferEvent::connect().  *  * 2. Request /index.cphp via HTTP/1.0  * using the output buffer.  *  * 3. Asyncronously read the response and print it to stdout.  */ /* Read callback */ function readcb($bev, $base) {     $input = $bev->getInput();     while (($n = $input->remove($buf, 1024)) > 0) {         echo $buf;     } } /* Event callback */ function eventcb($bev, $events, $base) {     if ($events & EventBufferEvent::CONNECTED) {         echo "Connected.\n";     } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {         if ($events & EventBufferEvent::ERROR) {             echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;         }         echo "Closing\n";         $base->exit();         exit("Done\n");     } } $base = new EventBase(); echo "step 1\n"; $bev = new EventBufferEvent($base, /* use internal socket */ NULL,     EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS); if (!$bev) {     exit("Failed creating bufferevent socket\n"); } echo "step 2\n"; $bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base); $bev->enable(Event::READ | Event::WRITE); echo "step 3\n"; /* Send request */ $output = $bev->getOutput(); if (!$output->add(     "GET /index.cphp HTTP/1.0\r\n".     "Connection: Close\r\n\r\n" )) {     exit("Failed adding request to output buffer\n"); } /* Connect to the host syncronously.  * We know the IP, and don't need to resolve DNS. */ if (!$bev->connect("127.0.0.1:80")) {     exit("Can't connect to host\n"); } /* Dispatch pending events */ $base->dispatch(); ``` The above example will output something similar to: ``` step 1 step 2 step 3 Connected. HTTP/1.1 200 OK Server: nginx/1.2.6 Date: Sat, 09 Mar 2013 10:06:58 GMT Content-Type: text/html; charset=utf-8 Connection: close X-Powered-By: PHP/5.4.11--pl2-gentoo sdfsdfsf Closing Done ``` **Example #2 Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console** ``` <?php class MyUnixSocketClient {     private $base, $bev;     function __construct($base, $sock_path) {         $this->base = $base;         $this->bev = new EventBufferEvent($base, NULL, EventBufferEvent::OPT_CLOSE_ON_FREE,             array ($this, "read_cb"), NULL, array ($this, "event_cb"));         if (!$this->bev->connect("unix:$sock_path")) {             trigger_error("Failed to connect to socket `$sock_path'", E_USER_ERROR);         }         $this->bev->enable(Event::READ);     }     function __destruct() {         if ($this->bev) {             $this->bev->free();             $this->bev = NULL;         }     }     function dispatch() {         $this->base->dispatch();     }     function read_cb($bev, $unused) {         $in = $bev->input;         printf("Received %ld bytes\n", $in->length);         printf("----- data ----\n");         printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));         $this->bev->free();         $this->bev = NULL;         $this->base->exit(NULL);     }     function event_cb($bev, $events, $unused) {         if ($events & EventBufferEvent::ERROR) {             echo "Error from bufferevent\n";         }         if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {             $bev->free();             $bev = NULL;         } elseif ($events & EventBufferEvent::CONNECTED) {             $bev->output->add("test\n");         }     } } if ($argc <= 1) {     exit("Socket path is not provided\n"); } $sock_path = $argv[1]; $base = new EventBase(); $cl = new MyUnixSocketClient($base, $sock_path); $cl->dispatch(); ?> ``` The above example will output something similar to: ``` Received 5 bytes ----- data ---- 5: test ``` ### See Also * [EventBufferEvent::connectHost()](eventbufferevent.connecthost) - Connects to a hostname with optionally asyncronous DNS resolving php SolrQuery::setEchoHandler SolrQuery::setEchoHandler ========================= (PECL solr >= 0.9.2) SolrQuery::setEchoHandler — Toggles the echoHandler parameter ### Description ``` public SolrQuery::setEchoHandler(bool $flag): SolrQuery ``` If set to true, Solr places the name of the handle used in the response to the client for debugging purposes. ### Parameters `flag` **`true`** or **`false`** ### Return Values Returns the current SolrQuery object, if the return value is used. php svn_log svn\_log ======== (PECL svn >= 0.1.0) svn\_log — Returns the commit log messages of a repository URL ### Description ``` svn_log( string $repos_url, int $start_revision = ?, int $end_revision = ?, int $limit = 0, int $flags = SVN_DISCOVER_CHANGED_PATHS | SVN_STOP_ON_COPY ): array ``` **svn\_log()** returns the complete history of the item at the repository URL `repos_url`, or the history of a specific revision if `start_revision` is set. This function is equivalent to **`svn log --verbose -r $start_revision $repos_url`**. ### Parameters `repos_url` Repository URL of the item to retrieve log history from. `start_revision` Revision number of the first log to retrieve. Use **`SVN_REVISION_HEAD`** to retrieve the log from the most recent revision. `end_revision` Revision number of the last log to retrieve. Defaults to `start_revision` if specified or to **`SVN_REVISION_INITIAL`** otherwise. `limit` Number of logs to retrieve. `flags` Any combination of **`SVN_OMIT_MESSAGES`**, **`SVN_DISCOVER_CHANGED_PATHS`** and **`SVN_STOP_ON_COPY`**. ### Return Values On success, this function returns an array file listing in the format of: ``` [0] => Array, ordered most recent (highest) revision first ( [rev] => integer revision number [author] => string author name [msg] => string log message [date] => string date formatted per ISO 8601, i.e. date('c') [paths] => Array, describing changed files ( [0] => Array ( [action] => string letter signifying change [path] => absolute repository path of changed file ) [1] => ... ) ) [1] => ... ``` > > **Note**: > > > The output will always be a numerically indexed array of arrays, even when there are none or only one log message(s). > > The value of action is a subset of the [» status output in the first column](http://svnbook.red-bean.com/en/1.2/svn.ref.svn.c.status.html), where possible values are: **Actions**| Letter | Description | | --- | --- | | M | Item/props was modified | | A | Item was added | | D | Item was deleted | | R | Item was replaced | If no changes were made to the item, an empty array is returned. ### Examples **Example #1 **svn\_log()** example** ``` <?php print_r( svn_log('http://www.example.com/', 23) ); ?> ``` The above example will output something similar to: ``` Array ( [0] => Array ( [rev] => 23 [author] => 'joe' [msg] => 'Add cheese and salami to our sandwich.' [date] => '2007-04-06T16:00:27-04:00' [paths] => Array ( [0] => Array ( [action] => 'M' [path] => '/sandwich.txt' ) ) ) ) ``` ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. ### See Also * [» SVN documentation on svn log](http://svnbook.red-bean.com/en/1.2/svn.ref.svn.c.log.html) php Pool::submit Pool::submit ============ (PECL pthreads >= 2.0.0) Pool::submit — Submits an object for execution ### Description ``` public Pool::submit(Threaded $task): int ``` Submit the task to the next Worker in the Pool ### Parameters `task` The task for execution ### Return Values the identifier of the Worker executing the object ### Examples **Example #1 Submitting Tasks** ``` <?php class MyWork extends Threaded {          public function run() {         /* ... */     } } class MyWorker extends Worker {          public function __construct(Something $something) {         $this->something = $something;     }          public function run() {         /** ... **/     } } $pool = new Pool(8, \MyWorker::class, [new Something()]); $pool->submit(new MyWork()); var_dump($pool); ?> ``` The above example will output: ``` object(Pool)#1 (6) { ["size":protected]=> int(8) ["class":protected]=> string(8) "MyWorker" ["workers":protected]=> array(1) { [0]=> object(MyWorker)#4 (1) { ["something"]=> object(Something)#5 (0) { } } } ["work":protected]=> array(1) { [0]=> object(MyWork)#3 (1) { ["worker"]=> object(MyWorker)#5 (1) { ["something"]=> object(Something)#6 (0) { } } } } ["ctor":protected]=> array(1) { [0]=> object(Something)#2 (0) { } } ["last":protected]=> int(1) } ``` php SolrDisMaxQuery::removeUserField SolrDisMaxQuery::removeUserField ================================ (No version information available, might only be in Git) SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf) ### Description ``` public SolrDisMaxQuery::removeUserField(string $field): SolrDisMaxQuery ``` Removes a field from The User Fields Parameter (uf) **Warning**This function is currently not documented; only its argument list is available. ### Parameters `field` Field Name ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::removeUserField()** example** ``` <?php $dismaxQuery = new SolrDisMaxQuery('lucene'); $dismaxQuery ->addUserField('cat') ->addUserField('text') ->addUserField('*_dt') ; echo $dismaxQuery.PHP_EOL; // remove field named 'text' $dismaxQuery ->removeUserField('text'); echo $dismaxQuery.PHP_EOL; ?> ``` The above example will output something similar to: ``` q=lucene&defType=%s&uf=cat text *_dt q=lucene&defType=%s&uf=cat *_dt ``` ### See Also * [SolrDisMaxQuery::addUserField()](solrdismaxquery.adduserfield) - Adds a field to User Fields Parameter (uf) * [SolrDisMaxQuery::setUserFields()](solrdismaxquery.setuserfields) - Sets User Fields parameter (uf) php EventConfig::avoidMethod EventConfig::avoidMethod ======================== (PECL event >= 1.2.6-beta) EventConfig::avoidMethod — Tells libevent to avoid specific event method ### Description ``` public EventConfig::avoidMethod( string $method ): bool ``` Tells libevent to avoid specific event method(backend). See [» Creating an event base](http://www.wangafu.net/~nickm/libevent-book/Ref2_eventbase.html#_creating_an_event_base) . ### Parameters `method` The backend method to avoid. See [EventConfig constants](class.eventconfig#eventconfig.constants) . ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **EventConfig::avoidMethod()** example** ``` <?php $cfg = new EventConfig(); if ($cfg->avoidMethod("select")) {     echo "'select' method avoided\n"; } ?> ``` ### See Also * [EventBase::\_\_construct()](eventbase.construct) - Constructs EventBase object php Ds\Map::ksorted Ds\Map::ksorted =============== (No version information available, might only be in Git) Ds\Map::ksorted — Returns a copy, sorted by key ### Description ``` public Ds\Map::ksorted(callable $comparator = ?): Ds\Map ``` Returns a copy sorted by key, using an optional `comparator` function. ### Parameters `comparator` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` **Caution** Returning *non-integer* values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ### Return Values Returns a copy of the map, sorted by key. ### Examples **Example #1 **Ds\Map::ksorted()** example** ``` <?php $map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]); print_r($map->ksorted()); ?> ``` The above example will output something similar to: ``` Ds\Map Object Ds\Map Object ( [0] => Ds\Pair Object ( [key] => a [value] => 1 ) [1] => Ds\Pair Object ( [key] => b [value] => 2 ) [2] => Ds\Pair Object ( [key] => c [value] => 3 ) ) ``` **Example #2 **Ds\Map::ksorted()** example using a comparator** ``` <?php $map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]); // Reverse $sorted = $map->ksorted(function($a, $b) {     return $b <=> $a; }); print_r($sorted); ?> ``` The above example will output something similar to: ``` Ds\Map Object Ds\Map Object ( [0] => Ds\Pair Object ( [key] => 2 [value] => y ) [1] => Ds\Pair Object ( [key] => 1 [value] => x ) [2] => Ds\Pair Object ( [key] => 0 [value] => z ) ) ```
programming_docs
php LimitIterator::seek LimitIterator::seek =================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) LimitIterator::seek — Seek to the given position ### Description ``` public LimitIterator::seek(int $offset): int ``` Moves the iterator to the offset specified by `offset`. ### Parameters `offset` The position to seek to. ### Return Values Returns the offset position after seeking. ### Errors/Exceptions Throws an [OutOfBoundsException](class.outofboundsexception) if the position is outside of the limits specified in [LimitIterator::\_\_construct()](limititerator.construct). ### See Also * [LimitIterator::current()](limititerator.current) - Get current element * [LimitIterator::key()](limititerator.key) - Get current key * [LimitIterator::rewind()](limititerator.rewind) - Rewind the iterator to the specified starting offset * [LimitIterator::next()](limititerator.next) - Move the iterator forward * [LimitIterator::valid()](limititerator.valid) - Check whether the current element is valid php Ds\Deque::copy Ds\Deque::copy ============== (PECL ds >= 1.0.0) Ds\Deque::copy — Returns a shallow copy of the deque ### Description ``` public Ds\Deque::copy(): Ds\Deque ``` Returns a shallow copy of the deque. ### Parameters This function has no parameters. ### Return Values A shallow copy of the deque. ### Examples **Example #1 **Ds\Deque::copy()** example** ``` <?php $a = new \Ds\Deque([1, 2, 3]); $b = $a->copy(); $b->push(4); print_r($a); print_r($b); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => 1 [1] => 2 [2] => 3 ) Ds\Deque Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ``` php imagecreatefromwbmp imagecreatefromwbmp =================== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) imagecreatefromwbmp — Create a new image from file or URL ### Description ``` imagecreatefromwbmp(string $filename): GdImage|false ``` **imagecreatefromwbmp()** returns an image identifier representing the image obtained from the given filename. > **Note**: WBMP images are Wireless Bitmaps, not Windows Bitmaps. The latter can be loaded with [imagecreatefrombmp()](function.imagecreatefrombmp). > > **Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. ### Parameters `filename` Path to the WBMP image. ### Return Values Returns an image object on success, **`false`** on errors. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. | ### Examples **Example #1 Example to handle an error during loading of a WBMP** ``` <?php function LoadWBMP($imgname) {     /* Attempt to open */     $im = @imagecreatefromwbmp($imgname);     /* See if it failed */     if(!$im)     {         /* Create a blank image */         $im  = imagecreatetruecolor(150, 30);         $bgc = imagecolorallocate($im, 255, 255, 255);         $tc  = imagecolorallocate($im, 0, 0, 0);         imagefilledrectangle($im, 0, 0, 150, 30, $bgc);         /* Output an error message */         imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);     }     return $im; } header('Content-Type: image/vnd.wap.wbmp'); $img = LoadWBMP('bogus.image'); imagewbmp($img); imagedestroy($img); ?> ``` php VarnishAdmin::setIdent VarnishAdmin::setIdent ====================== (PECL varnish >= 0.8) VarnishAdmin::setIdent — Set the class ident configuration param ### Description ``` public VarnishAdmin::setIdent(string $ident): void ``` ### Parameters `ident` Connection ident configuration parameter. ### Return Values php The EvPeriodic class The EvPeriodic class ==================== Introduction ------------ (PECL ev >= 0.2.0) Periodic watchers are also timers of a kind, but they are very versatile. Unlike [EvTimer](class.evtimer) , **EvPeriodic** watchers are not based on real time(or relative time, the physical time that passes) but on wall clock time(absolute time, calendar or clock). The difference is that wall clock time can run faster or slower than real time, and time jumps are not uncommon(e.g. when adjusting it). **EvPeriodic** watcher can be configured to trigger after some specific point in time. For example, if an **EvPeriodic** watcher is configured to trigger *"in 10 seconds"* (e.g. [EvLoop::now()](evloop.now) + **`10.0`** , i.e. an absolute time, not a delay), and the system clock is reset to *January of the previous year* , then it will take a year or more to trigger the event (unlike an [EvTimer](class.evtimer) , which would still trigger roughly **`10`** seconds after starting it as it uses a relative timeout). As with timers, the callback is guaranteed to be invoked only when the point in time where it is supposed to trigger has passed. If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones with later time-out values (but this is no longer true when a callback calls [EvLoop::run()](evloop.run) recursively). Class synopsis -------------- class **EvPeriodic** extends [EvWatcher](class.evwatcher) { /\* Properties \*/ public [$offset](class.evperiodic#evperiodic.props.offset); public [$interval](class.evperiodic#evperiodic.props.interval); /\* Inherited properties \*/ public [$is\_active](class.evwatcher#evwatcher.props.is-active); public [$data](class.evwatcher#evwatcher.props.data); public [$is\_pending](class.evwatcher#evwatcher.props.is-pending); public [$priority](class.evwatcher#evwatcher.props.priority); /\* Methods \*/ public [\_\_construct](evperiodic.construct)( float `$offset` , string `$interval` , [callable](language.types.callable) `$reschedule_cb` , [callable](language.types.callable) `$callback` , [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = **`null`** , int `$priority` = 0 ) ``` public again(): void ``` ``` public at(): float ``` ``` final public static createStopped( float $offset , float $interval , callable $reschedule_cb , callable $callback , mixed $data = null , int $priority = 0 ): EvPeriodic ``` ``` public set( float $offset , float $interval ): void ``` /\* Inherited methods \*/ ``` public EvWatcher::clear(): int ``` ``` public EvWatcher::feed( int $revents ): void ``` ``` public EvWatcher::getLoop(): EvLoop ``` ``` public EvWatcher::invoke( int $revents ): void ``` ``` public EvWatcher::keepalive( bool $value = ?): bool ``` ``` public EvWatcher::setCallback( callable $callback ): void ``` ``` public EvWatcher::start(): void ``` ``` public EvWatcher::stop(): void ``` } Properties ---------- offset When repeating, this contains the offset value, otherwise this is the absolute point in time(the offset value passed to [EvPeriodic::set()](evperiodic.set) , although *libev* might modify this value for better numerical stability). interval The current interval value. Can be modified any time, but changes only take effect when the periodic timer fires or [EvPeriodic::again()](evperiodic.again) is being called. Table of Contents ----------------- * [EvPeriodic::again](evperiodic.again) — Simply stops and restarts the periodic watcher again * [EvPeriodic::at](evperiodic.at) — Returns the absolute time that this watcher is supposed to trigger next * [EvPeriodic::\_\_construct](evperiodic.construct) — Constructs EvPeriodic watcher object * [EvPeriodic::createStopped](evperiodic.createstopped) — Create a stopped EvPeriodic watcher * [EvPeriodic::set](evperiodic.set) — Configures the watcher php Imagick::deskewImage Imagick::deskewImage ==================== (PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.3.0) Imagick::deskewImage — Removes skew from the image ### Description ``` public Imagick::deskewImage(float $threshold): bool ``` This method can be used to remove skew from for example scanned images where the paper was not properly placed on the scanning surface. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer. ### Parameters `threshold` Deskew threshold ### Return Values ### Examples **Example #1 **Imagick::deskewImage()**** ``` <?php function deskewImage($threshold) {     $imagick = new \Imagick(realpath("images/NYTimes-Page1-11-11-1918.jpg"));     $deskewImagick = clone $imagick;          //This is the only thing required for deskewing.     $deskewImagick->deskewImage($threshold);     //The rest of this example is to make the result obvious - because     //otherwise the result is not obvious.     $trim = 9;     $deskewImagick->cropImage($deskewImagick->getImageWidth() - $trim, $deskewImagick->getImageHeight(), $trim, 0);     $imagick->cropImage($imagick->getImageWidth() - $trim, $imagick->getImageHeight(), $trim, 0);     $deskewImagick->resizeimage($deskewImagick->getImageWidth() / 2, $deskewImagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);     $imagick->resizeimage($imagick->getImageWidth() / 2, $imagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);     $newCanvas = new \Imagick();     $newCanvas->newimage($imagick->getImageWidth() + $deskewImagick->getImageWidth() + 20, $imagick->getImageHeight(), 'red', 'jpg');     $newCanvas->compositeimage($imagick, \Imagick::COMPOSITE_COPY, 5, 0);     $newCanvas->compositeimage($deskewImagick, \Imagick::COMPOSITE_COPY, $imagick->getImageWidth() + 10, 0);     header("Content-Type: image/jpg");     echo $newCanvas->getImageBlob(); } ?> ``` php mysqli_driver::$report_mode mysqli\_driver::$report\_mode ============================= mysqli\_report ============== (PHP 5, PHP 7, PHP 8) mysqli\_driver::$report\_mode -- mysqli\_report — Sets mysqli error reporting mode ### Description Object-oriented style int [$mysqli\_driver->report\_mode](mysqli-driver.report-mode); Procedural style ``` mysqli_report(int $flags): bool ``` Depending on the flags, it sets mysqli error reporting mode to exception, warning or none. When set to **`MYSQLI_REPORT_ALL`** or **`MYSQLI_REPORT_INDEX`** it will also inform about queries that don't use an index (or use a bad index). As of PHP 8.1.0, the default setting is `MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT`. Previously, it was **`MYSQLI_REPORT_OFF`**. ### Parameters `flags` **Supported flags**| Name | Description | | --- | --- | | **`MYSQLI_REPORT_OFF`** | Turns reporting off | | **`MYSQLI_REPORT_ERROR`** | Report errors from mysqli function calls | | **`MYSQLI_REPORT_STRICT`** | Throw [mysqli\_sql\_exception](class.mysqli-sql-exception) for errors instead of warnings | | **`MYSQLI_REPORT_INDEX`** | Report if no index or bad index was used in a query | | **`MYSQLI_REPORT_ALL`** | Set all options (report all) | ### Return Values Returns **`true`**. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The default value is now `MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT`. Previously, it was **`MYSQLI_REPORT_OFF`**. | ### Examples **Example #1 Object-oriented style** ``` <?php /* activate reporting */ $driver = new mysqli_driver(); $driver->report_mode = MYSQLI_REPORT_ALL; try {     /* if the connection fails, a mysqli_sql_exception will be thrown */     $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");     /* this query should report an error */     $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");     /* this query should report a bad index if the column population doesn't have an index */     $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000"); } catch (mysqli_sql_exception $e) {     error_log($e->__toString()); } ``` **Example #2 Procedural style** ``` <?php /* activate reporting */ mysqli_report(MYSQLI_REPORT_ALL); try {     /* if the connection fails, a mysqli_sql_exception will be thrown */     $link = mysqli_connect("localhost", "my_user", "my_password", "my_db");     /* this query should report an error */     $result = mysqli_query($link, "SELECT Name FROM Nonexistingtable WHERE population > 50000");     /* this query should report a bad index if the column population doesn't have an index */     $result = mysqli_query($link, "SELECT Name FROM City WHERE population > 50000"); } catch (mysqli_sql_exception $e) {     error_log($e->__toString()); } ``` **Example #3 Error reporting except bad index errors** ``` <?php /* activate reporting */ mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try {     /* if the connection fails, a mysqli_sql_exception will be thrown */     $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");     /* this query should report an error */     $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");     /* this WILL NOT report any errors even if index is not available */     $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000"); } catch (mysqli_sql_exception $e) {     error_log($e->__toString()); } ``` ### See Also * [mysqli\_sql\_exception](class.mysqli-sql-exception) * [set\_exception\_handler()](function.set-exception-handler) - Sets a user-defined exception handler function * [error\_reporting()](function.error-reporting) - Sets which PHP errors are reported php pg_connection_busy pg\_connection\_busy ==================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_connection\_busy — Get connection is busy or not ### Description ``` pg_connection_busy(PgSql\Connection $connection): bool ``` **pg\_connection\_busy()** determines whether or not a connection is busy. If it is busy, a previous query is still executing. If [pg\_get\_result()](function.pg-get-result) is used on the connection, it will be blocked. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. ### Return Values Returns **`true`** if the connection is busy, **`false`** otherwise. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_connection\_busy()** example** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   $bs = pg_connection_busy($dbconn);   if ($bs) {       echo 'connection is busy';   } else {      echo 'connection is not busy';   } ?> ``` ### See Also * [pg\_connection\_status()](function.pg-connection-status) - Get connection status * [pg\_get\_result()](function.pg-get-result) - Get asynchronous query result php DirectoryIterator::getATime DirectoryIterator::getATime =========================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item ### Description ``` public DirectoryIterator::getATime(): int ``` Get the last access time of the current [DirectoryIterator](class.directoryiterator) item. ### Parameters This function has no parameters. ### Return Values Returns the time the file was last accessed, as a Unix timestamp. ### Examples **Example #1 A **DirectoryIterator::getATime()** example** Displays a list of the files in the directory of the script and their last access times. ``` <?php $iterator = new DirectoryIterator(dirname(__FILE__)); foreach ($iterator as $fileinfo) {     if ($fileinfo->isFile()) {         echo $fileinfo->getFilename() . " " . $fileinfo->getATime() . "\n";     } } ?> ``` The above example will output something similar to: ``` apple.jpg 1240047118 banana.jpg 1240065176 index.php 1240047208 pear.jpg 12240047979 ``` ### See Also * [DirectoryIterator::getCTime()](directoryiterator.getctime) - Get inode change time of the current DirectoryIterator item * [DirectoryIterator::getMTime()](directoryiterator.getmtime) - Get last modification time of current DirectoryIterator item * [fileatime()](function.fileatime) - Gets last access time of file php SQLite3Result::reset SQLite3Result::reset ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3Result::reset — Resets the result set back to the first row ### Description ``` public SQLite3Result::reset(): bool ``` Resets the result set back to the first row. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the result set is successfully reset back to the first row, **`false`** on failure. php QuickHashIntStringHash::__construct QuickHashIntStringHash::\_\_construct ===================================== (PECL quickhash >= Unknown) QuickHashIntStringHash::\_\_construct — Creates a new QuickHashIntStringHash object ### Description ``` public QuickHashIntStringHash::__construct(int $size, int $options = 0) ``` This constructor creates a new [QuickHashIntStringHash](class.quickhashintstringhash). The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported. ### Parameters `size` The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from `64` to `4194304`. `options` The options that you can pass in are: **`QuickHashIntStringHash::CHECK_FOR_DUPES`**, which makes sure no duplicate entries are added to the hash; **`QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC`** to not use PHP's internal memory manager as well as one of **`QuickHashIntStringHash::HASHER_NO_HASH`**, **`QuickHashIntStringHash::HASHER_JENKINS1`** or **`QuickHashIntStringHash::HASHER_JENKINS2`**. These last three configure which hashing algorithm to use. All options can be combined using bitmasks. ### Return Values Returns a new [QuickHashIntStringHash](class.quickhashintstringhash) object. ### Examples **Example #1 **QuickHashIntStringHash::\_\_construct()** example** ``` <?php var_dump( new QuickHashIntStringHash( 1024 ) ); var_dump( new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES ) ); var_dump(     new QuickHashIntStringHash(         1024,         QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntStringHash::HASHER_JENKINS2     ) ); ?> ``` php set_exception_handler set\_exception\_handler ======================= (PHP 5, PHP 7, PHP 8) set\_exception\_handler — Sets a user-defined exception handler function ### Description ``` set_exception_handler(?callable $callback): ?callable ``` Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the `callback` is called. ### Parameters `callback` The function to be called when an uncaught exception occurs. This handler function needs to accept one parameter, which will be the [Throwable](class.throwable) object that was thrown. Both [Error](class.error) and [Exception](class.exception) implement the [Throwable](class.throwable) interface. This is the handler signature: ``` handler(Throwable $ex): void ``` **`null`** may be passed instead, to reset this handler to its default state. ### Return Values Returns the previously defined exception handler, or **`null`** on error. If no previous handler was defined, **`null`** is also returned. ### Examples **Example #1 **set\_exception\_handler()** example** ``` <?php function exception_handler(Throwable $exception) {   echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed\n"; ?> ``` ### See Also * [restore\_exception\_handler()](function.restore-exception-handler) - Restores the previously defined exception handler function * [restore\_error\_handler()](function.restore-error-handler) - Restores the previous error handler function * [error\_reporting()](function.error-reporting) - Sets which PHP errors are reported * [PHP 5 Exceptions](language.exceptions)
programming_docs
php pg_field_type pg\_field\_type =============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_field\_type — Returns the type name for the corresponding field number ### Description ``` pg_field_type(PgSql\Result $result, int $field): string ``` **pg\_field\_type()** returns a string containing the base type name of the given `field` in the given `result` instance. > > **Note**: > > > If the field uses a PostgreSQL domain (rather than a basic type), it is the name of the domain's underlying type that is returned, rather than the name of the domain itself. > > > > **Note**: > > > This function used to be called **pg\_fieldtype()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `field` Field number, starting from 0. ### Return Values A string containing the base name of the field's type. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Getting information about fields** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   // Assume 'title' is a varchar type   $res = pg_query($dbconn, "select title from authors where author = 'Orwell'");   echo "Title field type: ", pg_field_type($res, 0); ?> ``` The above example will output: ``` Title field type: varchar ``` ### See Also * [pg\_field\_prtlen()](function.pg-field-prtlen) - Returns the printed length * [pg\_field\_name()](function.pg-field-name) - Returns the name of a field * [pg\_field\_type\_oid()](function.pg-field-type-oid) - Returns the type ID (OID) for the corresponding field number php gmp_random_bits gmp\_random\_bits ================= (PHP 5 >= 5.6.3, PHP 7, PHP 8) gmp\_random\_bits — Random number ### Description ``` gmp_random_bits(int $bits): GMP ``` Generate a random number. The number will be between 0 and (2 \*\* `bits`) - 1. `bits` must greater than 0, and the maximum value is restricted by available memory. ### Parameters `bits` The number of bits. ### Return Values A random GMP number. ### Examples **Example #1 **gmp\_random\_bits()** example** ``` <?php $rand1 = gmp_random_bits(3); // random number from 0 to 7 $rand2 = gmp_random_bits(5); // random number from 0 to 31 echo gmp_strval($rand1) . "\n"; echo gmp_strval($rand2) . "\n"; ?> ``` The above example will output: ``` 3 15 ``` php EvLoop::resume EvLoop::resume ============== (PECL ev >= 0.2.0) EvLoop::resume — Resume previously suspended default event loop ### Description ``` public EvLoop::resume(): void ``` [EvLoop::suspend()](evloop.suspend) and **EvLoop::resume()** methods suspend and resume a loop correspondingly. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [EvLoop::suspend()](evloop.suspend) - Suspend the loop * [Ev::resume()](ev.resume) - Resume previously suspended default event loop php ssh2_scp_recv ssh2\_scp\_recv =============== (PECL ssh2 >= 0.9.0) ssh2\_scp\_recv — Request a file via SCP ### Description ``` ssh2_scp_recv(resource $session, string $remote_file, string $local_file): bool ``` Copy a file from the remote server to the local filesystem using the SCP protocol. ### Parameters `session` An SSH connection link identifier, obtained from a call to [ssh2\_connect()](function.ssh2-connect). `remote_file` Path to the remote file. `local_file` Path to the local file. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Downloading a file via SCP** ``` <?php $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); ssh2_scp_recv($connection, '/remote/filename', '/local/filename'); ?> ``` ### See Also * [ssh2\_scp\_send()](function.ssh2-scp-send) - Send a file via SCP * [copy()](function.copy) - Copies file php ctype_punct ctype\_punct ============ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ctype\_punct — Check for any printable character which is not whitespace or an alphanumeric character ### Description ``` ctype_punct(mixed $text): bool ``` Checks if all of the characters in the provided string, `text`, are punctuation character. ### Parameters `text` The tested string. > > **Note**: > > > If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer. > > > **Warning** As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to [chr()](function.chr) should be made. ### Return Values Returns **`true`** if every character in `text` is printable, but neither letter, digit or blank, **`false`** otherwise. When called with an empty string the result will always be **`false`**. ### Examples **Example #1 A **ctype\_punct()** example** ``` <?php $strings = array('ABasdk!@!$#', '!@ # $', '*&$()'); foreach ($strings as $testcase) {     if (ctype_punct($testcase)) {         echo "The string $testcase consists of all punctuation.\n";     } else {         echo "The string $testcase does not consist of all punctuation.\n";     } } ?> ``` The above example will output: ``` The string ABasdk!@!$# does not consist of all punctuation. The string !@ # $ does not consist of all punctuation. The string *&$() consists of all punctuation. ``` ### See Also * [ctype\_cntrl()](function.ctype-cntrl) - Check for control character(s) * [ctype\_graph()](function.ctype-graph) - Check for any printable character(s) except space php pcntl_setpriority pcntl\_setpriority ================== (PHP 5, PHP 7, PHP 8) pcntl\_setpriority — Change the priority of any process ### Description ``` pcntl_setpriority(int $priority, ?int $process_id = null, int $mode = PRIO_PROCESS): bool ``` **pcntl\_setpriority()** sets the priority of `process_id`. ### Parameters `priority` `priority` is generally a value in the range `-20` to `20`. The default priority is `0` while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details. `process_id` If **`null`**, the process id of the current process is used. `mode` One of **`PRIO_PGRP`**, **`PRIO_USER`**, **`PRIO_PROCESS`**, **`PRIO_DARWIN_BG`** or **`PRIO_DARWIN_THREAD`**. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `process_id` is nullable now. | ### See Also * [pcntl\_getpriority()](function.pcntl-getpriority) - Get the priority of any process * **pcntl\_setpriority()** php The Yaf_Exception_DispatchFailed class The Yaf\_Exception\_DispatchFailed class ======================================== Introduction ------------ (Yaf >=1.0.0) Class synopsis -------------- class **Yaf\_Exception\_DispatchFailed** extends [Yaf\_Exception](class.yaf-exception) { /\* Properties \*/ /\* Methods \*/ /\* Inherited methods \*/ ``` public Yaf_Exception::getPrevious(): void ``` } php DOMDocument::createEntityReference DOMDocument::createEntityReference ================================== (PHP 5, PHP 7, PHP 8) DOMDocument::createEntityReference — Create new entity reference node ### Description ``` public DOMDocument::createEntityReference(string $name): DOMEntityReference|false ``` This function creates a new instance of class [DOMEntityReference](class.domentityreference). This node will not show up in the document unless it is inserted with (e.g.) [DOMNode::appendChild()](domnode.appendchild). ### Parameters `name` The content of the entity reference, e.g. the entity reference minus the leading `&` and the trailing `;` characters. ### Return Values The new [DOMEntityReference](class.domentityreference) or **`false`** if an error occurred. ### Errors/Exceptions **`DOM_INVALID_CHARACTER_ERR`** Raised if `name` contains an invalid character. ### See Also * [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children * [DOMDocument::createAttribute()](domdocument.createattribute) - Create new attribute * [DOMDocument::createAttributeNS()](domdocument.createattributens) - Create new attribute node with an associated namespace * [DOMDocument::createCDATASection()](domdocument.createcdatasection) - Create new cdata node * [DOMDocument::createComment()](domdocument.createcomment) - Create new comment node * [DOMDocument::createDocumentFragment()](domdocument.createdocumentfragment) - Create new document fragment * [DOMDocument::createElement()](domdocument.createelement) - Create new element node * [DOMDocument::createElementNS()](domdocument.createelementns) - Create new element node with an associated namespace * [DOMDocument::createProcessingInstruction()](domdocument.createprocessinginstruction) - Creates new PI node * [DOMDocument::createTextNode()](domdocument.createtextnode) - Create new text node php ImagickDraw::getTextKerning ImagickDraw::getTextKerning =========================== (PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.1.0) ImagickDraw::getTextKerning — Description ### Description ``` public ImagickDraw::getTextKerning(): float ``` Gets the text kerning. ### Parameters This function has no parameters. ### Return Values php ImagickDraw::setStrokeWidth ImagickDraw::setStrokeWidth =========================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines ### Description ``` public ImagickDraw::setStrokeWidth(float $stroke_width): bool ``` **Warning**This function is currently not documented; only its argument list is available. Sets the width of the stroke used to draw object outlines. ### Parameters `stroke_width` stroke width ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setStrokeWidth()** example** ``` <?php function setStrokeWidth($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeWidth(1);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->line(100, 100, 400, 145);     $draw->rectangle(100, 200, 225, 350);     $draw->setStrokeWidth(5);     $draw->line(100, 120, 400, 165);     $draw->rectangle(275, 200, 400, 350);     $image = new \Imagick();     $image->newImage(500, 400, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php VarnishAdmin::start VarnishAdmin::start =================== (PECL varnish >= 0.3) VarnishAdmin::start — Start varnish worker process ### Description ``` public VarnishAdmin::start(): int ``` ### Parameters This function has no parameters. ### Return Values Returns the varnish command status. php Threaded::shift Threaded::shift =============== (PECL pthreads >= 2.0.0) Threaded::shift — Manipulation ### Description ``` public Threaded::shift(): mixed ``` Shifts an item from the objects property table ### Parameters This function has no parameters. ### Return Values The first item from the objects property table ### Examples **Example #1 Shifting the first item from the property table of a threaded object** ``` <?php $safe = new Threaded(); while (count($safe) < 10)     $safe[] = count($safe); var_dump($safe->shift()); ?> ``` The above example will output: ``` int(0) ``` php None Numeric strings --------------- A PHP string is considered numeric if it can be interpreted as an int or a float. Formally as of PHP 8.0.0: ``` WHITESPACES \s* LNUM [0-9]+ DNUM ([0-9]*)[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM (({LNUM} | {DNUM}) [eE][+-]? {LNUM}) INT_NUM_STRING {WHITESPACES} [+-]? {LNUM} {WHITESPACES} FLOAT_NUM_STRING {WHITESPACES} [+-]? ({DNUM} | {EXPONENT_DNUM}) {WHITESPACES} NUM_STRING ({INT_NUM_STRING} | {FLOAT_NUM_STRING}) ``` PHP also has a concept of *leading* numeric strings. This is simply a string which starts like a numeric string followed by any characters. > > **Note**: > > > Any string that contains the letter `E` (case insensitive) bounded by numbers will be seen as a number expressed in scientific notation. This can produce unexpected results. > > > > ``` > <?php > var_dump("0D1" == "000"); // false, "0D1" is not scientific notation > var_dump("0E1" == "000"); // true, "0E1" is 0 * (10 ^ 1), or 0 > var_dump("2E1" == "020"); // true, "2E1" is 2 * (10 ^ 1), or 20 > ?> > ``` > ### Strings used in numeric contexts When a string needs to be evaluated as number (e.g. arithmetic operations, int type declaration, etc.) the following steps are taken to determine the outcome: 1. If the string is numeric, resolve to an int if the string is an integer numeric string and fits into the limits of the int type limits (as defined by **`PHP_INT_MAX`**), otherwise resolve to a float. 2. If the context allows leading numeric strings and the string is one, resolve to an int if the leading part of the string is an integer numeric string and fits into the limits of the int type limits (as defined by **`PHP_INT_MAX`**), otherwise resolve to a float. Additionally an error of level **`E_WARNING`** is raised. 3. The string is not numeric, throw a [TypeError](class.typeerror). ### Behavior prior to PHP 8.0.0 Prior to PHP 8.0.0, a string was considered numeric only if it had *leading* whitespaces, if it had *trailing* whitespaces then the string was considered to be leading numeric. Prior to PHP 8.0.0, when a string was used in a numeric context it would perform the same steps as above with the following differences: * The usage of a leading numeric string would raise an **`E_NOTICE`** instead of an **`E_WARNING`**. * If the string is not numeric, an **`E_WARNING`** was raised and the value `0` would be returned. Prior to PHP 7.1.0, neither **`E_NOTICE`** nor **`E_WARNING`** was raised. ``` <?php $foo = 1 + "10.5";                // $foo is float (11.5) $foo = 1 + "-1.3e3";              // $foo is float (-1299) $foo = 1 + "bob-1.3e3";           // TypeError as of PHP 8.0.0, $foo is integer (1) previously $foo = 1 + "bob3";                // TypeError as of PHP 8.0.0, $foo is integer (1) previously $foo = 1 + "10 Small Pigs";       // $foo is integer (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously $foo = "10.0 pigs " + 1;          // $foo is float (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously $foo = "10.0 pigs " + 1.0;        // $foo is float (11) and an E_WARNING is raised in PHP 8.0.0, E_NOTICE previously ?> ``` php ssh2_fetch_stream ssh2\_fetch\_stream =================== (PECL ssh2 >= 0.9.0) ssh2\_fetch\_stream — Fetch an extended data stream ### Description ``` ssh2_fetch_stream(resource $channel, int $streamid): resource ``` Fetches an alternate substream associated with an SSH2 channel stream. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of **`SSH2_STREAM_STDERR`** (defined as 1). ### Parameters `channel` `streamid` An SSH2 channel stream. ### Return Values Returns the requested stream resource. ### Examples **Example #1 Opening a shell and retrieving the stderr stream associated with it** ``` <?php $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $stdio_stream = ssh2_shell($connection); $stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR); ?> ``` ### See Also * [ssh2\_shell()](function.ssh2-shell) - Request an interactive shell * [ssh2\_exec()](function.ssh2-exec) - Execute a command on a remote server * [ssh2\_connect()](function.ssh2-connect) - Connect to an SSH server php imagegd2 imagegd2 ======== (PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8) imagegd2 — Output GD2 image to browser or file ### Description ``` imagegd2( GdImage $image, ?string $file = null, int $chunk_size = 128, int $mode = IMG_GD2_RAW ): bool ``` Outputs a GD2 image to the given `file`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `file` The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or **`null`**, the raw image stream will be output directly. `chunk_size` Chunk size. `mode` Either **`IMG_GD2_RAW`** or **`IMG_GD2_COMPRESSED`**. Default is **`IMG_GD2_RAW`**. ### Return Values Returns **`true`** on success or **`false`** on failure. **Caution**However, if libgd fails to output the image, this function returns **`true`**. ### Changelog | Version | Description | | --- | --- | | 8.0.3 | `file` is now nullable. | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Outputting a GD2 image** ``` <?php // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color); // Output the image imagegd2($im); // Free up memory imagedestroy($im); ?> ``` **Example #2 Saving a GD2 image** ``` <?php // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color); // Save the gd2 image // The file format for GD2 images is .gd2, see http://www.libgd.org/GdFileFormats imagegd2($im, 'simple.gd2'); // Free up memory imagedestroy($im); ?> ``` ### Notes > > **Note**: > > > The GD2 format is commonly used to allow fast loading of parts of images. Note that the GD2 format is only usable in GD2-compatible applications. > > **Warning**The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded *obsolete*, and should only be used for development and testing purposes. ### See Also * [imagegd()](function.imagegd) - Output GD image to browser or file php sem_remove sem\_remove =========== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) sem\_remove — Remove a semaphore ### Description ``` sem_remove(SysvSemaphore $semaphore): bool ``` **sem\_remove()** removes the given semaphore. After removing the semaphore, it is no longer accessible. ### Parameters `semaphore` A semaphore as returned by [sem\_get()](function.sem-get). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `semaphore` expects a [SysvSemaphore](class.sysvsemaphore) instance now; previously, a resource was expected. | ### See Also * [sem\_get()](function.sem-get) - Get a semaphore id * [sem\_release()](function.sem-release) - Release a semaphore * [sem\_acquire()](function.sem-acquire) - Acquire a semaphore
programming_docs
php php_ini_scanned_files php\_ini\_scanned\_files ======================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) php\_ini\_scanned\_files — Return a list of .ini files parsed from the additional ini dir ### Description ``` php_ini_scanned_files(): string|false ``` **php\_ini\_scanned\_files()** returns a comma-separated list of configuration files parsed after php.ini. The directories searched are set by a compile time option and, optionally, by an environment variable at run time: more information can be found in the [installation guide](https://www.php.net/manual/en/configuration.file.php#configuration.file.scan). The returned configuration files include the full path. ### Parameters This function has no parameters. ### Return Values Returns a comma-separated string of .ini files on success. Each comma is followed by a newline. If the configure directive **--with-config-file-scan-dir** wasn't set and the PHP\_INI\_SCAN\_DIR environment variable isn't set, **`false`** is returned. If it was set and the directory was empty, an empty string is returned. If a file is unrecognizable, the file will still make it into the returned string but a PHP error will also result. This PHP error will be seen both at compile time and while using **php\_ini\_scanned\_files()**. ### Examples **Example #1 A simple example to list the returned ini files** ``` <?php if ($filelist = php_ini_scanned_files()) {     if (strlen($filelist) > 0) {         $files = explode(',', $filelist);         foreach ($files as $file) {             echo "<li>" . trim($file) . "</li>\n";         }     } } ?> ``` ### See Also * [ini\_set()](function.ini-set) - Sets the value of a configuration option * [phpinfo()](function.phpinfo) - Outputs information about PHP's configuration * [php\_ini\_loaded\_file()](function.php-ini-loaded-file) - Retrieve a path to the loaded php.ini file php NumberFormatter::getAttribute NumberFormatter::getAttribute ============================= numfmt\_get\_attribute ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::getAttribute -- numfmt\_get\_attribute — Get an attribute ### Description Object-oriented style ``` public NumberFormatter::getAttribute(int $attribute): int|float|false ``` Procedural style ``` numfmt_get_attribute(NumberFormatter $formatter, int $attribute): int|float|false ``` Get a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. `attribute` Attribute specifier - one of the [numeric attribute](class.numberformatter#intl.numberformatter-constants.unumberformatattribute) constants. ### Return Values Return attribute value on success, or **`false`** on error. ### Examples **Example #1 **numfmt\_get\_attribute()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL ); echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n"; echo numfmt_format($fmt, 1234567.891234567890000)."\n"; numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2); echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n"; echo numfmt_format($fmt, 1234567.891234567890000)."\n"; ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL ); echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n"; echo $fmt->format(1234567.891234567890000)."\n"; $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2); echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n"; echo $fmt->format(1234567.891234567890000)."\n"; ?> ``` The above example will output: ``` Digits: 3 1.234.567,891 Digits: 2 1.234.567,89 ``` ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [numfmt\_get\_text\_attribute()](numberformatter.gettextattribute) - Get a text attribute * [numfmt\_set\_attribute()](numberformatter.setattribute) - Set an attribute php openal_context_current openal\_context\_current ======================== (PECL openal >= 0.1.0) openal\_context\_current — Make the specified context current ### Description ``` openal_context_current(resource $context): bool ``` ### Parameters `context` An [Open AL(Context)](https://www.php.net/manual/en/openal.resources.php) resource (previously created by [openal\_context\_create()](function.openal-context-create)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [openal\_context\_create()](function.openal-context-create) - Create an audio processing context php odbc_columns odbc\_columns ============= (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_columns — Lists the column names in specified tables ### Description ``` odbc_columns( resource $odbc, ?string $catalog = null, ?string $schema = null, ?string $table = null, ?string $column = null ): resource|false ``` Lists all columns in the requested range. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `catalog` The catalog ('qualifier' in ODBC 2 parlance). `schema` The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character. `table` The table name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character. `column` The column name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character. ### Return Values Returns an ODBC result identifier or **`false`** on failure. The result set has the following columns: * `TABLE_CAT` * `TABLE_SCHEM` * `TABLE_NAME` * `COLUMN_NAME` * `DATA_TYPE` * `TYPE_NAME` * `COLUMN_SIZE` * `BUFFER_LENGTH` * `DECIMAL_DIGITS` * `NUM_PREC_RADIX` * `NULLABLE` * `REMARKS` * `COLUMN_DEF` * `SQL_DATA_TYPE` * `SQL_DATETIME_SUB` * `CHAR_OCTET_LENGTH` * `ORDINAL_POSITION` * `IS_NULLABLE` Drivers can report additional columns. The result set is ordered by `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME` and `ORDINAL_POSITION`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `schema`, `table` and `column` are now nullable. | ### Examples **Example #1 List Columns of a Table** ``` <?php $conn = odbc_connect($dsn, $user, $pass); $columns = odbc_columns($conn, 'TutorialDB', 'dbo', 'test', '%'); while (($row = odbc_fetch_array($columns))) {     print_r($row);     break; // further rows omitted for brevity } ?> ``` The above example will output something similar to: ``` Array ( [TABLE_CAT] => TutorialDB [TABLE_SCHEM] => dbo [TABLE_NAME] => TEST [COLUMN_NAME] => id [DATA_TYPE] => 4 [TYPE_NAME] => int [COLUMN_SIZE] => 10 [BUFFER_LENGTH] => 4 [DECIMAL_DIGITS] => 0 [NUM_PREC_RADIX] => 10 [NULLABLE] => 0 [REMARKS] => [COLUMN_DEF] => [SQL_DATA_TYPE] => 4 [SQL_DATETIME_SUB] => [CHAR_OCTET_LENGTH] => [ORDINAL_POSITION] => 1 [IS_NULLABLE] => NO ) ``` ### See Also * [odbc\_columnprivileges()](function.odbc-columnprivileges) - Lists columns and associated privileges for the given table * [odbc\_procedurecolumns()](function.odbc-procedurecolumns) - Retrieve information about parameters to procedures php socket_create_pair socket\_create\_pair ==================== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_create\_pair — Creates a pair of indistinguishable sockets and stores them in an array ### Description ``` socket_create_pair( int $domain, int $type, int $protocol, array &$pair ): bool ``` **socket\_create\_pair()** creates two connected and indistinguishable sockets, and stores them in `pair`. This function is commonly used in IPC (InterProcess Communication). ### Parameters `domain` The `domain` parameter specifies the protocol family to be used by the socket. See [socket\_create()](function.socket-create) for the full list. `type` The `type` parameter selects the type of communication to be used by the socket. See [socket\_create()](function.socket-create) for the full list. `protocol` The `protocol` parameter sets the specific protocol within the specified `domain` to be used when communicating on the returned socket. The proper value can be retrieved by name by using [getprotobyname()](function.getprotobyname). If the desired protocol is TCP, or UDP the corresponding constants **`SOL_TCP`**, and **`SOL_UDP`** can also be used. See [socket\_create()](function.socket-create) for the full list of supported protocols. `pair` Reference to an array in which the two [Socket](class.socket) instances will be inserted. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `pair` is a reference to an array of [Socket](class.socket) instances now; previously, it was a reference to an array of resources. | ### Examples **Example #1 **socket\_create\_pair()** example** ``` <?php $sockets = array(); /* On Windows we need to use AF_INET */ $domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX); /* Setup socket pair */ if (socket_create_pair($domain, SOCK_STREAM, 0, $sockets) === false) {     echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error()); } /* Send and Receive Data */ if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {     echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0])); } if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {     echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1])); } var_dump($data); /* Close sockets */ socket_close($sockets[0]); socket_close($sockets[1]); ?> ``` **Example #2 **socket\_create\_pair()** IPC example** ``` <?php $ary = array(); $strone = 'Message From Parent.'; $strtwo = 'Message From Child.'; if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary) === false) {     echo "socket_create_pair() failed. Reason: ".socket_strerror(socket_last_error()); } $pid = pcntl_fork(); if ($pid == -1) {     echo 'Could not fork Process.'; } elseif ($pid) {     /*parent*/     socket_close($ary[0]);     if (socket_write($ary[1], $strone, strlen($strone)) === false) {         echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[1]));     }     if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) {         echo "Received $strtwo\n";     }     socket_close($ary[1]); } else {     /*child*/     socket_close($ary[1]);     if (socket_write($ary[0], $strtwo, strlen($strtwo)) === false) {         echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[0]));     }     if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) {         echo "Received $strone\n";     }     socket_close($ary[0]); } ?> ``` ### See Also * [socket\_create()](function.socket-create) - Create a socket (endpoint for communication) * [socket\_create\_listen()](function.socket-create-listen) - Opens a socket on port to accept connections * [socket\_bind()](function.socket-bind) - Binds a name to a socket * [socket\_listen()](function.socket-listen) - Listens for a connection on a socket * [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error php stream_context_get_options stream\_context\_get\_options ============================= (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) stream\_context\_get\_options — Retrieve options for a stream/wrapper/context ### Description ``` stream_context_get_options(resource $stream_or_context): array ``` Returns an array of options on the specified stream or context. ### Parameters `stream_or_context` The stream or context to get options from ### Return Values Returns an associative array with the options. ### Examples **Example #1 **stream\_context\_get\_options()** example** ``` <?php $params = array("method" => "POST"); stream_context_set_default(array("http" => $params)); var_dump(stream_context_get_options(stream_context_get_default())); ?> ``` The above example will output something similar to: ``` array(1) { ["http"]=> array(1) { ["method"]=> string(4) "POST" } } ``` php ldap_get_values_len ldap\_get\_values\_len ====================== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_get\_values\_len — Get all binary values from a result entry ### Description ``` ldap_get_values_len(LDAP\Connection $ldap, LDAP\ResultEntry $entry, string $attribute): array|false ``` Reads all the values of the attribute in the entry in the result. This function is used exactly like [ldap\_get\_values()](function.ldap-get-values) except that it handles binary data and not string data. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `entry` An [LDAP\ResultEntry](class.ldap-result-entry) instance. `attribute` ### Return Values Returns an array of values for the attribute on success and **`false`** on error. Individual values are accessed by integer index in the array. The first index is 0. The number of values can be found by indexing "count" in the resultant array. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `entry` parameter expects an [LDAP\ResultEntry](class.ldap-result-entry) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [ldap\_get\_values()](function.ldap-get-values) - Get all values from a result entry php Yac::info Yac::info ========= (PECL yac >= 1.0.0) Yac::info — Status of cache ### Description ``` public Yac::info(): array ``` Get status of cache system ### Parameters This function has no parameters. ### Return Values Return an array, consistent with: "memory\_size", "slots\_memory\_size", "values\_memory\_size", "segment\_size", "segment\_num", "miss", "hits", "fails", "kicks", "recycles", "slots\_size", "slots\_used" php runkit7_function_remove runkit7\_function\_remove ========================= (PECL runkit7 >= Unknown) runkit7\_function\_remove — Remove a function definition ### Description ``` runkit7_function_remove(string $function_name): bool ``` > **Note**: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the `runkit.internal_override` setting in php.ini. > > ### Parameters `function_name` Name of the function to be deleted ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [runkit7\_function\_add()](function.runkit7-function-add) - Add a new function, similar to create\_function * [runkit7\_function\_copy()](function.runkit7-function-copy) - Copy a function to a new function name * [runkit7\_function\_redefine()](function.runkit7-function-redefine) - Replace a function definition with a new implementation * [runkit7\_function\_rename()](function.runkit7-function-rename) - Change a function's name php ReflectionZendExtension::__clone ReflectionZendExtension::\_\_clone ================================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionZendExtension::\_\_clone — Clone handler ### Description ``` private ReflectionZendExtension::__clone(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values ### Changelog | Version | Description | | --- | --- | | 8.1.0 | This method is no longer final. | php mysqli_result::fetch_fields mysqli\_result::fetch\_fields ============================= mysqli\_fetch\_fields ===================== (PHP 5, PHP 7, PHP 8) mysqli\_result::fetch\_fields -- mysqli\_fetch\_fields — Returns an array of objects representing the fields in a result set ### Description Object-oriented style ``` public mysqli_result::fetch_fields(): array ``` Procedural style ``` mysqli_fetch_fields(mysqli_result $result): array ``` This function serves an identical purpose to the [mysqli\_fetch\_field()](mysqli-result.fetch-field) function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects. ### Parameters `result` Procedural style only: A [mysqli\_result](class.mysqli-result) object returned by [mysqli\_query()](mysqli.query), [mysqli\_store\_result()](mysqli.store-result), [mysqli\_use\_result()](mysqli.use-result) or [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result). ### Return Values Returns an array of objects containing field definition information. **Object properties**| Property | Description | | --- | --- | | name | The name of the column | | orgname | Original column name if an alias was specified | | table | The name of the table this field belongs to (if not calculated) | | orgtable | Original table name if an alias was specified | | max\_length | The maximum width of the field for the result set. | | length | The width of the field, in bytes, as specified in the table definition. Note that this number (bytes) might differ from your table definition value (characters), depending on the character set you use. For example, the character set utf8 has 3 bytes per character, so varchar(10) will return a length of 30 for utf8 (10\*3), but return 10 for latin1 (10\*1). | | charsetnr | The character set number (id) for the field. | | flags | An integer representing the bit-flags for the field. | | type | The data type used for this field | | decimals | The number of decimals used (for integer fields) | ### Examples **Example #1 Object-oriented style** ``` <?php $mysqli = new mysqli("127.0.0.1", "root", "foofoo", "sakila"); /* check connection */ if ($mysqli->connect_errno) {     printf("Connect failed: %s\n", $mysqli->connect_error);     exit(); } foreach (array('latin1', 'utf8') as $charset) {     // Set character set, to show its impact on some values (e.g., length in bytes)     $mysqli->set_charset($charset);     $query = "SELECT actor_id, last_name from actor ORDER BY actor_id";     echo "======================\n";     echo "Character Set: $charset\n";     echo "======================\n";          if ($result = $mysqli->query($query)) {         /* Get field information for all columns */         $finfo = $result->fetch_fields();         foreach ($finfo as $val) {             printf("Name:      %s\n",   $val->name);             printf("Table:     %s\n",   $val->table);             printf("Max. Len:  %d\n",   $val->max_length);             printf("Length:    %d\n",   $val->length);             printf("charsetnr: %d\n",   $val->charsetnr);             printf("Flags:     %d\n",   $val->flags);             printf("Type:      %d\n\n", $val->type);         }         $result->free();     } } $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php $link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } foreach (array('latin1', 'utf8') as $charset) {     // Set character set, to show its impact on some values (e.g., length in bytes)     mysqli_set_charset($link, $charset);     $query = "SELECT actor_id, last_name from actor ORDER BY actor_id";     echo "======================\n";     echo "Character Set: $charset\n";     echo "======================\n";     if ($result = mysqli_query($link, $query)) {         /* Get field information for all columns */         $finfo = mysqli_fetch_fields($result);         foreach ($finfo as $val) {             printf("Name:      %s\n",   $val->name);             printf("Table:     %s\n",   $val->table);             printf("Max. Len:  %d\n",   $val->max_length);             printf("Length:    %d\n",   $val->length);             printf("charsetnr: %d\n",   $val->charsetnr);             printf("Flags:     %d\n",   $val->flags);             printf("Type:      %d\n\n", $val->type);         }         mysqli_free_result($result);     } } mysqli_close($link); ?> ``` The above examples will output: ``` ====================== Character Set: latin1 ====================== Name: actor_id Table: actor Max. Len: 3 Length: 5 charsetnr: 63 Flags: 49699 Type: 2 Name: last_name Table: actor Max. Len: 12 Length: 45 charsetnr: 8 Flags: 20489 Type: 253 ====================== Character Set: utf8 ====================== Name: actor_id Table: actor Max. Len: 3 Length: 5 charsetnr: 63 Flags: 49699 Type: 2 Name: last_name Table: actor Max. Len: 12 Length: 135 charsetnr: 33 Flags: 20489 ``` ### See Also * [mysqli\_num\_fields()](mysqli-result.field-count) - Gets the number of fields in the result set * [mysqli\_fetch\_field\_direct()](mysqli-result.fetch-field-direct) - Fetch meta-data for a single field * [mysqli\_fetch\_field()](mysqli-result.fetch-field) - Returns the next field in the result set
programming_docs
php SolrUtils::getSolrVersion SolrUtils::getSolrVersion ========================= (PECL solr >= 0.9.2) SolrUtils::getSolrVersion — Returns the current version of the Solr extension ### Description ``` public static SolrUtils::getSolrVersion(): string ``` Returns the current Solr version. ### Parameters This function has no parameters. ### Return Values The current version of the Apache Solr extension. php The EmptyIterator class The EmptyIterator class ======================= Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) The EmptyIterator class for an empty iterator. Class synopsis -------------- class **EmptyIterator** implements [Iterator](class.iterator) { /\* Methods \*/ ``` public current(): never ``` ``` public key(): never ``` ``` public next(): void ``` ``` public rewind(): void ``` ``` public valid(): false ``` } Table of Contents ----------------- * [EmptyIterator::current](emptyiterator.current) — The current() method * [EmptyIterator::key](emptyiterator.key) — The key() method * [EmptyIterator::next](emptyiterator.next) — The next() method * [EmptyIterator::rewind](emptyiterator.rewind) — The rewind() method * [EmptyIterator::valid](emptyiterator.valid) — The valid() method php GearmanJob::sendWarning GearmanJob::sendWarning ======================= (PECL gearman >= 0.6.0) GearmanJob::sendWarning — Send a warning ### Description ``` public GearmanJob::sendWarning(string $warning): bool ``` Sends a warning for this job while it is running. ### Parameters `warning` A warning message. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanJob::sendComplete()](gearmanjob.sendcomplete) - Send the result and complete status * [GearmanJob::sendException()](gearmanjob.sendexception) - Send exception for running job (exception) * [GearmanJob::sendFail()](gearmanjob.sendfail) - Send fail status php SolrPingResponse::getResponse SolrPingResponse::getResponse ============================= (PECL solr >= 0.9.2) SolrPingResponse::getResponse — Returns the response from the server ### Description ``` public SolrPingResponse::getResponse(): string ``` Returns the response from the server. This should be empty because the request as a HEAD request. ### Parameters This function has no parameters. ### Return Values Returns an empty string. php SplFileObject::seek SplFileObject::seek =================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::seek — Seek to specified line ### Description ``` public SplFileObject::seek(int $line): void ``` Seek to specified line in the file. ### Parameters `line` The zero-based line number to seek to. ### Return Values No value is returned. ### Errors/Exceptions Throws a [LogicException](class.logicexception) if the `line` is negative. ### Examples **Example #1 **SplFileObject::seek()** example** This example outputs the third line of the script which is found at position 2. ``` <?php $file = new SplFileObject(__FILE__); $file->seek(2); echo $file->current(); ?> ``` The above example will output something similar to: ``` $file->seek(2); ``` ### See Also * [SplFileObject::current()](splfileobject.current) - Retrieve current line of file * [SplFileObject::key()](splfileobject.key) - Get line number * [SplFileObject::next()](splfileobject.next) - Read next line * [SplFileObject::rewind()](splfileobject.rewind) - Rewind the file to the first line * [SplFileObject::valid()](splfileobject.valid) - Not at EOF php readline_on_new_line readline\_on\_new\_line ======================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) readline\_on\_new\_line — Inform readline that the cursor has moved to a new line ### Description ``` readline_on_new_line(): void ``` Tells readline that the cursor has moved to a new line. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Notes > > **Note**: > > > This function is only available if supported by the underlying readline library. It is not supported on Windows. > > php pg_connect_poll pg\_connect\_poll ================= (PHP 5 >= 5.6.0, PHP 7, PHP 8) pg\_connect\_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt ### Description ``` pg_connect_poll(PgSql\Connection $connection): int ``` **pg\_connect\_poll()** polls the status of a PostgreSQL connection created by calling [pg\_connect()](function.pg-connect) with the **`PGSQL_CONNECT_ASYNC`** option. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. ### Return Values Returns **`PGSQL_POLLING_FAILED`**, **`PGSQL_POLLING_READING`**, **`PGSQL_POLLING_WRITING`**, **`PGSQL_POLLING_OK`**, or **`PGSQL_POLLING_ACTIVE`**. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | php Imagick::writeImage Imagick::writeImage =================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::writeImage — Writes an image to the specified filename ### Description ``` public Imagick::writeImage(string $filename = NULL): bool ``` Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Imagick::readImage() or Imagick::setImageFilename(). ### Parameters `filename` Filename where to write the image. The extension of the filename defines the type of the file. Format can be forced regardless of file extension using format: prefix, for example "jpg:test.png". ### Return Values Returns **`true`** on success. php enchant_broker_get_error enchant\_broker\_get\_error =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 ) enchant\_broker\_get\_error — Returns the last error of the broker ### Description ``` enchant_broker_get_error(EnchantBroker $broker): string|false ``` Returns the last error which occurred in this broker. ### Parameters `broker` An Enchant broker returned by [enchant\_broker\_init()](function.enchant-broker-init). ### Return Values Return the msg string if an error was found or **`false`** ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `broker` expects an [EnchantBroker](class.enchantbroker) instance now; previoulsy, a [resource](language.types.resource) was expected. | php pcntl_wifsignaled pcntl\_wifsignaled ================== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) pcntl\_wifsignaled — Checks whether the status code represents a termination due to a signal ### Description ``` pcntl_wifsignaled(int $status): bool ``` Checks whether the child process exited because of a signal which was not caught. ### Parameters `status` The `status` parameter is the status parameter supplied to a successful call to [pcntl\_waitpid()](function.pcntl-waitpid). ### Return Values Returns **`true`** if the child process exited because of a signal which was not caught, **`false`** otherwise. ### See Also * [pcntl\_waitpid()](function.pcntl-waitpid) - Waits on or returns the status of a forked child * [pcntl\_signal()](function.pcntl-signal) - Installs a signal handler php SolrQuery::collapse SolrQuery::collapse =================== (No version information available, might only be in Git) SolrQuery::collapse — Collapses the result set to a single document per group ### Description ``` public SolrQuery::collapse(SolrCollapseFunction $collapseFunction): SolrQuery ``` Collapses the result set to a single document per group before it forwards the result set to the rest of the search components. So all downstream components (faceting, highlighting, etc...) will work with the collapsed result set. ### Parameters `collapseFunction` ### Return Values Returns the current [SolrQuery](class.solrquery) object ### Examples **Example #1 **SolrQuery::collapse()** example** ``` <?php include "bootstrap.php"; $options = array (         'hostname' => SOLR_SERVER_HOSTNAME,         'login'    => SOLR_SERVER_USERNAME,         'password' => SOLR_SERVER_PASSWORD,         'port'     => SOLR_SERVER_PORT,         'path'     => SOLR_SERVER_PATH ); $client = new SolrClient($options); $query = new SolrQuery('*:*'); $collapseFunction = new SolrCollapseFunction('manu_id_s'); $collapseFunction ->setSize(2) ->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE); $query ->collapse($collapseFunction) ->setRows(4); $queryResponse = $client->query($query); $response = $queryResponse->getResponse(); print_r($response); ?> ``` The above example will output something similar to: ``` SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 1 [params] => SolrObject Object ( [q] => *:* [indent] => on [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore} [rows] => 4 [version] => 2.2 [wt] => xml ) ) [response] => SolrObject Object ( [numFound] => 14 [start] => 0 [docs] => Array ( [0] => SolrObject Object ( [id] => SP2514N [name] => Array ( [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133 ) [manu] => Array ( [0] => Samsung Electronics Co. Ltd. ) [manu_id_s] => samsung [cat] => Array ( [0] => electronics [1] => hard drive ) [features] => Array ( [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133 [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor ) [price] => Array ( [0] => 92 ) [popularity] => Array ( [0] => 6 ) [inStock] => Array ( [0] => 1 ) [manufacturedate_dt] => 2006-02-13T15:26:37Z [store] => Array ( [0] => 35.0752,-97.032 ) [_version_] => 1510294336412057600 ) [1] => SolrObject Object ( [id] => 6H500F0 [name] => Array ( [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300 ) [manu] => Array ( [0] => Maxtor Corp. ) [manu_id_s] => maxtor [cat] => Array ( [0] => electronics [1] => hard drive ) [features] => Array ( [0] => SATA 3.0Gb/s, NCQ [1] => 8.5ms seek [2] => 16MB cache ) [price] => Array ( [0] => 350 ) [popularity] => Array ( [0] => 6 ) [inStock] => Array ( [0] => 1 ) [store] => Array ( [0] => 45.17614,-93.87341 ) [manufacturedate_dt] => 2006-02-13T15:26:37Z [_version_] => 1510294336449806336 ) [2] => SolrObject Object ( [id] => F8V7067-APL-KIT [name] => Array ( [0] => Belkin Mobile Power Cord for iPod w/ Dock ) [manu] => Array ( [0] => Belkin ) [manu_id_s] => belkin [cat] => Array ( [0] => electronics [1] => connector ) [features] => Array ( [0] => car power adapter, white ) [weight] => Array ( [0] => 4 ) [price] => Array ( [0] => 19.95 ) [popularity] => Array ( [0] => 1 ) [inStock] => Array ( [0] => ) [store] => Array ( [0] => 45.18014,-93.87741 ) [manufacturedate_dt] => 2005-08-01T16:30:25Z [_version_] => 1510294336458194944 ) [3] => SolrObject Object ( [id] => MA147LL/A [name] => Array ( [0] => Apple 60 GB iPod with Video Playback Black ) [manu] => Array ( [0] => Apple Computer Inc. ) [manu_id_s] => apple [cat] => Array ( [0] => electronics [1] => music ) [features] => Array ( [0] => iTunes, Podcasts, Audiobooks [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight [3] => Up to 20 hours of battery life [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video [5] => Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication ) [includes] => Array ( [0] => earbud headphones, USB cable ) [weight] => Array ( [0] => 5.5 ) [price] => Array ( [0] => 399 ) [popularity] => Array ( [0] => 10 ) [inStock] => Array ( [0] => 1 ) [store] => Array ( [0] => 37.7752,-100.0232 ) [manufacturedate_dt] => 2005-10-12T08:00:00Z [_version_] => 1510294336562003968 ) ) ) ) ``` php GearmanClient::addTaskHighBackground GearmanClient::addTaskHighBackground ==================================== (PECL gearman >= 0.5.0) GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel ### Description ``` public GearmanClient::addTaskHighBackground( string $function_name, string $workload, mixed &$context = ?, string $unique = ? ): GearmanTask ``` Adds a high priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call [GearmanClient::runTasks()](gearmanclient.runtasks) to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority. ### Parameters `function_name` A registered function the worker is to execute `workload` Serialized data to be processed `context` Application context to associate with a task `unique` A unique ID used to identify a particular task ### Return Values A [GearmanTask](class.gearmantask) object or **`false`** if the task could not be added. ### See Also * [GearmanClient::addTask()](gearmanclient.addtask) - Add a task to be run in parallel * [GearmanClient::addTaskHigh()](gearmanclient.addtaskhigh) - Add a high priority task to run in parallel * [GearmanClient::addTaskLow()](gearmanclient.addtasklow) - Add a low priority task to run in parallel * [GearmanClient::addTaskBackground()](gearmanclient.addtaskbackground) - Add a background task to be run in parallel * [GearmanClient::addTaskLowBackground()](gearmanclient.addtasklowbackground) - Add a low priority background task to be run in parallel * [GearmanClient::runTasks()](gearmanclient.runtasks) - Run a list of tasks in parallel
programming_docs
php xml_set_end_namespace_decl_handler xml\_set\_end\_namespace\_decl\_handler ======================================= (PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8) xml\_set\_end\_namespace\_decl\_handler — Set up end namespace declaration handler ### Description ``` xml_set_end_namespace_decl_handler(XMLParser $parser, callable $handler): bool ``` Set a handler to be called when leaving the scope of a namespace declaration. This will be called, for each namespace declaration, after the handler for the end tag of the element in which the namespace was declared. **Caution** This event is not supported under libXML, so a registered handler wouldn't be called. ### Parameters `parser` A reference to the XML parser. `handler` `handler` is a string containing the name of a function that must exist when [xml\_parse()](function.xml-parse) is called for `parser`. The function named by `handler` must accept two parameters, and should return an integer value. If the value returned from the handler is **`false`** (which it will be if no value is returned), the XML parser will stop parsing and [xml\_get\_error\_code()](function.xml-get-error-code) will return **`XML_ERROR_EXTERNAL_ENTITY_HANDLING`**. ``` handler(XMLParser $parser, string $prefix) ``` `parser` The first parameter, parser, is a reference to the XML parser calling the handler. `prefix` The prefix is a string used to reference the namespace within an XML object. If a handler function is set to an empty string, or **`false`**, the handler in question is disabled. > **Note**: Instead of a function name, an array containing an object reference and a method name can also be supplied. > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `parser` expects an [XMLParser](class.xmlparser) instance now; previously, a resource was expected. | ### See Also * [xml\_set\_start\_namespace\_decl\_handler()](function.xml-set-start-namespace-decl-handler) - Set up start namespace declaration handler php Phar::canWrite Phar::canWrite ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::canWrite — Returns whether phar extension supports writing and creating phars ### Description ``` final public static Phar::canWrite(): bool ``` This static method determines whether write access has been disabled in the system php.ini via the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) ini variable. ### Parameters ### Return Values **`true`** if write access is enabled, **`false`** if it is disabled. ### Examples **Example #1 A **Phar::canWrite()** example** ``` <?php if (Phar::canWrite()) {     file_put_contents('phar://myphar.phar/file.txt', 'hi there'); } ?> ``` ### See Also * [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) * [Phar::isWritable()](phar.iswritable) - Returns true if the phar archive can be modified php Imagick::setImageCompose Imagick::setImageCompose ======================== (PECL imagick 2, PECL imagick 3) Imagick::setImageCompose — Sets the image composite operator ### Description ``` public Imagick::setImageCompose(int $compose): bool ``` Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the Imagick::montageImage() method. ### Parameters `compose` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php ssh2_disconnect ssh2\_disconnect ================ (PECL ssh2 >= 1.0) ssh2\_disconnect — Close a connection to a remote SSH server ### Description ``` ssh2_disconnect(resource $session): bool ``` Close a connection to a remote SSH server. ### Parameters `session` An SSH connection link identifier, obtained from a call to [ssh2\_connect()](function.ssh2-connect). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [ssh2\_connect()](function.ssh2-connect) - Connect to an SSH server php geoip_country_code_by_name geoip\_country\_code\_by\_name ============================== (PECL geoip >= 0.2.0) geoip\_country\_code\_by\_name — Get the two letter country code ### Description ``` geoip_country_code_by_name(string $hostname): string ``` The **geoip\_country\_code\_by\_name()** function will return the two letter country code corresponding to a hostname or an IP address. ### Parameters `hostname` The hostname or IP address whose location is to be looked-up. ### Return Values Returns the two letter ISO country code on success, or **`false`** if the address cannot be found in the database. ### Examples **Example #1 A **geoip\_country\_code\_by\_name()** example** This will print where the host example.com is located. ``` <?php $country = geoip_country_code_by_name('www.example.com'); if ($country) {     echo 'This host is located in: ' . $country; } ?> ``` The above example will output: ``` This host is located in: US ``` ### Notes **Caution** Please see [» http://www.maxmind.com/en/iso3166](http://www.maxmind.com/en/iso3166) for a complete list of possible return values, including special codes. ### See Also * [geoip\_country\_code3\_by\_name()](function.geoip-country-code3-by-name) - Get the three letter country code * [geoip\_country\_name\_by\_name()](function.geoip-country-name-by-name) - Get the full country name php IntlDateFormatter::setTimeZone IntlDateFormatter::setTimeZone ============================== datefmt\_set\_timezone ====================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0) IntlDateFormatter::setTimeZone -- datefmt\_set\_timezone — Sets formatterʼs timezone ### Description Object-oriented style ``` public IntlDateFormatter::setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): ?bool ``` Procedural style ``` datefmt_set_timezone(IntlDateFormatter $formatter, IntlTimeZone|DateTimeZone|string|null $timezone): ?bool ``` Sets the timezone used for the IntlDateFormatter. object. ### Parameters `formatter` The formatter resource. `timezone` The timezone to use for this formatter. This can be specified in the following forms: * **`null`**, in which case the default timezone will be used, as specified in the ini setting [date.timezone](https://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone) or through the function [date\_default\_timezone\_set()](function.date-default-timezone-set) and as returned by [date\_default\_timezone\_get()](function.date-default-timezone-get). * An [IntlTimeZone](class.intltimezone), which will be used directly. * A [DateTimeZone](class.datetimezone). Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs. * A string, which should be a valid ICU timezone identifier. See [IntlTimeZone::createTimeZoneIDEnumeration()](intltimezone.createtimezoneidenumeration). Raw offsets such as `"GMT+08:30"` are also accepted. ### Return Values Returns **`null`** on success and **`false`** on failure. ### Examples **Example #1 **IntlDateFormatter::setTimeZone()** examples** ``` <?php ini_set('date.timezone', 'Europe/Amsterdam'); $formatter = IntlDateFormatter::create(NULL, NULL, NULL, "UTC"); $formatter->setTimeZone(NULL); echo "NULL\n    ", $formatter->getTimeZone()->getId(), "\n"; $formatter->setTimeZone(IntlTimeZone::createTimeZone('Europe/Lisbon')); echo "IntlTimeZone\n    ", $formatter->getTimeZone()->getId(), "\n"; $formatter->setTimeZone(new DateTimeZone('Europe/Paris')); echo "DateTimeZone\n    ", $formatter->getTimeZone()->getId(), "\n"; $formatter->setTimeZone('Europe/Rome'); echo "String\n    ", $formatter->getTimeZone()->getId(), "\n"; $formatter->setTimeZone('GMT+00:30'); print_r($formatter->getTimeZone()); ``` The above example will output: ``` NULL Europe/Amsterdam IntlTimeZone Europe/Lisbon DateTimeZone Europe/Paris String Europe/Rome IntlTimeZone Object ( [valid] => 1 [id] => GMT+00:30 [rawOffset] => 1800000 [currentOffset] => 1800000 ) ``` ### See Also * [IntlDateFormatter::getTimeZone()](intldateformatter.gettimezone) - Get formatterʼs timezone php odbc_specialcolumns odbc\_specialcolumns ==================== (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_specialcolumns — Retrieves special columns ### Description ``` odbc_specialcolumns( resource $odbc, int $type, ?string $catalog, string $schema, string $table, int $scope, int $nullable ): resource|false ``` Retrieves either the optimal set of columns that uniquely identifies a row in the table, or columns that are automatically updated when any value in the row is updated by a transaction. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `type` When the type argument is **`SQL_BEST_ROWID`**, **odbc\_specialcolumns()** returns the column or columns that uniquely identify each row in the table. When the type argument is **`SQL_ROWVER`**, **odbc\_specialcolumns()** returns the column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction. `catalog` The catalog ('qualifier' in ODBC 2 parlance). `schema` The schema ('owner' in ODBC 2 parlance). `table` The table. `scope` The scope, which orders the result set. One of **`SQL_SCOPE_CURROW`**, **`SQL_SCOPE_TRANSACTION`** or **`SQL_SCOPE_SESSION`**. `nullable` Determines whether to return special columns that can have a NULL value. One of **`SQL_NO_NULLS`** or **`SQL_NULLABLE`** . ### Return Values Returns an ODBC result identifier or **`false`** on failure. The result set has the following columns: * `SCOPE` * `COLUMN_NAME` * `DATA_TYPE` * `TYPE_NAME` * `COLUMN_SIZE` * `BUFFER_LENGTH` * `DECIMAL_DIGITS` * `PSEUDO_COLUMN` Drivers can report additional columns. The result set is ordered by `SCOPE`. ### See Also * [odbc\_tables()](function.odbc-tables) - Get the list of table names stored in a specific data source php streamWrapper::stream_set_option streamWrapper::stream\_set\_option ================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) streamWrapper::stream\_set\_option — Change stream options ### Description ``` public streamWrapper::stream_set_option(int $option, int $arg1, int $arg2): bool ``` This method is called to set options on the stream. ### Parameters `option` One of: * **`STREAM_OPTION_BLOCKING`** (The method was called in response to [stream\_set\_blocking()](function.stream-set-blocking)) * **`STREAM_OPTION_READ_TIMEOUT`** (The method was called in response to [stream\_set\_timeout()](function.stream-set-timeout)) * **`STREAM_OPTION_WRITE_BUFFER`** (The method was called in response to [stream\_set\_write\_buffer()](function.stream-set-write-buffer)) `arg1` If `option` is * **`STREAM_OPTION_BLOCKING`**: requested blocking mode (1 meaning block 0 not blocking). * **`STREAM_OPTION_READ_TIMEOUT`**: the timeout in seconds. * **`STREAM_OPTION_WRITE_BUFFER`**: buffer mode (**`STREAM_BUFFER_NONE`** or **`STREAM_BUFFER_FULL`**). `arg2` If `option` is * **`STREAM_OPTION_BLOCKING`**: This option is not set. * **`STREAM_OPTION_READ_TIMEOUT`**: the timeout in microseconds. * **`STREAM_OPTION_WRITE_BUFFER`**: the requested buffer size. ### Return Values Returns **`true`** on success or **`false`** on failure. If `option` is not implemented, **`false`** should be returned. ### See Also * [stream\_set\_blocking()](function.stream-set-blocking) - Set blocking/non-blocking mode on a stream * [stream\_set\_timeout()](function.stream-set-timeout) - Set timeout period on a stream * [stream\_set\_write\_buffer()](function.stream-set-write-buffer) - Sets write file buffering on the given stream php Yaf_Request_Abstract::getRequestUri Yaf\_Request\_Abstract::getRequestUri ===================================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::getRequestUri — The getRequestUri purpose ### Description ``` public Yaf_Request_Abstract::getRequestUri(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php None 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()](function.array) An array can be created using the [array()](function.array) language construct. It takes any number of comma-separated `key => value` pairs as arguments. ``` array( key => value, key2 => value2, key3 => value3, ... ) ``` The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. `array(1, 2)` is preferred over `array(1, 2, )`. For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end. > > **Note**: > > > A short array syntax exists which replaces `array()` with `[]`. > > **Example #1 A simple array** ``` <?php $array = array(     "foo" => "bar",     "bar" => "foo", ); // Using the short array syntax $array = [     "foo" => "bar",     "bar" => "foo", ]; ?> ``` The key can either be an int or a string. The value can be of any type. Additionally the following key casts will occur: * Strings containing valid decimal ints, unless the number is preceded by a `+` sign, will be cast to the int type. E.g. the key `"8"` will actually be stored under `8`. On the other hand `"08"` will not be cast, as it isn't a valid decimal integer. * Floats are also cast to ints, which means that the fractional part will be truncated. E.g. the key `8.7` will actually be stored under `8`. * Bools are cast to ints, too, i.e. the key `true` will actually be stored under `1` and the key `false` under `0`. * Null will be cast to the empty string, i.e. the key `null` will actually be stored under `""`. * Arrays and objects *can not* be used as keys. Doing so will result in a warning: `Illegal offset type`. If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. **Example #2 Type Casting and Overwriting example** ``` <?php $array = array(     1    => "a",     "1"  => "b",     1.5  => "c",     true => "d", ); var_dump($array); ?> ``` The above example will output: ``` array(1) { [1]=> string(1) "d" } ``` As all the keys in the above example are cast to `1`, the value will be overwritten on every new element and the last assigned value `"d"` is the only one left over. PHP arrays can contain int and string keys at the same time as PHP does not distinguish between indexed and associative arrays. **Example #3 Mixed int and string keys** ``` <?php $array = array(     "foo" => "bar",     "bar" => "foo",     100   => -100,     -100  => 100, ); var_dump($array); ?> ``` The above example will output: ``` array(4) { ["foo"]=> string(3) "bar" ["bar"]=> string(3) "foo" [100]=> int(-100) [-100]=> int(100) } ``` The key is optional. If it is not specified, PHP will use the increment of the largest previously used int key. **Example #4 Indexed arrays without key** ``` <?php $array = array("foo", "bar", "hello", "world"); var_dump($array); ?> ``` The above example will output: ``` array(4) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(5) "hello" [3]=> string(5) "world" } ``` It is possible to specify the key only for some elements and leave it out for others: **Example #5 Keys not on all elements** ``` <?php $array = array(          "a",          "b",     6 => "c",          "d", ); var_dump($array); ?> ``` The above example will output: ``` array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [6]=> string(1) "c" [7]=> string(1) "d" } ``` As you can see the last value `"d"` was assigned the key `7`. This is because the largest integer key before that was `6`. **Example #6 Complex Type Casting and Overwriting example** This example includes all variations of type casting of keys and overwriting of elements. ``` <?php $array = array(     1    => 'a',     '1'  => 'b', // the value "a" will be overwritten by "b"     1.5  => 'c', // the value "b" will be overwritten by "c"     -1 => 'd',     '01'  => 'e', // as this is not an integer string it will NOT override the key for 1     '1.5' => 'f', // as this is not an integer string it will NOT override the key for 1     true => 'g', // the value "c" will be overwritten by "g"     false => 'h',     '' => 'i',     null => 'j', // the value "i" will be overwritten by "j"     'k', // value "k" is assigned the key 2. This is because the largest integer key before that was 1     2 => 'l', // the value "k" will be overwritten by "l" ); var_dump($array); ?> ``` The above example will output: ``` array(7) { [1]=> string(1) "g" [-1]=> string(1) "d" ["01"]=> string(1) "e" ["1.5"]=> string(1) "f" [0]=> string(1) "h" [""]=> string(1) "j" [2]=> string(1) "l" } ``` #### Accessing array elements with square bracket syntax Array elements can be accessed using the `array[key]` syntax. **Example #7 Accessing array elements** ``` <?php $array = array(     "foo" => "bar",     42    => 24,     "multi" => array(          "dimensional" => array(              "array" => "foo"          )     ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?> ``` The above example will output: ``` string(3) "bar" int(24) string(3) "foo" ``` > > **Note**: > > > Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. `$array[42]` and `$array{42}` would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0. > > **Example #8 Array dereferencing** ``` <?php function getArray() {     return array(1, 2, 3); } $secondElement = getArray()[1]; ?> ``` > > **Note**: > > > Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an **`E_WARNING`**-level error message (**`E_NOTICE`**-level prior to PHP 8.0.0) will be issued, and the result will be **`null`**. > > > > **Note**: > > > Array dereferencing a scalar value which is not a string yields **`null`**. Prior to PHP 7.4.0, that did not issue an error message. As of PHP 7.4.0, this issues **`E_NOTICE`**; as of PHP 8.0.0, this issues **`E_WARNING`**. > > #### Creating/modifying with square bracket syntax An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets (`[]`). ``` $arr[key] = value; $arr[] = value; // key may be an int or string // value may be any value of any type ``` If $arr doesn't exist yet or is set to **`null`** or **`false`**, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and `[]` may actually stand for [string access operator](language.types.string#language.types.string.substr). It is always better to initialize a variable by a direct assignment. > **Note**: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array. > > > **Note**: As of PHP 8.1.0, creating a new array from **`false`** value is deprecated. Creating a new array from **`null`** and undefined values is still allowed. > > To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the [unset()](function.unset) function on it. ``` <?php $arr = array(5 => 1, 12 => 2); $arr[] = 56;    // This is the same as $arr[13] = 56;                 // at this point of the script $arr["x"] = 42; // This adds a new element to                 // the array with key "x"                  unset($arr[5]); // This removes the element from the array unset($arr);    // This deletes the whole array ?> ``` > > **Note**: > > > As mentioned above, if no key is specified, the maximum of the existing int indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no int indices exist yet, the key will be `0` (zero). > > Note that the maximum integer key used for this *need not currently exist in the array*. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates: > > > ``` > <?php > // Create a simple array. > $array = array(1, 2, 3, 4, 5); > print_r($array); > > // Now delete every item, but leave the array itself intact: > foreach ($array as $i => $value) { >     unset($array[$i]); > } > print_r($array); > > // Append an item (note that the new key is 5, instead of 0). > $array[] = 6; > print_r($array); > > // Re-index: > $array = array_values($array); > $array[] = 7; > print_r($array); > ?> > ``` > The above example will output: > > > ``` > > Array > ( > [0] => 1 > [1] => 2 > [2] => 3 > [3] => 4 > [4] => 5 > ) > Array > ( > ) > Array > ( > [5] => 6 > ) > Array > ( > [0] => 6 > [1] => 7 > ) > > ``` > #### Array destructuring Arrays can be destructured using the `[]` (as of PHP 7.1.0) or [list()](function.list) language constructs. These constructs can be used to destructure an array into distinct variables. ``` <?php $source_array = ['foo', 'bar', 'baz']; [$foo, $bar, $baz] = $source_array; echo $foo;    // prints "foo" echo $bar;    // prints "bar" echo $baz;    // prints "baz" ?> ``` Array destructuring can be used in [foreach](control-structures.foreach) to destructure a multi-dimensional array while iterating over it. ``` <?php $source_array = [     [1, 'John'],     [2, 'Jane'], ]; foreach ($source_array as [$id, $name]) {     // logic here with $id and $name } ?> ``` Array elements will be ignored if the variable is not provided. Array destructuring always starts at index `0`. ``` <?php $source_array = ['foo', 'bar', 'baz']; // Assign the element at index 2 to the variable $baz [, , $baz] = $source_array; echo $baz;    // prints "baz" ?> ``` As of PHP 7.1.0, associative arrays can be destructured too. This also allows for easier selection of the right element in numerically indexed arrays as the index can be explicitly specified. ``` <?php $source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3]; // Assign the element at index 'baz' to the variable $three ['baz' => $three] = $source_array; echo $three;    // prints 3 $source_array = ['foo', 'bar', 'baz']; // Assign the element at index 2 to the variable $baz [2 => $baz] = $source_array; echo $baz;    // prints "baz" ?> ``` Array destructuring can be used for easy swapping of two variables. ``` <?php $a = 1; $b = 2; [$b, $a] = [$a, $b]; echo $a;    // prints 2 echo $b;    // prints 1 ?> ``` > > **Note**: > > > The spread operator (`...`) is not supported in assignments. > > > > **Note**: > > > Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an **`E_WARNING`**-level error message (**`E_NOTICE`**-level prior to PHP 8.0.0) will be issued, and the result will be **`null`**. > > ### Useful functions There are quite a few useful functions for working with arrays. See the [array functions](https://www.php.net/manual/en/ref.array.php) section. > > **Note**: > > > The [unset()](function.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.array-values) function. > > > ``` > <?php > $a = array(1 => 'one', 2 => 'two', 3 => 'three'); > unset($a[2]); > /* will produce an array that would have been defined as >    $a = array(1 => 'one', 3 => 'three'); >    and NOT >    $a = array(1 => 'one', 2 =>'three'); > */ > > $b = array_values($a); > // Now $b is array(0 => 'one', 1 =>'three') > ?> > ``` > The [foreach](control-structures.foreach) control structure exists specifically for arrays. It provides an easy way to traverse an array. ### Array do's and don'ts #### Why is `$foo[bar]` wrong? Always use quotes around a string literal array index. For example, `$foo['bar']` is correct, while `$foo[bar]` is not. But why? It is common to encounter this kind of syntax in old scripts: ``` <?php $foo[bar] = 'enemy'; echo $foo[bar]; // etc ?> ``` This is wrong, but it works. The reason is that this code has an undefined constant (`bar`) rather than a string (`'bar'` - notice the quotes). It works because PHP automatically converts a *bare string* (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named **`bar`**, then PHP will substitute in the string `'bar'` and use that. **Warning** The fallback to treat an undefined constant as bare string issues an error of level **`E_NOTICE`**. This has been deprecated as of PHP 7.2.0, and issues an error of level **`E_WARNING`**. As of PHP 8.0.0, it has been removed and throws an [Error](class.error) exception. > > **Note**: This does not mean to *always* quote the key. Do not quote keys which are [constants](language.constants) or [variables](https://www.php.net/manual/en/language.variables.php), as this will prevent PHP from interpreting them. > > > > ``` > <?php > error_reporting(E_ALL); > ini_set('display_errors', true); > ini_set('html_errors', false); > // Simple array: > $array = array(1, 2); > $count = count($array); > for ($i = 0; $i < $count; $i++) { >     echo "\nChecking $i: \n"; >     echo "Bad: " . $array['$i'] . "\n"; >     echo "Good: " . $array[$i] . "\n"; >     echo "Bad: {$array['$i']}\n"; >     echo "Good: {$array[$i]}\n"; > } > ?> > ``` > The above example will output: > > > ``` > > Checking 0: > Notice: Undefined index: $i in /path/to/script.html on line 9 > Bad: > Good: 1 > Notice: Undefined index: $i in /path/to/script.html on line 11 > Bad: > Good: 1 > > Checking 1: > Notice: Undefined index: $i in /path/to/script.html on line 9 > Bad: > Good: 2 > Notice: Undefined index: $i in /path/to/script.html on line 11 > Bad: > Good: 2 > > ``` > More examples to demonstrate this behaviour: ``` <?php // Show all errors error_reporting(E_ALL); $arr = array('fruit' => 'apple', 'veggie' => 'carrot'); // Correct print $arr['fruit'];  // apple print $arr['veggie']; // carrot // Incorrect.  This works but also throws a PHP error of level E_NOTICE because // of an undefined constant named fruit //  // Notice: Use of undefined constant fruit - assumed 'fruit' in... print $arr[fruit];    // apple // This defines a constant to demonstrate what's going on.  The value 'veggie' // is assigned to a constant named fruit. define('fruit', 'veggie'); // Notice the difference now print $arr['fruit'];  // apple print $arr[fruit];    // carrot // The following is okay, as it's inside a string. Constants are not looked for // within strings, so no E_NOTICE occurs here print "Hello $arr[fruit]";      // Hello apple // With one exception: braces surrounding arrays within strings allows constants // to be interpreted print "Hello {$arr[fruit]}";    // Hello carrot print "Hello {$arr['fruit']}";  // Hello apple // This will not work, and will result in a parse error, such as: // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // This of course applies to using superglobals in strings as well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; // Concatenation is another option print "Hello " . $arr['fruit']; // Hello apple ?> ``` When [error\_reporting](https://www.php.net/manual/en/errorfunc.configuration.php#ini.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](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) is set not to show notices. As stated in the [syntax](language.types.array#language.types.array.syntax) section, what's inside the square brackets ('`[`' and '`]`') must be an expression. This means that code like this works: ``` <?php echo $arr[somefunc($bar)]; ?> ``` This is an example of using a function return value as the array index. PHP also knows about constants: ``` <?php $error_descriptions[E_ERROR]   = "A fatal error has occurred"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE]  = "This is just an informal notice"; ?> ``` Note that **`E_ERROR`** is also a valid identifier, just like `bar` in the first example. But the last example is in fact the same as writing: ``` <?php $error_descriptions[1] = "A fatal error has occurred"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; ?> ``` because **`E_ERROR`** equals `1`, etc. ##### So why is it bad then? At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words `empty` and `default` this way, since they are [reserved keywords](https://www.php.net/manual/en/reserved.php). > **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](language.types.string#language.types.string.parsing). > > ### Converting to array For any of the types int, float, string, bool and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, `(array)$scalarValue` is exactly the same as `array($scalarValue)`. If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '\*' prepended to the variable name. These prepended values have `NUL` bytes on either side. Uninitialized [typed properties](language.oop5.properties#language.oop5.properties.typed-properties) are silently discarded. ``` <?php class A {     private $B;     protected $C;     public $D;     function __construct()     {         $this->{1} = null;     } } var_export((array) new A()); ?> ``` The above example will output: ``` array ( '' . "\0" . 'A' . "\0" . 'B' => NULL, '' . "\0" . '*' . "\0" . 'C' => NULL, 'D' => NULL, 1 => NULL, ) ``` These `NUL` can result in some unexpected behaviour: ``` <?php class A {     private $A; // This will become '\0A\0A' } class B extends A {     private $A; // This will become '\0B\0A'     public $AA; // This will become 'AA' } var_dump((array) new B()); ?> ``` The above example will output: ``` array(3) { ["BA"]=> NULL ["AA"]=> NULL ["AA"]=> NULL } ``` The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. Converting **`null`** to an array results in an empty array. ### Comparing It is possible to compare arrays with the [array\_diff()](function.array-diff) function and with [array operators](language.operators.array). ### Array unpacking An array prefixed by `...` will be expanded in place during the definition of the array. Only arrays and objects which implement [Traversable](class.traversable) can be expanded. Array unpacking with `...` is available as of PHP 7.4.0. It's possible to expand multiple times, and add normal elements before or after the `...` operator: **Example #9 Simple array unpacking** ``` <?php // Using short array syntax. // Also, works with array() syntax. $arr1 = [1, 2, 3]; $arr2 = [...$arr1]; //[1, 2, 3] $arr3 = [0, ...$arr1]; //[0, 1, 2, 3] $arr4 = [...$arr1, ...$arr2, 111]; //[1, 2, 3, 1, 2, 3, 111] $arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3] function getArr() {   return ['a', 'b']; } $arr6 = [...getArr(), 'c' => 'd']; //['a', 'b', 'c' => 'd'] ?> ``` Unpacking an array with the `...` operator follows the semantics of the [array\_merge()](function.array-merge) function. That is, later string keys overwrite earlier ones and integer keys are renumbered: **Example #10 Array unpacking with duplicate key** ``` <?php // string key $arr1 = ["a" => 1]; $arr2 = ["a" => 2]; $arr3 = ["a" => 0, ...$arr1, ...$arr2]; var_dump($arr3); // ["a" => 2] // integer key $arr4 = [1, 2, 3]; $arr5 = [4, 5, 6]; $arr6 = [...$arr4, ...$arr5]; var_dump($arr6); // [1, 2, 3, 4, 5, 6] // Which is [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6] // where the original integer keys have not been retained. ?> ``` > > **Note**: > > > Keys that are neither integers nor strings throw a [TypeError](class.typeerror). Such keys can only be generated by a [Traversable](class.traversable) object. > > > > **Note**: > > > Prior to PHP 8.1, unpacking an array which has a string key is not supported: > > > ``` > <?php > > $arr1 = [1, 2, 3]; > $arr2 = ['a' => 4]; > $arr3 = [...$arr1, ...$arr2]; > // Fatal error: Uncaught Error: Cannot unpack array with string keys in example.php:5 > > $arr4 = [1, 2, 3]; > $arr5 = [4, 5]; > $arr6 = [...$arr4, ...$arr5]; // works. [1, 2, 3, 4, 5] > ?> > ``` > ### Examples The array type in PHP is very versatile. Here are some examples: ``` <?php // This: $a = array( 'color' => 'red',             'taste' => 'sweet',             'shape' => 'round',             'name'  => 'apple',             4        // key will be 0           ); $b = array('a', 'b', 'c'); // . . .is completely equivalent with this: $a = array(); $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name']  = 'apple'; $a[]        = 4;        // key will be 0 $b = array(); $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // After the above code is executed, $a will be the array // array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',  // 'name' => 'apple', 0 => 4), and $b will be the array  // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c'). ?> ``` **Example #11 Using array()** ``` <?php // Array as (property-)map $map = array( 'version'    => 4,               'OS'         => 'Linux',               'lang'       => 'english',               'short_tags' => true             );              // strictly numerical keys $array = array( 7,                 8,                 0,                 156,                 -10               ); // this is the same as array(0 => 7, 1 => 8, ...) $switching = array(         10, // key = 0                     5    =>  6,                     3    =>  7,                      'a'  =>  4,                             11, // key = 6 (maximum of integer-indices was 5)                     '8'  =>  2, // key = 8 (integer!)                     '02' => 77, // key = '02'                     0    => 12  // the value 10 will be overwritten by 12                   );                    // empty array $empty = array();          ?> ``` **Example #12 Collection** ``` <?php $colors = array('red', 'blue', 'green', 'yellow'); foreach ($colors as $color) {     echo "Do you like $color?\n"; } ?> ``` The above example will output: ``` Do you like red? Do you like blue? Do you like green? Do you like yellow? ``` Changing the values of the array directly is possible by passing them by reference. **Example #13 Changing element in the loop** ``` <?php foreach ($colors as &$color) {     $color = strtoupper($color); } unset($color); /* ensure that following writes to $color will not modify the last array element */ print_r($colors); ?> ``` The above example will output: ``` Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW ) ``` This example creates a one-based array. **Example #14 One-based index** ``` <?php $firstquarter  = array(1 => 'January', 'February', 'March'); print_r($firstquarter); ?> ``` The above example will output: ``` Array ( [1] => 'January' [2] => 'February' [3] => 'March' ) ``` **Example #15 Filling an array** ``` <?php // fill an array with all items from a directory $handle = opendir('.'); while (false !== ($file = readdir($handle))) {     $files[] = $file; } closedir($handle);  ?> ``` Arrays are ordered. The order can be changed using various sorting functions. See the [array functions](https://www.php.net/manual/en/ref.array.php) section for more information. The [count()](function.count) function can be used to count the number of items in an array. **Example #16 Sorting an array** ``` <?php sort($files); print_r($files); ?> ``` Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays. **Example #17 Recursive and multi-dimensional arrays** ``` <?php $fruits = array ( "fruits"  => array ( "a" => "orange",                                        "b" => "banana",                                        "c" => "apple"                                      ),                   "numbers" => array ( 1,                                        2,                                        3,                                        4,                                        5,                                        6                                      ),                   "holes"   => array (      "first",                                        5 => "second",                                             "third"                                      )                 ); // Some examples to address values in the array above  echo $fruits["holes"][5];    // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]);  // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good";  ?> ``` Array assignment always involves value copying. Use the [reference operator](language.operators) to copy an array by reference. ``` <?php $arr1 = array(2, 3); $arr2 = $arr1; $arr2[] = 4; // $arr2 is changed,              // $arr1 is still array(2, 3)               $arr3 = &$arr1; $arr3[] = 4; // now $arr1 and $arr3 are the same ?> ```
programming_docs
php ArrayIterator::setFlags ArrayIterator::setFlags ======================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) ArrayIterator::setFlags — Set behaviour flags ### Description ``` public ArrayIterator::setFlags(int $flags): void ``` Set the flags that change the behavior of the ArrayIterator. ### Parameters `flags` The new ArrayIterator behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. The available behavior flags are listed below. The actual meanings of these flags are described in the [predefined constants](class.arrayiterator#arrayiterator.constants). **ArrayIterator behavior flags**| value | constant | | --- | --- | | 1 | [ArrayIterator::STD\_PROP\_LIST](class.arrayiterator#arrayiterator.constants.std-prop-list) | | 2 | [ArrayIterator::ARRAY\_AS\_PROPS](class.arrayiterator#arrayiterator.constants.array-as-props) | ### Return Values No value is returned. ### See Also * [ArrayIterator::getFlags()](arrayiterator.getflags) - Get behavior flags php finfo_close finfo\_close ============ (PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0) finfo\_close — Close finfo instance ### Description ``` finfo_close(finfo $finfo): bool ``` This function closes the instance opened by [finfo\_open()](function.finfo-open). ### Parameters `finfo` An [finfo](class.finfo) instance, returned by [finfo\_open()](function.finfo-open). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `finfo` parameter expects an [finfo](class.finfo) instance now; previously, a [resource](language.types.resource) was expected. | php ImagickDraw::setVectorGraphics ImagickDraw::setVectorGraphics ============================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setVectorGraphics — Sets the vector graphics ### Description ``` public ImagickDraw::setVectorGraphics(string $xml): bool ``` **Warning**This function is currently not documented; only its argument list is available. Sets the vector graphics associated with the specified ImagickDraw object. Use this method with [ImagickDraw::getVectorGraphics()](imagickdraw.getvectorgraphics) as a method to persist the vector graphics state. ### Parameters `xml` xml containing the vector graphics ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **ImagickDraw::setVectorGraphics()** example** ``` <?php function setVectorGraphics() {     //Setup a draw object with some drawing in it.     $draw = new \ImagickDraw();     $draw->setFillColor("red");     $draw->circle(20, 20, 50, 50);     $draw->setFillColor("blue");     $draw->circle(50, 70, 50, 50);     $draw->rectangle(50, 120, 80, 150);     //Get the drawing as a string     $SVG = $draw->getVectorGraphics();          //$svg is a string, and could be saved anywhere a string can be saved     //Use the saved drawing to generate a new draw object     $draw2 = new \ImagickDraw();     //Apparently the SVG text is missing the root element.      $draw2->setVectorGraphics("<root>".$SVG."</root>");     $imagick = new \Imagick();     $imagick->newImage(200, 200, 'white');     $imagick->setImageFormat("png");     $imagick->drawImage($draw2);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php Ds\Map::filter Ds\Map::filter ============== (PECL ds >= 1.0.0) Ds\Map::filter — Creates a new map using a [callable](language.types.callable) to determine which pairs to include ### Description ``` public Ds\Map::filter(callable $callback = ?): Ds\Map ``` Creates a new map using a [callable](language.types.callable) to determine which pairs to include. ### Parameters `callback` ``` callback(mixed $key, mixed $value): bool ``` Optional [callable](language.types.callable) which returns **`true`** if the pair should be included, **`false`** otherwise. If a callback is not provided, only values which are **`true`** (see [converting to boolean](language.types.boolean#language.types.boolean.casting)) will be included. ### Return Values A new map containing all the pairs for which either the `callback` returned **`true`**, or all values that convert to **`true`** if a `callback` was not provided. ### Examples **Example #1 **Ds\Map::filter()** example using callback function** ``` <?php $map = new \Ds\Map(["a", "b", "c", "d", "e"]); var_dump($map->filter(function($key, $value) {     return $key % 2 == 0; })); ?> ``` The above example will output something similar to: ``` object(Ds\Map)#3 (3) { [0]=> object(Ds\Pair)#2 (2) { ["key"]=> int(0) ["value"]=> string(1) "a" } [1]=> object(Ds\Pair)#4 (2) { ["key"]=> int(2) ["value"]=> string(1) "c" } [2]=> object(Ds\Pair)#5 (2) { ["key"]=> int(4) ["value"]=> string(1) "e" } } ``` **Example #2 **Ds\Map::filter()** example without a callback function** ``` <?php $map = new \Ds\Map(["a" => 0, "b" => 1, "c" => true, "d" => false]); var_dump($map->filter()); ?> ``` The above example will output something similar to: ``` object(Ds\Map)#2 (3) { [0]=> int(1) [1]=> string(1) "a" [2]=> bool(true) } ``` php RecursiveDirectoryIterator::hasChildren RecursiveDirectoryIterator::hasChildren ======================================= (PHP 5, PHP 7, PHP 8) RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..' ### Description ``` public RecursiveDirectoryIterator::hasChildren(bool $allowLinks = false): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `allowLinks` ### Return Values Returns whether the current entry is a directory, but not '.' or '..' php Imagick::sparseColorImage Imagick::sparseColorImage ========================= (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::sparseColorImage — Interpolates colors ### Description ``` public Imagick::sparseColorImage(int $SPARSE_METHOD, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` Given the arguments array containing numeric values this method interpolates the colors found at those coordinates across the whole image using `sparse_method`. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer. ### Parameters `SPARSE_METHOD` Refer to this list of [sparse method constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.sparsecolormethod) `arguments` An array containing the coordinates. The array is in format `array(1,1, 2,45)` `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) using bitwise operators. Defaults to **`Imagick::CHANNEL_DEFAULT`**. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 SPARSECOLORMETHOD\_BARYCENTRIC **Imagick::sparseColorImage()**** ``` <?php     function renderImageBarycentric2() {         $points = [             [0.30, 0.10, 'red'],             [0.10, 0.80, 'blue'],             [0.70, 0.60, 'lime'],             [0.80, 0.20, 'yellow'],         ];         $imagick = createGradientImage(             400, 400,             $points,             \Imagick::SPARSECOLORMETHOD_BARYCENTRIC         );         header("Content-Type: image/png");         echo $imagick->getImageBlob();     } ?> ``` **Example #2 SPARSECOLORMETHOD\_BILINEAR **Imagick::sparseColorImage()**** ``` <?php     function renderImageBilinear() {         $points = [[0.30, 0.10, 'red'], [0.10, 0.80, 'blue'], [0.70, 0.60, 'lime'], [0.80, 0.20, 'yellow'],];         $imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_BILINEAR);         header("Content-Type: image/png");         echo $imagick->getImageBlob();     } ?> ``` **Example #3 SPARSECOLORMETHOD\_SPEPARDS **Imagick::sparseColorImage()**** ``` <?php     function renderImageShepards() {         $points = [             [0.30, 0.10, 'red'],             [0.10, 0.80, 'blue'],             [0.70, 0.60, 'lime'],             [0.80, 0.20, 'yellow'],         ];         $imagick = createGradientImage(600, 600, $points, \Imagick::SPARSECOLORMETHOD_SPEPARDS);         header("Content-Type: image/png");         echo $imagick->getImageBlob();     } ?> ``` **Example #4 SPARSECOLORMETHOD\_VORONOI **Imagick::sparseColorImage()**** ``` <?php     function renderImageVoronoi() {         $points = [             [0.30, 0.10, 'red'],             [0.10, 0.80, 'blue'],             [0.70, 0.60, 'lime'],             [0.80, 0.20, 'yellow'],         ];         $imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_VORONOI);         header("Content-Type: image/png");         echo $imagick->getImageBlob();     } ?> ``` **Example #5 SPARSECOLORMETHOD\_BARYCENTRIC **Imagick::sparseColorImage()**** ``` <?php     function renderImageBarycentric() {         $points = [             [0, 0, 'skyblue'],             [-1, 1, 'skyblue'],             [1, 1, 'black'],         ];         $imagick = createGradientImage(600, 200, $points, \Imagick::SPARSECOLORMETHOD_BARYCENTRIC);         header("Content-Type: image/png");         echo $imagick->getImageBlob();     } ?> ``` **Example #6 createGradientImage is used by other examples. **Imagick::sparseColorImage()**** ``` <?php function createGradientImage($width, $height, $colorPoints, $sparseMethod, $absolute = false) {     $imagick = new \Imagick();     $imagick->newImage($width, $height, "white");     $imagick->setImageFormat("png");     $barycentricPoints = array();     foreach ($colorPoints as $colorPoint) {         if ($absolute == true) {             $barycentricPoints[] = $colorPoint[0];             $barycentricPoints[] = $colorPoint[1];         }         else {             $barycentricPoints[] = $colorPoint[0] * $width;             $barycentricPoints[] = $colorPoint[1] * $height;         }         if (is_string($colorPoint[2])) {             $imagickPixel = new \ImagickPixel($colorPoint[2]);         }         else if ($colorPoint[2] instanceof \ImagickPixel) {             $imagickPixel = $colorPoint[2];         }         else{             $errorMessage = sprintf(                 "Value %s is neither a string nor an ImagickPixel class. Cannot use as a color.",                 $colorPoint[2]             );             throw new \InvalidArgumentException(                 $errorMessage             );         }         $red = $imagickPixel->getColorValue(\Imagick::COLOR_RED);         $green = $imagickPixel->getColorValue(\Imagick::COLOR_GREEN);         $blue = $imagickPixel->getColorValue(\Imagick::COLOR_BLUE);         $alpha = $imagickPixel->getColorValue(\Imagick::COLOR_ALPHA);         $barycentricPoints[] = $red;         $barycentricPoints[] = $green;         $barycentricPoints[] = $blue;         $barycentricPoints[] = $alpha;     }     $imagick->sparseColorImage($sparseMethod, $barycentricPoints);     return $imagick; } ?> ``` php PharFileInfo::delMetadata PharFileInfo::delMetadata ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0) PharFileInfo::delMetadata — Deletes the metadata of the entry ### Description ``` public PharFileInfo::delMetadata(): bool ``` Deletes the metadata of the entry, if any. ### Parameters No parameters. ### Return Values Returns **`true`** if successful, **`false`** if the entry had no metadata. As with all functionality that modifies the contents of a phar, the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable must be off in order to succeed if the file is within a [Phar](class.phar) archive. Files within [PharData](class.phardata) archives do not have this restriction. ### Errors/Exceptions Throws [PharException](class.pharexception) if errors occurred while flushing changes to disk, and [BadMethodCallException](class.badmethodcallexception) if write access is disabled. ### Examples **Example #1 A **PharFileInfo::delMetaData()** example** ``` <?php try {     $a = new Phar('myphar.phar');     $a['hi'] = 'hi';     var_dump($a['hi']->delMetadata());     $a['hi']->setMetadata('there');     var_dump($a['hi']->delMetadata());     var_dump($a['hi']->delMetadata()); } catch (Exception $e) {     // handle errors } ?> ``` The above example will output: ``` bool(false) bool(true) bool(false) ``` ### See Also * [PharFileInfo::setMetadata()](pharfileinfo.setmetadata) - Sets file-specific meta-data saved with a file * [PharFileInfo::hasMetadata()](pharfileinfo.hasmetadata) - Returns the metadata of the entry * [PharFileInfo::getMetadata()](pharfileinfo.getmetadata) - Returns file-specific meta-data saved with a file * [Phar::setMetadata()](phar.setmetadata) - Sets phar archive meta-data * [Phar::hasMetadata()](phar.hasmetadata) - Returns whether phar has global meta-data * [Phar::getMetadata()](phar.getmetadata) - Returns phar archive meta-data php EvStat::createStopped EvStat::createStopped ===================== (PECL ev >= 0.2.0) EvStat::createStopped — Create a stopped EvStat watcher object ### Description ``` final public static EvStat::createStopped( string $path , float $interval , callable $callback , mixed $data = null , int $priority = 0 ): void ``` Creates EvStat watcher object, but doesn't start it automatically(unlike [EvStat::\_\_construct()](evstat.construct) ). ### Parameters `path` The path to wait for status changes on. `interval` Hint on how quickly a change is expected to be detected and should normally be specified as **`0.0`** to let *libev* choose a suitable value. `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### Return Values Returns a stopped EvStat watcher object on success. ### See Also * [EvStat::\_\_construct()](evstat.construct) - Constructs EvStat watcher object * [EvWatcher::start()](evwatcher.start) - Starts the watcher php IntlCalendar::getKeywordValuesForLocale IntlCalendar::getKeywordValuesForLocale ======================================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values ### Description Object-oriented style ``` public static IntlCalendar::getKeywordValuesForLocale(string $keyword, string $locale, bool $onlyCommon): IntlIterator|false ``` Procedural style ``` intlcal_get_keyword_values_for_locale(string $keyword, string $locale, bool $onlyCommon): IntlIterator|false ``` For a given locale key, get the set of values for that key that would result in a different behavior. For now, only the `'calendar'` keyword is supported. This function requires ICU 4.2 or later. ### Parameters `keyword` The locale keyword for which relevant values are to be queried. Only `'calendar'` is supported. `locale` The locale onto which the keyword/value pair are to be appended. `onlyCommon` Whether to show only the values commonly used for the specified locale. ### Return Values An iterator that yields strings with the locale keyword values or **`false`** on failure. ### Examples **Example #1 **IntlCalendar::getKeyworkValuesForLocale()**** ``` <?php print_r(         iterator_to_array(                 IntlCalendar::getKeywordValuesForLocale(                         'calendar', 'fa_IR', true))); print_r(         iterator_to_array(                 IntlCalendar::getKeywordValuesForLocale(                         'calendar', 'fa_IR', false))); ``` The above example will output: ``` Array ( [0] => persian [1] => gregorian [2] => islamic [3] => islamic-civil ) Array ( [0] => persian [1] => gregorian [2] => islamic [3] => islamic-civil [4] => japanese [5] => buddhist [6] => roc [7] => hebrew [8] => chinese [9] => indian [10] => coptic [11] => ethiopic [12] => ethiopic-amete-alem ) ``` php UConverter::reasonText UConverter::reasonText ====================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) UConverter::reasonText — Get string representation of the callback reason ### Description ``` public static UConverter::reasonText(int $reason): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `reason` ### Return Values php openssl_get_privatekey openssl\_get\_privatekey ======================== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) openssl\_get\_privatekey — Alias of [openssl\_pkey\_get\_private()](function.openssl-pkey-get-private) ### Description This function is an alias of: [openssl\_pkey\_get\_private()](function.openssl-pkey-get-private). php mysqli::commit mysqli::commit ============== mysqli\_commit ============== (PHP 5, PHP 7, PHP 8) mysqli::commit -- mysqli\_commit — Commits the current transaction ### Description Object-oriented style ``` public mysqli::commit(int $flags = 0, ?string $name = null): bool ``` Procedural style ``` mysqli_commit(mysqli $mysql, int $flags = 0, ?string $name = null): bool ``` Commits the current transaction for the database connection. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `flags` A bitmask of **`MYSQLI_TRANS_COR_*`** constants. `name` If provided then `COMMIT/*name*/` is executed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `name` is now nullable. | ### Examples See the [[mysqli::begin\_transaction()](mysqli.begin-transaction) example](mysqli.begin-transaction#mysqli.begin-transaction.example.basic). ### Notes > > **Note**: > > > This function does not work with non transactional table types (like MyISAM or ISAM). > > ### See Also * [mysqli\_autocommit()](mysqli.autocommit) - Turns on or off auto-committing database modifications * [mysqli\_begin\_transaction()](mysqli.begin-transaction) - Starts a transaction * [mysqli\_rollback()](mysqli.rollback) - Rolls back current transaction * [mysqli\_savepoint()](mysqli.savepoint) - Set a named transaction savepoint php GmagickDraw::settextdecoration GmagickDraw::settextdecoration ============================== (PECL gmagick >= Unknown) GmagickDraw::settextdecoration — Specifies a decoration ### Description ``` public GmagickDraw::settextdecoration(int $decoration): GmagickDraw ``` Specifies a decoration to be applied when annotating with text. ### Parameters `int` Text decoration. One of NoDecoration, UnderlineDecoration, OverlineDecoration, or LineThroughDecoration ### Return Values The [GmagickDraw](class.gmagickdraw) object. php mysqli::change_user mysqli::change\_user ==================== mysqli\_change\_user ==================== (PHP 5, PHP 7, PHP 8) mysqli::change\_user -- mysqli\_change\_user — Changes the user of the specified database connection ### Description Object-oriented style ``` public mysqli::change_user(string $username, string $password, ?string $database): bool ``` Procedural style ``` mysqli_change_user( mysqli $mysql, string $username, string $password, ?string $database ): bool ``` Changes the user of the specified database connection and sets the current database. In order to successfully change users a valid `username` and `password` parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `username` The MySQL user name. `password` The MySQL password. `database` The database to change to. If desired, the **`null`** value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the [mysqli\_select\_db()](mysqli.select-db) function. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **mysqli::change\_user()** example** Object-oriented style ``` <?php /* connect database test */ $mysqli = new mysqli("localhost", "my_user", "my_password", "test"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* Set Variable a */ $mysqli->query("SET @a:=1"); /* reset all and select a new database */ $mysqli->change_user("my_user", "my_password", "world"); if ($result = $mysqli->query("SELECT DATABASE()")) {     $row = $result->fetch_row();     printf("Default database: %s\n", $row[0]);     $result->close(); } if ($result = $mysqli->query("SELECT @a")) {     $row = $result->fetch_row();     if ($row[0] === NULL) {         printf("Value of variable a is NULL\n");     }     $result->close(); } /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php /* connect database test */ $link = mysqli_connect("localhost", "my_user", "my_password", "test"); /* check connection */ if (!$link) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* Set Variable a */ mysqli_query($link, "SET @a:=1"); /* reset all and select a new database */ mysqli_change_user($link, "my_user", "my_password", "world"); if ($result = mysqli_query($link, "SELECT DATABASE()")) {     $row = mysqli_fetch_row($result);     printf("Default database: %s\n", $row[0]);     mysqli_free_result($result); } if ($result = mysqli_query($link, "SELECT @a")) {     $row = mysqli_fetch_row($result);     if ($row[0] === NULL) {         printf("Value of variable a is NULL\n");     }     mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Default database: world Value of variable a is NULL ``` ### Notes > > **Note**: > > > Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables. > > ### See Also * [mysqli\_connect()](function.mysqli-connect) - Alias of mysqli::\_\_construct * [mysqli\_select\_db()](mysqli.select-db) - Selects the default database for database queries
programming_docs
php ibase_free_result ibase\_free\_result =================== (PHP 5, PHP 7 < 7.4.0) ibase\_free\_result — Free a result set ### Description ``` ibase_free_result(resource $result_identifier): bool ``` Frees a result set. ### Parameters `result_identifier` A result set created by [ibase\_query()](function.ibase-query) or [ibase\_execute()](function.ibase-execute). ### Return Values Returns **`true`** on success or **`false`** on failure. php The Parle\Token class The Parle\Token class ===================== Introduction ------------ (PECL parle >= 0.5.2) This class represents a token. Lexer returns instances of this class. Class synopsis -------------- class **Parle\Token** { /\* Constants \*/ const int [EOI](class.parle-token#parle-token.constants.eoi) = 0; const int [UNKNOWN](class.parle-token#parle-token.constants.unknown) = -1; const int [SKIP](class.parle-token#parle-token.constants.skip) = -2; /\* Properties \*/ public int [$id](class.parle-token#parle-token.props.id); public string [$value](class.parle-token#parle-token.props.value); /\* Methods \*/ } Properties ---------- id Token id. value Token value. Predefined Constants -------------------- **`Parle\Token::EOI`** End of input token id. **`Parle\Token::UNKNOWN`** Unknown token id. **`Parle\Token::SKIP`** Skip token id. php mb_list_encodings mb\_list\_encodings =================== (PHP 5, PHP 7, PHP 8) mb\_list\_encodings — Returns an array of all supported encodings ### Description ``` mb_list_encodings(): array ``` Returns an array containing all supported encodings. ### Parameters This function has no parameters. ### Return Values Returns a numerically indexed array. ### Errors/Exceptions This function does not emit any errors. ### Examples **Example #1 **mb\_list\_encodings()** example** ``` <?php print_r(mb_list_encodings()); ?> ``` The above example will output something similar to: ``` Array ( [0] => pass [1] => auto [2] => wchar [3] => byte2be [4] => byte2le [5] => byte4be [6] => byte4le [7] => BASE64 [8] => UUENCODE [9] => HTML-ENTITIES [10] => Quoted-Printable [11] => 7bit [12] => 8bit [13] => UCS-4 [14] => UCS-4BE [15] => UCS-4LE [16] => UCS-2 [17] => UCS-2BE [18] => UCS-2LE [19] => UTF-32 [20] => UTF-32BE [21] => UTF-32LE [22] => UTF-16 [23] => UTF-16BE [24] => UTF-16LE [25] => UTF-8 [26] => UTF-7 [27] => UTF7-IMAP [28] => ASCII [29] => EUC-JP [30] => SJIS [31] => eucJP-win [32] => SJIS-win [33] => JIS [34] => ISO-2022-JP [35] => Windows-1252 [36] => ISO-8859-1 [37] => ISO-8859-2 [38] => ISO-8859-3 [39] => ISO-8859-4 [40] => ISO-8859-5 [41] => ISO-8859-6 [42] => ISO-8859-7 [43] => ISO-8859-8 [44] => ISO-8859-9 [45] => ISO-8859-10 [46] => ISO-8859-13 [47] => ISO-8859-14 [48] => ISO-8859-15 [49] => EUC-CN [50] => CP936 [51] => HZ [52] => EUC-TW [53] => BIG-5 [54] => EUC-KR [55] => UHC [56] => ISO-2022-KR [57] => Windows-1251 [58] => CP866 [59] => KOI8-R ) ``` ### See Also * [mb\_encoding\_aliases()](function.mb-encoding-aliases) - Get aliases of a known encoding type php Ds\Set::last Ds\Set::last ============ (PECL ds >= 1.0.0) Ds\Set::last — Returns the last value in the set ### Description ``` public Ds\Set::last(): mixed ``` Returns the last value in the set. ### Parameters This function has no parameters. ### Return Values The last value in the set. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Set::last()** example** ``` <?php $set = new \Ds\Set([1, 2, 3]); var_dump($set->last()); ?> ``` The above example will output something similar to: ``` int(3) ``` php Gmagick::quantizeimage Gmagick::quantizeimage ====================== (PECL gmagick >= Unknown) Gmagick::quantizeimage — Analyzes the colors within a reference image ### Description ``` public Gmagick::quantizeimage( int $numColors, int $colorspace, int $treeDepth, bool $dither, bool $measureError ): Gmagick ``` Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time. ### Parameters `numColors` The number of colors. `colorspace` Perform color reduction in this colorspace, typically RGBColorspace. `treeDepth` Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number\_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number\_colors) is required. To expand the color tree completely, use a value of 8. `dither` A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve. `measureError` A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value. ### Return Values The Gmagick object on success ### Errors/Exceptions Throws an **GmagickException** on error. php mysqli_warning::__construct mysqli\_warning::\_\_construct ============================== (PHP 5, PHP 7, PHP 8) mysqli\_warning::\_\_construct — Private constructor to disallow direct instantiation ### Description private **mysqli\_warning::\_\_construct**() ### Parameters This function has no parameters. php The SolrDocumentField class The SolrDocumentField class =========================== Introduction ------------ (PECL solr >= 0.9.2) This represents a field in a Solr document. All its properties are read-only. Class synopsis -------------- final class **SolrDocumentField** { /\* Properties \*/ public readonly string [$name](class.solrdocumentfield#solrdocumentfield.props.name); public readonly float [$boost](class.solrdocumentfield#solrdocumentfield.props.boost); public readonly array [$values](class.solrdocumentfield#solrdocumentfield.props.values); /\* Methods \*/ public [\_\_construct](solrdocumentfield.construct)() public [\_\_destruct](solrdocumentfield.destruct)() } Properties ---------- name The name of the field. boost The boost value for the field values An array of values for this field Table of Contents ----------------- * [SolrDocumentField::\_\_construct](solrdocumentfield.construct) — Constructor * [SolrDocumentField::\_\_destruct](solrdocumentfield.destruct) — Destructor php dba_optimize dba\_optimize ============= (PHP 4, PHP 5, PHP 7, PHP 8) dba\_optimize — Optimize database ### Description ``` dba_optimize(resource $dba): bool ``` **dba\_optimize()** optimizes the underlying database. ### Parameters `dba` The database handler, returned by [dba\_open()](function.dba-open) or [dba\_popen()](function.dba-popen). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [dba\_sync()](function.dba-sync) - Synchronize database php Yaf_Request_Abstract::isCli Yaf\_Request\_Abstract::isCli ============================= (Yaf >=1.0.0) Yaf\_Request\_Abstract::isCli — Determine if request is CLI request ### Description ``` public Yaf_Request_Abstract::isCli(): bool ``` ### Parameters This function has no parameters. ### Return Values bolean ### See Also * [Yaf\_Request\_Abstract::isHead()](yaf-request-abstract.ishead) - Determine if request is HEAD request * [Yaf\_Request\_Abstract::isGet()](yaf-request-abstract.isget) - Determine if request is GET request * [Yaf\_Request\_Abstract::isPost()](yaf-request-abstract.ispost) - Determine if request is POST request * [Yaf\_Request\_Abstract::isPut()](yaf-request-abstract.isput) - Determine if request is PUT request * [Yaf\_Request\_Abstract::isOptions()](yaf-request-abstract.isoptions) - Determine if request is OPTIONS request * [Yaf\_Request\_Abstract::isXmlHTTPRequest()](yaf-request-abstract.isxmlhttprequest) - Determine if request is AJAX request php Imagick::identifyImage Imagick::identifyImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::identifyImage — Identifies an image and fetches attributes ### Description ``` public Imagick::identifyImage(bool $appendRawOutput = false): array ``` Identifies an image and returns the attributes. Attributes include the image width, height, size, and others. ### Parameters `appendRawOutput` If **`true`** then the raw output is appended to the array. ### Return Values Identifies an image and returns the attributes. Attributes include the image width, height, size, and others. ### Errors/Exceptions Throws ImagickException on error. **Example #1 Example Result Format** ``` Array ( [imageName] => /some/path/image.jpg [format] => JPEG (Joint Photographic Experts Group JFIF format) [geometry] => Array ( [width] => 90 [height] => 90 ) [type] => TrueColor [colorSpace] => RGB [resolution] => Array ( [x] => 300 [y] => 300 ) [units] => PixelsPerInch [fileSize] => 1.88672kb [compression] => JPEG [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da ) ``` php None Variable variables ------------------ Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as: ``` <?php $a = 'hello'; ?> ``` A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, *hello*, can be used as the name of a variable by using two dollar signs. i.e. ``` <?php $$a = 'world'; ?> ``` At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement: ``` <?php echo "$a ${$a}"; ?> ``` produces the exact same output as: ``` <?php echo "$a $hello"; ?> ``` i.e. they both produce: hello world. In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second. Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access. Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of multiple parts, or when the property name contains characters that are not otherwise valid (e.g. from [json\_decode()](function.json-decode) or [SimpleXML](https://www.php.net/manual/en/book.simplexml.php)). **Example #1 Variable property example** ``` <?php class foo {     var $bar = 'I am bar.';     var $arr = array('I am A.', 'I am B.', 'I am C.');     var $r   = 'I am r.'; } $foo = new foo(); $bar = 'bar'; $baz = array('foo', 'bar', 'baz', 'quux'); echo $foo->$bar . "\n"; echo $foo->{$baz[1]} . "\n"; $start = 'b'; $end   = 'ar'; echo $foo->{$start . $end} . "\n"; $arr = 'arr'; echo $foo->{$arr[1]} . "\n"; ?> ``` The above example will output: I am bar. I am bar. I am bar. I am r. **Warning** Please note that variable variables cannot be used with PHP's [Superglobal arrays](language.variables.superglobals) within functions or class methods. The variable `$this` is also a special variable that cannot be referenced dynamically. php SolrObject::offsetExists SolrObject::offsetExists ======================== (PECL solr >= 0.9.2) SolrObject::offsetExists — Checks if the property exists ### Description ``` public SolrObject::offsetExists(string $property_name): bool ``` Checks if the property exists. This is used when the object is treated as an array. ### Parameters `property_name` The name of the property. ### Return Values Returns **`true`** on success or **`false`** on failure. php IntlChar::ord IntlChar::ord ============= (PHP 7, PHP 8) IntlChar::ord — Return Unicode code point value of character ### Description ``` public static IntlChar::ord(int|string $character): ?int ``` Returns the Unicode code point value of the given character. This function complements [IntlChar::chr()](intlchar.chr). ### Parameters `character` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns the Unicode code point value as an integer. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::ord("A")); var_dump(IntlChar::ord(" ")); var_dump(IntlChar::ord("\u{2603}")); ?> ``` The above example will output: ``` int(65) int(32) int(9731) ``` ### See Also * [IntlChar::chr()](intlchar.chr) - Return Unicode character by code point value * [mb\_ord()](function.mb-ord) - Get Unicode code point of character * [ord()](function.ord) - Convert the first byte of a string to a value between 0 and 255 php ReflectionUnionType::getTypes ReflectionUnionType::getTypes ============================= (PHP 8) ReflectionUnionType::getTypes — Returns the types included in the union type ### Description ``` public ReflectionUnionType::getTypes(): array ``` Returns the reflections of types included in the union type. ### Parameters This function has no parameters. ### Return Values An array of [ReflectionType](class.reflectiontype) objects. ### Examples **Example #1 **ReflectionUnionType::getTypes()** example** ``` <?php function someFunction(int|float $number) {} $reflectionFunc = new ReflectionFunction('someFunction'); $reflectionParam = $reflectionFunc->getParameters()[0]; var_dump($reflectionParam->getType()->getTypes()); ``` The above example will output something similar to: ``` array(2) { [0] => class ReflectionNamedType#4(0) { } [1] => class ReflectionNamedType#5(0) { } } ``` ### See Also * [ReflectionType::allowsNull()](reflectiontype.allowsnull) - Checks if null is allowed * [ReflectionParameter::getType()](reflectionparameter.gettype) - Gets a parameter's type php ReflectionFunctionAbstract::getStaticVariables ReflectionFunctionAbstract::getStaticVariables ============================================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ReflectionFunctionAbstract::getStaticVariables — Gets static variables ### Description ``` public ReflectionFunctionAbstract::getStaticVariables(): array ``` Get the static variables. ### Parameters This function has no parameters. ### Return Values An array of static variables. ### See Also * [ReflectionFunctionAbstract::getParameters()](reflectionfunctionabstract.getparameters) - Gets parameters php IntlCalendar::getMinimalDaysInFirstWeek IntlCalendar::getMinimalDaysInFirstWeek ======================================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have ### Description Object-oriented style ``` public IntlCalendar::getMinimalDaysInFirstWeek(): int|false ``` Procedural style ``` intlcal_get_minimal_days_in_first_week(IntlCalendar $calendar): int|false ``` Returns the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by [IntlCalendar::getFirstDayOfWeek()](intlcalendar.getfirstdayofweek); otherwise it will be the previous yearʼs last week. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. ### Return Values An int representing a number of days or **`false`** on failure. ### Examples **Example #1 **IntlCalendar::getMinimalDaysInFirstWeek()**** ``` <?php ini_set('date.timezone', 'UTC'); ini_set('intl.default_locale', 'en_US'); $cal = new IntlGregorianCalendar(2013, 0 /* January */, 2); var_dump(IntlDateFormatter::formatObject($cal, 'cccc')); // Wednesday var_dump($cal->getMinimalDaysInFirstWeek(), // 1 $cal->getFirstDayofWeek()); // 1 (Sunday) // Week 1 of 2013 var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y")); $cal->setMinimalDaysInFirstWeek(4); // Still Week 1 of 2013 (1st week has 5 days in the new year) var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y")); $cal->setMinimalDaysInFirstWeek(6); // Week 53 of 2012 var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y")); ``` The above example will output: ``` string(9) "Wednesday" int(1) int(1) string(14) "Week 1 of 2013" string(14) "Week 1 of 2013" string(15) "Week 53 of 2012" ``` php stream_bucket_make_writeable stream\_bucket\_make\_writeable =============================== (PHP 5, PHP 7, PHP 8) stream\_bucket\_make\_writeable — Returns a bucket object from the brigade to operate on ### Description ``` stream_bucket_make_writeable(resource $brigade): ?object ``` This function is called whenever there is the need to access and operate on the content contains in a brigade. It is typically called from [php\_user\_filter::filter()](php-user-filter.filter). ### Parameters `brigade` The brigade to return a bucket object from. ### Return Values Returns a bucket object with the properties listed below or **`null`**. data (string) `data` `bucket` The current string in the bucket. datalen (integer) `datalen` `bucket` The length of the string in the bucket. ### See Also * [stream\_bucket\_append()](function.stream-bucket-append) - Append bucket to brigade * [stream\_bucket\_prepend()](function.stream-bucket-prepend) - Prepend bucket to brigade php bzread bzread ====== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) bzread — Binary safe bzip2 file read ### Description ``` bzread(resource $bz, int $length = 1024): string|false ``` **bzread()** reads from the given bzip2 file pointer. Reading stops when `length` (uncompressed) bytes have been read or EOF is reached, whichever comes first. ### Parameters `bz` The file pointer. It must be valid and must point to a file successfully opened by [bzopen()](function.bzopen). `length` If not specified, **bzread()** will read 1024 (uncompressed) bytes at a time. A maximum of 8192 uncompressed bytes will be read at a time. ### Return Values Returns the uncompressed data, or **`false`** on error. ### Examples **Example #1 **bzread()** example** ``` <?php $file = "/tmp/foo.bz2"; $bz = bzopen($file, "r") or die("Couldn't open $file"); $decompressed_file = ''; while (!feof($bz)) {   $decompressed_file .= bzread($bz, 4096); } bzclose($bz); echo "The contents of $file are: <br />\n"; echo $decompressed_file; ?> ``` ### See Also * [bzwrite()](function.bzwrite) - Binary safe bzip2 file write * [feof()](function.feof) - Tests for end-of-file on a file pointer * [bzopen()](function.bzopen) - Opens a bzip2 compressed file
programming_docs
php gmp_invert gmp\_invert =========== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_invert — Inverse by modulo ### Description ``` gmp_invert(GMP|int|string $num1, GMP|int|string $num2): GMP|false ``` Computes the inverse of `num1` modulo `num2`. ### Parameters `num1` A [GMP](class.gmp) object, an int or a numeric string. `num2` A [GMP](class.gmp) object, an int or a numeric string. ### Return Values A GMP number on success or **`false`** if an inverse does not exist. ### Examples **Example #1 **gmp\_invert()** example** ``` <?php echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE $invert = gmp_invert("5", "11"); echo gmp_strval($invert) . "\n"; ?> ``` The above example will output: ``` 9 ``` php QuickHashIntHash::__construct QuickHashIntHash::\_\_construct =============================== (PECL quickhash >= Unknown) QuickHashIntHash::\_\_construct — Creates a new QuickHashIntHash object ### Description ``` public QuickHashIntHash::__construct(int $size, int $options = ?) ``` This constructor creates a new [QuickHashIntHash](class.quickhashinthash). The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported. ### Parameters `size` The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from `64` to `4194304`. `options` The options that you can pass in are: **`QuickHashIntHash::CHECK_FOR_DUPES`**, which makes sure no duplicate entries are added to the hash; **`QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC`** to not use PHP's internal memory manager as well as one of **`QuickHashIntHash::HASHER_NO_HASH`**, **`QuickHashIntHash::HASHER_JENKINS1`** or **`QuickHashIntHash::HASHER_JENKINS2`**. These last three configure which hashing algorithm to use. All options can be combined using bitmasks. ### Return Values Returns a new [QuickHashIntHash](class.quickhashinthash) object. ### Examples **Example #1 **QuickHashIntHash::\_\_construct()** example** ``` <?php var_dump( new QuickHashIntHash( 1024 ) ); var_dump( new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES ) ); var_dump(     new QuickHashIntHash(         1024,         QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntHash::HASHER_JENKINS2      ) ); ?> ``` php is_file is\_file ======== (PHP 4, PHP 5, PHP 7, PHP 8) is\_file — Tells whether the filename is a regular file ### Description ``` is_file(string $filename): bool ``` Tells whether the given file is a regular file. ### Parameters `filename` Path to the file. ### Return Values Returns **`true`** if the filename exists and is a regular file, **`false`** otherwise. > **Note**: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. > > ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 **is\_file()** example** ``` <?php var_dump(is_file('a_file.txt')) . "\n"; var_dump(is_file('/usr/bin/')) . "\n"; ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### Notes > **Note**: The results of this function are cached. See [clearstatcache()](function.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](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality. ### See Also * [is\_dir()](function.is-dir) - Tells whether the filename is a directory * [is\_link()](function.is-link) - Tells whether the filename is a symbolic link * [SplFileInfo](class.splfileinfo) php opcache_is_script_cached opcache\_is\_script\_cached =========================== (PHP 5 >= 5.5.11, PHP 7, PHP 8, PECL ZendOpcache >= 7.0.4) opcache\_is\_script\_cached — Tells whether a script is cached in OPCache ### Description ``` opcache_is_script_cached(string $filename): bool ``` This function checks if a PHP script has been cached in OPCache. This can be used to more easily detect the "warming" of the cache for a particular script. This function only checks in-memory cache, not file cache. ### Parameters `filename` The path to the PHP script to be checked. ### Return Values Returns **`true`** if `filename` is cached in OPCache, **`false`** otherwise. ### See Also * [opcache\_compile\_file()](function.opcache-compile-file) - Compiles and caches a PHP script without executing it php stream_set_blocking stream\_set\_blocking ===================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) stream\_set\_blocking — Set blocking/non-blocking mode on a stream ### Description ``` stream_set_blocking(resource $stream, bool $enable): bool ``` Sets blocking or non-blocking mode on a `stream`. This function works for any stream that supports non-blocking mode (currently, regular files and socket streams). ### Parameters `stream` The stream. `enable` If `enable` is **`false`**, the given stream will be switched to non-blocking mode, and if **`true`**, it will be switched to blocking mode. This affects calls like [fgets()](function.fgets) and [fread()](function.fread) that read from the stream. In non-blocking mode an [fgets()](function.fgets) call will always return right away while in blocking mode it will wait for data to become available on the stream. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Notes > > **Note**: > > > On Windows, this has no affect on local files. Non-blocking IO for local files is not supported on Windows. > > ### See Also * [stream\_select()](function.stream-select) - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds php Parle\RParser::precedence Parle\RParser::precedence ========================= (PECL parle >= 0.7.0) Parle\RParser::precedence — Declare a precedence rule ### Description ``` public Parle\RParser::precedence(string $tok): void ``` Declares a precedence rule for a fictious terminal symbol. This rule can be later used in the specific grammar rules. ### Parameters `tok` Token name. ### Return Values No value is returned. php session_cache_expire session\_cache\_expire ====================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) session\_cache\_expire — Get and/or set current cache expire ### Description ``` session_cache_expire(?int $value = null): int|false ``` **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](https://www.php.net/manual/en/session.configuration.php#ini.session.cache-expire) at request startup time. Thus, you need to call **session\_cache\_expire()** for every request (and before [session\_start()](function.session-start) is called). ### Parameters `value` If `value` is given and not **`null`**, the current cache expire is replaced with `value`. > **Note**: Setting `value` is of value only, if `session.cache_limiter` is set to a value *different* from `nocache`. > > ### Return Values Returns the current setting of `session.cache_expire`. The value returned should be read in minutes, defaults to 180. On failure to change the value, **`false`** is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `value` is nullable now. | ### Examples **Example #1 **session\_cache\_expire()** example** ``` <?php /* set the cache limiter to 'private' */ session_cache_limiter('private'); $cache_limiter = session_cache_limiter(); /* set the cache expire to 30 minutes */ session_cache_expire(30); $cache_expire = session_cache_expire(); /* start the session */ session_start(); echo "The cache limiter is now set to $cache_limiter<br />"; echo "The cached session pages expire after $cache_expire minutes"; ?> ``` ### See Also * [session.cache\_expire](https://www.php.net/manual/en/session.configuration.php#ini.session.cache-expire) * [session.cache\_limiter](https://www.php.net/manual/en/session.configuration.php#ini.session.cache-limiter) * [session\_cache\_limiter()](function.session-cache-limiter) - Get and/or set the current cache limiter php mysqli::use_result mysqli::use\_result =================== mysqli\_use\_result =================== (PHP 5, PHP 7, PHP 8) mysqli::use\_result -- mysqli\_use\_result — Initiate a result set retrieval ### Description Object-oriented style ``` public mysqli::use_result(): mysqli_result|false ``` Procedural style ``` mysqli_use_result(mysqli $mysql): mysqli_result|false ``` Used to initiate the retrieval of a result set from the last query executed using the [mysqli\_real\_query()](mysqli.real-query) function on the database connection. Either this or the [mysqli\_store\_result()](mysqli.store-result) function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing. > > **Note**: > > > The **mysqli\_use\_result()** function does not transfer the entire result set from the database and hence cannot be used functions such as [mysqli\_data\_seek()](mysqli-result.data-seek) to move to a particular row within the set. To use this functionality, the result set must be stored using [mysqli\_store\_result()](mysqli.store-result). One should not use **mysqli\_use\_result()** if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched. > > ### Parameters This function has no parameters. ### Return Values Returns an unbuffered result object or **`false`** if an error occurred. ### Examples **Example #1 **mysqli::use\_result()** example** Object-oriented style ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query  = "SELECT CURRENT_USER();"; $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; /* execute multi query */ if ($mysqli->multi_query($query)) {     do {         /* store first result set */         if ($result = $mysqli->use_result()) {             while ($row = $result->fetch_row()) {                 printf("%s\n", $row[0]);             }             $result->close();         }         /* print divider */         if ($mysqli->more_results()) {             printf("-----------------\n");         }     } while ($mysqli->next_result()); } /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query  = "SELECT CURRENT_USER();"; $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; /* execute multi query */ if (mysqli_multi_query($link, $query)) {     do {         /* store first result set */         if ($result = mysqli_use_result($link)) {             while ($row = mysqli_fetch_row($result)) {                 printf("%s\n", $row[0]);             }             mysqli_free_result($result);         }         /* print divider */         if (mysqli_more_results($link)) {             printf("-----------------\n");         }     } while (mysqli_next_result($link)); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer ``` ### See Also * [mysqli\_real\_query()](mysqli.real-query) - Execute an SQL query * [mysqli\_store\_result()](mysqli.store-result) - Transfers a result set from the last query php Threaded::notify Threaded::notify ================ (PECL pthreads >= 2.0.0) Threaded::notify — Synchronization ### Description ``` public Threaded::notify(): bool ``` Send notification to the referenced object ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Notifications and Waiting** ``` <?php class My extends Thread {     public function run() {         /** cause this thread to wait **/         $this->synchronized(function($thread){             if (!$thread->done)                 $thread->wait();         }, $this);     } } $my = new My(); $my->start(); /** send notification to the waiting thread **/ $my->synchronized(function($thread){     $thread->done = true;     $thread->notify(); }, $my); var_dump($my->join()); ?> ``` The above example will output: ``` bool(true) ``` php DOMDocument::schemaValidateSource DOMDocument::schemaValidateSource ================================= (PHP 5, PHP 7, PHP 8) DOMDocument::schemaValidateSource — Validates a document based on a schema ### Description ``` public DOMDocument::schemaValidateSource(string $source, int $flags = 0): bool ``` Validates a document based on a schema defined in the given string. ### Parameters `source` A string containing the schema. `flags` A bitmask of Libxml schema validation flags. Currently the only supported value is [LIBXML\_SCHEMA\_CREATE](https://www.php.net/manual/en/libxml.constants.php). Available since Libxml 2.6.14. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [DOMDocument::schemaValidate()](domdocument.schemavalidate) - Validates a document based on a schema. Only XML Schema 1.0 is supported. * [DOMDocument::relaxNGValidate()](domdocument.relaxngvalidate) - Performs relaxNG validation on the document * [DOMDocument::relaxNGValidateSource()](domdocument.relaxngvalidatesource) - Performs relaxNG validation on the document * [DOMDocument::validate()](domdocument.validate) - Validates the document based on its DTD php Superglobals Superglobals ============ Superglobals — Built-in variables that are always available in all scopes ### Description Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do **global $variable;** to access them within functions or methods. These superglobal variables are: * [$GLOBALS](reserved.variables.globals) * [$\_SERVER](reserved.variables.server) * [$\_GET](reserved.variables.get) * [$\_POST](reserved.variables.post) * [$\_FILES](reserved.variables.files) * [$\_COOKIE](reserved.variables.cookies) * [$\_SESSION](reserved.variables.session) * [$\_REQUEST](reserved.variables.request) * [$\_ENV](reserved.variables.environment) ### 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](https://www.php.net/manual/en/ini.core.php#ini.variables-order). > > > > **Note**: **Variable variables** > > > > Superglobals cannot be used as [variable variables](language.variables.variable) inside functions or class methods. > > ### See Also * [variable scope](language.variables.scope) * The [variables\_order](https://www.php.net/manual/en/ini.core.php#ini.variables-order) directive * [The filter extension](https://www.php.net/manual/en/book.filter.php) php sodium_crypto_auth_verify sodium\_crypto\_auth\_verify ============================ (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_auth\_verify — Verifies that the tag is valid for the message ### Description ``` sodium_crypto_auth_verify(string $mac, string $message, string $key): bool ``` Verify the authentication tag is valid for a given message and key. Unlike with digital signatures (e.g. [sodium\_crypto\_sign\_verify\_detached()](function.sodium-crypto-sign-verify-detached)), any party capable of verifying a message is also capable of authenticating their own messages. (Hence, symmetric authentication.) ### Parameters `mac` Authentication tag produced by [sodium\_crypto\_auth()](function.sodium-crypto-auth) `message` Message `key` Authentication key ### Return Values Returns **`true`** on success or **`false`** on failure. php None Generators overview ------------------- (PHP 5 >= 5.5.0, PHP 7, PHP 8) Generators provide an easy way to implement simple [iterators](language.oop5.iterations) without the overhead or complexity of implementing a class that implements the [Iterator](class.iterator) interface. A generator allows you to write code that uses [foreach](control-structures.foreach) to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal [function](functions.user-defined), except that instead of [return](functions.returning-values)ing once, a generator can [yield](language.generators.syntax#control-structures.yield) as many times as it needs to in order to provide the values to be iterated over. A simple example of this is to reimplement the [range()](function.range) function as a generator. The standard [range()](function.range) function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling **range(0, 1000000)** will result in well over 100 MB of memory being used. As an alternative, we can implement an `xrange()` generator, which will only ever need enough memory to create an [Iterator](class.iterator) object and track the current state of the generator internally, which turns out to be less than 1 kilobyte. **Example #1 Implementing [range()](function.range) as a generator** ``` <?php function xrange($start, $limit, $step = 1) {     if ($start <= $limit) {         if ($step <= 0) {             throw new LogicException('Step must be positive');         }         for ($i = $start; $i <= $limit; $i += $step) {             yield $i;         }     } else {         if ($step >= 0) {             throw new LogicException('Step must be negative');         }         for ($i = $start; $i >= $limit; $i += $step) {             yield $i;         }     } } /*  * Note that both range() and xrange() result in the same  * output below.  */ echo 'Single digit odd numbers from range():  '; foreach (range(1, 9, 2) as $number) {     echo "$number "; } echo "\n"; echo 'Single digit odd numbers from xrange(): '; foreach (xrange(1, 9, 2) as $number) {     echo "$number "; } ?> ``` The above example will output: ``` Single digit odd numbers from range(): 1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9 ``` ### [Generator](class.generator) objects When a generator function is called, a new object of the internal [Generator](class.generator) class is returned. This object implements the [Iterator](class.iterator) interface in much the same way as a forward-only iterator object would, and provides methods that can be called to manipulate the state of the generator, including sending values to and returning values from it.
programming_docs
php Transliterator::createInverse Transliterator::createInverse ============================= transliterator\_create\_inverse =============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0) Transliterator::createInverse -- transliterator\_create\_inverse — Create an inverse transliterator ### Description Object-oriented style ``` public Transliterator::createInverse(): ?Transliterator ``` Procedural style ``` transliterator_create_inverse(Transliterator $transliterator): ?Transliterator ``` Opens the inverse transliterator. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns a [Transliterator](class.transliterator) object on success, or **`null`** on failure ### See Also * [Transliterator::getErrorMessage()](transliterator.geterrormessage) - Get last error message * [Transliterator::create()](transliterator.create) - Create a transliterator php Ds\Sequence::slice Ds\Sequence::slice ================== (PECL ds >= 1.0.0) Ds\Sequence::slice — Returns a sub-sequence of a given range ### Description ``` abstract public Ds\Sequence::slice(int $index, int $length = ?): Ds\Sequence ``` Creates a sub-sequence of a given range. ### Parameters `index` The index at which the sub-sequence starts. If positive, the sequence will start at that index in the sequence. If negative, the sequence will start that far from the end. `length` If a length is given and is positive, the resulting sequence will have up to that many values in it. If the length results in an overflow, only values up to the end of the sequence will be included. If a length is given and is negative, the sequence will stop that many values from the end. If a length is not provided, the resulting sequence will contain all values between the index and the end of the sequence. ### Return Values A sub-sequence of the given range. ### Examples **Example #1 **Ds\Sequence::slice()** example** ``` <?php $sequence = new \Ds\Vector(["a", "b", "c", "d", "e"]); // Slice from 2 onwards print_r($sequence->slice(2)); // Slice from 1, for a length of 3 print_r($sequence->slice(1, 3)); // Slice from 1 onwards print_r($sequence->slice(1)); // Slice from 2 from the end onwards print_r($sequence->slice(-2)); // Slice from 1 to 1 from the end print_r($sequence->slice(1, -1)); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => c [1] => d [2] => e ) Ds\Vector Object ( [0] => b [1] => c [2] => d ) Ds\Vector Object ( [0] => b [1] => c [2] => d [3] => e ) Ds\Vector Object ( [0] => d [1] => e ) Ds\Vector Object ( [0] => b [1] => c [2] => d ) ``` php ReflectionFunctionAbstract::returnsReference ReflectionFunctionAbstract::returnsReference ============================================ (PHP 5 >= 5.2.0, PHP 7, PHP 8) ReflectionFunctionAbstract::returnsReference — Checks if returns reference ### Description ``` public ReflectionFunctionAbstract::returnsReference(): bool ``` Checks whether the function returns a reference. ### Parameters This function has no parameters. ### Return Values **`true`** if it returns a reference, otherwise **`false`** ### See Also * [ReflectionFunctionAbstract::isClosure()](reflectionfunctionabstract.isclosure) - Checks if closure php EvStat::attr EvStat::attr ============ (PECL ev >= 0.2.0) EvStat::attr — Returns the values most recently detected by Ev ### Description ``` public EvStat::attr(): array ``` Returns array of the values most recently detected by Ev ### Parameters This function has no parameters. ### Return Values Returns array with the values most recently detect by Ev(without actual `stat` 'ing): **List for item keys of the array returned by **EvStat::attr()**** | Key | Description | | --- | --- | | **`'dev'`** | ID of device containing file | | **`'ino'`** | inode number | | **`'mode'`** | protection | | **`'nlink'`** | number of hard links | | **`'uid'`** | user ID of owner | | **`'size'`** | total size, in bytes | | **`'gid'`** | group ID of owner | | **`'rdev'`** | device ID (if special file) | | **`'blksize'`** | blocksize for file system I/O | | **`'blocks'`** | number of 512B blocks allocated | | **`'atime'`** | time of last access | | **`'ctime'`** | time of last status change | | **`'mtime'`** | time of last modification | See `stat(2)` man page for details. ### Examples **Example #1 Monitor changes of /var/log/messages** ``` <?php // Use 10 second update interval. $w = new EvStat("/var/log/messages", 8, function ($w) {     echo "/var/log/messages changed\n";     $attr = $w->attr();     if ($attr['nlink']) {         printf("Current size: %ld\n", $attr['size']);         printf("Current atime: %ld\n", $attr['atime']);         printf("Current mtime: %ld\n", $attr['mtime']);     } else {         fprintf(STDERR, "`messages` file is not there!");         $w->stop();     } }); Ev::run(); ?> ``` ### See Also * [EvStat::prev()](evstat.prev) - Returns the previous set of values returned by EvStat::attr * [EvStat::stat()](evstat.stat) - Initiates the stat call php Zookeeper::connect Zookeeper::connect ================== (PECL zookeeper >= 0.2.0) Zookeeper::connect — Create a handle to used communicate with zookeeper ### Description ``` public Zookeeper::connect(string $host, callable $watcher_cb = null, int $recv_timeout = 10000): void ``` This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO\_CONNECTED\_STATE is received. ### Parameters `host` Comma separated host:port pairs, each corresponding to a zk server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002" `watcher_cb` The global watcher callback function. When notifications are triggered this function will be invoked. `recv_timeout` The timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO\_CONNECTED\_STATE). ### Return Values No value is returned. ### Errors/Exceptions This method emits PHP error/warning when parameters count or types are wrong or could not init instance. **Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives. ### See Also * [Zookeeper::\_\_construct()](zookeeper.construct) - Create a handle to used communicate with zookeeper * [ZookeeperException](class.zookeeperexception) php sodium_crypto_secretbox_keygen sodium\_crypto\_secretbox\_keygen ================================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_secretbox\_keygen — Generate random key for sodium\_crypto\_secretbox ### Description ``` sodium_crypto_secretbox_keygen(): string ``` Generate a key for use with [sodium\_crypto\_secretbox()](function.sodium-crypto-secretbox) and [sodium\_crypto\_secretbox\_open()](function.sodium-crypto-secretbox-open). ### Parameters This function has no parameters. ### Return Values Returns the generated string of cryptographically secure random bytes. ### Examples **Example #1 **sodium\_crypto\_secretbox\_keygen()** example** ``` <?php $key = sodium_crypto_secretbox_keygen(); var_dump( sodium_bin2hex( $key ) ); ?> ``` The above example will output something similar to: ``` string(64) "88bd1dc51ec81984f3ddc5a8f59a3d95b647e2da3e879f1b9ceb0abd89e7286c" ``` **Example #2 Comparing **sodium\_crypto\_secretbox\_keygen()** with [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php)** ``` <?php $key = sodium_crypto_secretbox_keygen(); $bytes = random_bytes( SODIUM_CRYPTO_SECRETBOX_KEYBYTES ); var_dump( mb_strlen( $key, '8bit' ) === mb_strlen( $bytes, '8bit' ) ); ?> ``` The above example will output: ``` bool(true) ``` ### See Also * [sodium\_bin2hex()](function.sodium-bin2hex) - Encode to hexadecimal * [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php) - Get cryptographically secure random bytes php The XMLWriter class The XMLWriter class =================== Introduction ------------ (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) Class synopsis -------------- class **XMLWriter** { /\* Methods \*/ public [\_\_construct](xmlwriter.construct)() ``` public endAttribute(): bool ``` ``` public endCdata(): bool ``` ``` public endComment(): bool ``` ``` public endDocument(): bool ``` ``` public endDtd(): bool ``` ``` public endDtdAttlist(): bool ``` ``` public endDtdElement(): bool ``` ``` public endDtdEntity(): bool ``` ``` public endElement(): bool ``` ``` public endPi(): bool ``` ``` public flush(bool $empty = true): string|int ``` ``` public fullEndElement(): bool ``` ``` public openMemory(): bool ``` ``` public openUri(string $uri): bool ``` ``` public outputMemory(bool $flush = true): string ``` ``` public setIndent(bool $enable): bool ``` ``` public setIndentString(string $indentation): bool ``` ``` public startAttribute(string $name): bool ``` ``` public startAttributeNs(?string $prefix, string $name, ?string $namespace): bool ``` ``` public startCdata(): bool ``` ``` public startComment(): bool ``` ``` public startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool ``` ``` public startDtd(string $qualifiedName, ?string $publicId = null, ?string $systemId = null): bool ``` ``` public startDtdAttlist(string $name): bool ``` ``` public startDtdElement(string $qualifiedName): bool ``` ``` public startDtdEntity(string $name, bool $isParam): bool ``` ``` public startElement(string $name): bool ``` ``` public startElementNs(?string $prefix, string $name, ?string $namespace): bool ``` ``` public startPi(string $target): bool ``` ``` public text(string $content): bool ``` ``` public writeAttribute(string $name, string $value): bool ``` ``` public writeAttributeNs( ?string $prefix, string $name, ?string $namespace, string $value ): bool ``` ``` public writeCdata(string $content): bool ``` ``` public writeComment(string $content): bool ``` ``` public writeDtd( string $name, ?string $publicId = null, ?string $systemId = null, ?string $content = null ): bool ``` ``` public writeDtdAttlist(string $name, string $content): bool ``` ``` public writeDtdElement(string $name, string $content): bool ``` ``` public writeDtdEntity( string $name, string $content, bool $isParam = false, ?string $publicId = null, ?string $systemId = null, ?string $notationData = null ): bool ``` ``` public writeElement(string $name, ?string $content = null): bool ``` ``` public writeElementNs( ?string $prefix, string $name, ?string $namespace, ?string $content = null ): bool ``` ``` public writePi(string $target, string $content): bool ``` ``` public writeRaw(string $content): bool ``` } Table of Contents ----------------- * [XMLWriter::\_\_construct](xmlwriter.construct) — Construct a new XMLWriter instance * [XMLWriter::endAttribute](xmlwriter.endattribute) — End attribute * [XMLWriter::endCdata](xmlwriter.endcdata) — End current CDATA * [XMLWriter::endComment](xmlwriter.endcomment) — Create end comment * [XMLWriter::endDocument](xmlwriter.enddocument) — End current document * [XMLWriter::endDtd](xmlwriter.enddtd) — End current DTD * [XMLWriter::endDtdAttlist](xmlwriter.enddtdattlist) — End current DTD AttList * [XMLWriter::endDtdElement](xmlwriter.enddtdelement) — End current DTD element * [XMLWriter::endDtdEntity](xmlwriter.enddtdentity) — End current DTD Entity * [XMLWriter::endElement](xmlwriter.endelement) — End current element * [XMLWriter::endPi](xmlwriter.endpi) — End current PI * [XMLWriter::flush](xmlwriter.flush) — Flush current buffer * [XMLWriter::fullEndElement](xmlwriter.fullendelement) — End current element * [XMLWriter::openMemory](xmlwriter.openmemory) — Create new xmlwriter using memory for string output * [XMLWriter::openUri](xmlwriter.openuri) — Create new xmlwriter using source uri for output * [XMLWriter::outputMemory](xmlwriter.outputmemory) — Returns current buffer * [XMLWriter::setIndent](xmlwriter.setindent) — Toggle indentation on/off * [XMLWriter::setIndentString](xmlwriter.setindentstring) — Set string used for indenting * [XMLWriter::startAttribute](xmlwriter.startattribute) — Create start attribute * [XMLWriter::startAttributeNs](xmlwriter.startattributens) — Create start namespaced attribute * [XMLWriter::startCdata](xmlwriter.startcdata) — Create start CDATA tag * [XMLWriter::startComment](xmlwriter.startcomment) — Create start comment * [XMLWriter::startDocument](xmlwriter.startdocument) — Create document tag * [XMLWriter::startDtd](xmlwriter.startdtd) — Create start DTD tag * [XMLWriter::startDtdAttlist](xmlwriter.startdtdattlist) — Create start DTD AttList * [XMLWriter::startDtdElement](xmlwriter.startdtdelement) — Create start DTD element * [XMLWriter::startDtdEntity](xmlwriter.startdtdentity) — Create start DTD Entity * [XMLWriter::startElement](xmlwriter.startelement) — Create start element tag * [XMLWriter::startElementNs](xmlwriter.startelementns) — Create start namespaced element tag * [XMLWriter::startPi](xmlwriter.startpi) — Create start PI tag * [XMLWriter::text](xmlwriter.text) — Write text * [XMLWriter::writeAttribute](xmlwriter.writeattribute) — Write full attribute * [XMLWriter::writeAttributeNs](xmlwriter.writeattributens) — Write full namespaced attribute * [XMLWriter::writeCdata](xmlwriter.writecdata) — Write full CDATA tag * [XMLWriter::writeComment](xmlwriter.writecomment) — Write full comment tag * [XMLWriter::writeDtd](xmlwriter.writedtd) — Write full DTD tag * [XMLWriter::writeDtdAttlist](xmlwriter.writedtdattlist) — Write full DTD AttList tag * [XMLWriter::writeDtdElement](xmlwriter.writedtdelement) — Write full DTD element tag * [XMLWriter::writeDtdEntity](xmlwriter.writedtdentity) — Write full DTD Entity tag * [XMLWriter::writeElement](xmlwriter.writeelement) — Write full element tag * [XMLWriter::writeElementNs](xmlwriter.writeelementns) — Write full namespaced element tag * [XMLWriter::writePi](xmlwriter.writepi) — Writes a PI * [XMLWriter::writeRaw](xmlwriter.writeraw) — Write a raw XML text php The Yaf_Route_Static class The Yaf\_Route\_Static class ============================ Introduction ------------ (Yaf >=1.0.0) Defaultly, [Yaf\_Router](class.yaf-router) only have a **Yaf\_Route\_Static** as its default route. And **Yaf\_Route\_Static** is designed to handle the 80% requirement. please \*NOTE\* that it is unnecessary to instance a **Yaf\_Route\_Static**, also unecesary to add it into [Yaf\_Router](class.yaf-router)'s routes stack, since there is always be one in [Yaf\_Router](class.yaf-router)'s routes stack, and always be called at the last time. Class synopsis -------------- class **Yaf\_Route\_Static** implements [Yaf\_Router](class.yaf-router) { /\* Methods \*/ ``` public assemble(array $info, array $query = ?): string ``` ``` public match(string $uri): void ``` ``` public route(Yaf_Request_Abstract $request): bool ``` } Table of Contents ----------------- * [Yaf\_Route\_Static::assemble](yaf-route-static.assemble) — Assemble a url * [Yaf\_Route\_Static::match](yaf-route-static.match) — The match purpose * [Yaf\_Route\_Static::route](yaf-route-static.route) — Route a request php ReflectionParameter::__toString ReflectionParameter::\_\_toString ================================= (PHP 5, PHP 7, PHP 8) ReflectionParameter::\_\_toString — To string ### Description ``` public ReflectionParameter::__toString(): string ``` To string. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values ### See Also * [ReflectionParameter::export()](reflectionparameter.export) - Exports * [\_\_toString()](language.oop5.magic#object.tostring) php GearmanClient::removeOptions GearmanClient::removeOptions ============================ (PECL gearman >= 0.6.0) GearmanClient::removeOptions — Remove client options ### Description ``` public GearmanClient::removeOptions(int $options): bool ``` Removes (unsets) one or more options. ### Parameters `options` The options to be removed (unset) ### Return Values Always returns **`true`**. php ReflectionProperty::getAttributes ReflectionProperty::getAttributes ================================= (PHP 8) ReflectionProperty::getAttributes — Gets Attributes ### Description ``` public ReflectionProperty::getAttributes(?string $name = null, int $flags = 0): array ``` Returns all attributes declared on this class property as an array of [ReflectionAttribute](class.reflectionattribute). **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` `flags` ### Return Values Array of attributes, as a [ReflectionAttribute](class.reflectionattribute) object. ### See Also * [ReflectionClass::getAttributes()](reflectionclass.getattributes) - Gets Attributes * [ReflectionClassConstant::getAttributes()](reflectionclassconstant.getattributes) - Gets Attributes * [ReflectionFunctionAbstract::getAttributes()](reflectionfunctionabstract.getattributes) - Gets Attributes * [ReflectionParameter::getAttributes()](reflectionparameter.getattributes) - Gets Attributes php ImagickPixel::isPixelSimilarQuantum ImagickPixel::isPixelSimilarQuantum =================================== (PECL imagick 3 >= 3.3.0) ImagickPixel::isPixelSimilarQuantum — Description ### Description ``` public ImagickPixel::isPixelSimilarQuantum(string $color, string $fuzz = ?): bool ``` Returns true if the distance between two colors is less than the specified distance. The fuzz value should be in the range 0-QuantumRange. The maximum value represents the longest possible distance in the colorspace. e.g. from RGB(0, 0, 0) to RGB(255, 255, 255) for the RGB colorspace ### Parameters `color` `fuzz` ### Return Values php Ds\Sequence::insert Ds\Sequence::insert =================== (PECL ds >= 1.0.0) Ds\Sequence::insert — Inserts values at a given index ### Description ``` abstract public Ds\Sequence::insert(int $index, mixed ...$values): void ``` Inserts values into the sequence at a given index. ### Parameters `index` The index at which to insert. `0 <= index <= count` > > **Note**: > > > You can insert at the index equal to the number of values. > > `values` The value or values to insert. ### Return Values No value is returned. ### Errors/Exceptions [OutOfRangeException](class.outofrangeexception) if the index is not valid. ### Examples **Example #1 **Ds\Sequence::insert()** example** ``` <?php $sequence = new \Ds\Vector(); $sequence->insert(0, "e");             // [e] $sequence->insert(1, "f");             // [e, f] $sequence->insert(2, "g");             // [e, f, g] $sequence->insert(0, "a", "b");        // [a, b, e, f, g] $sequence->insert(2, ...["c", "d"]);   // [a, b, c, d, e, f, g] var_dump($sequence); ?> ``` The above example will output something similar to: ``` object(Ds\Vector)#1 (7) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" [4]=> string(1) "e" [5]=> string(1) "f" [6]=> string(1) "g" } ``` php streamWrapper::stream_flush streamWrapper::stream\_flush ============================ (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) streamWrapper::stream\_flush — Flushes the output ### Description ``` public streamWrapper::stream_flush(): bool ``` This method is called in response to [fflush()](function.fflush) and when the stream is being closed while any unflushed data has been written to it before. If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now. ### Parameters This function has no parameters. ### Return Values Should return **`true`** if the cached data was successfully stored (or if there was no data to store), or **`false`** if the data could not be stored. ### Notes > > **Note**: > > > If not implemented, **`false`** is assumed as the return value. > > ### See Also * [fflush()](function.fflush) - Flushes the output to a file
programming_docs
php EvLoop::idle EvLoop::idle ============ (PECL ev >= 0.2.0) EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance ### Description ``` final public EvLoop::idle( callable $callback , mixed $data = null , int $priority = 0 ): EvIdle ``` Creates EvIdle watcher object associated with the current event loop instance ### Parameters All the parameters have the same meaning as for [EvIdle::\_\_construct()](evidle.construct) ### Return Values Returns EvIdle object on success. ### See Also * [EvIdle::\_\_construct()](evidle.construct) - Constructs the EvIdle watcher object php posix_getlogin posix\_getlogin =============== (PHP 4, PHP 5, PHP 7, PHP 8) posix\_getlogin — Return login name ### Description ``` posix_getlogin(): string|false ``` Returns the login name of the user owning the current process. ### Parameters This function has no parameters. ### Return Values Returns the login name of the user, as a string, or **`false`** on failure. ### Examples **Example #1 Example use of **posix\_getlogin()**** ``` <?php echo posix_getlogin(); //apache ?> ``` ### See Also * [posix\_getpwnam()](function.posix-getpwnam) - Return info about a user by username * POSIX man page GETLOGIN(3) php SyncEvent::__construct SyncEvent::\_\_construct ======================== (PECL sync >= 1.0.0) SyncEvent::\_\_construct — Constructs a new SyncEvent object ### Description ``` public SyncEvent::__construct(string $name = ?, bool $manual = false, bool $prefire = false) ``` Constructs a named or unnamed event object. ### Parameters `name` The name of the event if this is a named event object. > > **Note**: > > > If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message. > > `manual` Specifies whether or not the event object must be reset manually. > > **Note**: > > > Manual reset event objects allow all waiting processes through until the object is reset. > > `prefire` Specifies whether or not to prefire (signal) the event object. > > **Note**: > > > Only has impact if the calling process/thread is the first to create the object. > > ### Return Values The new [SyncEvent](class.syncevent) object. ### Errors/Exceptions An exception is thrown if the event object cannot be created or opened. ### Examples **Example #1 **SyncEvent::\_\_construct()** example** ``` <?php // In a web application: $event = new SyncEvent("GetAppReport"); $event->fire(); // In a cron job: $event = new SyncEvent("GetAppReport"); $event->wait(); ?> ``` ### Changelog | Version | Description | | --- | --- | | PECL sync 1.1.0 | Added `prefire`. | ### See Also * [SyncEvent::fire()](syncevent.fire) - Fires/sets the event * [SyncEvent::reset()](syncevent.reset) - Resets a manual event * [SyncEvent::wait()](syncevent.wait) - Waits for the event to be fired/set php The IntlIterator class The IntlIterator class ====================== Introduction ------------ (PHP 5 >= 5.5.0, PHP 7, PHP 8) This class represents iterator objects throughout the intl extension whenever the iterator cannot be identified with any other object provided by the extension. The distinct iterator object used internally by the [`foreach` construct](control-structures.foreach) can only be obtained (in the relevant part here) from objects, so objects of this class serve the purpose of providing the hook through which this internal object can be obtained. As a convenience, this class also implements the [Iterator](class.iterator) interface, allowing the collection of values to be navigated using the methods defined in that interface. Both these methods and the internal iterator objects provided to `foreach` are backed by the same state (e.g. the position of the iterator and its current value). Subclasses may provide richer functionality. Class synopsis -------------- class **IntlIterator** implements [Iterator](class.iterator) { /\* Methods \*/ ``` public current(): mixed ``` ``` public key(): mixed ``` ``` public next(): void ``` ``` public rewind(): void ``` ``` public valid(): bool ``` } Table of Contents ----------------- * [IntlIterator::current](intliterator.current) — Get the current element * [IntlIterator::key](intliterator.key) — Get the current key * [IntlIterator::next](intliterator.next) — Move forward to the next element * [IntlIterator::rewind](intliterator.rewind) — Rewind the iterator to the first element * [IntlIterator::valid](intliterator.valid) — Check if current position is valid php base_convert base\_convert ============= (PHP 4, PHP 5, PHP 7, PHP 8) base\_convert — Convert a number between arbitrary bases ### Description ``` base_convert(string $num, int $from_base, int $to_base): string ``` Returns a string containing `num` represented in base `to_base`. The base in which `num` is given is specified in `from_base`. Both `from_base` and `to_base` have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35. The case of the letters doesn't matter, i.e. `num` is interpreted case-insensitively. **Warning** **base\_convert()** may lose precision on large numbers due to properties related to the internal float type used. Please see the [Floating point numbers](language.types.float) section in the manual for more specific information and limitations. ### Parameters `num` The number to convert. Any invalid characters in `num` are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated. `from_base` The base `num` is in `to_base` The base to convert `num` to ### Return Values `num` converted to base `to_base` ### Changelog | Version | Description | | --- | --- | | 7.4.0 | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist. | ### Examples **Example #1 **base\_convert()** example** ``` <?php $hexadecimal = 'a37334'; echo base_convert($hexadecimal, 16, 2); ?> ``` The above example will output: ``` 101000110111001100110100 ``` ### See Also * [intval()](function.intval) - Get the integer value of a variable php Imagick::paintTransparentImage Imagick::paintTransparentImage ============================== (PECL imagick 2, PECL imagick 3) Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::paintTransparentImage(mixed $target, float $alpha, float $fuzz): bool ``` Changes any pixel that matches color with the color defined by fill. ### Parameters `target` Change this target color to specified opacity value within the image. `alpha` The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent. `fuzz` The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object. | php DateTimeImmutable::getLastErrors DateTimeImmutable::getLastErrors ================================ (PHP 5 >= 5.5.0, PHP 7, PHP 8) DateTimeImmutable::getLastErrors — Returns the warnings and errors ### Description ``` public static DateTimeImmutable::getLastErrors(): array|false ``` Returns an array of warnings and errors found while parsing a date/time string. ### Parameters This function has no parameters. ### Return Values Returns array containing info about warnings and errors, or **`false`** if there are neither warnings nor errors. ### Examples **Example #1 **DateTimeImmutable::getLastErrors()** example** ``` <?php try {     $date = new DateTimeImmutable('asdfasdf'); } catch (Exception $e) {     // For demonstration purposes only...     print_r(DateTimeImmutable::getLastErrors());     // The real object-oriented way to do this is     // echo $e->getMessage(); } ?> ``` The above examples will output: ``` Array ( [warning_count] => 1 [warnings] => Array ( [6] => Double timezone specification ) [error_count] => 1 [errors] => Array ( [0] => The timezone could not be found in the database ) ) ``` The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred. php socket_clear_error socket\_clear\_error ==================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) socket\_clear\_error — Clears the error on the socket or the last error code ### Description ``` socket_clear_error(?Socket $socket = null): void ``` This function clears the error code on the given socket or the global last socket error if no socket is specified. This function allows explicitly resetting the error code value either of a socket or of the extension global last error code. This may be useful to detect within a part of the application if an error occurred or not. ### Parameters `socket` A [Socket](class.socket) instance created with [socket\_create()](function.socket-create). ### Return Values No value is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | | 8.0.0 | `socket` is nullable now. | ### See Also * [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error php ArrayAccess::offsetUnset ArrayAccess::offsetUnset ======================== (PHP 5, PHP 7, PHP 8) ArrayAccess::offsetUnset — Unset an offset ### Description ``` public ArrayAccess::offsetUnset(mixed $offset): void ``` Unsets an offset. > > **Note**: > > > This method will *not* be called when type-casting to [(unset)](language.types.type-juggling#language.types.typecasting) > > ### Parameters `offset` The offset to unset. ### Return Values No value is returned. php mysqli_stmt::free_result mysqli\_stmt::free\_result ========================== mysqli\_stmt\_free\_result ========================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::free\_result -- mysqli\_stmt\_free\_result — Frees stored result memory for the given statement handle ### Description Object-oriented style ``` public mysqli_stmt::free_result(): void ``` Procedural style ``` mysqli_stmt_free_result(mysqli_stmt $statement): void ``` Frees the result memory associated with the statement, which was allocated by [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result). ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values No value is returned. ### See Also * [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result) - Stores a result set in an internal buffer php dl dl == (PHP 4, PHP 5, PHP 7, PHP 8) dl — Loads a PHP extension at runtime ### Description ``` dl(string $extension_filename): bool ``` Loads the PHP extension given by the parameter `extension_filename`. Use [extension\_loaded()](function.extension-loaded) to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or **dl()**). **Warning** This function is only available for the CLI and embed SAPIs, and the CGI SAPI when run from the command line. ### Parameters `extension_filename` This parameter is *only* the filename of the extension to load which also depends on your platform. For example, the [sockets](https://www.php.net/manual/en/ref.sockets.php) extension (if compiled as a shared module, not the default!) would be called sockets.so on Unix platforms whereas it is called php\_sockets.dll on the Windows platform. The directory where the extension is loaded from depends on your platform: Windows - If not explicitly set in the php.ini, the extension is loaded from C:\php5\ by default. Unix - If not explicitly set in the php.ini, the default extension directory depends on * whether PHP has been built with `--enable-debug` or not * whether PHP has been built with ZTS (Zend Thread Safety) support or not * the current internal `ZEND_MODULE_API_NO` (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. `20010901`) Taking into account the above, the directory then defaults to `<install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO`, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901. ### Return Values Returns **`true`** on success or **`false`** on failure. If the functionality of loading modules is not available or has been disabled (by setting [enable\_dl](https://www.php.net/manual/en/info.configuration.php#ini.enable-dl) off in php.ini) an **`E_ERROR`** is emitted and execution is stopped. If **dl()** fails because the specified library couldn't be loaded, in addition to **`false`** an **`E_WARNING`** message is emitted. ### Examples **Example #1 **dl()** examples** ``` <?php // Example loading an extension based on OS if (!extension_loaded('sqlite')) {     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {         dl('php_sqlite.dll');     } else {         dl('sqlite.so');     } } // Or using PHP_SHLIB_SUFFIX constant if (!extension_loaded('sqlite')) {     $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';     dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX); } ?> ``` ### Notes > > **Note**: > > > **dl()** is case sensitive on Unix platforms. > > ### See Also * [Extension Loading Directives](https://www.php.net/manual/en/ini.core.php#ini.extension) * [extension\_loaded()](function.extension-loaded) - Find out whether an extension is loaded php socket_read socket\_read ============ (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_read — Reads a maximum of length bytes from a socket ### Description ``` socket_read(Socket $socket, int $length, int $mode = PHP_BINARY_READ): string|false ``` The function **socket\_read()** reads from the [Socket](class.socket) instance `socket` created by the [socket\_create()](function.socket-create) or [socket\_accept()](function.socket-accept) functions. ### Parameters `socket` A [Socket](class.socket) instance created with [socket\_create()](function.socket-create) or [socket\_accept()](function.socket-accept). `length` The maximum number of bytes read is specified by the `length` parameter. Otherwise you can use **`\r`**, **`\n`**, or **`\0`** to end reading (depending on the `mode` parameter, see below). `mode` Optional `mode` parameter is a named constant: * **`PHP_BINARY_READ`** (Default) - use the system `recv()` function. Safe for reading binary data. * **`PHP_NORMAL_READ`** - reading stops at `\n` or `\r`. ### Return Values **socket\_read()** returns the data as a string on success, or **`false`** on error (including if the remote host has closed the connection). The error code can be retrieved with [socket\_last\_error()](function.socket-last-error). This code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual representation of the error. > > **Note**: > > > **socket\_read()** returns a zero length string ("") when there is no more data to read. > > ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | ### See Also * [socket\_accept()](function.socket-accept) - Accepts a connection on a socket * [socket\_bind()](function.socket-bind) - Binds a name to a socket * [socket\_connect()](function.socket-connect) - Initiates a connection on a socket * [socket\_listen()](function.socket-listen) - Listens for a connection on a socket * [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error * [socket\_write()](function.socket-write) - Write to a socket php SplFileInfo::setFileClass SplFileInfo::setFileClass ========================= (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::setFileClass — Sets the class used with [SplFileInfo::openFile()](splfileinfo.openfile) ### Description ``` public SplFileInfo::setFileClass(string $class = SplFileObject::class): void ``` Use this method to set a custom class which will be used when [SplFileInfo::openFile()](splfileinfo.openfile) is called. The class name passed to this method must be [SplFileObject](class.splfileobject) or a class derived from [SplFileObject](class.splfileobject). ### Parameters `class` The class name to use when [SplFileInfo::openFile()](splfileinfo.openfile) is called. ### Return Values No value is returned. ### Examples **Example #1 **SplFileInfo::setFileClass()** example** ``` <?php // Create a class extending SplFileObject class MyFoo extends SplFileObject {} $info = new SplFileInfo(__FILE__); // Set the class to use $info->setFileClass('MyFoo'); var_dump($info->openFile()); ?> ``` The above example will output something similar to: ``` object(MyFoo)#2 (0) { } ``` ### See Also * [SplFileInfo::openFile()](splfileinfo.openfile) - Gets an SplFileObject object for the file php uopz_unset_hook uopz\_unset\_hook ================= (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_unset\_hook — Removes previously set hook on function or method ### Description ``` uopz_unset_hook(string $function): bool ``` ``` uopz_unset_hook(string $class, string $function): bool ``` Removes the previously set hook on a function or method. ### Parameters `class` The name of the class. `function` The name of the function or method. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Basic **uopz\_unset\_hook()** Usage** ``` <?php function foo() {     echo 'foo'; } uopz_set_hook('foo', function () {echo 'bar';}); foo(); echo PHP_EOL; uopz_unset_hook('foo'); foo(); ?> ``` The above example will output: ``` barfoo foo ``` ### See Also * [uopz\_set\_hook()](function.uopz-set-hook) - Sets hook to execute when entering a function or method * [uopz\_get\_hook()](function.uopz-get-hook) - Gets previously set hook on function or method php Yac::__construct Yac::\_\_construct ================== (PECL yac >= 1.0.0) Yac::\_\_construct — Constructor ### Description public **Yac::\_\_construct**(string `$prefix` = "") prefix is used to prepended to keys, this could be used to avoiding conflicts between apps. ### Parameters `prefix` string prefix ### Errors/Exceptions Throws an [Exception](class.exception) if Yac is not enabled. Throws [Exception](class.exception) if `prefix` exceeds max key length of 48 (**`YAC_MAX_KEY_LEN`**) bytes.
programming_docs
php Ds\Map::apply Ds\Map::apply ============= (PECL ds >= 1.0.0) Ds\Map::apply — Updates all values by applying a callback function to each value ### Description ``` public Ds\Map::apply(callable $callback): void ``` Updates all values by applying a `callback` function to each value in the map. ### Parameters `callback` ``` callback(mixed $key, mixed $value): mixed ``` A [callable](language.types.callable) to apply to each value in the map. The callback should return what the value should be replaced by. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Map::apply()** example** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); $map->apply(function($key, $value) { return $value * 2; }); print_r($map); ?> ``` The above example will output something similar to: ``` Ds\Map Object ( [0] => Ds\Pair Object ( [key] => a [value] => 2 ) [1] => Ds\Pair Object ( [key] => b [value] => 4 ) [2] => Ds\Pair Object ( [key] => c [value] => 6 ) ) ``` php stats_kurtosis stats\_kurtosis =============== (PECL stats >= 1.0.0) stats\_kurtosis — Computes the kurtosis of the data in the array ### Description ``` stats_kurtosis(array $a): float ``` Returns the kurtosis of the values in `a`. ### Parameters `a` The input array ### Return Values Returns the kurtosis of the values in `a`, or **`false`** if `a` is empty or is not an array. php SessionHandler::gc SessionHandler::gc ================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SessionHandler::gc — Cleanup old sessions ### Description ``` public SessionHandler::gc(int $max_lifetime): int|false ``` Cleans up expired sessions. Called randomly by PHP internally when a session starts or when [session\_start()](function.session-start) is invoked. The frequency this is called is based on the [session.gc\_divisor](https://www.php.net/manual/en/session.configuration.php#ini.session.gc-divisor) and [session.gc\_probability](https://www.php.net/manual/en/session.configuration.php#ini.session.gc-probability) configuration directives. This method wraps the internal PHP save handler defined in the [session.save\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.save-handler) ini setting that was set before this handler was set by [session\_set\_save\_handler()](function.session-set-save-handler). If this class is extended by inheritance, calling the parent `gc` method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered. For more information on what this method is expected to do, please refer to the documentation at [SessionHandlerInterface::gc()](sessionhandlerinterface.gc). ### Parameters `max_lifetime` Sessions that have not updated for the last `max_lifetime` seconds will be removed. ### Return Values Returns the number of deleted sessions on success, or **`false`** on failure. Note this value is returned internally to PHP for processing. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | Prior to this version, the function returned **`true`** on success. | php xdiff_file_bdiff xdiff\_file\_bdiff ================== (PECL xdiff >= 1.5.0) xdiff\_file\_bdiff — Make binary diff of two files ### Description ``` xdiff_file_bdiff(string $old_file, string $new_file, string $dest): bool ``` Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using [xdiff\_file\_bpatch()](function.xdiff-file-bpatch)/[xdiff\_string\_bpatch()](function.xdiff-string-bpatch). ### Parameters `old_file` Path to the first file. This file acts as "old" file. `new_file` Path to the second file. This file acts as "new" file. `dest` Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **xdiff\_file\_bdiff()** example** The following code makes binary diff of two archives. ``` <?php $old_version = 'my_script_1.0.tgz'; $new_version = 'my_script_1.1.tgz'; xdiff_file_bdiff($old_version, $new_version, 'my_script.bdiff'); ?> ``` ### Notes > > **Note**: > > > Both files will be loaded into memory so ensure that your memory\_limit is set high enough. > > ### See Also * [xdiff\_file\_bpatch()](function.xdiff-file-bpatch) - Patch a file with a binary diff php SolrQuery::getFilterQueries SolrQuery::getFilterQueries =========================== (PECL solr >= 0.9.2) SolrQuery::getFilterQueries — Returns an array of filter queries ### Description ``` public SolrQuery::getFilterQueries(): array ``` Returns an array of filter queries. These are queries that can be used to restrict the super set of documents that can be returned, without influencing score ### Parameters This function has no parameters. ### Return Values Returns an array on success and **`null`** if not set. php error_reporting error\_reporting ================ (PHP 4, PHP 5, PHP 7, PHP 8) error\_reporting — Sets which PHP errors are reported ### Description ``` error_reporting(?int $error_level = null): int ``` The **error\_reporting()** function sets the [error\_reporting](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. If the optional `error_level` is not set, **error\_reporting()** will just return the current error reporting level. ### Parameters `error_level` The new [error\_reporting](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected. The available error level constants and the actual meanings of these error levels are described in the [predefined constants](https://www.php.net/manual/en/errorfunc.constants.php). ### Return Values Returns the old [error\_reporting](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) level or the current level if no `error_level` parameter is given. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `error_level` is nullable now. | ### Examples **Example #1 **error\_reporting()** examples** ``` <?php // Turn off all error reporting error_reporting(0); // Report simple running errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Reporting E_NOTICE can be good too (to report uninitialized // variables or catch variable name misspellings ...) error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); // Report all errors except E_NOTICE error_reporting(E_ALL & ~E_NOTICE); // Report all PHP errors error_reporting(E_ALL); // Report all PHP errors error_reporting(-1); // Same as error_reporting(E_ALL); ini_set('error_reporting', E_ALL); ?> ``` ### Notes **Tip** Passing in the value `-1` will show every possible error, even when new levels and constants are added in future PHP versions. The behavior is equivalent to passing **`E_ALL`** constant. ### See Also * The [display\_errors](https://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors) directive * The [html\_errors](https://www.php.net/manual/en/errorfunc.configuration.php#ini.html-errors) directive * The [xmlrpc\_errors](https://www.php.net/manual/en/errorfunc.configuration.php#ini.xmlrpc-errors) directive * [ini\_set()](function.ini-set) - Sets the value of a configuration option php geoip_db_get_all_info geoip\_db\_get\_all\_info ========================= (PECL geoip >= 1.0.1) geoip\_db\_get\_all\_info — Returns detailed information about all GeoIP database types ### Description ``` geoip_db_get_all_info(): array ``` The **geoip\_db\_get\_all\_info()** function will return detailed information as a multi-dimensional array about all the GeoIP database types. This function is available even if no databases are installed. It will simply list them as non-available. The names of the different keys of the returning associative array are as follows: * "available" -- Boolean, indicate if DB is available (see [geoip\_db\_avail()](function.geoip-db-avail)) * "description" -- The database description * "filename" -- The database filename on disk (see [geoip\_db\_filename()](function.geoip-db-filename)) ### Parameters This function has no parameters. ### Return Values Returns the associative array. ### Examples **Example #1 A **geoip\_db\_get\_all\_info()** example** This will print the array containing all the information. ``` <?php $infos = geoip_db_get_all_info(); if (is_array($infos)) {     var_dump($infos); } ?> ``` The above example will output: ``` array(11) { [1]=> array(3) { ["available"]=> bool(true) ["description"]=> string(21) "GeoIP Country Edition" ["filename"]=> string(32) "/usr/share/GeoIP/GeoIP.dat" } [ ... ] [11]=> array(3) { ["available"]=> bool(false) ["description"]=> string(25) "GeoIP Domain Name Edition" ["filename"]=> string(38) "/usr/share/GeoIP/GeoIPDomain.dat" } } ``` **Example #2 A **geoip\_db\_get\_all\_info()** example** You can use the various constants as keys to get only parts of the information. ``` <?php $infos = geoip_db_get_all_info(); if ($infos[GEOIP_COUNTRY_EDITION]['available']) {     echo $infos[GEOIP_COUNTRY_EDITION]['description']; } ?> ``` The above example will output: ``` GeoIP Country Edition ``` php ldap_modify ldap\_modify ============ (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_modify — Alias of [ldap\_mod\_replace()](function.ldap-mod-replace) ### Description This function is an alias of: [ldap\_mod\_replace()](function.ldap-mod-replace). ### See Also * [ldap\_rename()](function.ldap-rename) - Modify the name of an entry php fdf_get_opt fdf\_get\_opt ============= (PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECLv) fdf\_get\_opt — Gets a value from the opt array of a field ### Description ``` fdf_get_opt(resource $fdf_document, string $fieldname, int $element = -1): mixed ``` **Warning**This function is currently not documented; only its argument list is available. php PharData::delete PharData::delete ================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) PharData::delete — Delete a file within a tar/zip archive ### Description ``` public PharData::delete(string $localName): bool ``` Delete a file within an archive. This is the functional equivalent of calling [unlink()](function.unlink) on the stream wrapper equivalent, as shown in the example below. ### Parameters `localName` Path within an archive to the file to delete. ### Return Values returns **`true`** on success, but it is better to check for thrown exception, and assume success if none is thrown. ### Errors/Exceptions Throws [PharException](class.pharexception) if errors occur while flushing changes to disk. ### Examples **Example #1 A **PharData::delete()** example** ``` <?php try {     $phar = new PharData('myphar.zip');     $phar->delete('unlink/me.php');     // this is equivalent to:     unlink('phar://myphar.phar/unlink/me.php'); } catch (Exception $e) {     // handle errors } ?> ``` ### See Also * [Phar::delete()](phar.delete) - Delete a file within a phar archive php phpdbg_color phpdbg\_color ============= (PHP 5 >= 5.6.0, PHP 7, PHP 8) phpdbg\_color — Sets the color of certain elements ### Description ``` phpdbg_color(int $element, string $color): void ``` Set the `color` of the given `element`. ### Parameters `element` One of the **`PHPDBG_COLOR_*`** constants. `color` The name of the color. One of `white`, `red`, `green`, `yellow`, `blue`, `purple`, `cyan` or `black`, optionally with either a trailing `-bold` or `-underline`, for instance, `white-bold` or `green-underline`. ### Return Values No value is returned. ### See Also * [phpdbg\_prompt()](function.phpdbg-prompt) - Sets the command prompt php SolrResponse::getRequestUrl SolrResponse::getRequestUrl =========================== (PECL solr >= 0.9.2) SolrResponse::getRequestUrl — Returns the full URL the request was sent to ### Description ``` public SolrResponse::getRequestUrl(): string ``` Returns the full URL the request was sent to. ### Parameters This function has no parameters. ### Return Values Returns the full URL the request was sent to php Exception class for intl errors Exception class for intl errors =============================== Introduction ------------ (PHP 5 > 5.5.0, PHP 7, PHP 8, PECL intl > 3.0.0a1) This class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when [intl.use\_exceptions](https://www.php.net/manual/en/intl.configuration.php#ini.intl.use-exceptions) is enabled. Class synopsis -------------- class **IntlException** extends [Exception](class.exception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php Generator::current Generator::current ================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) Generator::current — Get the yielded value ### Description ``` public Generator::current(): mixed ``` ### Parameters This function has no parameters. ### Return Values Returns the yielded value. php odbc_foreignkeys odbc\_foreignkeys ================= (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_foreignkeys — Retrieves a list of foreign keys ### Description ``` odbc_foreignkeys( resource $odbc, ?string $pk_catalog, string $pk_schema, string $pk_table, string $fk_catalog, string $fk_schema, string $fk_table ): resource|false ``` Retrieves a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `pk_catalog` The catalog ('qualifier' in ODBC 2 parlance) of the primary key table. `pk_schema` The schema ('owner' in ODBC 2 parlance) of the primary key table. `pk_table` The primary key table. `fk_catalog` The catalog ('qualifier' in ODBC 2 parlance) of the foreign key table. `fk_schema` The schema ('owner' in ODBC 2 parlance) of the foreign key table. `fk_table` The foreign key table. ### Return Values Returns an ODBC result identifier or **`false`** on failure. The result set has the following columns: * `PKTABLE_CAT` * `PKTABLE_SCHEM` * `PKTABLE_NAME` * `PKCOLUMN_NAME` * `FKTABLE_CAT` * `FKTABLE_SCHEM` * `FKTABLE_NAME` * `FKCOLUMN_NAME` * `KEY_SEQ` * `UPDATE_RULE` * `DELETE_RULE` * `FK_NAME` * `PK_NAME` * `DEFERRABILITY` Drivers can report additional columns. If the foreign keys associated with a primary key are requested, the result set is ordered by `FKTABLE_CAT`, `FKTABLE_SCHEM`, `FKTABLE_NAME` and `KEY_SEQ`. If the primary keys associated with a foreign key are requested, the result set is ordered by `PKTABLE_CAT`, `PKTABLE_SCHEM`, `PKTABLE_NAME` and `KEY_SEQ`. If `pk_table` contains a table name, **odbc\_foreignkeys()** returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it. If `fk_table` contains a table name, **odbc\_foreignkeys()** returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer. If both `pk_table` and `fk_table` contain table names, **odbc\_foreignkeys()** returns the foreign keys in the table specified in `fk_table` that refer to the primary key of the table specified in `pk_table`. This should be one key at most. ### See Also * [odbc\_tables()](function.odbc-tables) - Get the list of table names stored in a specific data source * [odbc\_primarykeys()](function.odbc-primarykeys) - Gets the primary keys for a table php imageistruecolor imageistruecolor ================ (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) imageistruecolor — Finds whether an image is a truecolor image ### Description ``` imageistruecolor(GdImage $image): bool ``` **imageistruecolor()** finds whether the image `image` is a truecolor image. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). ### Return Values Returns **`true`** if the `image` is truecolor, **`false`** otherwise. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Simple detection of true color image instances using **imageistruecolor()**** ``` <?php // $im is an image instance // Check if image is a true color image or not if(!imageistruecolor($im)) {     // Create a new true color image instance     $tc = imagecreatetruecolor(imagesx($im), imagesy($im));     // Copy over the pixels     imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));     imagedestroy($im);     $im = $tc;     $tc = NULL;     // OR use imagepalettetotruecolor() } // Continue working with image instance ?> ``` ### See Also * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image * [imagepalettetotruecolor()](function.imagepalettetotruecolor) - Converts a palette based image to true color php Yaf_Response_Abstract::getHeader Yaf\_Response\_Abstract::getHeader ================================== (Yaf >=1.0.0) Yaf\_Response\_Abstract::getHeader — The getHeader purpose ### Description ``` public Yaf_Response_Abstract::getHeader(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values ### See Also * [Yaf\_Response\_Abstract::setHeader()](yaf-response-abstract.setheader) - Set reponse header * **Yaf\_Response\_Abstract::cleanHeaders()**
programming_docs
php Error::getTraceAsString Error::getTraceAsString ======================= (PHP 7, PHP 8) Error::getTraceAsString — Gets the stack trace as a string ### Description ``` final public Error::getTraceAsString(): string ``` Returns the stack trace as a string. ### Parameters This function has no parameters. ### Return Values Returns the stack trace as a string. ### Examples **Example #1 **Error::getTraceAsString()** example** ``` <?php function test() {     throw new Error; } try {     test(); } catch(Error $e) {     echo $e->getTraceAsString(); } ?> ``` The above example will output something similar to: ``` #0 /home/bjori/tmp/ex.php(7): test() #1 {main} ``` ### See Also * [Throwable::getTraceAsString()](throwable.gettraceasstring) - Gets the stack trace as a string php stream_supports_lock stream\_supports\_lock ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) stream\_supports\_lock — Tells whether the stream supports locking ### Description ``` stream_supports_lock(resource $stream): bool ``` Tells whether the stream supports locking through [flock()](function.flock). ### Parameters `stream` The stream to check. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [flock()](function.flock) - Portable advisory file locking php SplObjectStorage::offsetSet SplObjectStorage::offsetSet =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplObjectStorage::offsetSet — Associates data to an object in the storage ### Description ``` public SplObjectStorage::offsetSet(object $object, mixed $info = null): void ``` Associate data to an object in the storage. > > **Note**: > > > **SplObjectStorage::offsetSet()** is an alias of [SplObjectStorage::attach()](splobjectstorage.attach). > > ### Parameters `object` The object to associate data with. `info` The data to associate with the object. ### Return Values No value is returned. ### Examples **Example #1 **SplObjectStorage::offsetSet()** example** ``` <?php $s = new SplObjectStorage; $o1 = new StdClass; $s->offsetSet($o1, "hello"); // Similar to $s[$o1] = "hello"; var_dump($s[$o1]); ?> ``` The above example will output something similar to: ``` string(5) "hello" ``` ### See Also * [SplObjectStorage::attach()](splobjectstorage.attach) - Adds an object in the storage * [SplObjectStorage::offsetGet()](splobjectstorage.offsetget) - Returns the data associated with an object * [SplObjectStorage::offsetExists()](splobjectstorage.offsetexists) - Checks whether an object exists in the storage * [SplObjectStorage::offsetUnset()](splobjectstorage.offsetunset) - Removes an object from the storage php The WeakMap class The WeakMap class ================= Introduction ------------ (PHP 8) A **WeakMap** is map (or dictionary) that accepts objects as keys. However, unlike the otherwise similar [SplObjectStorage](class.splobjectstorage), an object in a key of **WeakMap** does not contribute toward the object's reference count. That is, if at any point the only remaining reference to an object is the key of a **WeakMap**, the object will be garbage collected and removed from the **WeakMap**. Its primary use case is for building caches of data derived from an object that do not need to live longer than the object. **WeakMap** implements [ArrayAccess](class.arrayaccess), [Iterator](class.iterator), and [Countable](class.countable), so in most cases it can be used in the same fashion as an associative array. Class synopsis -------------- final class **WeakMap** implements [ArrayAccess](class.arrayaccess), [Countable](class.countable), [IteratorAggregate](class.iteratoraggregate) { /\* Methods \*/ public [\_\_construct](ext-weakmap.construct)() ``` public count(): int ``` ``` public getIterator(): Iterator ``` ``` public offsetExists(object $object): bool ``` ``` public offsetGet(object $object): mixed ``` ``` public offsetSet(object $object, mixed $value): void ``` ``` public offsetUnset(object $object): void ``` } Examples -------- **Example #1 **Weakmap** usage example** ``` <?php $wm = new WeakMap(); $o = new StdClass; class A {     public function __destruct() {         echo "Dead!\n";     } } $wm[$o] = new A; var_dump(count($wm)); echo "Unsetting...\n"; unset($o); echo "Done\n"; var_dump(count($wm)); ``` The above example will output: ``` int(1) Unsetting... Dead! Done int(0) ``` Table of Contents ----------------- * [WeakMap::\_\_construct](ext-weakmap.construct) — Constructs a new map * [WeakMap::count](weakmap.count) — Counts the number of live entries in the map * [WeakMap::getIterator](weakmap.getiterator) — Retrieve an external iterator * [WeakMap::offsetExists](weakmap.offsetexists) — Checks whether a certain object is in the map * [WeakMap::offsetGet](weakmap.offsetget) — Returns the value pointed to by a certain object * [WeakMap::offsetSet](weakmap.offsetset) — Updates the map with a new key-value pair * [WeakMap::offsetUnset](weakmap.offsetunset) — Removes an entry from the map php mcrypt_generic mcrypt\_generic =============== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_generic — This function encrypts data **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_generic(resource $td, string $data): string ``` This function encrypts data. The data is padded with "`\0`" to make sure the length of the data is n \* blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer than the input, due to the padding of the data. If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt\_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use [mcrypt\_enc\_get\_block\_size()](function.mcrypt-enc-get-block-size) to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by [mdecrypt\_generic()](function.mdecrypt-generic) will be 16 characters as well...use rtrim($str, "\0") to remove the padding. If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead. ### Parameters `td` The encryption descriptor. The encryption handle should always be initialized with [mcrypt\_generic\_init()](function.mcrypt-generic-init) with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling [mcrypt\_generic\_deinit()](function.mcrypt-generic-deinit). See [mcrypt\_module\_open()](function.mcrypt-module-open) for an example. `data` The data to encrypt. ### Return Values Returns the encrypted data. ### See Also * [mdecrypt\_generic()](function.mdecrypt-generic) - Decrypts data * [mcrypt\_generic\_init()](function.mcrypt-generic-init) - This function initializes all buffers needed for encryption * [mcrypt\_generic\_deinit()](function.mcrypt-generic-deinit) - This function deinitializes an encryption module php Imagick::getQuantum Imagick::getQuantum =================== (PECL imagick 3 >= 3.3.0) Imagick::getQuantum — Description ### Description ``` public static Imagick::getQuantum(): int ``` Returns the ImageMagick quantum range as an integer. ### Parameters This function has no parameters. ### Return Values php exif_tagname exif\_tagname ============= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) exif\_tagname — Get the header name for an index ### Description ``` exif_tagname(int $index): string|false ``` ### Parameters `index` The Tag ID for which a Tag Name will be looked up. ### Return Values Returns the header name, or **`false`** if `index` is not a defined EXIF tag id. ### Examples **Example #1 **exif\_tagname()** example** ``` <?php echo "256: ".exif_tagname(256).PHP_EOL; echo "257: ".exif_tagname(257).PHP_EOL; ?> ``` The above example will output: ``` 256: ImageWidth 257: ImageLength ``` ### See Also * [exif\_imagetype()](function.exif-imagetype) - Determine the type of an image * [» EXIF Specification](http://exif.org/Exif2-2.PDF) * [» EXIF Tags](http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html) php imap_timeout imap\_timeout ============= (PHP 4 >= 4.3.3, PHP 5, PHP 7, PHP 8) imap\_timeout — Set or fetch imap timeout ### Description ``` imap_timeout(int $timeout_type, int $timeout = -1): int|bool ``` Sets or fetches the imap timeout. ### Parameters `timeout_type` One of the following: **`IMAP_OPENTIMEOUT`**, **`IMAP_READTIMEOUT`**, **`IMAP_WRITETIMEOUT`**, or **`IMAP_CLOSETIMEOUT`**. `timeout` The timeout, in seconds. ### Return Values If the `timeout` parameter is set, this function returns **`true`** on success and **`false`** on failure. If `timeout` is not provided or evaluates to -1, the current timeout value of `timeout_type` is returned as an integer. ### Examples **Example #1 **imap\_timeout()** example** ``` <?php echo "The current read timeout is " . imap_timeout(IMAP_READTIMEOUT) . "\n"; ?> ``` php dio_seek dio\_seek ========= (PHP 4 >= 4.2.0, PHP 5 < 5.1.0) dio\_seek — Seeks to pos on fd from whence ### Description ``` dio_seek(resource $fd, int $pos, int $whence = SEEK_SET): int ``` The function **dio\_seek()** is used to change the file position of the given file descriptor. ### Parameters `fd` The file descriptor returned by [dio\_open()](function.dio-open). `pos` The new position. `whence` Specifies how the position `pos` should be interpreted: * **`SEEK_SET`** (default) - specifies that `pos` is specified from the beginning of the file. * **`SEEK_CUR`** - Specifies that `pos` is a count of characters from the current file position. This count may be positive or negative. * **`SEEK_END`** - Specifies that `pos` is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position. ### Return Values ### Examples **Example #1 Positioning in a file** ``` <?php $fd = dio_open('/dev/ttyS0', O_RDWR); dio_seek($fd, 10, SEEK_SET); // position is now at 10 characters from the start of the file dio_seek($fd, -2, SEEK_CUR); // position is now at 8 characters from the start of the file dio_seek($fd, -5, SEEK_END); // position is now at 5 characters from the end of the file dio_seek($fd, 10, SEEK_END); // position is now at 10 characters past the end of the file.  // The 10 characters between the end of the file and the current // position are filled with zeros. dio_close($fd); ?> ``` php UConverter::getAliases UConverter::getAliases ====================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) UConverter::getAliases — Get the aliases of the given name ### Description ``` public static UConverter::getAliases(string $name): array|false|null ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php imagettftext imagettftext ============ (PHP 4, PHP 5, PHP 7, PHP 8) imagettftext — Write text to the image using TrueType fonts ### Description ``` imagettftext( GdImage $image, float $size, float $angle, int $x, int $y, int $color, string $font_filename, string $text, array $options = [] ): array|false ``` Writes the given `text` into the image using TrueType fonts. > > **Note**: > > > Prior to PHP 8.0.0, [imagefttext()](function.imagefttext) was an extended variant of **imagettftext()** which additionally supported the `extrainfo`. As of PHP 8.0.0, **imagettftext()** is an alias of [imagefttext()](function.imagefttext). > > ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `size` The font size in points. `angle` The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text. `x` The coordinates given by `x` and `y` will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the [imagestring()](function.imagestring), where `x` and `y` define the upper-left corner of the first character. For example, "top left" is 0, 0. `y` The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character. `color` The color index. Using the negative of a color index has the effect of turning off antialiasing. See [imagecolorallocate()](function.imagecolorallocate). `fontfile` The path to the TrueType font you wish to use. Depending on which version of the GD library PHP is using, *when `fontfile` does not begin with a leading `/` then `.ttf` will be appended* to the filename and the library will attempt to search for that filename along a library-defined font path. When using versions of the GD library lower than 2.0.18, a `space` character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: `Warning: Could not find/open font`. For these affected versions, the only solution is moving the font to a path which does not contain spaces. In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems. ``` <?php // Set the environment variable for GD putenv('GDFONTPATH=' . realpath('.')); // Name the font to be used (note the lack of the .ttf extension) $font = 'SomeFont'; ?> ``` > > **Note**: > > > Note that [open\_basedir](https://www.php.net/manual/en/ini.core.php#ini.open-basedir) does *not* apply to `fontfile`. > > `text` The text string in UTF-8 encoding. May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127. The hexadecimal format (like &#xA9;) is supported. Strings in UTF-8 encoding can be passed directly. Named entities, such as &copy;, are not supported. Consider using [html\_entity\_decode()](function.html-entity-decode) to decode these named entities into UTF-8 strings. If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character. ### Return Values Returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally. Returns **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | The `options` has been added. | ### Examples **Example #1 **imagettftext()** example** This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial. ``` <?php // Set the content-type header('Content-Type: image/png'); // Create the image $im = imagecreatetruecolor(400, 30); // Create some colors $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 399, 29, $white); // The text to draw $text = 'Testing...'; // Replace path by your own font path $font = 'arial.ttf'; // Add some shadow to the text imagettftext($im, 20, 0, 11, 21, $grey, $font, $text); // Add the text imagettftext($im, 20, 0, 10, 20, $black, $font, $text); // Using imagepng() results in clearer text compared with imagejpeg() imagepng($im); imagedestroy($im); ?> ``` The above example will output something similar to: ### Notes > **Note**: This function is only available if PHP is compiled with freetype support (**--with-freetype-dir=DIR**) > > ### See Also * [imagettfbbox()](function.imagettfbbox) - Give the bounding box of a text using TrueType fonts * [imagefttext()](function.imagefttext) - Write text to the image using fonts using FreeType 2 php Imagick::getImageIndex Imagick::getImageIndex ====================== (PECL imagick 2, PECL imagick 3) Imagick::getImageIndex — Gets the index of the current active image **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::getImageIndex(): int ``` Returns the index of the current active image within the Imagick object. This method has been deprecated. See [Imagick::getIteratorIndex()](imagick.getiteratorindex). ### Parameters This function has no parameters. ### Return Values Returns an integer containing the index of the image in the stack. ### Errors/Exceptions Throws ImagickException on error. php XMLReader::getAttributeNo XMLReader::getAttributeNo ========================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::getAttributeNo — Get the value of an attribute by index ### Description ``` public XMLReader::getAttributeNo(int $index): ?string ``` Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node. ### Parameters `index` The position of the attribute. ### Return Values The value of the attribute, or **`null`** if no attribute exists at `index` or is not positioned on the element. ### See Also * [XMLReader::getAttribute()](xmlreader.getattribute) - Get the value of a named attribute * [XMLReader::getAttributeNs()](xmlreader.getattributens) - Get the value of an attribute by localname and URI php SolrQuery::setFacetMethod SolrQuery::setFacetMethod ========================= (PECL solr >= 0.9.2) SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field ### Description ``` public SolrQuery::setFacetMethod(string $method, string $field_override = ?): SolrQuery ``` Specifies the type of algorithm to use when faceting a field. This method accepts optional field override. ### Parameters `method` The method to use. `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php fbird_field_info fbird\_field\_info ================== (PHP 5, PHP 7 < 7.4.0) fbird\_field\_info — Alias of [ibase\_field\_info()](function.ibase-field-info) ### Description This function is an alias of: [ibase\_field\_info()](function.ibase-field-info). ### See Also * [fbird\_num\_fields()](function.fbird-num-fields) - Alias of ibase\_num\_fields php None Mixed ----- The [mixed](language.types.declarations#language.types.declarations.mixed) type accepts every value. It is equivalent to the [union type](language.types.type-system#language.types.type-system.composite.union) `object|resource|array|string|float|int|bool|null`. Available as of PHP 8.0.0. [mixed](language.types.declarations#language.types.declarations.mixed) is, in type theory parlance, the top type. Meaning every other type is a subtype of it.
programming_docs
php Imagick::queryFontMetrics Imagick::queryFontMetrics ========================= (PECL imagick 2, PECL imagick 3) Imagick::queryFontMetrics — Returns an array representing the font metrics ### Description ``` public Imagick::queryFontMetrics(ImagickDraw $properties, string $text, bool $multiline = ?): array ``` Returns a multi-dimensional array representing the font metrics. ### Parameters `properties` ImagickDraw object containing font properties `text` The text `multiline` Multiline parameter. If left empty it is autodetected ### Return Values Returns a multi-dimensional array representing the font metrics. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::queryFontMetrics()**:** Query the metrics for the text and dump the results on the screen. ``` <?php /* Create a new Imagick object */ $im = new Imagick(); /* Create an ImagickDraw object */ $draw = new ImagickDraw(); /* Set the font */ $draw->setFont('/path/to/font.ttf'); /* Dump the font metrics, autodetect multiline */ var_dump($im->queryFontMetrics($draw, "Hello World!")); ?> ``` php ReflectionClass::getName ReflectionClass::getName ======================== (PHP 5, PHP 7, PHP 8) ReflectionClass::getName — Gets class name ### Description ``` public ReflectionClass::getName(): string ``` Gets the class name. ### Parameters This function has no parameters. ### Return Values The class name. ### Examples **Example #1 **ReflectionClass::getName()** example** ``` <?php namespace A\B; class Foo { } $function = new \ReflectionClass('stdClass'); var_dump($function->inNamespace()); var_dump($function->getName()); var_dump($function->getNamespaceName()); var_dump($function->getShortName()); $function = new \ReflectionClass('A\\B\\Foo'); var_dump($function->inNamespace()); var_dump($function->getName()); var_dump($function->getNamespaceName()); var_dump($function->getShortName()); ?> ``` The above example will output: ``` bool(false) string(8) "stdClass" string(0) "" string(8) "stdClass" bool(true) string(7) "A\B\Foo" string(3) "A\B" string(3) "Foo" ``` ### See Also * [ReflectionClass::getNamespaceName()](reflectionclass.getnamespacename) - Gets namespace name php wincache_ocache_fileinfo wincache\_ocache\_fileinfo ========================== (PECL wincache >= 1.0.0) wincache\_ocache\_fileinfo — Retrieves information about files cached in the opcode cache ### Description ``` wincache_ocache_fileinfo(bool $summaryonly = false): array|false ``` Retrieves information about opcode cache content and its usage. **Warning**This function was *REMOVED* in PHP 7.0.0. ### Parameters `summaryonly` Controls whether the returned array will contain information about individual cache entries along with the opcode cache summary. ### Return Values Array of meta data about opcode cache or **`false`** on failure The array returned by this function contains the following elements: * `total_cache_uptime` - total time in seconds that the opcode cache has been active * `total_file_count` - total number of files that are currently in the opcode cache * `total_hit_count` - number of times the compiled opcode have been served from the cache * `total_miss_count` - number of times the compiled opcode have not been found in the cache * `is_local_cache` - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache * `file_entries` - an array that contains the information about all the cached files: + `file_name` - absolute file name of the cached file + `add_time` - time in seconds since the file has been added to the opcode cache + `use_time` - time in seconds since the file has been accessed in the opcode cache + `last_check` - time in seconds since the file has been checked for modifications + `hit_count` - number of times the file has been served from the cache + `function_count` - number of functions in the cached file + `class_count` - number of classes in the cached file ### Examples **Example #1 A **wincache\_ocache\_fileinfo()** example** ``` <pre> <?php print_r(wincache_ocache_fileinfo()); ?> </pre> ``` The above example will output: ``` Array ( [total_cache_uptime] => 17357 [total_file_count] => 121 [total_hit_count] => 36562 [total_miss_count] => 201 [file_entries] => Array ( [1] => Array ( [file_name] => c:\inetpub\wwwroot\checkcache.php [add_time] => 17356 [use_time] => 7 [last_check] => 10 [hit_count] => 454 [function_count] => 0 [class_count] => 1 ) [2] => Array (...iterates for each cached file) ) ) ``` ### See Also * [wincache\_fcache\_fileinfo()](function.wincache-fcache-fileinfo) - Retrieves information about files cached in the file cache * [wincache\_fcache\_meminfo()](function.wincache-fcache-meminfo) - Retrieves information about file cache memory usage * [wincache\_ocache\_meminfo()](function.wincache-ocache-meminfo) - Retrieves information about opcode cache memory usage * [wincache\_rplist\_fileinfo()](function.wincache-rplist-fileinfo) - Retrieves information about resolve file path cache * [wincache\_rplist\_meminfo()](function.wincache-rplist-meminfo) - Retrieves information about memory usage by the resolve file path cache * [wincache\_refresh\_if\_changed()](function.wincache-refresh-if-changed) - Refreshes the cache entries for the cached files * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache * [wincache\_scache\_info()](function.wincache-scache-info) - Retrieves information about files cached in the session cache * [wincache\_scache\_meminfo()](function.wincache-scache-meminfo) - Retrieves information about session cache memory usage php zip_entry_compressedsize zip\_entry\_compressedsize ========================== (PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0) zip\_entry\_compressedsize — Retrieve the compressed size of a directory entry **Warning**This function has been *DEPRECATED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` zip_entry_compressedsize(resource $zip_entry): int|false ``` Returns the compressed size of the specified directory entry. ### Parameters `zip_entry` A directory entry returned by [zip\_read()](function.zip-read). ### Return Values The compressed size, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function is deprecated in favor of the Object API, see [ZipArchive::statIndex()](ziparchive.statindex). | ### See Also * [zip\_open()](function.zip-open) - Open a ZIP file archive * [zip\_read()](function.zip-read) - Read next entry in a ZIP file archive php sinh sinh ==== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) sinh — Hyperbolic sine ### Description ``` sinh(float $num): float ``` Returns the hyperbolic sine of `num`, defined as `(exp($num) - exp(-$num))/2`. ### Parameters `num` The argument to process ### Return Values The hyperbolic sine of `num` ### See Also * [sin()](function.sin) - Sine * [asinh()](function.asinh) - Inverse hyperbolic sine * [cosh()](function.cosh) - Hyperbolic cosine * [tanh()](function.tanh) - Hyperbolic tangent php ftp_nb_continue ftp\_nb\_continue ================= (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) ftp\_nb\_continue — Continues retrieving/sending a file (non-blocking) ### Description ``` ftp_nb_continue(FTP\Connection $ftp): int ``` Continues retrieving/sending a file non-blocking. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. ### Return Values Returns **`FTP_FAILED`** or **`FTP_FINISHED`** or **`FTP_MOREDATA`**. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_nb\_continue()** example** ``` <?php // Initiate the download $ret = ftp_nb_get($ftp, "test", "README", FTP_BINARY); while ($ret == FTP_MOREDATA) {    // Continue downloading...    $ret = ftp_nb_continue($ftp); } if ($ret != FTP_FINISHED) {    echo "There was an error downloading the file...";    exit(1); } ?> ``` php RegexIterator::getMode RegexIterator::getMode ====================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) RegexIterator::getMode — Returns operation mode ### Description ``` public RegexIterator::getMode(): int ``` Returns the operation mode, see [RegexIterator::setMode()](regexiterator.setmode) for the list of operation modes. ### Parameters This function has no parameters. ### Return Values Returns the operation mode. ### Examples **Example #1 **RegexIterator::getMode()** example** ``` <?php $test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123'); $arrayIterator = new ArrayIterator($test); $regexIterator = new RegexIterator($arrayIterator, '/^[a-z]+/', RegexIterator::GET_MATCH); $mode = $regexIterator->getMode(); if ($mode & RegexIterator::GET_MATCH) {     echo 'Getting the match for each item.'; } elseif ($mode & RegexIterator::ALL_MATCHES) {     echo 'Getting all matches for each item.'; } elseif ($mode & RegexIterator::MATCH) {     echo 'Getting each item if it matches.'; } elseif ($mode & RegexIterator::SPLIT) {     echo 'Getting split pieces of each.'; } ?> ``` The above example will output: ``` Getting the match for each item. ``` ### See Also * [RegexIterator::setMode()](regexiterator.setmode) - Sets the operation mode php get_headers get\_headers ============ (PHP 5, PHP 7, PHP 8) get\_headers — Fetches all the headers sent by the server in response to an HTTP request ### Description ``` get_headers(string $url, bool $associative = false, ?resource $context = null): array|false ``` **get\_headers()** returns an array with the headers sent by the server in response to a HTTP request. ### Parameters `url` The target URL. `associative` If the optional `associative` parameter is set to true, **get\_headers()** parses the response and sets the array's keys. `context` A valid context resource created with [stream\_context\_create()](function.stream-context-create), or **`null`** to use the default context. ### Return Values Returns an indexed or associative array with the headers, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | The `associative` has been changed from int to bool. | | 7.1.0 | The `context` parameter was added. | ### Examples **Example #1 **get\_headers()** example** ``` <?php $url = 'http://www.example.com'; print_r(get_headers($url)); print_r(get_headers($url, true)); ?> ``` The above example will output something similar to: ``` Array ( [0] => HTTP/1.1 200 OK [1] => Date: Sat, 29 May 2004 12:28:13 GMT [2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux) [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT [4] => ETag: "3f80f-1b6-3e1cb03b" [5] => Accept-Ranges: bytes [6] => Content-Length: 438 [7] => Connection: close [8] => Content-Type: text/html ) Array ( [0] => HTTP/1.1 200 OK [Date] => Sat, 29 May 2004 12:28:14 GMT [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux) [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT [ETag] => "3f80f-1b6-3e1cb03b" [Accept-Ranges] => bytes [Content-Length] => 438 [Connection] => close [Content-Type] => text/html ) ``` **Example #2 **get\_headers()** using HEAD example** ``` <?php // By default get_headers uses a GET request to fetch the headers. If you // want to send a HEAD request instead, you can do so using a stream context: stream_context_set_default(     array(         'http' => array(             'method' => 'HEAD'         )     ) ); $headers = get_headers('http://example.com'); ?> ``` ### See Also * [apache\_request\_headers()](function.apache-request-headers) - Fetch all HTTP request headers php iconv_strlen iconv\_strlen ============= (PHP 5, PHP 7, PHP 8) iconv\_strlen — Returns the character count of string ### Description ``` iconv_strlen(string $string, ?string $encoding = null): int|false ``` In contrast to [strlen()](function.strlen), **iconv\_strlen()** counts the occurrences of characters in the given byte sequence `string` on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte. ### Parameters `string` The string. `encoding` If `encoding` parameter is omitted or **`null`**, `string` is assumed to be encoded in [iconv.internal\_encoding](https://www.php.net/manual/en/iconv.configuration.php). ### Return Values Returns the character count of `string`, as an integer, or **`false`** if an error occurs during the encoding. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | ### See Also * [grapheme\_strlen()](function.grapheme-strlen) - Get string length in grapheme units * [mb\_strlen()](function.mb-strlen) - Get string length * [strlen()](function.strlen) - Get string length php GearmanClient::setExceptionCallback GearmanClient::setExceptionCallback =================================== (PECL gearman >= 0.5.0) GearmanClient::setExceptionCallback — Set a callback for worker exceptions ### Description ``` public GearmanClient::setExceptionCallback(callable $callback): bool ``` Specifies a function to call when a worker for a task sends an exception. ### Parameters `callback` Function to call when the worker throws an exception ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanClient::setDataCallback()](gearmanclient.setdatacallback) - Callback function when there is a data packet for a task * [GearmanClient::setCompleteCallback()](gearmanclient.setcompletecallback) - Set a function to be called on task completion * [GearmanClient::setCreatedCallback()](gearmanclient.setcreatedcallback) - Set a callback for when a task is queued * [GearmanClient::setFailCallback()](gearmanclient.setfailcallback) - Set callback for job failure * [GearmanClient::setStatusCallback()](gearmanclient.setstatuscallback) - Set a callback for collecting task status * [GearmanClient::setWarningCallback()](gearmanclient.setwarningcallback) - Set a callback for worker warnings * [GearmanClient::setWorkloadCallback()](gearmanclient.setworkloadcallback) - Set a callback for accepting incremental data updates php Yaf_Request_Http::getRequest Yaf\_Request\_Http::getRequest ============================== (Yaf >=1.0.0) Yaf\_Request\_Http::getRequest — The getRequest purpose ### Description ``` public Yaf_Request_Http::getRequest(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php ImagickPixel::setIndex ImagickPixel::setIndex ====================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) ImagickPixel::setIndex — Description ### Description ``` public ImagickPixel::setIndex(int $index): bool ``` Sets the colormap index of the pixel wand. ### Parameters `index` ### Return Values Returns **`true`** on success. php Transliterator::transliterate Transliterator::transliterate ============================= transliterator\_transliterate ============================= (PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0) Transliterator::transliterate -- transliterator\_transliterate — Transliterate a string ### Description Object-oriented style ``` public Transliterator::transliterate(string $string, int $start = 0, int $end = -1): string|false ``` Procedural style ``` transliterator_transliterate( Transliterator|string $transliterator, string $string, int $start = 0, int $end = -1 ): string|false ``` Transforms a string or part thereof using an ICU transliterator. ### Parameters `transliterator` In the procedural version, either a [Transliterator](class.transliterator) or a string from which a [Transliterator](class.transliterator) can be built. `string` The string to be transformed. `start` The start index (in UTF-16 code units) from which the string will start to be transformed, inclusive. Indexing starts at 0. The text before will be left as is. `end` The end index (in UTF-16 code units) until which the string will be transformed, exclusive. Indexing starts at 0. The text after will be left as is. ### Return Values The transformed string on success, or **`false`** on failure. ### Examples **Example #1 Converting escaped UTF-16 code units** ``` <?php $s = "\u304A\u65E9\u3046\u3054\u3056\u3044\u307E\u3059"; echo transliterator_transliterate("Hex-Any/Java", $s), "\n"; //now the reverse operation with a supplementary character $supplChar = html_entity_decode('&#x1D11E;'); echo mb_strlen($supplChar, "UTF-8"), "\n"; $encSupplChar = transliterator_transliterate("Any-Hex/Java", $supplChar); //echoes two encoded UTF-16 code units echo $encSupplChar, "\n"; //and back echo transliterator_transliterate("Hex-Any/Java", $encSupplChar), "\n"; ?> ``` The above example will output something similar to: ``` お早うございます 1 \uD834\uDD1E 𝄞 ``` ### See Also * [Transliterator::getErrorMessage()](transliterator.geterrormessage) - Get last error message * [Transliterator::\_\_construct()](transliterator.construct) - Private constructor to deny instantiation php mb_ereg_replace mb\_ereg\_replace ================= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) mb\_ereg\_replace — Replace regular expression with multibyte support ### Description ``` mb_ereg_replace( string $pattern, string $replacement, string $string, ?string $options = null ): string|false|null ``` Scans `string` for matches to `pattern`, then replaces the matched text with `replacement` ### Parameters `pattern` The regular expression pattern. Multibyte characters may be used in `pattern`. `replacement` The replacement text. `string` The string being checked. `options` The search option. See [mb\_regex\_set\_options()](function.mb-regex-set-options) for explanation. ### Return Values The resultant string on success, or **`false`** on error. If `string` is not valid for the current encoding, **`null`** is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `options` is nullable now. | | 7.1.0 | The function checks whether `string` is valid for the current encoding. | | 7.1.0 | The `e` modifier has been deprecated. | ### Notes > > **Note**: > > > The internal encoding or the character encoding specified by [mb\_regex\_encoding()](function.mb-regex-encoding) will be used as the character encoding for this function. > > > **Warning**Never use the `e` modifier when working on untrusted input. No automatic escaping will happen (as known from [preg\_replace()](function.preg-replace)). Not taking care of this will most likely create remote code execution vulnerabilities in your application. ### See Also * [mb\_regex\_encoding()](function.mb-regex-encoding) - Set/Get character encoding for multibyte regex * [mb\_eregi\_replace()](function.mb-eregi-replace) - Replace regular expression with multibyte support ignoring case
programming_docs
php bcpow bcpow ===== (PHP 4, PHP 5, PHP 7, PHP 8) bcpow — Raise an arbitrary precision number to another ### Description ``` bcpow(string $num, string $exponent, ?int $scale = null): string ``` Raise `num` to the power `exponent`. ### Parameters `num` The base, as a string. `exponent` The exponent, as a string. If the exponent is non-integral, it is truncated. The valid range of the exponent is platform specific, but is at least `-2147483648` to `2147483647`. `scale` This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the [bcscale()](function.bcscale) function, or fallback to `0` if this has not been set. ### Return Values Returns the result as a string. ### Changelog | Version | Description | | --- | --- | | 7.3.0 | **bcpow()** now returns numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes. | ### Examples **Example #1 **bcpow()** example** ``` <?php echo bcpow('4.2', '3', 2); // 74.08 ?> ``` ### Notes > > **Note**: > > > Before PHP 7.3.0 **bcpow()** may return a result with fewer digits after the decimal point than the `scale` parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the `scale`. For example: > > > **Example #2 **bcpow()** scale example** > > > ``` > <?php > echo bcpow('5', '2', 2);     // prints "25", not "25.00" > ?> > ``` > ### See Also * [bcpowmod()](function.bcpowmod) - Raise an arbitrary precision number to another, reduced by a specified modulus * [bcsqrt()](function.bcsqrt) - Get the square root of an arbitrary precision number php The Stack class The Stack class =============== Introduction ------------ (No version information available, might only be in Git) A Stack is a “last in, first out” or “LIFO” collection that only allows access to the value at the top of the structure and iterates in that order, destructively. Uses a **Ds\Vector** internally. Class synopsis -------------- class **Ds\Stack** implements **Ds\Collection**, [ArrayAccess](class.arrayaccess) { /\* Methods \*/ ``` public allocate(int $capacity): void ``` ``` public capacity(): int ``` ``` public clear(): void ``` ``` public copy(): Ds\Stack ``` ``` public isEmpty(): bool ``` ``` public peek(): mixed ``` ``` public pop(): mixed ``` ``` public push(mixed ...$values): void ``` ``` public toArray(): array ``` } Changelog --------- | Version | Description | | --- | --- | | PECL ds 1.3.0 | The class now implements [ArrayAccess](class.arrayaccess). | Table of Contents ----------------- * [Ds\Stack::allocate](ds-stack.allocate) — Allocates enough memory for a required capacity * [Ds\Stack::capacity](ds-stack.capacity) — Returns the current capacity * [Ds\Stack::clear](ds-stack.clear) — Removes all values * [Ds\Stack::\_\_construct](ds-stack.construct) — Creates a new instance * [Ds\Stack::copy](ds-stack.copy) — Returns a shallow copy of the stack * [Ds\Stack::count](ds-stack.count) — Returns the number of values in the stack * [Ds\Stack::isEmpty](ds-stack.isempty) — Returns whether the stack is empty * [Ds\Stack::jsonSerialize](ds-stack.jsonserialize) — Returns a representation that can be converted to JSON * [Ds\Stack::peek](ds-stack.peek) — Returns the value at the top of the stack * [Ds\Stack::pop](ds-stack.pop) — Removes and returns the value at the top of the stack * [Ds\Stack::push](ds-stack.push) — Pushes values onto the stack * [Ds\Stack::toArray](ds-stack.toarray) — Converts the stack to an array php mb_detect_encoding mb\_detect\_encoding ==================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_detect\_encoding — Detect character encoding ### Description ``` mb_detect_encoding(string $string, array|string|null $encodings = null, bool $strict = false): string|false ``` Detects the most likely character encoding for string `string` from an ordered list of candidates. Automatic detection of the intended character encoding can never be entirely reliable; without some additional information, it is similar to decoding an encrypted string without the key. It is always preferable to use an indication of character encoding stored or transmitted with the data, such as a "Content-Type" HTTP header. This function is most useful with multibyte encodings, where not all sequences of bytes form a valid string. If the input string contains such a sequence, that encoding will be rejected, and the next encoding checked. ### Parameters `string` The string being inspected. `encodings` A list of character encodings to try, in order. The list may be specified as an array of strings, or a single string separated by commas. If `encodings` is omitted or **`null`**, the current detect\_order (set with the [mbstring.detect\_order](https://www.php.net/manual/en/mbstring.configuration.php#ini.mbstring.detect-order) configuration option, or [mb\_detect\_order()](function.mb-detect-order) function) will be used. `strict` Controls the behaviour when `string` is not valid in any of the listed `encodings`. If `strict` is set to **`false`**, the closest matching encoding will be returned; if `strict` is set to **`true`**, **`false`** will be returned. The default value for `strict` can be set with the [mbstring.strict\_detection](https://www.php.net/manual/en/mbstring.configuration.php#ini.mbstring.strict-detection) configuration option. ### Return Values The detected character encoding, or **`false`** if the string is not valid in any of the listed encodings. ### Examples **Example #1 **mb\_detect\_encoding()** example** ``` <?php // Detect character encoding with current detect_order echo mb_detect_encoding($str); // "auto" is expanded according to mbstring.language echo mb_detect_encoding($str, "auto"); // Specify "encodings" parameter by list separated by comma echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win"); // Use array to specify "encodings" parameter $encodings = [   "ASCII",   "JIS",   "EUC-JP" ]; echo mb_detect_encoding($str, $encodings); ?> ``` **Example #2 Effect of `strict` parameter** ``` <?php // 'áéóú' encoded in ISO-8859-1 $str = "\xE1\xE9\xF3\xFA"; // The string is not valid ASCII or UTF-8, but UTF-8 is considered a closer match var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], false)); var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], true)); // If a valid encoding is found, the strict parameter does not change the result var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], false)); var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], true)); ?> ``` The above example will output: ``` string(5) "UTF-8" bool(false) string(10) "ISO-8859-1" string(10) "ISO-8859-1" ``` In some cases, the same sequence of bytes may form a valid string in multiple character encodings, and it is impossible to know which interpretation was intended. For instance, among many others, the byte sequence "\xC4\xA2" could be: * "Ä¢" (U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS followed by U+00A2 CENT SIGN) encoded in any of ISO-8859-1, ISO-8859-15, or Windows-1252 * "ФЂ" (U+0424 CYRILLIC CAPITAL LETTER EF followed by U+0402 CYRILLIC CAPITAL LETTER DJE) encoded in ISO-8859-5 * "Ģ" (U+0122 LATIN CAPITAL LETTER G WITH CEDILLA) encoded in UTF-8 **Example #3 Effect of order when multiple encodings match** ``` <?php $str = "\xC4\xA2"; // The string is valid in all three encodings, so the first one listed will be returned var_dump(mb_detect_encoding($str, ['UTF-8', 'ISO-8859-1', 'ISO-8859-5'])); var_dump(mb_detect_encoding($str, ['ISO-8859-1', 'ISO-8859-5', 'UTF-8'])); var_dump(mb_detect_encoding($str, ['ISO-8859-5', 'UTF-8', 'ISO-8859-1'])); ?> ``` The above example will output: ``` string(5) "UTF-8" string(10) "ISO-8859-1" string(10) "ISO-8859-5" ``` ### See Also * [mb\_detect\_order()](function.mb-detect-order) - Set/Get character encoding detection order php SolrParams::add SolrParams::add =============== (PECL solr >= 0.9.2) SolrParams::add — Alias of [SolrParams::addParam()](solrparams.addparam) ### Description ``` final public SolrParams::add(string $name, string $value): SolrParams ``` This is an alias for SolrParams::addParam ### Parameters `name` The name of the parameter `value` The value of the parameter ### Return Values Returns a SolrParams instance on success php OAuthProvider::callconsumerHandler OAuthProvider::callconsumerHandler ================================== (No version information available, might only be in Git) OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback ### Description ``` public OAuthProvider::callconsumerHandler(): void ``` Calls the registered consumer handler callback function, which is set with [OAuthProvider::consumerHandler()](oauthprovider.consumerhandler). **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Errors/Exceptions Emits an **`E_ERROR`** level error if the callback function cannot be called, or was not specified. ### See Also * [OAuthProvider::consumerHandler()](oauthprovider.consumerhandler) - Set the consumerHandler handler callback php XMLReader::__construct XMLReader::\_\_construct ======================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::\_\_construct — Construct a new XMLReader instance ### Description public **XMLReader::\_\_construct**() Constructs a new [XMLReader](class.xmlreader) instance. ### Parameters This function has no parameters. php Imagick::getImageGravity Imagick::getImageGravity ======================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::getImageGravity — Gets the image gravity ### Description ``` public Imagick::getImageGravity(): int ``` Gets the current gravity value of the image. Unlike [Imagick::getGravity()](imagick.getgravity), this method returns the gravity defined for the current image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer. ### Parameters This function has no parameters. ### Return Values Returns the images gravity property. Refer to the list of [gravity constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.gravity). php Phar::getMetadata Phar::getMetadata ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::getMetadata — Returns phar archive meta-data ### Description ``` public Phar::getMetadata(array $unserializeOptions = []): mixed ``` Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized. ### Parameters No parameters. ### Return Values Any PHP value that can be serialized and is stored as meta-data for the Phar archive, or **`null`** if no meta-data is stored. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | The parameter `unserializeOptions` has been added. | ### Examples **Example #1 A **Phar::getMetadata()** example** ``` <?php // make sure it doesn't exist @unlink('brandnewphar.phar'); try {     $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');     $p['file.php'] = '<?php echo "hello";';     $p->setMetadata(array('bootstrap' => 'file.php'));     var_dump($p->getMetadata()); } catch (Exception $e) {     echo 'Could not modify phar:', $e; } ?> ``` The above example will output: ``` array(1) { ["bootstrap"]=> string(8) "file.php" } ``` ### See Also * [Phar::setMetadata()](phar.setmetadata) - Sets phar archive meta-data * [Phar::delMetadata()](phar.delmetadata) - Deletes the global metadata of the phar * [Phar::hasMetadata()](phar.hasmetadata) - Returns whether phar has global meta-data php The Event class The Event class =============== Introduction ------------ (PECL event >= 1.2.6-beta) **Event** class represents and event firing on a file descriptor being ready to read from or write to; a file descriptor becoming ready to read from or write to(edge-triggered I/O only); a timeout expiring; a signal occurring; a user-triggered event. Every event is associated with [EventBase](class.eventbase) . However, event will never fire until it is *added* (via [Event::add()](event.add) ). An added event remains in *pending* state until the registered event occurs, thus turning it to *active* state. To handle events user may register a callback which is called when event becomes active. If event is configured *persistent* , it remains pending. If it is not persistent, it stops being pending when it's callback runs. [Event::del()](event.del) method *deletes* event, thus making it non-pending. By means of [Event::add()](event.add) method it could be added again. Class synopsis -------------- final class **Event** { /\* Constants \*/ const int [ET](class.event#event.constants.et) = 32; const int [PERSIST](class.event#event.constants.persist) = 16; const int [READ](class.event#event.constants.read) = 2; const int [WRITE](class.event#event.constants.write) = 4; const int [SIGNAL](class.event#event.constants.signal) = 8; const int [TIMEOUT](class.event#event.constants.timeout) = 1; /\* Properties \*/ public readonly bool [$pending](class.event#event.props.pending); /\* Methods \*/ ``` public add( float $timeout = ?): bool ``` ``` public __construct( EventBase $base , mixed $fd , int $what , callable $cb , mixed $arg = NULL ) ``` ``` public del(): bool ``` ``` public free(): void ``` ``` public static getSupportedMethods(): array ``` ``` public pending( int $flags ): bool ``` ``` public set( EventBase $base , mixed $fd , int $what = ?, callable $cb = ?, mixed $arg = ? ): bool ``` ``` public setPriority( int $priority ): bool ``` ``` public setTimer( EventBase $base , callable $cb , mixed $arg = ?): bool ``` ``` public static signal( EventBase $base , int $signum , callable $cb , mixed $arg = ? ): Event ``` ``` public static timer( EventBase $base , callable $cb , mixed $arg = ?): Event ``` } Properties ---------- pending Whether event is pending. See [About event persistence](https://www.php.net/manual/en/event.persistence.php) . Predefined Constants -------------------- **`Event::ET`** Indicates that the event should be edge-triggered, if the underlying event base backend supports edge-triggered events. This affects the semantics of **`Event::READ`** and **`Event::WRITE`** . **`Event::PERSIST`** Indicates that the event is persistent. See [About event persistence](https://www.php.net/manual/en/event.persistence.php) . **`Event::READ`** This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading. **`Event::WRITE`** This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading. **`Event::SIGNAL`** Used to implement signal detection. See "Constructing signal events" below. **`Event::TIMEOUT`** This flag indicates an event that becomes active after a timeout elapses. The **`Event::TIMEOUT`** flag is ignored when constructing an event: one can either set a timeout when event is *added* , or not. It is set in the `$what` argument to the callback function when a timeout has occurred. Table of Contents ----------------- * [Event::add](event.add) — Makes event pending * [Event::addSignal](event.addsignal) — Alias of Event::add * [Event::addTimer](event.addtimer) — Alias of Event::add * [Event::\_\_construct](event.construct) — Constructs Event object * [Event::del](event.del) — Makes event non-pending * [Event::delSignal](event.delsignal) — Alias of Event::del * [Event::delTimer](event.deltimer) — Alias of Event::del * [Event::free](event.free) — Make event non-pending and free resources allocated for this event * [Event::getSupportedMethods](event.getsupportedmethods) — Returns array with of the names of the methods supported in this version of Libevent * [Event::pending](event.pending) — Detects whether event is pending or scheduled * [Event::set](event.set) — Re-configures event * [Event::setPriority](event.setpriority) — Set event priority * [Event::setTimer](event.settimer) — Re-configures timer event * [Event::signal](event.signal) — Constructs signal event object * [Event::timer](event.timer) — Constructs timer event object php ArrayObject::offsetExists ArrayObject::offsetExists ========================= (PHP 5, PHP 7, PHP 8) ArrayObject::offsetExists — Returns whether the requested index exists ### Description ``` public ArrayObject::offsetExists(mixed $key): bool ``` ### Parameters `key` The index being checked. ### Return Values **`true`** if the requested index exists, otherwise **`false`** ### Examples **Example #1 **ArrayObject::offsetExists()** example** ``` <?php $arrayobj = new ArrayObject(array('zero', 'one', 'example'=>'e.g.')); var_dump($arrayobj->offsetExists(1)); var_dump($arrayobj->offsetExists('example')); var_dump($arrayobj->offsetExists('notfound')); ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) ``` php SplDoublyLinkedList::setIteratorMode SplDoublyLinkedList::setIteratorMode ==================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration ### Description ``` public SplDoublyLinkedList::setIteratorMode(int $mode): int ``` ### Parameters `mode` There are two orthogonal sets of modes that can be set: * The direction of the iteration (either one or the other): + **`SplDoublyLinkedList::IT_MODE_LIFO`** (Stack style) + **`SplDoublyLinkedList::IT_MODE_FIFO`** (Queue style) * The behavior of the iterator (either one or the other): + **`SplDoublyLinkedList::IT_MODE_DELETE`** (Elements are deleted by the iterator) + **`SplDoublyLinkedList::IT_MODE_KEEP`** (Elements are traversed by the iterator) The default mode is: **`SplDoublyLinkedList::IT_MODE_FIFO`** | **`SplDoublyLinkedList::IT_MODE_KEEP`** ### Return Values Returns the different modes and flags that affect the iteration. php The Threaded class The Threaded class ================== Introduction ------------ (PECL pthreads >= 2.0.0) Threaded objects form the basis of pthreads ability to execute user code in parallel; they expose synchronization methods and various useful interfaces. Threaded objects, most importantly, provide implicit safety for the programmer; all operations on the object scope are safe. Class synopsis -------------- class **Threaded** implements [Collectable](class.collectable), [Traversable](class.traversable), [Countable](class.countable), [ArrayAccess](class.arrayaccess) { /\* Methods \*/ ``` public chunk(int $size, bool $preserve): array ``` ``` public count(): int ``` ``` public extend(string $class): bool ``` ``` public isRunning(): bool ``` ``` public isTerminated(): bool ``` ``` public merge(mixed $from, bool $overwrite = ?): bool ``` ``` public notify(): bool ``` ``` public notifyOne(): bool ``` ``` public pop(): bool ``` ``` public run(): void ``` ``` public shift(): mixed ``` ``` public synchronized(Closure $block, mixed ...$args): mixed ``` ``` public wait(int $timeout = ?): bool ``` } Table of Contents ----------------- * [Threaded::chunk](threaded.chunk) — Manipulation * [Threaded::count](threaded.count) — Manipulation * [Threaded::extend](threaded.extend) — Runtime Manipulation * [Threaded::isRunning](thread.isrunning) — State Detection * [Threaded::isTerminated](threaded.isterminated) — State Detection * [Threaded::merge](threaded.merge) — Manipulation * [Threaded::notify](threaded.notify) — Synchronization * [Threaded::notifyOne](threaded.notifyone) — Synchronization * [Threaded::pop](threaded.pop) — Manipulation * [Threaded::run](threaded.run) — Execution * [Threaded::shift](threaded.shift) — Manipulation * [Threaded::synchronized](threaded.synchronized) — Synchronization * [Threaded::wait](threaded.wait) — Synchronization
programming_docs
php ReflectionParameter::__construct ReflectionParameter::\_\_construct ================================== (PHP 5, PHP 7, PHP 8) ReflectionParameter::\_\_construct — Construct ### Description public **ReflectionParameter::\_\_construct**(string|array|object `$function`, int|string `$param`) Constructs a [ReflectionParameter](class.reflectionparameter) instance. ### Parameters `function` The function to reflect parameters from. `param` Either an int specifying the position of the parameter (starting with zero), or the parameter name as string. ### Examples **Example #1 Using the [ReflectionParameter](class.reflectionparameter) class** ``` <?php function foo($a, $b, $c) { } function bar(Exception $a, &$b, $c) { } function baz(ReflectionFunction $a, $b = 1, $c = null) { } function abc() { } $reflect = new ReflectionFunction('foo'); echo $reflect; foreach ($reflect->getParameters() as $i => $param) {     printf(         "-- Parameter #%d: %s {\n".         "   Class: %s\n".         "   Allows NULL: %s\n".         "   Passed to by reference: %s\n".         "   Is optional?: %s\n".         "}\n",         $i, // $param->getPosition() can be used         $param->getName(),         var_export($param->getClass(), 1),         var_export($param->allowsNull(), 1),         var_export($param->isPassedByReference(), 1),         $param->isOptional() ? 'yes' : 'no'     ); } ?> ``` The above example will output something similar to: ``` Function [ <user> function foo ] { @@ /Users/philip/cvs/phpdoc/a 2 - 2 - Parameters [3] { Parameter #0 [ <required> $a ] Parameter #1 [ <required> $b ] Parameter #2 [ <required> $c ] } } -- Parameter #0: a { Class: NULL Allows NULL: true Passed to by reference: false Is optional?: no } -- Parameter #1: b { Class: NULL Allows NULL: true Passed to by reference: false Is optional?: no } -- Parameter #2: c { Class: NULL Allows NULL: true Passed to by reference: false Is optional?: no } ``` ### See Also * [ReflectionFunctionAbstract::getParameters()](reflectionfunctionabstract.getparameters) - Gets parameters * [ReflectionFunction::\_\_construct()](reflectionfunction.construct) - Constructs a ReflectionFunction object * [ReflectionMethod::\_\_construct()](reflectionmethod.construct) - Constructs a ReflectionMethod * [Constructors](language.oop5.decon#language.oop5.decon.constructor) php SplFileInfo::isExecutable SplFileInfo::isExecutable ========================= (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::isExecutable — Tells if the file is executable ### Description ``` public SplFileInfo::isExecutable(): bool ``` Checks if the file is executable. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if executable, **`false`** otherwise. ### Examples **Example #1 **SplFileInfo::isExecutable()** example** ``` <?php $info = new SplFileInfo('/usr/bin/php'); var_dump($info->isExecutable());  $info = new SplFileInfo('/usr/bin'); var_dump($info->isExecutable()); $info = new SplFileInfo('foo'); var_dump($info->isExecutable()); ?> ``` The above example will output something similar to: ``` bool(true) bool(true) bool(false) ``` php sodium_bin2base64 sodium\_bin2base64 ================== (PHP 7 >= 7.2.0, PHP 8) sodium\_bin2base64 — Encodes a raw binary string with base64. ### Description ``` sodium_bin2base64(string $string, int $id): string ``` Converts a raw binary string into a base64-encoded string. Unlike [base64\_encode()](function.base64-encode), **sodium\_bin2base64()** is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys) and supports multiple character sets. ### Parameters `string` Raw binary string. `id` * **`SODIUM_BASE64_VARIANT_ORIGINAL`** for standard (`A-Za-z0-9/\+`) Base64 encoding. * **`SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING`** for standard (`A-Za-z0-9/\+`) Base64 encoding, without `=` padding characters. * **`SODIUM_BASE64_VARIANT_URLSAFE`** for URL-safe (`A-Za-z0-9\-_`) Base64 encoding. * **`SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING`** for URL-safe (`A-Za-z0-9\-_`) Base64 encoding, without `=` padding characters. ### Return Values Base64-encoded string. php radius_get_tagged_attr_data radius\_get\_tagged\_attr\_data =============================== (PECL radius >= 1.3.0) radius\_get\_tagged\_attr\_data — Extracts the data from a tagged attribute ### Description ``` radius_get_tagged_attr_data(string $data): string|false ``` If a tagged attribute has been returned from [radius\_get\_attr()](function.radius-get-attr), **radius\_get\_tagged\_attr\_data()** will return the data from the attribute. ### Parameters `data` The tagged attribute to be decoded. ### Return Values Returns the data from the tagged attribute or **`false`** on failure. ### Examples **Example #1 **radius\_get\_tagged\_attr\_data()** example** ``` <?php while ($resa = radius_get_attr($res)) {     if (!is_array($resa)) {         printf ("Error getting attribute: %s\n",  radius_strerror($res));         exit;     }     $attr = $resa['attr'];     $data = $resa['data'];     $tag = radius_get_tagged_attr_tag($data);     $value = radius_get_tagged_attr_data($data);     printf("Got tagged attribute with tag %d and value %s\n", $tag, $value); } ?> ``` ### See Also * [radius\_get\_attr()](function.radius-get-attr) - Extracts an attribute * [radius\_get\_tagged\_attr\_tag()](function.radius-get-tagged-attr-tag) - Extracts the tag from a tagged attribute php Gmagick::embossimage Gmagick::embossimage ==================== (PECL gmagick >= Unknown) Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect ### Description ``` public Gmagick::embossimage(float $radius, float $sigma): Gmagick ``` Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you. ### Parameters `radius` The radius of the effect. `sigma` The sigma of the effect. ### Return Values The embossed [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php The EventListener class The EventListener class ======================= Introduction ------------ (PECL event >= 1.5.0) Represents a connection listener. Class synopsis -------------- final class **EventListener** { /\* Constants \*/ const int [OPT\_LEAVE\_SOCKETS\_BLOCKING](class.eventlistener#eventlistener.constants.opt-leave-sockets-blocking) = 1; const int [OPT\_CLOSE\_ON\_FREE](class.eventlistener#eventlistener.constants.opt-close-on-free) = 2; const int [OPT\_CLOSE\_ON\_EXEC](class.eventlistener#eventlistener.constants.opt-close-on-exec) = 4; const int [OPT\_REUSEABLE](class.eventlistener#eventlistener.constants.opt-reuseable) = 8; const int [OPT\_THREADSAFE](class.eventlistener#eventlistener.constants.opt-threadsafe) = 16; /\* Properties \*/ public readonly int [$fd](class.eventlistener#eventlistener.props.fd); /\* Methods \*/ ``` public __construct( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target ) ``` ``` public disable(): bool ``` ``` public enable(): bool ``` ``` public getBase(): void ``` ``` public static getSocketName( string &$address , mixed &$port = ?): bool ``` ``` public setCallback( callable $cb , mixed $arg = null ): void ``` ``` public setErrorCallback( string $cb ): void ``` } Properties ---------- fd Numeric file descriptor of the underlying socket. (Added in `event-1.6.0` .) Predefined Constants -------------------- **`EventListener::OPT_LEAVE_SOCKETS_BLOCKING`** By default Libevent turns underlying file descriptors, or sockets, to non-blocking mode. This flag tells Libevent to leave them in blocking mode. **`EventListener::OPT_CLOSE_ON_FREE`** If this option is set, the connection listener closes its underlying socket when the **EventListener** object is freed. **`EventListener::OPT_CLOSE_ON_EXEC`** If this option is set, the connection listener sets the close-on-exec flag on the underlying listener socket. See platform documentation for `fcntl` and **`FD_CLOEXEC`** for more information. **`EventListener::OPT_REUSEABLE`** By default on some platforms, once a listener socket is closed, no other socket can bind to the same port until a while has passed. Setting this option makes Libevent mark the socket as reusable, so that once it is closed, another socket can be opened to listen on the same port. **`EventListener::OPT_THREADSAFE`** Allocate locks for the listener, so that it’s safe to use it from multiple threads. Table of Contents ----------------- * [EventListener::\_\_construct](eventlistener.construct) — Creates new connection listener associated with an event base * [EventListener::disable](eventlistener.disable) — Disables an event connect listener object * [EventListener::enable](eventlistener.enable) — Enables an event connect listener object * [EventListener::getBase](eventlistener.getbase) — Returns event base associated with the event listener * [EventListener::getSocketName](eventlistener.getsocketname) — Retreives the current address to which the listener's socket is bound * [EventListener::setCallback](eventlistener.setcallback) — The setCallback purpose * [EventListener::setErrorCallback](eventlistener.seterrorcallback) — Set event listener's error callback php EvTimer::again EvTimer::again ============== (PECL ev >= 0.2.0) EvTimer::again — Restarts the timer watcher ### Description ``` public EvTimer::again(): void ``` This will act as if the timer timed out and restart it again if it is repeating. The exact semantics are: 1. if the timer is pending, its pending status is cleared. 2. if the timer is started but non-repeating, stop it (as if it timed out). 3. if the timer is repeating, either start it if necessary (with the repeat value), or reset the running timer to the repeat value. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [EvWatcher::stop()](evwatcher.stop) - Stops the watcher php mysqli_report mysqli\_report ============== (PHP 5, PHP 7, PHP 8) mysqli\_report — Alias of [mysqli\_driver->report\_mode](mysqli-driver.report-mode) ### Description This function is an alias of: [mysqli\_driver->report\_mode](mysqli-driver.report-mode) php Yaf_Request_Abstract::isPost Yaf\_Request\_Abstract::isPost ============================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::isPost — Determine if request is POST request ### Description ``` public Yaf_Request_Abstract::isPost(): bool ``` ### Parameters This function has no parameters. ### Return Values boolean ### See Also * [Yaf\_Request\_Abstract::isGet()](yaf-request-abstract.isget) - Determine if request is GET request * [Yaf\_Request\_Abstract::isCli()](yaf-request-abstract.iscli) - Determine if request is CLI request * [Yaf\_Request\_Abstract::isHead()](yaf-request-abstract.ishead) - Determine if request is HEAD request * [Yaf\_Request\_Abstract::isPut()](yaf-request-abstract.isput) - Determine if request is PUT request * [Yaf\_Request\_Abstract::isOptions()](yaf-request-abstract.isoptions) - Determine if request is OPTIONS request * [Yaf\_Request\_Abstract::isXmlHTTPRequest()](yaf-request-abstract.isxmlhttprequest) - Determine if request is AJAX request php GearmanClient::setCompleteCallback GearmanClient::setCompleteCallback ================================== (PECL gearman >= 0.5.0) GearmanClient::setCompleteCallback — Set a function to be called on task completion ### Description ``` public GearmanClient::setCompleteCallback(callable $callback): bool ``` Use to set a function to be called when a [GearmanTask](class.gearmantask) is completed, or when [GearmanJob::sendComplete()](gearmanjob.sendcomplete) is invoked by a worker (whichever happens first). This callback executes only when executing a [GearmanTask](class.gearmantask) using [GearmanClient::runTasks()](gearmanclient.runtasks). It is not used for individual jobs. ### Parameters `callback` A function to be called ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanClient::setDataCallback()](gearmanclient.setdatacallback) - Callback function when there is a data packet for a task * [GearmanClient::setCreatedCallback()](gearmanclient.setcreatedcallback) - Set a callback for when a task is queued * [GearmanClient::setExceptionCallback()](gearmanclient.setexceptioncallback) - Set a callback for worker exceptions * [GearmanClient::setFailCallback()](gearmanclient.setfailcallback) - Set callback for job failure * [GearmanClient::setStatusCallback()](gearmanclient.setstatuscallback) - Set a callback for collecting task status * [GearmanClient::setWarningCallback()](gearmanclient.setwarningcallback) - Set a callback for worker warnings * [GearmanClient::setWorkloadCallback()](gearmanclient.setworkloadcallback) - Set a callback for accepting incremental data updates php The SolrUpdateResponse class The SolrUpdateResponse class ============================ Introduction ------------ (PECL solr >= 0.9.2) Represents a response to an update request. Class synopsis -------------- final class **SolrUpdateResponse** extends [SolrResponse](class.solrresponse) { /\* Constants \*/ const int [PARSE\_SOLR\_OBJ](class.solrupdateresponse#solrupdateresponse.constants.parse-solr-obj) = 0; const int [PARSE\_SOLR\_DOC](class.solrupdateresponse#solrupdateresponse.constants.parse-solr-doc) = 1; /\* Inherited properties \*/ const int [SolrResponse::PARSE\_SOLR\_OBJ](class.solrresponse#solrresponse.constants.parse-solr-obj) = 0; const int [SolrResponse::PARSE\_SOLR\_DOC](class.solrresponse#solrresponse.constants.parse-solr-doc) = 1; protected int [$http\_status](class.solrresponse#solrresponse.props.http-status); protected int [$parser\_mode](class.solrresponse#solrresponse.props.parser-mode); protected bool [$success](class.solrresponse#solrresponse.props.success); protected string [$http\_status\_message](class.solrresponse#solrresponse.props.http-status-message); protected string [$http\_request\_url](class.solrresponse#solrresponse.props.http-request-url); protected string [$http\_raw\_request\_headers](class.solrresponse#solrresponse.props.http-raw-request-headers); protected string [$http\_raw\_request](class.solrresponse#solrresponse.props.http-raw-request); protected string [$http\_raw\_response\_headers](class.solrresponse#solrresponse.props.http-raw-response-headers); protected string [$http\_raw\_response](class.solrresponse#solrresponse.props.http-raw-response); protected string [$http\_digested\_response](class.solrresponse#solrresponse.props.http-digested-response); /\* Methods \*/ public [\_\_construct](solrupdateresponse.construct)() public [\_\_destruct](solrupdateresponse.destruct)() /\* Inherited methods \*/ ``` public SolrResponse::getDigestedResponse(): string ``` ``` public SolrResponse::getHttpStatus(): int ``` ``` public SolrResponse::getHttpStatusMessage(): string ``` ``` public SolrResponse::getRawRequest(): string ``` ``` public SolrResponse::getRawRequestHeaders(): string ``` ``` public SolrResponse::getRawResponse(): string ``` ``` public SolrResponse::getRawResponseHeaders(): string ``` ``` public SolrResponse::getRequestUrl(): string ``` ``` public SolrResponse::getResponse(): SolrObject ``` ``` public SolrResponse::setParseMode(int $parser_mode = 0): bool ``` ``` public SolrResponse::success(): bool ``` } Predefined Constants -------------------- SolrUpdateResponse Class Constants ---------------------------------- **`SolrUpdateResponse::PARSE_SOLR_OBJ`** Documents should be parsed as SolrObject instances **`SolrUpdateResponse::PARSE_SOLR_DOC`** Documents should be parsed as SolrDocument instances. Table of Contents ----------------- * [SolrUpdateResponse::\_\_construct](solrupdateresponse.construct) — Constructor * [SolrUpdateResponse::\_\_destruct](solrupdateresponse.destruct) — Destructor php svn_fs_make_dir svn\_fs\_make\_dir ================== (PECL svn >= 0.2.0) svn\_fs\_make\_dir — Creates a new empty directory ### Description ``` svn_fs_make_dir(resource $root, string $path): bool ``` **Warning**This function is currently not documented; only its argument list is available. Creates a new empty directory. ### Parameters `root` `path` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php ReflectionFunctionAbstract::__toString ReflectionFunctionAbstract::\_\_toString ======================================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ReflectionFunctionAbstract::\_\_toString — To string ### Description ``` abstract public ReflectionFunctionAbstract::__toString(): void ``` To string. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The string. ### See Also * **ReflectionClass::clone()** * [\_\_toString()](language.oop5.magic#object.tostring) php ImagickPixelIterator::resetIterator ImagickPixelIterator::resetIterator =================================== (PECL imagick 2, PECL imagick 3) ImagickPixelIterator::resetIterator — Resets the pixel iterator ### Description ``` public ImagickPixelIterator::resetIterator(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Resets the pixel iterator. Use it in conjunction with ImagickPixelIterator::getNextIteratorRow() to iterate over all the pixels in a pixel container. ### Return Values Returns **`true`** on success. ### Examples **Example #1 **ImagickPixelIterator::resetIterator()**** ``` <?php function resetIterator($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imageIterator = $imagick->getPixelIterator();     /* Loop trough pixel rows */     foreach ($imageIterator as $pixels) {         /* Loop through the pixels in the row (columns) */         foreach ($pixels as $column => $pixel) {             /** @var $pixel \ImagickPixel */             if ($column % 2) {                 /* Make every second pixel 25% red*/                 $pixel->setColorValue(\Imagick::COLOR_RED, 64);              }         }         /* Sync the iterator, this is important to do on each iteration */         $imageIterator->syncIterator();     }     $imageIterator->resetiterator();     /* Loop trough pixel rows */     foreach ($imageIterator as $pixels) {         /* Loop through the pixels in the row (columns) */         foreach ($pixels as $column => $pixel) {             /** @var $pixel \ImagickPixel */             if ($column % 3) {                 $pixel->setColorValue(\Imagick::COLOR_BLUE, 64); /* Make every second pixel a little blue*/                 //$pixel->setColor("rgba(0, 0, 128, 0)"); /* Paint every second pixel black*/             }         }         $imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */     }     $imageIterator->clear();     header("Content-Type: image/jpg");     echo $imagick; } ?> ```
programming_docs
php xml_set_unparsed_entity_decl_handler xml\_set\_unparsed\_entity\_decl\_handler ========================================= (PHP 4, PHP 5, PHP 7, PHP 8) xml\_set\_unparsed\_entity\_decl\_handler — Set up unparsed entity declaration handler ### Description ``` xml_set_unparsed_entity_decl_handler(XMLParser $parser, callable $handler): bool ``` Sets the unparsed entity declaration handler function for the XML parser `parser`. The `handler` will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following: ``` <!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>} NDATA <parameter>notationName</parameter> ``` See [» section 4.2.2 of the XML 1.0 spec](http://www.w3.org/TR/1998/REC-xml-19980210#sec-external-ent) for the definition of notation declared external entities. ### Parameters `parser` A reference to the XML parser to set up unparsed entity declaration handler function. `handler` `handler` is a string containing the name of a function that must exist when [xml\_parse()](function.xml-parse) is called for `parser`. The function named by `handler` must accept six parameters: ``` handler( XMLParser $parser, string $entity_name, string $base, string $system_id, string $public_id, string $notation_name ) ``` `parser` The first parameter, parser, is a reference to the XML parser calling the handler. `entity_name` The name of the entity that is about to be defined. `base` This is the base for resolving the system identifier (`systemId`) of the external entity.Currently this parameter will always be set to an empty string. `system_id` System identifier for the external entity. `public_id` Public identifier for the external entity. `notation_name` Name of the notation of this entity (see [xml\_set\_notation\_decl\_handler()](function.xml-set-notation-decl-handler)). If a handler function is set to an empty string, or **`false`**, the handler in question is disabled. > **Note**: Instead of a function name, an array containing an object reference and a method name can also be supplied. > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `parser` expects an [XMLParser](class.xmlparser) instance now; previously, a resource was expected. | php Ds\Map::get Ds\Map::get =========== (PECL ds >= 1.0.0) Ds\Map::get — Returns the value for a given key ### Description ``` public Ds\Map::get(mixed $key, mixed $default = ?): mixed ``` Returns the value for a given key, or an optional default value if the key could not be found. > > **Note**: > > > Keys of type object are supported. If an object implements **Ds\Hashable**, equality will be determined by the object's `equals` function. If an object does not implement **Ds\Hashable**, objects must be references to the same instance to be considered equal. > > > > **Note**: > > > You can also use array syntax to access values by key, eg. `$map["key"]`. > > **Caution** Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, `$map["1"]` will attempt to access `int(1)`, while `$map->get("1")` will correctly look up the string key. See [Arrays](language.types.array). ### Parameters `key` The key to look up. `default` The optional default value, returned if the key could not be found. ### Return Values The value mapped to the given `key`, or the `default` value if provided and the key could not be found in the map. ### Errors/Exceptions [OutOfBoundsException](class.outofboundsexception) if the key could not be found and a default value was not provided. ### Examples **Example #1 **Ds\Map::get()** example** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); var_dump($map->get("a"));       // 1 var_dump($map->get("d", 10));   // 10 (default used) ?> ``` The above example will output something similar to: ``` int(1) int(10) ``` **Example #2 **Ds\Map::get()** example using array syntax** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); var_dump($map["a"]); // 1 ?> ``` The above example will output something similar to: ``` int(1) ``` php CompileError CompileError ============ Introduction ------------ (PHP 7 > 7.3.0, PHP 8) **CompileError** is thrown for some compilation errors, which formerly issued a fatal error. Class synopsis -------------- class **CompileError** extends [Error](class.error) { /\* Inherited properties \*/ protected string [$message](class.error#error.props.message) = ""; private string [$string](class.error#error.props.string) = ""; protected int [$code](class.error#error.props.code); protected string [$file](class.error#error.props.file) = ""; protected int [$line](class.error#error.props.line); private array [$trace](class.error#error.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.error#error.props.previous) = null; /\* Inherited methods \*/ ``` final public Error::getMessage(): string ``` ``` final public Error::getPrevious(): ?Throwable ``` ``` final public Error::getCode(): int ``` ``` final public Error::getFile(): string ``` ``` final public Error::getLine(): int ``` ``` final public Error::getTrace(): array ``` ``` final public Error::getTraceAsString(): string ``` ``` public Error::__toString(): string ``` ``` private Error::__clone(): void ``` } php None break ----- (PHP 4, PHP 5, PHP 7, PHP 8) `break` ends execution of the current `for`, `foreach`, `while`, `do-while` or `switch` structure. `break` accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is `1`, only the immediate enclosing structure is broken out of. ``` <?php $arr = array('one', 'two', 'three', 'four', 'stop', 'five'); foreach ($arr as $val) {     if ($val == 'stop') {         break;    /* You could also write 'break 1;' here. */     }     echo "$val<br />\n"; } /* Using the optional argument. */ $i = 0; while (++$i) {     switch ($i) {         case 5:             echo "At 5<br />\n";             break 1;  /* Exit only the switch. */         case 10:             echo "At 10; quitting<br />\n";             break 2;  /* Exit the switch and the while. */         default:             break;     } } ?> ``` php The SQLite3Stmt class The SQLite3Stmt class ===================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) A class that handles prepared statements for the SQLite 3 extension. Class synopsis -------------- class **SQLite3Stmt** { /\* Methods \*/ private [\_\_construct](sqlite3stmt.construct)([SQLite3](class.sqlite3) `$sqlite3`, string `$query`) ``` public bindParam(string|int $param, mixed &$var, int $type = SQLITE3_TEXT): bool ``` ``` public bindValue(string|int $param, mixed $value, int $type = SQLITE3_TEXT): bool ``` ``` public clear(): bool ``` ``` public close(): bool ``` ``` public execute(): SQLite3Result|false ``` ``` public getSQL(bool $expand = false): string|false ``` ``` public paramCount(): int ``` ``` public readOnly(): bool ``` ``` public reset(): bool ``` } Table of Contents ----------------- * [SQLite3Stmt::bindParam](sqlite3stmt.bindparam) — Binds a parameter to a statement variable * [SQLite3Stmt::bindValue](sqlite3stmt.bindvalue) — Binds the value of a parameter to a statement variable * [SQLite3Stmt::clear](sqlite3stmt.clear) — Clears all current bound parameters * [SQLite3Stmt::close](sqlite3stmt.close) — Closes the prepared statement * [SQLite3Stmt::\_\_construct](sqlite3stmt.construct) — Constructs an SQLite3Stmt object * [SQLite3Stmt::execute](sqlite3stmt.execute) — Executes a prepared statement and returns a result set object * [SQLite3Stmt::getSQL](sqlite3stmt.getsql) — Get the SQL of the statement * [SQLite3Stmt::paramCount](sqlite3stmt.paramcount) — Returns the number of parameters within the prepared statement * [SQLite3Stmt::readOnly](sqlite3stmt.readonly) — Returns whether a statement is definitely read only * [SQLite3Stmt::reset](sqlite3stmt.reset) — Resets the prepared statement php xhprof_enable xhprof\_enable ============== (PECL xhprof >= 0.9.0) xhprof\_enable — Start xhprof profiler ### Description ``` xhprof_enable(int $flags = 0, array $options = ?): void ``` Start xhprof profiling. ### Parameters `flags` Optional flags to add additional information to the profiling. See the [XHprof constants](https://www.php.net/manual/en/xhprof.constants.php) for further information about these flags, e.g., **`XHPROF_FLAGS_MEMORY`** to enable memory profiling. `options` An array of optional options, namely, the 'ignored\_functions' option to pass in functions to be ignored during profiling. ### Return Values **`null`** ### Changelog | Version | Description | | --- | --- | | PECL xhprof 0.9.2 | The optional `options` parameter was added. | ### Examples **Example #1 **xhprof\_enable()** examples** ``` <?php // 1. elapsed time + memory + CPU profiling; and ignore built-in (internal) functions xhprof_enable(XHPROF_FLAGS_NO_BUILTINS | XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY); // 2. elapsed time profiling; ignore call_user_func* during profiling xhprof_enable(     0,     array('ignored_functions' =>  array('call_user_func',                                         'call_user_func_array')));                                         // 3. elapsed time + memory profiling; ignore call_user_func* during profiling xhprof_enable(     XHPROF_FLAGS_MEMORY,     array('ignored_functions' =>  array('call_user_func',                                         'call_user_func_array'))); ?> ``` ### See Also * [xhprof\_disable()](function.xhprof-disable) - Stops xhprof profiler * [xhprof\_sample\_enable()](function.xhprof-sample-enable) - Start XHProf profiling in sampling mode * [memory\_get\_usage()](function.memory-get-usage) - Returns the amount of memory allocated to PHP * [getrusage()](function.getrusage) - Gets the current resource usages php uopz_unset_mock uopz\_unset\_mock ================= (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_unset\_mock — Unset previously set mock ### Description ``` uopz_unset_mock(string $class): void ``` Unsets the previously set mock for `class`. ### Parameters `class` The name of the mocked class. ### Return Values No value is returned. ### Errors/Exceptions A [RuntimeException](class.runtimeexception) is thrown, if no mock was previously set for `class`. ### Examples **Example #1 **uopz\_unset\_mock()** example** ``` <?php class A {     public static function who() {         echo "A";     } } class mockA {     public static function who() {         echo "mockA";     } } uopz_set_mock(A::class, mockA::class); uopz_unset_mock(A::class); A::who(); ?> ``` The above example will output: ``` A ``` ### See Also * [uopz\_set\_mock()](function.uopz-set-mock) - Use mock instead of class for new objects * [uopz\_get\_mock()](function.uopz-get-mock) - Get the current mock for a class php Imagick::getSamplingFactors Imagick::getSamplingFactors =========================== (PECL imagick 2, PECL imagick 3) Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor ### Description ``` public Imagick::getSamplingFactors(): array ``` Gets the horizontal and vertical sampling factor. ### Parameters This function has no parameters. ### Return Values Returns an associative array with the horizontal and vertical sampling factors of the image. ### Errors/Exceptions Throws ImagickException on error. php GearmanTask::__construct GearmanTask::\_\_construct ========================== (PECL gearman >= 0.5.0) GearmanTask::\_\_construct — Create a GearmanTask instance ### Description ``` public GearmanTask::__construct() ``` Creates a [GearmanTask](class.gearmantask) instance representing a task to be submitted to a job server. ### Parameters This function has no parameters. ### Return Values A [GearmanTask](class.gearmantask) object. php UConverter::toUCallback UConverter::toUCallback ======================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) UConverter::toUCallback — Default "to" callback function ### Description ``` public UConverter::toUCallback( int $reason, string $source, string $codeUnits, int &$error ): string|int|array|null ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `reason` `source` `codeUnits` `error` ### Return Values php fileinode fileinode ========= (PHP 4, PHP 5, PHP 7, PHP 8) fileinode — Gets file inode ### Description ``` fileinode(string $filename): int|false ``` Gets the file inode. ### Parameters `filename` Path to the file. ### Return Values Returns the inode number of the file, or **`false`** on failure. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 Comparing the inode of a file with the current file** ``` <?php $filename = 'index.php'; if (getmyinode() == fileinode($filename)) {     echo 'You are checking the current file.'; } ?> ``` ### Notes > **Note**: The results of this function are cached. See [clearstatcache()](function.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](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality. ### See Also * [getmyinode()](function.getmyinode) - Gets the inode of the current script * [stat()](function.stat) - Gives information about a file php SolrQuery::getMltCount SolrQuery::getMltCount ====================== (PECL solr >= 0.9.2) SolrQuery::getMltCount — Returns the number of similar documents to return for each result ### Description ``` public SolrQuery::getMltCount(): int ``` Returns the number of similar documents to return for each result ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php WeakReference::get WeakReference::get ================== (PHP 7 >= 7.4.0, PHP 8) WeakReference::get — Get a weakly referenced Object ### Description ``` public WeakReference::get(): ?object ``` Gets a weakly referenced object. If the object has already been destroyed, **`null`** is returned. ### Parameters This function has no parameters. ### Return Values Returns the referenced object, or **`null`** if the object has been destroyed. php SolrModifiableParams::__destruct SolrModifiableParams::\_\_destruct ================================== (PECL solr >= 0.9.2) SolrModifiableParams::\_\_destruct — Destructor ### Description public **SolrModifiableParams::\_\_destruct**() Destructor ### Parameters This function has no parameters. ### Return Values None php ZipArchive::getExternalAttributesIndex ZipArchive::getExternalAttributesIndex ====================================== (PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4) ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index ### Description ``` public ZipArchive::getExternalAttributesIndex( int $index, int &$opsys, int &$attr, int $flags = 0 ): bool ``` Retrieve the external attributes of an entry defined by its index. ### Parameters `index` Index of the entry. `opsys` On success, receive the operating system code defined by one of the ZipArchive::OPSYS\_ constants. `attr` On success, receive the external attributes. Value depends on operating system. `flags` If flags is set to **`ZipArchive::FL_UNCHANGED`**, the original unchanged attributes are returned. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples This example extract all the entries of a ZIP archive test.zip and set the Unix rights from external attributes. **Example #1 Extract all entries with Unix rights** ``` <?php $zip = new ZipArchive(); if ($zip->open('test.zip') === TRUE) {     for ($idx=0 ; $s = $zip->statIndex($idx) ; $idx++) {         if ($zip->extractTo('.', $s['name'])) {             if ($zip->getExternalAttributesIndex($idx, $opsys, $attr)                  && $opsys==ZipArchive::OPSYS_UNIX) {                chmod($s['name'], ($attr >> 16) & 0777);             }         }     }     $zip->close();     echo "Ok\n"; } else {     echo "KO\n"; } ?> ``` php None Attribute syntax ---------------- There are several parts to the attributes syntax. First, an attribute declaration is always enclosed with a starting `#[` and a corresponding ending `]`. Inside, one or many attributes are listed, separated by comma. The attribute name is an unqualified, qualified or fully-qualified name as described in [Using Namespaces Basics](language.namespaces.basics). Arguments to the attribute are optional, but are enclosed in the usual parenthesis `()`. Arguments to attributes can only be literal values or constant expressions. Both positional and named arguments syntax can be used. Attribute names and their arguments are resolved to a class and the arguments are passed to its constructor, when an instance of the attribute is requested through the Reflection API. As such a class should be introduced for each attribute. **Example #1 Attribute Syntax** ``` <?php // a.php namespace MyExample; use Attribute; #[Attribute] class MyAttribute {     const VALUE = 'value';     private $value;     public function __construct($value = null)     {         $this->value = $value;     } } // b.php namespace Another; use MyExample\MyAttribute; #[MyAttribute] #[\MyExample\MyAttribute] #[MyAttribute(1234)] #[MyAttribute(value: 1234)] #[MyAttribute(MyAttribute::VALUE)] #[MyAttribute(array("key" => "value"))] #[MyAttribute(100 + 200)] class Thing { } #[MyAttribute(1234), MyAttribute(5678)] class AnotherThing { } ``` php SolrQuery::setFacetPrefix SolrQuery::setFacetPrefix ========================= (PECL solr >= 0.9.2) SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet ### Description ``` public SolrQuery::setFacetPrefix(string $prefix, string $field_override = ?): SolrQuery ``` Specifies a string prefix with which to limits the terms on which to facet. ### Parameters `prefix` The prefix string `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php SolrQuery::getFacet SolrQuery::getFacet =================== (PECL solr >= 0.9.2) SolrQuery::getFacet — Returns the value of the facet parameter ### Description ``` public SolrQuery::getFacet(): bool ``` Returns the value of the facet parameter. ### Parameters This function has no parameters. ### Return Values Returns a boolean on success and **`null`** if not set php The PDO class The PDO class ============= Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0) Represents a connection between PHP and a database server. Class synopsis -------------- class **PDO** { /\* Methods \*/ public [\_\_construct](pdo.construct)( string `$dsn`, ?string `$username` = **`null`**, ?string `$password` = **`null`**, ?array `$options` = **`null`** ) ``` public beginTransaction(): bool ``` ``` public commit(): bool ``` ``` public errorCode(): ?string ``` ``` public errorInfo(): array ``` ``` public exec(string $statement): int|false ``` ``` public getAttribute(int $attribute): mixed ``` ``` public static getAvailableDrivers(): array ``` ``` public inTransaction(): bool ``` ``` public lastInsertId(?string $name = null): string|false ``` ``` public prepare(string $query, array $options = []): PDOStatement|false ``` ``` public query(string $query, ?int $fetchMode = null): PDOStatement|false ``` ``` public query(string $query, ?int $fetchMode = PDO::FETCH_COLUMN, int $colno): PDOStatement|false ``` ``` public query( string $query, ?int $fetchMode = PDO::FETCH_CLASS, string $classname, array $constructorArgs ): PDOStatement|false ``` ``` public query(string $query, ?int $fetchMode = PDO::FETCH_INTO, object $object): PDOStatement|false ``` ``` public quote(string $string, int $type = PDO::PARAM_STR): string|false ``` ``` public rollBack(): bool ``` ``` public setAttribute(int $attribute, mixed $value): bool ``` } Table of Contents ----------------- * [PDO::beginTransaction](pdo.begintransaction) — Initiates a transaction * [PDO::commit](pdo.commit) — Commits a transaction * [PDO::\_\_construct](pdo.construct) — Creates a PDO instance representing a connection to a database * [PDO::errorCode](pdo.errorcode) — Fetch the SQLSTATE associated with the last operation on the database handle * [PDO::errorInfo](pdo.errorinfo) — Fetch extended error information associated with the last operation on the database handle * [PDO::exec](pdo.exec) — Execute an SQL statement and return the number of affected rows * [PDO::getAttribute](pdo.getattribute) — Retrieve a database connection attribute * [PDO::getAvailableDrivers](pdo.getavailabledrivers) — Return an array of available PDO drivers * [PDO::inTransaction](pdo.intransaction) — Checks if inside a transaction * [PDO::lastInsertId](pdo.lastinsertid) — Returns the ID of the last inserted row or sequence value * [PDO::prepare](pdo.prepare) — Prepares a statement for execution and returns a statement object * [PDO::query](pdo.query) — Prepares and executes an SQL statement without placeholders * [PDO::quote](pdo.quote) — Quotes a string for use in a query * [PDO::rollBack](pdo.rollback) — Rolls back a transaction * [PDO::setAttribute](pdo.setattribute) — Set an attribute
programming_docs
php SplHeap::next SplHeap::next ============= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplHeap::next — Move to the next node ### Description ``` public SplHeap::next(): void ``` Move to the next node. This will delete the top node of the heap. ### Parameters This function has no parameters. ### Return Values No value is returned. php basename basename ======== (PHP 4, PHP 5, PHP 7, PHP 8) basename — Returns trailing name component of path ### Description ``` basename(string $path, string $suffix = ""): string ``` Given a string containing the path to a file or directory, this function will return the trailing name component. > > **Note**: > > > **basename()** operates naively on the input string, and is not aware of the actual filesystem, or path components such as "`..`". > > **Caution** **basename()** is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the [setlocale()](function.setlocale) function. If `path` contains characters which are invalid for the current locale, the behavior of **basename()** is undefined. ### Parameters `path` A path. On Windows, both slash (`/`) and backslash (`\`) are used as directory separator character. In other environments, it is the forward slash (`/`). `suffix` If the name component ends in `suffix` this will also be cut off. ### Return Values Returns the base name of the given `path`. ### Examples **Example #1 **basename()** example** ``` <?php echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL; echo "2) ".basename("/etc/sudoers.d").PHP_EOL; echo "3) ".basename("/etc/passwd").PHP_EOL; echo "4) ".basename("/etc/").PHP_EOL; echo "5) ".basename(".").PHP_EOL; echo "6) ".basename("/"); ?> ``` The above example will output: ``` 1) sudoers 2) sudoers.d 3) passwd 4) etc 5) . 6) ``` ### See Also * [dirname()](function.dirname) - Returns a parent directory's path * [pathinfo()](function.pathinfo) - Returns information about a file path php mcrypt_module_get_supported_key_sizes mcrypt\_module\_get\_supported\_key\_sizes ========================================== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_module\_get\_supported\_key\_sizes — Returns an array with the supported keysizes of the opened algorithm **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_module_get_supported_key_sizes(string $algorithm, string $lib_dir = ?): array ``` Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and [mcrypt\_module\_get\_algo\_key\_size()](function.mcrypt-module-get-algo-key-size) are supported by the algorithm. ### Parameters `algorithm` The algorithm to be used. `lib_dir` The optional `lib_dir` parameter can contain the location where the algorithm module is on the system. ### Return Values Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and [mcrypt\_module\_get\_algo\_key\_size()](function.mcrypt-module-get-algo-key-size) are supported by the algorithm. ### See Also * [mcrypt\_enc\_get\_supported\_key\_sizes()](function.mcrypt-enc-get-supported-key-sizes) - Returns an array with the supported keysizes of the opened algorithm php pg_num_rows pg\_num\_rows ============= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_num\_rows — Returns the number of rows in a result ### Description ``` pg_num_rows(PgSql\Result $result): int ``` **pg\_num\_rows()** will return the number of rows in an [PgSql\Result](class.pgsql-result) instance. > > **Note**: > > > This function used to be called **pg\_numrows()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). ### Return Values The number of rows in the result. On error, `-1` is returned. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_num\_rows()** example** ``` <?php $result = pg_query($conn, "SELECT 1"); $rows = pg_num_rows($result); echo $rows . " row(s) returned.\n"; ?> ``` The above example will output: ``` 1 row(s) returned. ``` ### See Also * [pg\_num\_fields()](function.pg-num-fields) - Returns the number of fields in a result * [pg\_affected\_rows()](function.pg-affected-rows) - Returns number of affected records (tuples) php mcrypt_module_close mcrypt\_module\_close ===================== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_module\_close — Closes the mcrypt module **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_module_close(resource $td): bool ``` Closes the specified encryption handle. ### Parameters `td` The encryption descriptor. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [mcrypt\_module\_open()](function.mcrypt-module-open) - Opens the module of the algorithm and the mode to be used php EvLoop::io EvLoop::io ========== (PECL ev >= 0.2.0) EvLoop::io — Create EvIo watcher object associated with the current event loop instance ### Description ``` final public EvLoop::io( mixed $fd , int $events , callable $callback , mixed $data = null , int $priority = 0 ): EvIo ``` Create EvIo watcher object associated with the current event loop instance. ### Parameters All parameters have the same meaning as for [EvIo::\_\_construct()](evio.construct) ### Return Values Returns EvIo object on success. ### See Also * [EvIo::\_\_construct()](evio.construct) - Constructs EvIo watcher object php openssl_x509_checkpurpose openssl\_x509\_checkpurpose =========================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) openssl\_x509\_checkpurpose — Verifies if a certificate can be used for a particular purpose ### Description ``` openssl_x509_checkpurpose( OpenSSLCertificate|string $certificate, int $purpose, array $ca_info = [], ?string $untrusted_certificates_file = null ): bool|int ``` **openssl\_x509\_checkpurpose()** examines a certificate to see if it can be used for the specified `purpose`. ### Parameters `certificate` The examined certificate. `purpose` ****openssl\_x509\_checkpurpose()** purposes**| Constant | Description | | --- | --- | | X509\_PURPOSE\_SSL\_CLIENT | Can the certificate be used for the client side of an SSL connection? | | X509\_PURPOSE\_SSL\_SERVER | Can the certificate be used for the server side of an SSL connection? | | X509\_PURPOSE\_NS\_SSL\_SERVER | Can the cert be used for Netscape SSL server? | | X509\_PURPOSE\_SMIME\_SIGN | Can the cert be used to sign S/MIME email? | | X509\_PURPOSE\_SMIME\_ENCRYPT | Can the cert be used to encrypt S/MIME email? | | X509\_PURPOSE\_CRL\_SIGN | Can the cert be used to sign a certificate revocation list (CRL)? | | X509\_PURPOSE\_ANY | Can the cert be used for Any/All purposes? | These options are not bitfields - you may specify one only! `ca_info` `ca_info` should be an array of trusted CA files/dirs as described in [Certificate Verification](https://www.php.net/manual/en/openssl.cert.verification.php). `untrusted_certificates_file` If specified, this should be the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust is placed in the certificates that come from that file. ### Return Values Returns **`true`** if the certificate can be used for the intended purpose, **`false`** if it cannot, or -1 on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was accepted. | | 8.0.0 | `untrusted_certificates_file` is nullable now. | php Gmagick::getimageblueprimary Gmagick::getimageblueprimary ============================ (PECL gmagick >= Unknown) Gmagick::getimageblueprimary — Returns the chromaticy blue primary point ### Description ``` public Gmagick::getimageblueprimary(): array ``` Returns the chromaticity blue primary point for the image. ### Parameters `x` The chromaticity blue primary x-point. `y` The chromaticity blue primary y-point. ### Return Values Array consisting of "x" and "y" coordinates of point. ### Errors/Exceptions Throws an **GmagickException** on error. php Imagick::getImageChannelDepth Imagick::getImageChannelDepth ============================= (PECL imagick 2, PECL imagick 3) Imagick::getImageChannelDepth — Gets the depth for a particular image channel ### Description ``` public Imagick::getImageChannelDepth(int $channel): int ``` Gets the depth for a particular image channel. ### Parameters `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) using bitwise operators. Defaults to **`Imagick::CHANNEL_DEFAULT`**. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) ### Return Values Returns **`true`** on success. php DateTimeImmutable::createFromMutable DateTimeImmutable::createFromMutable ==================================== (PHP 5 >= 5.6.0, PHP 7, PHP 8) DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable instance encapsulating the given DateTime object ### Description ``` public static DateTimeImmutable::createFromMutable(DateTime $object): static ``` ### Parameters `object` The mutable [DateTime](class.datetime) object that you want to convert to an immutable version. This object is not modified, but instead a new [DateTimeImmutable](class.datetimeimmutable) instance is created containing the same date time and timezone information. ### Return Values Returns a new [DateTimeImmutable](class.datetimeimmutable) instance. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | The method returns an instance of the currently invoked class now. Previously, it created a new instance of [DateTimeImmutable](class.datetimeimmutable). | ### Examples **Example #1 Creating an immutable date time object** ``` <?php $date = new DateTime("2014-06-20 11:45 Europe/London"); $immutable = DateTimeImmutable::createFromMutable( $date ); ?> ``` php ReflectionParameter::getDefaultValueConstantName ReflectionParameter::getDefaultValueConstantName ================================================ (PHP 5 >= 5.4.6, PHP 7, PHP 8) ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null ### Description ``` public ReflectionParameter::getDefaultValueConstantName(): ?string ``` Returns the default value's constant name of the parameter of any user-defined or internal function or method, if default value is constant or null. If the parameter is not optional a [ReflectionException](class.reflectionexception) will be thrown. ### Parameters This function has no parameters. ### Return Values Returns string on success or **`null`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This method now allows getting the default values' constant names of built-in functions and built-in class methods. Previously, a [ReflectionException](class.reflectionexception) was thrown. | ### Examples **Example #1 Getting default values' constant names of function parameters** ``` <?php function foo($test, $bar = PHP_INT_MIN) {     echo $test . $bar; } $function = new ReflectionFunction('foo'); foreach ($function->getParameters() as $param) {     echo 'Name: ' . $param->getName() . PHP_EOL;     if ($param->isOptional()) {         echo 'Default value: ' . $param->getDefaultValueConstantName() . PHP_EOL;     }     echo PHP_EOL; } ?> ``` The above example will output: ``` Name: test Name: bar Default value: PHP_INT_MIN ``` ### See Also * [ReflectionParameter::isOptional()](reflectionparameter.isoptional) - Checks if optional * [ReflectionParameter::isDefaultValueConstant()](reflectionparameter.isdefaultvalueconstant) - Returns whether the default value of this parameter is a constant * [ReflectionParameter::getDefaultValue()](reflectionparameter.getdefaultvalue) - Gets default parameter value php imagedestroy imagedestroy ============ (PHP 4, PHP 5, PHP 7, PHP 8) imagedestroy — Destroy an image ### Description ``` imagedestroy(GdImage $image): bool ``` > > **Note**: > > > This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource. > > Prior to PHP 8.0.0, **imagedestroy()** freed any memory associated with image `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function is a NOP now. | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Using **imagedestroy()** prior to PHP 8.0.0** ``` <?php // create a 100 x 100 image $im = imagecreatetruecolor(100, 100); // alter or save the image // frees image from memory imagedestroy($im); ?> ``` php filegroup filegroup ========= (PHP 4, PHP 5, PHP 7, PHP 8) filegroup — Gets file group ### Description ``` filegroup(string $filename): int|false ``` Gets the file group. The group ID is returned in numerical format, use [posix\_getgrgid()](function.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()](function.posix-getgrgid) to resolve it to a group name. Upon failure, **`false`** is returned. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 Finding the group of a file** ``` <?php $filename = 'index.php'; print_r(posix_getgrgid(filegroup($filename))); ?> ``` ### Notes > **Note**: The results of this function are cached. See [clearstatcache()](function.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](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality. ### See Also * [fileowner()](function.fileowner) - Gets file owner * [posix\_getgrgid()](function.posix-getgrgid) - Return info about a group by group id php Collator::sort Collator::sort ============== collator\_sort ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Collator::sort -- collator\_sort — Sort array using specified collator ### Description Object-oriented style ``` public Collator::sort(array &$array, int $flags = Collator::SORT_REGULAR): bool ``` Procedural style ``` collator_sort(Collator $object, array &$array, int $flags = Collator::SORT_REGULAR): bool ``` This function sorts an array according to current locale rules. Equivalent to standard PHP [sort()](function.sort) . ### Parameters `object` [Collator](class.collator) object. `array` Array of strings to sort. `flags` Optional sorting type, one of the following: * **`Collator::SORT_REGULAR`** - compare items normally (don't change types) * **`Collator::SORT_NUMERIC`** - compare items numerically * **`Collator::SORT_STRING`** - compare items as strings Default sorting type is **`Collator::SORT_REGULAR`**. It is also used if an invalid `flags` value has been specified. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **collator\_sort()** example** ``` <?php $coll = collator_create( 'en_US' ); $arr  = array( 'at', 'às', 'as' ); var_export( $arr ); collator_sort( $coll, $arr ); var_export( $arr ); ?> ``` The above example will output: ``` array ( 0 => 'at', 1 => 'às', 2 => 'as', )array ( 0 => 'as', 1 => 'às', 2 => 'at', ) ``` ### See Also * [[Collator](class.collator) constants](class.collator#intl.collator-constants) * [collator\_asort()](collator.asort) - Sort array maintaining index association * [collator\_sort\_with\_sort\_keys()](collator.sortwithsortkeys) - Sort array using specified collator and sort keys php ibase_close ibase\_close ============ (PHP 5, PHP 7 < 7.4.0) ibase\_close — Close a connection to an InterBase database ### Description ``` ibase_close(resource $connection_id = null): bool ``` Closes the link to an InterBase database that's associated with a connection id returned from [ibase\_connect()](function.ibase-connect). Default transaction on link is committed, other transactions are rolled back. ### Parameters `connection_id` An InterBase link identifier returned from [ibase\_connect()](function.ibase-connect). If omitted, the last opened link is assumed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [ibase\_connect()](function.ibase-connect) - Open a connection to a database * [ibase\_pconnect()](function.ibase-pconnect) - Open a persistent connection to an InterBase database php grapheme_strstr grapheme\_strstr ================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) grapheme\_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack ### Description Procedural style ``` grapheme_strstr(string $haystack, string $needle, bool $beforeNeedle = false): string|false ``` Returns part of haystack string from the first occurrence of needle to the end of haystack (including the needle). ### Parameters `haystack` The input string. Must be valid UTF-8. `needle` The string to look for. Must be valid UTF-8. `beforeNeedle` If **`true`**, **grapheme\_strstr()** returns the part of the `haystack` before the first occurrence of the `needle` (excluding the `needle`). ### Return Values Returns the portion of `haystack`, or **`false`** if `needle` is not found. ### Examples **Example #1 **grapheme\_strstr()** example** ``` <?php $char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D" $char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D" print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_o_diaeresis_nfd)); ?> ``` The above example will output: ``` o%CC%88a%CC%8A ``` ### See Also * [grapheme\_stristr()](function.grapheme-stristr) - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack * [grapheme\_stripos()](function.grapheme-stripos) - Find position (in grapheme units) of first occurrence of a case-insensitive string * [grapheme\_strpos()](function.grapheme-strpos) - Find position (in grapheme units) of first occurrence of a string * [grapheme\_strripos()](function.grapheme-strripos) - Find position (in grapheme units) of last occurrence of a case-insensitive string * [grapheme\_strrpos()](function.grapheme-strrpos) - Find position (in grapheme units) of last occurrence of a string * [» Unicode Text Segmentation: Grapheme Cluster Boundaries](http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
programming_docs
php wincache_ocache_meminfo wincache\_ocache\_meminfo ========================= (PECL wincache >= 1.0.0) wincache\_ocache\_meminfo — Retrieves information about opcode cache memory usage ### Description ``` wincache_ocache_meminfo(): array|false ``` Retrieves information about memory usage by opcode cache. ### Parameters This function has no parameters. ### Return Values Array of meta data about opcode cache memory usage or **`false`** on failure The array returned by this function contains the following elements: * `memory_total` - amount of memory in bytes allocated for the opcode cache * `memory_free` - amount of free memory in bytes available for the opcode cache * `num_used_blks` - number of memory blocks used by the opcode cache * `num_free_blks` - number of free memory blocks available for the opcode cache * `memory_overhead` - amount of memory in bytes used for the opcode cache internal structures **Warning**This function was *REMOVED* in PHP 7.0.0. ### Examples **Example #1 A **wincache\_ocache\_meminfo()** example** ``` <pre> <?php print_r(wincache_ocache_meminfo()); ?> </pre> ``` The above example will output: ``` Array ( [memory_total] => 134217728 [memory_free] => 112106972 [num_used_blks] => 15469 [num_free_blks] => 4 [memory_overhead] => 247600 ) ``` ### See Also * [wincache\_fcache\_fileinfo()](function.wincache-fcache-fileinfo) - Retrieves information about files cached in the file cache * [wincache\_fcache\_meminfo()](function.wincache-fcache-meminfo) - Retrieves information about file cache memory usage * [wincache\_ocache\_fileinfo()](function.wincache-ocache-fileinfo) - Retrieves information about files cached in the opcode cache * [wincache\_rplist\_fileinfo()](function.wincache-rplist-fileinfo) - Retrieves information about resolve file path cache * [wincache\_rplist\_meminfo()](function.wincache-rplist-meminfo) - Retrieves information about memory usage by the resolve file path cache * [wincache\_refresh\_if\_changed()](function.wincache-refresh-if-changed) - Refreshes the cache entries for the cached files * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache * [wincache\_scache\_info()](function.wincache-scache-info) - Retrieves information about files cached in the session cache * [wincache\_scache\_meminfo()](function.wincache-scache-meminfo) - Retrieves information about session cache memory usage php ssh2_auth_password ssh2\_auth\_password ==================== (PECL ssh2 >= 0.9.0) ssh2\_auth\_password — Authenticate over SSH using a plain password ### Description ``` ssh2_auth_password(resource $session, string $username, string $password): bool ``` Authenticate over SSH using a plain password. Since version 0.12 this function also supports keyboard\_interactive method. ### Parameters `session` An SSH connection link identifier, obtained from a call to [ssh2\_connect()](function.ssh2-connect). `username` Remote user name. `password` Password for `username` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Authenticating with a password** ``` <?php $connection = ssh2_connect('shell.example.com', 22); if (ssh2_auth_password($connection, 'username', 'secret')) {   echo "Authentication Successful!\n"; } else {   die('Authentication Failed...'); } ?> ``` php Yaf_Request_Abstract::getParam Yaf\_Request\_Abstract::getParam ================================ (Yaf >=1.0.0) Yaf\_Request\_Abstract::getParam — Retrieve calling parameter ### Description ``` public Yaf_Request_Abstract::getParam(string $name, string $default = ?): mixed ``` ### Parameters `name` `default` ### Return Values ### See Also * [Yaf\_Request\_Abstract::setParam()](yaf-request-abstract.setparam) - Set a calling parameter to a request php IntlCalendar::getLocale IntlCalendar::getLocale ======================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getLocale — Get the locale associated with the object ### Description Object-oriented style ``` public IntlCalendar::getLocale(int $type): string|false ``` Procedural style ``` intlcal_get_locale(IntlCalendar $calendar, int $type): string|false ``` Returns the locale used by this calendar object. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `type` Whether to fetch the actual locale (the locale from which the calendar data originates, with **`Locale::ACTUAL_LOCALE`**) or the valid locale, i.e., the most specific locale supported by ICU relatively to the requested locale – see **`Locale::VALID_LOCALE`**. From the most general to the most specific, the locales are ordered in this fashion – actual locale, valid locale, requested locale. ### Return Values A locale string or **`false`** on failure. ### Examples **Example #1 **IntlCalendar::getLocale()**** ``` <?php $cal = IntlCalendar::createInstance(IntlTimeZone::getGMT(), 'en_US_CALIFORNIA'); var_dump(     $cal->getLocale(Locale::ACTUAL_LOCALE),     $cal->getLocale(Locale::VALID_LOCALE) ); ``` The above example will output: ``` string(2) "en" string(5) "en_US" ``` php RecursiveTreeIterator::__construct RecursiveTreeIterator::\_\_construct ==================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::\_\_construct — Construct a RecursiveTreeIterator ### Description public **RecursiveTreeIterator::\_\_construct**( [RecursiveIterator](class.recursiveiterator)|[IteratorAggregate](class.iteratoraggregate) `$iterator`, int `$flags` = RecursiveTreeIterator::BYPASS\_KEY, int `$cachingIteratorFlags` = CachingIterator::CATCH\_GET\_CHILD, int `$mode` = RecursiveTreeIterator::SELF\_FIRST ) Constructs a new [RecursiveTreeIterator](class.recursivetreeiterator) from the supplied recursive iterator. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `iterator` The [RecursiveIterator](class.recursiveiterator) or [IteratorAggregate](class.iteratoraggregate) to iterate over. `flags` Flags may be provided which will affect the behavior of some methods. A list of the flags can found under [RecursiveTreeIterator predefined constants](class.recursivetreeiterator#recursivetreeiterator.constants). `caching_it_flags` Flags to affect the behavior of the [RecursiveCachingIterator](class.recursivecachingiterator) used internally. `mode` Flags to affect the behavior of the [RecursiveIteratorIterator](class.recursiveiteratoriterator) used internally. php imageaffinematrixconcat imageaffinematrixconcat ======================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) imageaffinematrixconcat — Concatenate two affine transformation matrices ### Description ``` imageaffinematrixconcat(array $matrix1, array $matrix2): array|false ``` Returns the concatenation of two affine transformation matrices, what is useful if multiple transformations should be applied to the same image in one go. ### Parameters `matrix1` An affine transformation matrix (an array with keys `0` to `5` and float values). `matrix2` An affine transformation matrix (an array with keys `0` to `5` and float values). ### Return Values An affine transformation matrix (an array with keys `0` to `5` and float values) or **`false`** on failure. ### Examples **Example #1 **imageaffinematrixconcat()** example** ``` <?php $m1 = imageaffinematrixget(IMG_AFFINE_TRANSLATE, array('x' => 2, 'y' => 3)); $m2 = imageaffinematrixget(IMG_AFFINE_SCALE, array('x' => 4, 'y' => 5)); $matrix = imageaffinematrixconcat($m1, $m2); print_r($matrix); ?> ``` The above example will output: ``` Array ( [0] => 4 [1] => 0 [2] => 0 [3] => 5 [4] => 8 [5] => 15 ) ``` ### See Also * [imageaffine()](function.imageaffine) - Return an image containing the affine transformed src image, using an optional clipping area * [imageaffinematrixget()](function.imageaffinematrixget) - Get an affine transformation matrix php getmyuid getmyuid ======== (PHP 4, PHP 5, PHP 7, PHP 8) getmyuid — Gets PHP script owner's UID ### Description ``` getmyuid(): int|false ``` Gets the user ID of the current script. ### Parameters This function has no parameters. ### Return Values Returns the user ID of the current script, or **`false`** on error. ### See Also * [getmygid()](function.getmygid) - Get PHP script owner's GID * [getmypid()](function.getmypid) - Gets PHP's process ID * [get\_current\_user()](function.get-current-user) - Gets the name of the owner of the current PHP script * [getmyinode()](function.getmyinode) - Gets the inode of the current script * [getlastmod()](function.getlastmod) - Gets time of last page modification php SolrObject::offsetGet SolrObject::offsetGet ===================== (PECL solr >= 0.9.2) SolrObject::offsetGet — Used to retrieve a property ### Description ``` public SolrObject::offsetGet(string $property_name): mixed ``` Used to get the value of a property. This is used when the object is treated as an array. ### Parameters `property_name` Name of the property. ### Return Values Returns the property value. php SplObjectStorage::getHash SplObjectStorage::getHash ========================= (PHP 5 >= 5.4.0, PHP 7, PHP 8) SplObjectStorage::getHash — Calculate a unique identifier for the contained objects ### Description ``` public SplObjectStorage::getHash(object $object): string ``` This method calculates an identifier for the objects added to an [SplObjectStorage](class.splobjectstorage) object. The implementation in [SplObjectStorage](class.splobjectstorage) returns the same value as [spl\_object\_hash()](function.spl-object-hash). The storage object will never contain more than one object with the same identifier. As such, it can be used to implement a set (a collection of unique values) where the quality of an object being unique is determined by the value returned by this function being unique. ### Parameters `object` The object whose identifier is to be calculated. ### Return Values A string with the calculated identifier. ### Errors/Exceptions A [RuntimeException](class.runtimeexception) is thrown when the returned value is not a string. ### Examples **Example #1 **SplObjectStorage::getHash()** example** ``` <?php class OneSpecimenPerClassStorage extends SplObjectStorage {     public function getHash($o) {         return get_class($o);     } } class A {} $s = new OneSpecimenPerClassStorage; $o1 = new stdClass; $o2 = new stdClass; $o3 = new A; $s[$o1] = 1; //$o2 is considered equal to $o1 so the value is replaced $s[$o2] = 2; $s[$o3] = 3; //these are considered equal to the objects before //so they can be used to access the values stored under them $p1 = new stdClass; $p2 = new A; echo $s[$p1], "\n"; echo $s[$p2], "\n"; ?> ``` The above example will output something similar to: ``` 2 3 ``` ### See Also * [spl\_object\_hash()](function.spl-object-hash) - Return hash id for given object php OAuth::setRequestEngine OAuth::setRequestEngine ======================= (PECL OAuth >= 1.0.0) OAuth::setRequestEngine — The setRequestEngine purpose ### Description ``` public OAuth::setRequestEngine(int $reqengine): void ``` Sets the Request Engine, that will be sending the HTTP requests. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `reqengine` The desired request engine. Set to **`OAUTH_REQENGINE_STREAMS`** to use PHP Streams, or **`OAUTH_REQENGINE_CURL`** to use [Curl](https://www.php.net/manual/en/book.curl.php). ### Return Values No value is returned. ### Errors/Exceptions Emits an [OAuthException](class.oauthexception) exception if an invalid request engine is chosen. ### Examples **Example #1 **OAuth::setRequestEngine()** example** ``` <?php $consumer = new OAuth(); $consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS); ?> ``` ### See Also * [Curl](https://www.php.net/manual/en/book.curl.php) * [PHP streams](https://www.php.net/manual/en/book.stream.php) * [OAuthException](class.oauthexception) php radius_server_secret radius\_server\_secret ====================== (PECL radius >= 1.1.0) radius\_server\_secret — Returns the shared secret ### Description ``` radius_server_secret(resource $radius_handle): string ``` The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys. ### Parameters `radius_handle` The RADIUS resource. ### Return Values Returns the server's shared secret as string, or **`false`** on error. php svn_fs_node_prop svn\_fs\_node\_prop =================== (PECL svn >= 0.1.0) svn\_fs\_node\_prop — Returns the value of a property for a node ### Description ``` svn_fs_node_prop(resource $fsroot, string $path, string $propname): string ``` **Warning**This function is currently not documented; only its argument list is available. Returns the value of a property for a node ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php imagecopyresized imagecopyresized ================ (PHP 4, PHP 5, PHP 7, PHP 8) imagecopyresized — Copy and resize part of an image ### Description ``` imagecopyresized( GdImage $dst_image, GdImage $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_width, int $dst_height, int $src_width, int $src_height ): bool ``` **imagecopyresized()** copies a rectangular portion of one image to another image. `dst_image` is the destination image, `src_image` is the source image identifier. In other words, **imagecopyresized()** will take a rectangular area from `src_image` of width `src_width` and height `src_height` at position (`src_x`,`src_y`) and place it in a rectangular area of `dst_image` of width `dst_width` and height `dst_height` at position (`dst_x`,`dst_y`). If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if `dst_image` is the same as `src_image`) but if the regions overlap the results will be unpredictable. ### Parameters `dst_image` Destination image resource. `src_image` Source image resource. `dst_x` x-coordinate of destination point. `dst_y` y-coordinate of destination point. `src_x` x-coordinate of source point. `src_y` y-coordinate of source point. `dst_width` Destination width. `dst_height` Destination height. `src_width` Source width. `src_height` Source height. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `dst_image` and `src_image` expect [GdImage](class.gdimage) instances now; previously, resources were expected. | ### Examples **Example #1 Resizing an image** This example will display the image at half size. ``` <?php // File and new size $filename = 'test.jpg'; $percent = 0.5; // Content type header('Content-Type: image/jpeg'); // Get new sizes list($width, $height) = getimagesize($filename); $newwidth = $width * $percent; $newheight = $height * $percent; // Load $thumb = imagecreatetruecolor($newwidth, $newheight); $source = imagecreatefromjpeg($filename); // Resize imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Output imagejpeg($thumb); ?> ``` The above example will output something similar to: The image will be output at half size, though better quality could be obtained using [imagecopyresampled()](function.imagecopyresampled). ### Notes > > **Note**: > > > There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by [imagecreatetruecolor()](function.imagecreatetruecolor). > > ### See Also * [imagecopyresampled()](function.imagecopyresampled) - Copy and resize part of an image with resampling * [imagescale()](function.imagescale) - Scale an image using the given new width and height * [imagecrop()](function.imagecrop) - Crop an image to the given rectangle php RecursiveDirectoryIterator::key RecursiveDirectoryIterator::key =============================== (PHP 5, PHP 7, PHP 8) RecursiveDirectoryIterator::key — Return path and filename of current dir entry ### Description ``` public RecursiveDirectoryIterator::key(): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The path and filename of the current dir entry. php tidy::isXml tidy::isXml =========== tidy\_is\_xml ============= (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy::isXml -- tidy\_is\_xml — Indicates if the document is a generic (non HTML/XHTML) XML document ### Description Object-oriented style ``` public tidy::isXml(): bool ``` Procedural style ``` tidy_is_xml(tidy $tidy): bool ``` Tells if the document is a generic (non HTML/XHTML) XML document. ### Parameters `tidy` The [Tidy](class.tidy) object. ### Return Values This function returns **`true`** if the specified tidy `tidy` is a generic XML document (non HTML/XHTML), or **`false`** otherwise. **Warning** This function is not yet implemented in the Tidylib itself, so it always return **`false`**. php Ds\Vector::shift Ds\Vector::shift ================ (PECL ds >= 1.0.0) Ds\Vector::shift — Removes and returns the first value ### Description ``` public Ds\Vector::shift(): mixed ``` Removes and returns the first value. ### Parameters This function has no parameters. ### Return Values The first value, which was removed. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Vector::shift()** example** ``` <?php $vector = new \Ds\Vector(["a", "b", "c"]); var_dump($vector->shift()); var_dump($vector->shift()); var_dump($vector->shift()); ?> ``` The above example will output something similar to: ``` string(1) "a" string(1) "b" string(1) "c" ``` php PharData::setAlias PharData::setAlias ================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData) ### Description ``` public PharData::setAlias(string $alias): bool ``` Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception. ### Parameters `alias` A shorthand string that this archive can be referred to in `phar` stream wrapper access. This parameter is ignored. ### Return Values ### Errors/Exceptions Throws [PharException](class.pharexception) on all method calls ### See Also * [Phar::setAlias()](phar.setalias) - Set the alias for the Phar archive
programming_docs
php None Enumeration methods ------------------- Enums (both Pure Enums and Backed Enums) may contain methods, and may implement interfaces. If an Enum implements an interface, then any type check for that interface will also accept all cases of that Enum. ``` <?php interface Colorful {     public function color(): string; } enum Suit implements Colorful {     case Hearts;     case Diamonds;     case Clubs;     case Spades;     // Fulfills the interface contract.     public function color(): string     {         return match($this) {             Suit::Hearts, Suit::Diamonds => 'Red',             Suit::Clubs, Suit::Spades => 'Black',         };     }     // Not part of an interface; that's fine.     public function shape(): string     {         return "Rectangle";     } } function paint(Colorful $c) { ... } paint(Suit::Clubs);  // Works print Suit::Diamonds->shape(); // prints "Rectangle" ?> ``` In this example, all four instances of `Suit` have two methods, `color()` and `shape()`. As far as calling code and type checks are concerned, they behave exactly the same as any other object instance. On a Backed Enum, the interface declaration goes after the backing type declaration. ``` <?php interface Colorful {     public function color(): string; } enum Suit: string implements Colorful {     case Hearts = 'H';     case Diamonds = 'D';     case Clubs = 'C';     case Spades = 'S';     // Fulfills the interface contract.     public function color(): string     {         return match($this) {             Suit::Hearts, Suit::Diamonds => 'Red',             Suit::Clubs, Suit::Spades => 'Black',         };     } } ?> ``` Inside a method, the `$this` variable is defined and refers to the Case instance. Methods may be arbitrarily complex, but in practice will usually return a static value or [match](control-structures.match) on `$this` to provide different results for different cases. Note that in this case it would be a better data modeling practice to also define a `SuitColor` Enum Type with values Red and Black and return that instead. However, that would complicate this example. The above hierarchy is logically similar to the following class structure (although this is not the actual code that runs): ``` <?php interface Colorful {     public function color(): string; } final class Suit implements UnitEnum, Colorful {     public const Hearts = new self('Hearts');     public const Diamonds = new self('Diamonds');     public const Clubs = new self('Clubs');     public const Spades = new self('Spades');     private function __construct(public readonly string $name) {}     public function color(): string     {         return match($this) {             Suit::Hearts, Suit::Diamonds => 'Red',             Suit::Clubs, Suit::Spades => 'Black',         };     }     public function shape(): string     {         return "Rectangle";     }     public static function cases(): array     {         // Illegal method, because manually defining a cases() method on an Enum is disallowed.         // See also "Value listing" section.     } } ?> ``` Methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed. php ssh2_poll ssh2\_poll ========== (PECL ssh2 >= 0.9.0) ssh2\_poll — Poll the channels/listeners/streams for events ### Description ``` ssh2_poll(array &$desc, int $timeout = 30): int ``` Polls the channels/listeners/streams for events, and returns the number of descriptors which returned non-zero revents. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `desc` An indexed array of subarrays with the keys `'resource'` and `'events'`. The value of the resource is a (channel) stream or an SSH2 Listener resource. The value of the event are SSH2\_POLL\* flags bitwise ORed together. Each subarray will be populated with an `'revents'` element on return, whose values are SSH2\_POLL\* flags bitwise ORed together of the events that occurred. `timeout` The timeout in seconds. ### Return Values Returns the number of descriptors which returned non-zero revents. php Imagick::labelImage Imagick::labelImage =================== (PECL imagick 2, PECL imagick 3) Imagick::labelImage — Adds a label to an image ### Description ``` public Imagick::labelImage(string $label): bool ``` Adds a label to an image. ### Parameters `label` The label to add ### Return Values Returns **`true`** on success. php socket_recvfrom socket\_recvfrom ================ (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_recvfrom — Receives data from a socket whether or not it is connection-oriented ### Description ``` socket_recvfrom( Socket $socket, string &$data, int $length, int $flags, string &$address, int &$port = null ): int|false ``` The **socket\_recvfrom()** function receives `length` bytes of data in `data` from `address` on port `port` (if the socket is not of type **`AF_UNIX`**) using `socket`. **socket\_recvfrom()** can be used to gather data from both connected and unconnected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function. The `address` and `port` must be passed by reference. If the socket is not connection-oriented, `address` will be set to the internet protocol address of the remote host or the path to the UNIX socket. If the socket is connection-oriented, `address` is **`null`**. Additionally, the `port` will contain the port of the remote host in the case of an unconnected **`AF_INET`** or **`AF_INET6`** socket. > **Note**: This function is binary-safe. > > ### Parameters `socket` The `socket` must be a [Socket](class.socket) instance previously created by socket\_create(). `data` The data received will be fetched to the variable specified with `data`. `length` Up to `length` bytes will be fetched from remote host. `flags` The value of `flags` can be any combination of the following flags, joined with the binary OR (`|`) operator. **Possible values for `flags`**| Flag | Description | | --- | --- | | **`MSG_OOB`** | Process out-of-band data. | | **`MSG_PEEK`** | Receive data from the beginning of the receive queue without removing it from the queue. | | **`MSG_WAITALL`** | Block until at least `length` are received. However, if a signal is caught or the remote host disconnects, the function may return less data. | | **`MSG_DONTWAIT`** | With this flag set, the function returns even if it would normally have blocked. | `address` If the socket is of the type **`AF_UNIX`** type, `address` is the path to the file. Else, for unconnected sockets, `address` is the IP address of, the remote host, or **`null`** if the socket is connection-oriented. `port` This argument only applies to **`AF_INET`** and **`AF_INET6`** sockets, and specifies the remote port from which the data is received. If the socket is connection-oriented, `port` will be **`null`**. ### Return Values **socket\_recvfrom()** returns the number of bytes received, or **`false`** if there was an error. The actual error code can be retrieved by calling [socket\_last\_error()](function.socket-last-error). This error code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual explanation of the error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | ### Examples **Example #1 **socket\_recvfrom()** example** ``` <?php $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_bind($socket, '127.0.0.1', 1223); $from = ''; $port = 0; socket_recvfrom($socket, $buf, 12, 0, $from, $port); echo "Received $buf from remote address $from and remote port $port" . PHP_EOL; ?> ``` This example will initiate a UDP socket on port 1223 of 127.0.0.1 and print at most 12 characters received from a remote host. ### See Also * [socket\_recv()](function.socket-recv) - Receives data from a connected socket * [socket\_send()](function.socket-send) - Sends data to a connected socket * [socket\_sendto()](function.socket-sendto) - Sends a message to a socket, whether it is connected or not * [socket\_create()](function.socket-create) - Create a socket (endpoint for communication) php openal_buffer_create openal\_buffer\_create ====================== (PECL openal >= 0.1.0) openal\_buffer\_create — Generate OpenAL buffer ### Description ``` openal_buffer_create(): resource ``` ### Parameters This function has no parameters. ### Return Values Returns an [Open AL(Buffer)](https://www.php.net/manual/en/openal.resources.php) resource on success or **`false`** on failure. ### See Also * [openal\_buffer\_loadwav()](function.openal-buffer-loadwav) - Load a .wav file into a buffer * [openal\_buffer\_data()](function.openal-buffer-data) - Load a buffer with data php SolrInputDocument::hasChildDocuments SolrInputDocument::hasChildDocuments ==================================== (PECL solr >= 2.3.0) SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents ### Description ``` public SolrInputDocument::hasChildDocuments(): bool ``` Checks whether the document has any child documents ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrInputDocument::addChildDocument()](solrinputdocument.addchilddocument) - Adds a child document for block indexing * [SolrInputDocument::addChildDocuments()](solrinputdocument.addchilddocuments) - Adds an array of child documents * [SolrInputDocument::getChildDocuments()](solrinputdocument.getchilddocuments) - Returns an array of child documents (SolrInputDocument) * [SolrInputDocument::getChildDocumentsCount()](solrinputdocument.getchilddocumentscount) - Returns the number of child documents php ImagickDraw::affine ImagickDraw::affine =================== (PECL imagick 2, PECL imagick 3) ImagickDraw::affine — Adjusts the current affine transformation matrix ### Description ``` public ImagickDraw::affine(array $affine): bool ``` **Warning**This function is currently not documented; only its argument list is available. Adjusts the current affine transformation matrix with the specified affine transformation matrix. ### Parameters `affine` Affine matrix parameters ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::affine()** example** ``` <?php function affine($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeWidth(1);     $draw->setStrokeOpacity(1);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(2);     $PI = 3.141592653589794;     $angle = 60 * $PI / 360;     //Scale the drawing co-ordinates.     $affineScale = array("sx" => 1.75, "sy" => 1.75, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);     //Shear the drawing co-ordinates.     $affineShear = array("sx" => 1, "sy" => 1, "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0);     //Rotate the drawing co-ordinates. The shear affine matrix     //produces incorrectly scaled drawings.     $affineRotate = array("sx" => cos($angle), "sy" => cos($angle), "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0,);     //Translate (offset) the drawing     $affineTranslate = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 30, "ty" => 30);     //The identiy affine matrix     $affineIdentity = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);     $examples = [$affineScale, $affineShear, $affineRotate, $affineTranslate, $affineIdentity,];     $count = 0;     foreach ($examples as $example) {         $draw->push();         $draw->translate(($count % 2) * 250, intval($count / 2) * 250);         $draw->translate(100, 100);         $draw->affine($example);         $draw->rectangle(-50, -50, 50, 50);         $draw->pop();         $count++;     }     //Create an image object which the draw commands can be rendered into     $image = new \Imagick();     $image->newImage(500, 750, $backgroundColor);     $image->setImageFormat("png");     //Render the draw commands in the ImagickDraw object      //into the image.     $image->drawImage($draw);     //Send the image to the browser     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php The Parle\ErrorInfo class The Parle\ErrorInfo class ========================= Introduction ------------ (PECL parle >= 0.5.2) The class represents detailed error information as supplied by [Parle\Parser::errorInfo()](parle-parser.errorinfo) Class synopsis -------------- class **Parle\ErrorInfo** { /\* Properties \*/ public int [$id](class.parle-errorinfo#parle-errorinfo.props.id); public int [$position](class.parle-errorinfo#parle-errorinfo.props.position); public [mixed](language.types.declarations#language.types.declarations.mixed) [$token](class.parle-errorinfo#parle-errorinfo.props.token); /\* Methods \*/ } Properties ---------- id Error id. position Position in the input, where the error occurred. token If applicable - the [Parle\Token](class.parle-token) related to the error, otherwise **`null`**. php SolrQuery::setMltMinWordLength SolrQuery::setMltMinWordLength ============================== (PECL solr >= 0.9.2) SolrQuery::setMltMinWordLength — Sets the minimum word length ### Description ``` public SolrQuery::setMltMinWordLength(int $minWordLength): SolrQuery ``` Sets the minimum word length below which words will be ignored. ### Parameters `minWordLength` The minimum word length below which words will be ignored ### Return Values Returns the current SolrQuery object, if the return value is used. php None Object Serialization -------------------- Serializing objects - objects in sessions ----------------------------------------- [serialize()](function.serialize) returns a string containing a byte-stream representation of any value that can be stored in PHP. [unserialize()](function.unserialize) can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class. In order to be able to [unserialize()](function.unserialize) an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variables contained in it. If you want to be able to unserialize this in another file, an object of class A, the definition of class A must be present in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of the [spl\_autoload\_register()](function.spl-autoload-register) function. ``` <?php // classa.inc:      class A {       public $one = 1;            public function show_one() {           echo $this->one;       }   }    // page1.php:   include("classa.inc");      $a = new A;   $s = serialize($a);   // store $s somewhere where page2.php can find it.   file_put_contents('store', $s); // page2.php:      // this is needed for the unserialize to work properly.   include("classa.inc");   $s = file_get_contents('store');   $a = unserialize($s);   // now use the function show_one() of the $a object.     $a->show_one(); ?> ``` It is strongly recommended that if an application serializes objects, for use later in the application, that the application includes the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of **\_\_PHP\_Incomplete\_Class\_Name**, which has no methods and would render the object useless. So if in the example above $a became part of a session by running `session_register("a")`, you should include the file `classa.inc` on all of your pages, not only page1.php and page2.php. Beyond the above advice, note that you can also hook into the serialization and unserialization events on an object using the [\_\_sleep()](language.oop5.magic#object.sleep) and [\_\_wakeup()](language.oop5.magic#object.wakeup) methods. Using [\_\_sleep()](language.oop5.magic#object.sleep) also allows you to only serialize a subset of the object's properties. php getdate getdate ======= (PHP 4, PHP 5, PHP 7, PHP 8) getdate — Get date/time information ### Description ``` getdate(?int $timestamp = null): array ``` Returns an associative array containing the date information of the `timestamp`, or the current local time if `timestamp` is omitted or **`null`**. ### Parameters `timestamp` The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or **`null`**. In other words, it defaults to the value of [time()](function.time). ### Return Values Returns an associative array of information related to the `timestamp`. Elements from the returned associative array are as follows: **Key elements of the returned associative array**| Key | Description | Example returned values | | --- | --- | --- | | `"seconds"` | Numeric representation of seconds | `0` to `59` | | `"minutes"` | Numeric representation of minutes | `0` to `59` | | `"hours"` | Numeric representation of hours | `0` to `23` | | `"mday"` | Numeric representation of the day of the month | `1` to `31` | | `"wday"` | Numeric representation of the day of the week | `0` (for Sunday) through `6` (for Saturday) | | `"mon"` | Numeric representation of a month | `1` through `12` | | `"year"` | A full numeric representation of a year, 4 digits | Examples: `1999` or `2003` | | `"yday"` | Numeric representation of the day of the year | `0` through `365` | | `"weekday"` | A full textual representation of the day of the week | `Sunday` through `Saturday` | | `"month"` | A full textual representation of a month, such as January or March | `January` through `December` | | `0` | Seconds since the Unix Epoch, similar to the values returned by [time()](function.time) and used by [date()](function.date). | System Dependent, typically `-2147483648` through `2147483647`. | ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `timestamp` is nullable now. | ### Examples **Example #1 **getdate()** example** ``` <?php $today = getdate(); print_r($today); ?> ``` The above example will output something similar to: ``` Array ( [seconds] => 40 [minutes] => 58 [hours] => 21 [mday] => 17 [wday] => 2 [mon] => 6 [year] => 2003 [yday] => 167 [weekday] => Tuesday [month] => June [0] => 1055901520 ) ``` ### See Also * [date()](function.date) - Format a Unix timestamp * [idate()](function.idate) - Format a local time/date part as integer * [localtime()](function.localtime) - Get the local time * [time()](function.time) - Return current Unix timestamp * [setlocale()](function.setlocale) - Set locale information php Pool::shutdown Pool::shutdown ============== (PECL pthreads >= 2.0.0) Pool::shutdown — Shutdown all workers ### Description ``` public Pool::shutdown(): void ``` Shuts down all of the workers in the pool. This will block until all submitted tasks have been executed. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 Shutting down a pool** ``` <?php class Task extends Threaded {     public function run()     {         usleep(500000);     } } $pool = new Pool(4); for ($i = 0; $i < 10; ++$i) {     $pool->submit(new Task()); } $pool->shutdown(); // blocks until all submitted tasks have finished executing ```
programming_docs
php The Yar_Server class The Yar\_Server class ===================== Introduction ------------ (No version information available, might only be in Git) Class synopsis -------------- class **Yar\_Server** { /\* Properties \*/ protected [$\_executor](class.yar-server#yar-server.props.executor); /\* Methods \*/ ``` final public __construct(Object $obj) ``` ``` public handle(): bool ``` } Properties ---------- \_executor Table of Contents ----------------- * [Yar\_Server::\_\_construct](yar-server.construct) — Register a server * [Yar\_Server::handle](yar-server.handle) — Start RPC Server php None if -- (PHP 4, PHP 5, PHP 7, PHP 8) The `if` construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an `if` structure that is similar to that of C: ``` if (expr) statement ``` As described in [the section about expressions](language.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'](language.types.boolean#language.types.boolean.casting) section. The following example would display a is bigger than b if $a is bigger than $b: ``` <?php if ($a > $b)   echo "a is bigger than b"; ?> ``` Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an `if` clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b: ``` <?php if ($a > $b) {   echo "a is bigger than b";   $b = $a; } ?> ``` `If` statements can be nested infinitely within other `if` statements, which provides you with complete flexibility for conditional execution of the various parts of your program. php array_keys array\_keys =========== (PHP 4, PHP 5, PHP 7, PHP 8) array\_keys — Return all the keys or a subset of the keys of an array ### Description ``` array_keys(array $array): array ``` ``` array_keys(array $array, mixed $filter_value, bool $strict = false): array ``` **array\_keys()** returns the keys, numeric and string, from the `array`. If a `filter_value` is specified, then only the keys for that value are returned. Otherwise, all the keys from the `array` are returned. ### Parameters `array` An array containing keys to return. `filter_value` If specified, then only keys containing this value are returned. `strict` Determines if strict comparison (===) should be used during the search. ### Return Values Returns an array of all the keys in `array`. ### Examples **Example #1 **array\_keys()** example** ``` <?php $array = array(0 => 100, "color" => "red"); print_r(array_keys($array)); $array = array("blue", "red", "green", "blue", "blue"); print_r(array_keys($array, "blue")); $array = array("color" => array("blue", "red", "green"),                "size"  => array("small", "medium", "large")); print_r(array_keys($array)); ?> ``` The above example will output: ``` Array ( [0] => 0 [1] => color ) Array ( [0] => 0 [1] => 3 [2] => 4 ) Array ( [0] => color [1] => size ) ``` ### See Also * [array\_values()](function.array-values) - Return all the values of an array * [array\_combine()](function.array-combine) - Creates an array by using one array for keys and another for its values * [array\_key\_exists()](function.array-key-exists) - Checks if the given key or index exists in the array * [array\_search()](function.array-search) - Searches the array for a given value and returns the first corresponding key if successful php ftp_put ftp\_put ======== (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_put — Uploads a file to the FTP server ### Description ``` ftp_put( FTP\Connection $ftp, string $remote_filename, string $local_filename, int $mode = FTP_BINARY, int $offset = 0 ): bool ``` **ftp\_put()** stores a local file on the FTP server. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `remote_filename` The remote file path. `local_filename` The local file path. `mode` The transfer mode. Must be either **`FTP_ASCII`** or **`FTP_BINARY`**. `offset` The position in the remote file to start uploading to. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 7.3.0 | The `mode` parameter is now optional. Formerly it has been mandatory. | ### Examples **Example #1 **ftp\_put()** example** ``` <?php $file = 'somefile.txt'; $remote_file = 'readme.txt'; // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); // upload a file if (ftp_put($ftp, $remote_file, $file, FTP_ASCII)) {  echo "successfully uploaded $file\n"; } else {  echo "There was a problem while uploading $file\n"; } // close the connection ftp_close($ftp); ?> ``` ### See Also * [ftp\_pasv()](function.ftp-pasv) - Turns passive mode on or off * [ftp\_fput()](function.ftp-fput) - Uploads from an open file to the FTP server * [ftp\_nb\_fput()](function.ftp-nb-fput) - Stores a file from an open file to the FTP server (non-blocking) * [ftp\_nb\_put()](function.ftp-nb-put) - Stores a file on the FTP server (non-blocking) php IntlTimeZone::getErrorMessage IntlTimeZone::getErrorMessage ============================= intltz\_get\_error\_message =========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::getErrorMessage -- intltz\_get\_error\_message — Get last error message on the object ### Description Object-oriented style (method): ``` public IntlTimeZone::getErrorMessage(): string|false ``` Procedural style: ``` intltz_get_error_message(IntlTimeZone $timezone): string|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Imagick::setIteratorIndex Imagick::setIteratorIndex ========================= (PECL imagick 2, PECL imagick 3) Imagick::setIteratorIndex — Set the iterator position ### Description ``` public Imagick::setIteratorIndex(int $index): bool ``` Set the iterator to the position in the image list specified with the index parameter. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `index` The position to set the iterator to ### Return Values Returns **`true`** on success. ### Examples **Example #1 Using **Imagick::setIteratorIndex()**:** Create images, set and get the iterator index ``` <?php $im = new Imagick(); $im->newImage(100, 100, new ImagickPixel("red")); $im->newImage(100, 100, new ImagickPixel("green")); $im->newImage(100, 100, new ImagickPixel("blue")); $im->setIteratorIndex(1); echo $im->getIteratorIndex(); ?> ``` ### See Also * [Imagick::getIteratorIndex()](imagick.getiteratorindex) - Gets the index of the current active image * [Imagick::getImageIndex()](imagick.getimageindex) - Gets the index of the current active image * [Imagick::setImageIndex()](imagick.setimageindex) - Set the iterator position php Phar::mungServer Phar::mungServer ================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::mungServer — Defines a list of up to 4 $\_SERVER variables that should be modified for execution ### Description ``` final public static Phar::mungServer(array $variables): void ``` **Phar::mungServer()** should only be called within the stub of a phar archive. Defines a list of up to 4 [$\_SERVER](reserved.variables.server) variables that should be modified for execution. Variables that can be modified to remove traces of phar execution are `REQUEST_URI`, `PHP_SELF`, `SCRIPT_NAME` and `SCRIPT_FILENAME`. On its own, this method does nothing. Only when combined with [Phar::webPhar()](phar.webphar) does it take effect, and only when the requested file is a PHP file to be parsed. Note that the `PATH_INFO` and `PATH_TRANSLATED` variables are always modified. The original values of variables that are modified are stored in the SERVER array with `PHAR_` prepended, so for instance `SCRIPT_NAME` would be saved as `PHAR_SCRIPT_NAME`. ### Parameters `variables` an array containing as string indices any of `REQUEST_URI`, `PHP_SELF`, `SCRIPT_NAME` and `SCRIPT_FILENAME`. Other values trigger an exception, and **Phar::mungServer()** is case-sensitive. ### Return Values No return. ### Errors/Exceptions Throws [UnexpectedValueException](class.unexpectedvalueexception) if any problems are found with the passed in data. ### Examples **Example #1 A **Phar::mungServer()** example** ``` <?php // example stub Phar::mungServer(array('REQUEST_URI')); Phar::webPhar(); __HALT_COMPILER(); ?> ``` ### See Also * [Phar::webPhar()](phar.webphar) - Routes a request from a web browser to an internal file within the phar archive * [Phar::setStub()](phar.setstub) - Used to set the PHP loader or bootstrap stub of a Phar archive php None Alternation ----------- Vertical bar characters are used to separate alternative patterns. For example, the pattern `gilbert|sullivan` matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern. php Yaf_Session::has Yaf\_Session::has ================= (Yaf >=1.0.0) Yaf\_Session::has — The has purpose ### Description ``` public Yaf_Session::has(string $name): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php The LimitIterator class The LimitIterator class ======================= Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) The **LimitIterator** class allows iteration over a limited subset of items in an [Iterator](class.iterator). Class synopsis -------------- class **LimitIterator** extends [IteratorIterator](class.iteratoriterator) { /\* Methods \*/ public [\_\_construct](limititerator.construct)([Iterator](class.iterator) `$iterator`, int `$offset` = 0, int `$limit` = -1) ``` public current(): mixed ``` ``` public getInnerIterator(): Iterator ``` ``` public getPosition(): int ``` ``` public key(): mixed ``` ``` public next(): void ``` ``` public rewind(): void ``` ``` public seek(int $offset): int ``` ``` public valid(): bool ``` /\* Inherited methods \*/ ``` public IteratorIterator::current(): mixed ``` ``` public IteratorIterator::getInnerIterator(): ?Iterator ``` ``` public IteratorIterator::key(): mixed ``` ``` public IteratorIterator::next(): void ``` ``` public IteratorIterator::rewind(): void ``` ``` public IteratorIterator::valid(): bool ``` } Examples -------- **Example #1 **LimitIterator** usage example** ``` <?php // Create an iterator to be limited $fruits = new ArrayIterator(array(     'apple',     'banana',     'cherry',     'damson',     'elderberry' )); // Loop over first three fruits only foreach (new LimitIterator($fruits, 0, 3) as $fruit) {     var_dump($fruit); } echo "\n"; // Loop from third fruit until the end // Note: offset starts from zero for apple foreach (new LimitIterator($fruits, 2) as $fruit) {     var_dump($fruit); } ?> ``` The above example will output: ``` string(5) "apple" string(6) "banana" string(6) "cherry" string(6) "cherry" string(6) "damson" string(10) "elderberry" ``` Table of Contents ----------------- * [LimitIterator::\_\_construct](limititerator.construct) — Construct a LimitIterator * [LimitIterator::current](limititerator.current) — Get current element * [LimitIterator::getInnerIterator](limititerator.getinneriterator) — Get inner iterator * [LimitIterator::getPosition](limititerator.getposition) — Return the current position * [LimitIterator::key](limititerator.key) — Get current key * [LimitIterator::next](limititerator.next) — Move the iterator forward * [LimitIterator::rewind](limititerator.rewind) — Rewind the iterator to the specified starting offset * [LimitIterator::seek](limititerator.seek) — Seek to the given position * [LimitIterator::valid](limititerator.valid) — Check whether the current element is valid php Imagick::shaveImage Imagick::shaveImage =================== (PECL imagick 2, PECL imagick 3) Imagick::shaveImage — Shaves pixels from the image edges ### Description ``` public Imagick::shaveImage(int $columns, int $rows): bool ``` Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image. ### Parameters `columns` `rows` ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::shaveImage()**** ``` <?php function shaveImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->shaveImage(100, 50);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php ftp_fput ftp\_fput ========= (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_fput — Uploads from an open file to the FTP server ### Description ``` ftp_fput( FTP\Connection $ftp, string $remote_filename, resource $stream, int $mode = FTP_BINARY, int $offset = 0 ): bool ``` **ftp\_fput()** uploads the data from a file pointer to a remote file on the FTP server. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `remote_filename` The remote file path. `stream` An open file pointer on the local file. Reading stops at end of file. `mode` The transfer mode. Must be either **`FTP_ASCII`** or **`FTP_BINARY`**. `offset` The position in the remote file to start uploading to. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 7.3.0 | The `mode` parameter is now optional. Formerly it has been mandatory. | ### Examples **Example #1 **ftp\_fput()** example** ``` <?php // open some file for reading $file = 'somefile.txt'; $fp = fopen($file, 'r'); // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); // try to upload $file if (ftp_fput($ftp, $file, $fp, FTP_ASCII)) {     echo "Successfully uploaded $file\n"; } else {     echo "There was a problem while uploading $file\n"; } // close the connection and the file handler ftp_close($ftp); fclose($fp); ?> ``` ### See Also * [ftp\_put()](function.ftp-put) - Uploads a file to the FTP server * [ftp\_nb\_fput()](function.ftp-nb-fput) - Stores a file from an open file to the FTP server (non-blocking) * [ftp\_nb\_put()](function.ftp-nb-put) - Stores a file on the FTP server (non-blocking) php fpassthru fpassthru ========= (PHP 4, PHP 5, PHP 7, PHP 8) fpassthru — Output all remaining data on a file pointer ### Description ``` fpassthru(resource $stream): int ``` Reads to EOF on the given file pointer from the current position and writes the results to the output buffer. You may need to call [rewind()](function.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()](function.readfile), which saves you the [fopen()](function.fopen) call. ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen) (and not yet closed by [fclose()](function.fclose)). ### Return Values Returns the number of characters read from `stream` and passed through to the output. ### Examples **Example #1 Using **fpassthru()** with binary files** ``` <?php // open the file in a binary mode $name = './img/ok.png'; $fp = fopen($name, 'rb'); // send the right headers header("Content-Type: image/png"); header("Content-Length: " . filesize($name)); // dump the picture and stop the script fpassthru($fp); exit; ?> ``` ### Notes > > **Note**: > > > When using **fpassthru()** on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a `b` to the mode used in the call to [fopen()](function.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()](function.readfile) - Outputs a file * [fopen()](function.fopen) - Opens file or URL * [popen()](function.popen) - Opens process file pointer * [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection php SVMModel::getSvmType SVMModel::getSvmType ==================== (PECL svm >= 0.1.5) SVMModel::getSvmType — Get the SVM type the model was trained with ### Description ``` public SVMModel::getSvmType(): int ``` Returns an integer value representing the type of the SVM model used, e.g SVM::C\_SVC. ### Parameters This function has no parameters. ### Return Values Return an integer SVM type php GearmanJob::warning GearmanJob::warning =================== (PECL gearman <= 0.5.0) GearmanJob::warning — Send a warning (deprecated) ### Description ``` public GearmanJob::warning(string $warning): bool ``` Sends a warning for this job while it is running. > > **Note**: > > > This method has been replaced by [GearmanJob::sendWarning()](gearmanjob.sendwarning) in the 0.6.0 release of the Gearman extension. > > ### Parameters `warning` A warning messages. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanJob::sendComplete()](gearmanjob.sendcomplete) - Send the result and complete status * [GearmanJob::sendException()](gearmanjob.sendexception) - Send exception for running job (exception) * [GearmanJob::sendFail()](gearmanjob.sendfail) - Send fail status php CURLFile::__construct CURLFile::\_\_construct ======================= curl\_file\_create ================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) CURLFile::\_\_construct -- curl\_file\_create — Create a CURLFile object ### Description Object-oriented style public **CURLFile::\_\_construct**(string `$filename`, ?string `$mime_type` = **`null`**, ?string `$posted_filename` = **`null`**) Procedural style ``` curl_file_create(string $filename, ?string $mime_type = null, ?string $posted_filename = null): CURLFile ``` Creates a [CURLFile](class.curlfile) object, used to upload a file with **`CURLOPT_POSTFIELDS`**. ### Parameters `filename` Path to the file which will be uploaded. `mime_type` Mimetype of the file. `posted_filename` Name of the file to be used in the upload data. ### Return Values Returns a [CURLFile](class.curlfile) object. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `mime_type` and `posted_filename` are nullable now; previously their default was `0`. | ### Examples **Example #1 **CURLFile::\_\_construct()** example** Object-oriented style ``` <?php /* http://example.com/upload.php: <?php var_dump($_FILES); ?> */ // Create a cURL handle $ch = curl_init('http://example.com/upload.php'); // Create a CURLFile object $cfile = new CURLFile('cats.jpg','image/jpeg','test_name'); // Assign POST data $data = array('test_file' => $cfile); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Execute the handle curl_exec($ch); ?> ``` Procedural style ``` <?php /* http://example.com/upload.php: <?php var_dump($_FILES); ?> */ // Create a cURL handle $ch = curl_init('http://example.com/upload.php'); // Create a CURLFile object $cfile = curl_file_create('cats.jpg','image/jpeg','test_name'); // Assign POST data $data = array('test_file' => $cfile); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Execute the handle curl_exec($ch); ?> ``` The above example will output: ``` array(1) { ["test_file"]=> array(5) { ["name"]=> string(9) "test_name" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpPC9Kbx" ["error"]=> int(0) ["size"]=> int(46334) } } ``` **Example #2 **CURLFile::\_\_construct()** uploading multiple files example** Object-oriented style ``` <?php $request = curl_init('http://www.example.com/upload.php'); curl_setopt($request, CURLOPT_POST, true); curl_setopt($request, CURLOPT_SAFE_UPLOAD, true); curl_setopt($request, CURLOPT_POSTFIELDS, [     'blob[0]' => new CURLFile(realpath('first-file.jpg'), 'image/jpeg'),     'blob[1]' => new CURLFile(realpath('second-file.txt'), 'text/plain'),     'blob[2]' => new CURLFile(realpath('third-file.exe'), 'application/octet-stream'), ]); curl_setopt($request, CURLOPT_RETURNTRANSFER, true); echo curl_exec($request); var_dump(curl_getinfo($request)); curl_close($request); ``` Procedural style ``` <?php // procedural $request = curl_init('http://www.example.com/upload.php'); curl_setopt($request, CURLOPT_POST, true);  curl_setopt($request, CURLOPT_SAFE_UPLOAD, true); curl_setopt($request, CURLOPT_POSTFIELDS, [     'blob[0]' => curl_file_create(realpath('first-file.jpg'), 'image/jpeg'),     'blob[1]' => curl_file_create(realpath('second-file.txt'), 'text/plain'),     'blob[2]' => curl_file_create(realpath('third-file.exe'), 'application/octet-stream'), ]); curl_setopt($request, CURLOPT_RETURNTRANSFER, true); echo curl_exec($request); var_dump(curl_getinfo($request)); curl_close($request); ``` The above example will output: ``` array(26) { ["url"]=> string(31) "http://www.example.com/upload.php" ["content_type"]=> string(24) "text/html; charset=UTF-8" ["http_code"]=> int(200) ["header_size"]=> int(198) ["request_size"]=> int(196) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.060062) ["namelookup_time"]=> float(0.028575) ["connect_time"]=> float(0.029011) ["pretransfer_time"]=> float(0.029121) ["size_upload"]=> float(3230730) ["size_download"]=> float(811) ["speed_download"]=> float(13516) ["speed_upload"]=> float(53845500) ["download_content_length"]=> float(811) ["upload_content_length"]=> float(3230730) ["starttransfer_time"]=> float(0.030355) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "0.0.0.0" ["certinfo"]=> array(0) { } ["primary_port"]=> int(80) ["local_ip"]=> string(12) "0.0.0.0" ["local_port"]=> int(34856) } ``` ### See Also * [curl\_setopt()](function.curl-setopt) - Set an option for a cURL transfer
programming_docs
php SolrQuery::setTermsUpperBound SolrQuery::setTermsUpperBound ============================= (PECL solr >= 0.9.2) SolrQuery::setTermsUpperBound — Sets the term to stop at ### Description ``` public SolrQuery::setTermsUpperBound(string $upperBound): SolrQuery ``` Sets the term to stop at ### Parameters `upperBound` The term to stop at ### Return Values Returns the current SolrQuery object, if the return value is used. php Imagick::__construct Imagick::\_\_construct ====================== (PECL imagick 2, PECL imagick 3) Imagick::\_\_construct — The Imagick constructor ### Description public **Imagick::\_\_construct**([mixed](language.types.declarations#language.types.declarations.mixed) `$files` = ?) Creates an Imagick instance for a specified image or set of images. ### Parameters `files` The path to an image to load or an array of paths. Paths can include wildcards for file names, or can be URLs. ### Errors/Exceptions Throws ImagickException on error. php Memcached::get Memcached::get ============== (PECL memcached >= 0.1.0) Memcached::get — Retrieve an item ### Description ``` public Memcached::get(string $key, callable $cache_cb = ?, int $flags = ?): mixed ``` **Memcached::get()** returns the item that was previously stored under the `key`. If the item is found and the `flags` is given **`Memcached::GET_EXTENDED`**, it will also return the CAS token value for the item. See [Memcached::cas()](memcached.cas) for how to use CAS tokens. [Read-through caching callback](https://www.php.net/manual/en/memcached.callbacks.php) may be specified via `cache_cb` parameter. ### Parameters `key` The key of the item to retrieve. `cache_cb` Read-through caching callback or **`null`**. `flags` Flags to control the returned result. When **`Memcached::GET_EXTENDED`** is given, the function will also return the CAS token. ### Return Values Returns the value stored in the cache or **`false`** otherwise. If the `flags` is set to **`Memcached::GET_EXTENDED`**, an array containing the value and the CAS token is returned instead of only the value. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTFOUND`** if the key does not exist. ### Changelog | Version | Description | | --- | --- | | PECL memcached 3.0.0 | The `&cas_token` parameter was removed. Instead `flags` was added and when it is given the value of **`Memcached::GET_EXTENDED`** it will ensure the CAS token to be fetched. | ### Examples **Example #1 **Memcached::get()** example #1** ``` <?php $m = new Memcached(); $m->addServer('localhost', 11211); $m->set('foo', 100); var_dump($m->get('foo')); ?> ``` The above example will output: ``` int(100) ``` **Example #2 **Memcached::get()** example #2** ``` <?php $m = new Memcached(); $m->addServer('localhost', 11211); if (!($ip = $m->get('ip_block'))) {     if ($m->getResultCode() == Memcached::RES_NOTFOUND) {         $ip = array();         $m->set('ip_block', $ip);     } else {         /* log error */         /* ...       */     } } ?> ``` ### See Also * [Memcached::getByKey()](memcached.getbykey) - Retrieve an item from a specific server * [Memcached::getMulti()](memcached.getmulti) - Retrieve multiple items * [Memcached::getDelayed()](memcached.getdelayed) - Request multiple items php None Object Interfaces ----------------- Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented. Interfaces share a namespace with classes and traits, so they may not use the same name. Interfaces are defined in the same way as a class, but with the `interface` keyword replacing the `class` keyword and without any of the methods having their contents defined. All methods declared in an interface must be public; this is the nature of an interface. In practice, interfaces serve two complementary purposes: * To allow developers to create objects of different classes that may be used interchangeably because they implement the same interface or interfaces. A common example is multiple database access services, multiple payment gateways, or different caching strategies. Different implementations may be swapped out without requiring any changes to the code that uses them. * To allow a function or method to accept and operate on a parameter that conforms to an interface, while not caring what else the object may do or how it is implemented. These interfaces are often named like `Iterable`, `Cacheable`, `Renderable`, or so on to describe the significance of the behavior. Interfaces may define [magic methods](language.oop5.magic) to require implementing classes to implement those methods. > > **Note**: > > > Although they are supported, including [constructors](language.oop5.decon#language.oop5.decon.constructor) in interfaces is strongly discouraged. Doing so significantly reduces the flexibility of the object implementing the interface. Additionally, constructors are not enforced by inheritance rules, which can cause inconsistent and unexpected behavior. > > ### `implements` To implement an interface, the `implements` operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma. **Warning** A class that implements an interface may use a different name for its parameters than the interface. However, as of PHP 8.0 the language supports [named arguments](functions.arguments#functions.named-arguments), which means callers may rely on the parameter name in the interface. For that reason, it is strongly recommended that developers use the same parameter names as the interface being implemented. > > **Note**: > > > Interfaces can be extended like classes using the [extends](language.oop5.inheritance) operator. > > > > **Note**: > > > The class implementing the interface must declare all methods in the interface with a [compatible signature](language.oop5.basic#language.oop.lsp). A class can implement multiple interfaces which declare a method with the same name. In this case, the implementation must follow the [signature compatibility rules](language.oop5.basic#language.oop.lsp) for all the interfaces. So [covariance and contravariance](language.oop5.variance) can be applied. > > ### `Constants` It's possible for interfaces to have constants. Interface constants work exactly like [class constants](language.oop5.constants). Prior to PHP 8.1.0, they cannot be overridden by a class/interface that inherits them. ### Examples **Example #1 Interface example** ``` <?php // Declare the interface 'Template' interface Template {     public function setVariable($name, $var);     public function getHtml($template); } // Implement the interface // This will work class WorkingTemplate implements Template {     private $vars = [];        public function setVariable($name, $var)     {         $this->vars[$name] = $var;     }        public function getHtml($template)     {         foreach($this->vars as $name => $value) {             $template = str_replace('{' . $name . '}', $value, $template);         }           return $template;     } } // This will not work // Fatal error: Class BadTemplate contains 1 abstract methods // and must therefore be declared abstract (Template::getHtml) class BadTemplate implements Template {     private $vars = [];        public function setVariable($name, $var)     {         $this->vars[$name] = $var;     } } ?> ``` **Example #2 Extendable Interfaces** ``` <?php interface A {     public function foo(); } interface B extends A {     public function baz(Baz $baz); } // This will work class C implements B {     public function foo()     {     }     public function baz(Baz $baz)     {     } } // This will not work and result in a fatal error class D implements B {     public function foo()     {     }     public function baz(Foo $foo)     {     } } ?> ``` **Example #3 Variance compatibility with multiple interfaces** ``` <?php class Foo {} class Bar extends Foo {} interface A {     public function myfunc(Foo $arg): Foo; } interface B {     public function myfunc(Bar $arg): Bar; } class MyClass implements A, B {     public function myfunc(Foo $arg): Bar     {         return new Bar();     } } ?> ``` **Example #4 Multiple interface inheritance** ``` <?php interface A {     public function foo(); } interface B {     public function bar(); } interface C extends A, B {     public function baz(); } class D implements C {     public function foo()     {     }     public function bar()     {     }     public function baz()     {     } } ?> ``` **Example #5 Interfaces with constants** ``` <?php interface A {     const B = 'Interface constant'; } // Prints: Interface constant echo A::B; class B implements A {     const B = 'Class constant'; } // Prints: Class constant // Prior to PHP 8.1.0, this will however not work because it was not // allowed to override constants. echo B::B; ?> ``` **Example #6 Interfaces with abstract classes** ``` <?php interface A {     public function foo(string $s): string;     public function bar(int $i): int; } // An abstract class may implement only a portion of an interface. // Classes that extend the abstract class must implement the rest. abstract class B implements A {     public function foo(string $s): string     {         return $s . PHP_EOL;     } } class C extends B {     public function bar(int $i): int     {         return $i * 2;     } } ?> ``` **Example #7 Extending and implementing simultaneously** ``` <?php class One {     /* ... */ } interface Usable {     /* ... */ } interface Updatable {     /* ... */ } // The keyword order here is important. 'extends' must come first. class Two extends One implements Usable, Updatable {     /* ... */ } ?> ``` An interface, together with type declarations, provides a good way to make sure that a particular object contains particular methods. See [instanceof](language.operators.type) operator and [type declarations](language.types.declarations). php hash_hmac_file hash\_hmac\_file ================ (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1) hash\_hmac\_file — Generate a keyed hash value using the HMAC method and the contents of a given file ### Description ``` hash_hmac_file( string $algo, string $filename, string $key, bool $binary = false ): string|false ``` ### Parameters `algo` Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See [hash\_hmac\_algos()](function.hash-hmac-algos) for a list of supported algorithms. `filename` URL describing location of file to be hashed; Supports fopen wrappers. `key` Shared secret key used for generating the HMAC variant of the message digest. `binary` When set to **`true`**, outputs raw binary data. **`false`** outputs lowercase hexits. ### Return Values Returns a string containing the calculated message digest as lowercase hexits unless `binary` is set to true in which case the raw binary representation of the message digest is returned. Returns **`false`** if the file `filename` cannot be read. ### Errors/Exceptions Throws a [ValueError](class.valueerror) exception if `algo` is unknown or is a non-cryptographic hash function. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Now throws a [ValueError](class.valueerror) exception if `algo` is unknown or is a non-cryptographic hash function; previously, **`false`** was returned instead. | | 7.2.0 | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled. | ### Examples **Example #1 **hash\_hmac\_file()** example** ``` <?php /* Create a file to calculate hash of */ file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.'); echo hash_hmac_file('md5', 'example.txt', 'secret'); ?> ``` The above example will output: ``` 7eb2b5c37443418fc77c136dd20e859c ``` ### See Also * [hash\_hmac\_algos()](function.hash-hmac-algos) - Return a list of registered hashing algorithms suitable for hash\_hmac * [hash\_hmac()](function.hash-hmac) - Generate a keyed hash value using the HMAC method * [hash\_file()](function.hash-file) - Generate a hash value using the contents of a given file php Yac::delete Yac::delete =========== (PECL yac >= 1.0.0) Yac::delete — Remove items from cache ### Description ``` public Yac::delete(string|array $keys, int $ttl = ?): bool ``` remove items from cache ### Parameters `keys` string key, or array of multiple keys to be removed `ttl` if delay is set, delete will mark the items to be invalid in ttl second. ### Return Values php The RuntimeException class The RuntimeException class ========================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Exception thrown if an error which can only be found on runtime occurs. Class synopsis -------------- class **RuntimeException** extends [Exception](class.exception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php xattr_set xattr\_set ========== (PECL xattr >= 0.9.0) xattr\_set — Set an extended attribute ### Description ``` xattr_set( string $filename, string $name, string $value, int $flags = 0 ): bool ``` This function sets the value of an extended attribute of a file. Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter. ### Parameters `filename` The file in which we set the attribute. `name` The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the `flags` parameter. `value` The value of the attribute. `flags` **Supported xattr flags**| **`XATTR_CREATE`** | Function will fail if extended attribute already exists. | | **`XATTR_REPLACE`** | Function will fail if extended attribute doesn't exist. | | **`XATTR_DONTFOLLOW`** | Do not follow the symbolic link but operate on symbolic link itself. | | **`XATTR_ROOT`** | Set attribute in root (trusted) namespace. Requires root privileges. | ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Sets extended attributes on .wav file** ``` <?php $file = 'my_favourite_song.wav'; xattr_set($file, 'Artist', 'Someone'); xattr_set($file, 'My ranking', 'Good'); xattr_set($file, 'Listen count', '34'); /* ... other code ... */ printf("You've played this song %d times", xattr_get($file, 'Listen count'));  ?> ``` ### See Also * [xattr\_get()](function.xattr-get) - Get an extended attribute * [xattr\_remove()](function.xattr-remove) - Remove an extended attribute php gmp_divexact gmp\_divexact ============= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_divexact — Exact division of numbers ### Description ``` gmp_divexact(GMP|int|string $num1, GMP|int|string $num2): GMP ``` Divides `num1` by `num2`, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that `num2` divides `num1`. ### Parameters `num1` The number being divided. A [GMP](class.gmp) object, an int or a numeric string. `num2` The number that `a` is being divided by. A [GMP](class.gmp) object, an int or a numeric string. ### Return Values A [GMP](class.gmp) object. ### Examples **Example #1 **gmp\_divexact()** example** ``` <?php $div1 = gmp_divexact("10", "2"); echo gmp_strval($div1) . "\n"; $div2 = gmp_divexact("10", "3"); // bogus result echo gmp_strval($div2) . "\n"; ?> ``` The above example will output: ``` 5 2863311534 ``` php svn_commit svn\_commit =========== (PECL svn >= 0.1.0) svn\_commit — Sends changes from the local working copy to the repository ### Description ``` svn_commit(string $log, array $targets, bool $recursive = true): array ``` Commits changes made in the local working copy files enumerated in the `targets` array to the repository, with the log message `log`. Directories in the `targets` array will be recursively committed unless `recursive` is set to **`false`**. > **Note**: This function does not have any parameters for specifying authentication, so a username and password must be set using [svn\_auth\_set\_parameter()](function.svn-auth-set-parameter) > > ### Parameters `log` String log text to commit `targets` Array of local paths of files to be committed **Warning** This parameter must be an array, a string for a single target is not acceptable. > **Note**: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use [realpath()](function.realpath) or dirname(\_\_FILE\_\_). > > `recursive` Boolean flag to disable recursive committing of directories in the `targets` array. Default is **`true`**. ### Return Values Returns array in form of: ``` array( 0 => integer revision number of commit 1 => string ISO 8601 date and time of commit 2 => name of committer ) ``` Returns **`false`** on failure. ### Examples **Example #1 Basic example** This example commits the calculator directory to a repository, using the username Bob and the password abc123 (hopefully, his password is stronger): ``` <?php svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob'); svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123'); var_dump(svn_commit('Log message of Bob\'s commit', array(realpath('calculator')))); ?> ``` The above example will output: ``` array( 0 => 1415, 1 => '2007-05-26T01:44:28.453125Z', 2 => 'Bob' ) ``` ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. ### See Also * [svn\_auth\_set\_parameter()](function.svn-auth-set-parameter) - Sets an authentication parameter * [» SVN documentation on svn commit](http://svnbook.red-bean.com/en/1.2/svn.ref.svn.c.commit.html) php Parle\RParser::sigil Parle\RParser::sigil ==================== (PECL parle >= 0.7.0) Parle\RParser::sigil — Retrieve a matching part of a rule ### Description ``` public Parle\RParser::sigil(int $idx = ?): string ``` Retrieve a part of the match by a rule. This method is equivalent to the pseudo variable functionality in Bison. ### Parameters `idx` Match index, zero based. ### Return Values Returns a string with the matched part.
programming_docs
php Yar_Client_Exception::getType Yar\_Client\_Exception::getType =============================== (PECL yar >= 1.0.0) Yar\_Client\_Exception::getType — Retrieve exception's type ### Description ``` public Yar_Client_Exception::getType(): string ``` ### Parameters This function has no parameters. ### Return Values Returns `"Yar_Exception_Client"`. ### Examples **Example #1 **Yar\_Client\_Exception::getType()** example** ``` <?php /* ... */ ?> ``` The above example will output something similar to: ``` ... ``` ### See Also * **Yaf\_Server\_Exception::getType()** php openal_source_stop openal\_source\_stop ==================== (PECL openal >= 0.1.0) openal\_source\_stop — Stop playing the source ### Description ``` openal_source_stop(resource $source): bool ``` ### Parameters `source` An [Open AL(Source)](https://www.php.net/manual/en/openal.resources.php) resource (previously created by [openal\_source\_create()](function.openal-source-create)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [openal\_source\_play()](function.openal-source-play) - Start playing the source * [openal\_source\_pause()](function.openal-source-pause) - Pause the source * [openal\_source\_rewind()](function.openal-source-rewind) - Rewind the source php ibase_trans ibase\_trans ============ (PHP 5, PHP 7 < 7.4.0) ibase\_trans — Begin a transaction ### Description ``` ibase_trans(int $trans_args = ?, resource $link_identifier = ?): resource ``` ``` ibase_trans(resource $link_identifier = ?, int $trans_args = ?): resource ``` Begins a transaction. > > **Note**: > > > The first call to **ibase\_trans()** will not return the default transaction of a connection. All transactions started by **ibase\_trans()** will be rolled back at the end of the script if they were not committed or rolled back by either [ibase\_commit()](function.ibase-commit) or [ibase\_rollback()](function.ibase-rollback). > > > > **Note**: > > > This function will accept multiple `trans_args` and `link_identifier` arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query! > > If you use transactions over multiple databases, you will have to specify both the `link_id` and `transaction_id` in calls to [ibase\_query()](function.ibase-query) and [ibase\_prepare()](function.ibase-prepare). > > ### Parameters `trans_args` `trans_args` can be a combination of **`IBASE_READ`**, **`IBASE_WRITE`**, **`IBASE_COMMITTED`**, **`IBASE_CONSISTENCY`**, **`IBASE_CONCURRENCY`**, **`IBASE_REC_VERSION`**, **`IBASE_REC_NO_VERSION`**, **`IBASE_WAIT`** and **`IBASE_NOWAIT`**. `link_identifier` An InterBase link identifier. If omitted, the last opened link is assumed. ### Return Values Returns a transaction handle, or **`false`** on error. php ReflectionClassConstant::isProtected ReflectionClassConstant::isProtected ==================================== (PHP 7 >= 7.1.0, PHP 8) ReflectionClassConstant::isProtected — Checks if class constant is protected ### Description ``` public ReflectionClassConstant::isProtected(): bool ``` Checks if the class constant is protected. ### Parameters This function has no parameters. ### Return Values **`true`** if the class constant is protected, otherwise **`false`** ### See Also * [ReflectionClassConstant::isFinal()](reflectionclassconstant.isfinal) - Checks if class constant is final * [ReflectionClassConstant::isPublic()](reflectionclassconstant.ispublic) - Checks if class constant is public * [ReflectionClassConstant::isPrivate()](reflectionclassconstant.isprivate) - Checks if class constant is private php SplDoublyLinkedList::rewind SplDoublyLinkedList::rewind =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::rewind — Rewind iterator back to the start ### Description ``` public SplDoublyLinkedList::rewind(): void ``` This rewinds the iterator to the beginning. ### Parameters This function has no parameters. ### Return Values No value is returned. php pg_affected_rows pg\_affected\_rows ================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_affected\_rows — Returns number of affected records (tuples) ### Description ``` pg_affected_rows(PgSql\Result $result): int ``` **pg\_affected\_rows()** returns the number of tuples (instances/records/rows) affected by `INSERT`, `UPDATE`, and `DELETE` queries. Since PostgreSQL 9.0 and above, the server returns the number of SELECTed rows. Older PostgreSQL return 0 for SELECT. > > **Note**: > > > This function used to be called **pg\_cmdtuples()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). ### Return Values The number of rows affected by the query. If no tuple is affected, it will return `0`. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_affected\_rows()** example** ``` <?php $result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')"); $cmdtuples = pg_affected_rows($result); echo $cmdtuples . " tuples are affected.\n"; ?> ``` The above example will output: ``` 1 tuples are affected. ``` ### See Also * [pg\_query()](function.pg-query) - Execute a query * [pg\_query\_params()](function.pg-query-params) - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text * [pg\_execute()](function.pg-execute) - Sends a request to execute a prepared statement with given parameters, and waits for the result * [pg\_num\_rows()](function.pg-num-rows) - Returns the number of rows in a result php Imagick::getGravity Imagick::getGravity =================== (PECL imagick 2, PECL imagick 3) Imagick::getGravity — Gets the gravity ### Description ``` public Imagick::getGravity(): int ``` Gets the global gravity property for the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer. ### Parameters This function has no parameters. ### Return Values Returns the gravity property. Refer to the list of [gravity constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.gravity). php bccomp bccomp ====== (PHP 4, PHP 5, PHP 7, PHP 8) bccomp — Compare two arbitrary precision numbers ### Description ``` bccomp(string $num1, string $num2, ?int $scale = null): int ``` Compares the `num1` to the `num2` and returns the result as an integer. ### Parameters `num1` The left operand, as a string. `num2` The right operand, as a string. `scale` The optional `scale` parameter is used to set the number of digits after the decimal place which will be used in the comparison. ### Return Values Returns 0 if the two operands are equal, 1 if the `num1` is larger than the `num2`, -1 otherwise. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `scale` is now nullable. | ### Examples **Example #1 **bccomp()** example** ``` <?php echo bccomp('1', '2') . "\n";   // -1 echo bccomp('1.00001', '1', 3); // 0 echo bccomp('1.00001', '1', 5); // 1 ?> ``` php linkinfo linkinfo ======== (PHP 4, PHP 5, PHP 7, PHP 8) linkinfo — Gets information about a link ### Description ``` linkinfo(string $path): int|false ``` Gets information about a link. This function is used to verify if a link (pointed to by `path`) really exists (using the same method as the S\_ISLNK macro defined in stat.h). ### Parameters `path` Path to the link. ### Return Values **linkinfo()** returns the `st_dev` field of the Unix C stat structure returned by the `lstat` system call. Returns a non-negative integer on success, -1 in case the link was not found, or **`false`** if an open.base\_dir violation occurs. ### Examples **Example #1 **linkinfo()** example** ``` <?php echo linkinfo('/vmlinuz'); // 835 ?> ``` ### See Also * [symlink()](function.symlink) - Creates a symbolic link * [link()](function.link) - Create a hard link * [readlink()](function.readlink) - Returns the target of a symbolic link php SVMModel::predict_probability SVMModel::predict\_probability ============================== (PECL svm >= 0.1.4) SVMModel::predict\_probability — Return class probabilities for previous unseen data ### Description ``` public SVMModel::predict_probability(array $data): float ``` This function accepts an array of data and attempts to predict the class, as with the predict function. Additionally, however, this function returns an array of probabilities, one per class in the model, which represent the estimated chance of the data supplied being a member of that class. Requires that the model to be used has been trained with the probability parameter set to true. ### Parameters `data` The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous. `probabilities` The supplied value will be filled with the probabilities. This will be either null, in the case of a model without probability information, or an array where the index is the class name and the value the predicted probability. ### Return Values Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error ### See Also * **SVM::predict()** php ReflectionClass::getConstructor ReflectionClass::getConstructor =============================== (PHP 5, PHP 7, PHP 8) ReflectionClass::getConstructor — Gets the constructor of the class ### Description ``` public ReflectionClass::getConstructor(): ?ReflectionMethod ``` Gets the constructor of the reflected class. ### Parameters This function has no parameters. ### Return Values A [ReflectionMethod](class.reflectionmethod) object reflecting the class' constructor, or **`null`** if the class has no constructor. ### Examples **Example #1 Basic usage of **ReflectionClass::getConstructor()**** ``` <?php $class = new ReflectionClass('ReflectionClass'); $constructor = $class->getConstructor(); var_dump($constructor); ?> ``` The above example will output: ``` object(ReflectionMethod)#2 (2) { ["name"]=> string(11) "__construct" ["class"]=> string(15) "ReflectionClass" } ``` ### See Also * [ReflectionClass::getName()](reflectionclass.getname) - Gets class name php date_time_set date\_time\_set =============== (PHP 5 >= 5.2.0, PHP 7, PHP 8) date\_time\_set — Alias of [DateTime::setTime()](datetime.settime) ### Description This function is an alias of: [DateTime::setTime()](datetime.settime) php Imagick::setImageIndex Imagick::setImageIndex ====================== (PECL imagick 2, PECL imagick 3) Imagick::setImageIndex — Set the iterator position **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::setImageIndex(int $index): bool ``` Set the iterator to the position in the image list specified with the index parameter. This method has been deprecated. See [Imagick::setIteratorIndex()](imagick.setiteratorindex). ### Parameters `index` The position to set the iterator to ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php socket_accept socket\_accept ============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_accept — Accepts a connection on a socket ### Description ``` socket_accept(Socket $socket): Socket|false ``` After the socket `socket` has been created using [socket\_create()](function.socket-create), bound to a name with [socket\_bind()](function.socket-bind), and told to listen for connections with [socket\_listen()](function.socket-listen), this function will accept incoming connections on that socket. Once a successful connection is made, a new [Socket](class.socket) instance is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, **socket\_accept()** will block until a connection becomes present. If `socket` has been made non-blocking using [socket\_set\_blocking()](function.socket-set-blocking) or [socket\_set\_nonblock()](function.socket-set-nonblock), **`false`** will be returned. The [Socket](class.socket) instance returned by **socket\_accept()** may not be used to accept new connections. The original listening socket `socket`, however, remains open and may be reused. ### Parameters `socket` A [Socket](class.socket) instance created with [socket\_create()](function.socket-create). ### Return Values Returns a new [Socket](class.socket) instance on success, or **`false`** on error. The actual error code can be retrieved by calling [socket\_last\_error()](function.socket-last-error). This error code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual explanation of the error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [Socket](class.socket) instance now; previously, a resource was returned. | ### See Also * [socket\_connect()](function.socket-connect) - Initiates a connection on a socket * [socket\_listen()](function.socket-listen) - Listens for a connection on a socket * [socket\_create()](function.socket-create) - Create a socket (endpoint for communication) * [socket\_bind()](function.socket-bind) - Binds a name to a socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error php ReflectionFunctionAbstract::getClosureThis ReflectionFunctionAbstract::getClosureThis ========================================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure ### Description ``` public ReflectionFunctionAbstract::getClosureThis(): ?object ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns $this pointer. Returns **`null`** in case of an error. php lzf_compress lzf\_compress ============= (PECL lzf >= 0.1.0) lzf\_compress — LZF compression ### Description ``` lzf_compress(string $data): string ``` **lzf\_compress()** compresses the given `data` string using LZF encoding. ### Parameters `data` The string to compress. ### Return Values Returns the compressed data or **`false`** if an error occurred. ### See Also * [lzf\_decompress()](function.lzf-decompress) - LZF decompression php SolrQuery::getTermsReturnRaw SolrQuery::getTermsReturnRaw ============================ (PECL solr >= 0.9.2) SolrQuery::getTermsReturnRaw — Whether or not to return raw characters ### Description ``` public SolrQuery::getTermsReturnRaw(): bool ``` Returns a boolean indicating whether or not to return the raw characters of the indexed term, regardless of if it is human readable ### Parameters This function has no parameters. ### Return Values Returns a boolean on success and **`null`** if not set. php http_response_code http\_response\_code ==================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) http\_response\_code — Get or Set the HTTP response code ### Description ``` http_response_code(int $response_code = 0): int|bool ``` Gets or sets the HTTP response status code. ### Parameters `response_code` The optional `response_code` will set the response code. ### Return Values If `response_code` is provided, then the previous status code will be returned. If `response_code` is not provided, then the current status code will be returned. Both of these values will default to a `200` status code if used in a web server environment. **`false`** will be returned if `response_code` is not provided and it is not invoked in a web server environment (such as from a CLI application). **`true`** will be returned if `response_code` is provided and it is not invoked in a web server environment (but only when no previous response status has been set). ### Examples **Example #1 Using **http\_response\_code()** in a web server environment** ``` <?php // Get the current response code and set a new one var_dump(http_response_code(404)); // Get the new response code var_dump(http_response_code()); ?> ``` The above example will output: ``` int(200) int(404) ``` **Example #2 Using **http\_response\_code()** in a CLI environment** ``` <?php // Get the current default response code var_dump(http_response_code()); // Set a response code var_dump(http_response_code(201)); // Get the new response code var_dump(http_response_code()); ?> ``` The above example will output: ``` bool(false) bool(true) int(201) ``` ### See Also * [header()](function.header) - Send a raw HTTP header * [headers\_list()](function.headers-list) - Returns a list of response headers sent (or ready to send) php IntlCalendar::setRepeatedWallTimeOption IntlCalendar::setRepeatedWallTimeOption ======================================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions ### Description Object-oriented style ``` public IntlCalendar::setRepeatedWallTimeOption(int $option): bool ``` Procedural style ``` intlcal_set_repeated_wall_time_option(IntlCalendar $calendar, int $option): bool ``` Sets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is **`IntlCalendar::WALLTIME_LAST`** (take the post-DST instant). The other possible value is **`IntlCalendar::WALLTIME_FIRST`** (take the instant that occurs during DST). This function requires ICU 4.9 or later. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `option` One of the constants **`IntlCalendar::WALLTIME_FIRST`** or **`IntlCalendar::WALLTIME_LAST`**. ### Return Values Always returns **`true`**. ### Examples See the example on [IntlCalendar::getRepeatedWallTimeOption()](intlcalendar.getrepeatedwalltimeoption). ### See Also * [intlCalendar::getRepeatedWallTimeOption()](intlcalendar.getrepeatedwalltimeoption) - Get behavior for handling repeating wall time * [intlCalendar::setSkippedWallTimeOption()](intlcalendar.setskippedwalltimeoption) - Set behavior for handling skipped wall times at positive timezone offset transitions * [intlCalendar::getSkippedWallTimeOption()](intlcalendar.getskippedwalltimeoption) - Get behavior for handling skipped wall time php Imagick::clampImage Imagick::clampImage =================== (PECL imagick 3 >= 3.3.0) Imagick::clampImage — Description ### Description ``` public Imagick::clampImage(int $channel = Imagick::CHANNEL_DEFAULT): bool ``` Restricts the color range from 0 to the quantum depth. ### Parameters `channel` ### Return Values Returns **`true`** on success or **`false`** on failure.
programming_docs
php CURLStringFile::__construct CURLStringFile::\_\_construct ============================= (PHP 8 >= 8.1.0) CURLStringFile::\_\_construct — Create a CURLStringFile object ### Description public **CURLStringFile::\_\_construct**(string `$data`, string `$postname`, string `$mime` = "application/octet-stream") Creates a [CURLStringFile](class.curlstringfile) object, used to upload a file with **`CURLOPT_POSTFIELDS`**. ### Parameters `data` The contents to be uploaded. `postname` The name of the file to be used in the upload data. `mime` MIME type of the file (default is `application/octet-stream`). ### Examples **Example #1 **CURLStringFile::\_\_construct()** example** ``` <?php /* http://example.com/upload.php: <?php var_dump($_FILES); var_dump(file_get_contents($_FILES['test_string']['tmp_name'])); ?> */ // Create a cURL handle $ch = curl_init('http://example.com/upload.php'); // Create a CURLStringFile object $cstringfile = new CURLStringFile('test upload contents','test.txt','text/plain'); // Assign POST data $data = array('test_string' => $cstringfile); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Execute the handle curl_exec($ch); ?> ``` The above example will output: ``` array(1) { ["test_string"]=> array(5) { ["name"]=> string(8) "test.txt" ["type"]=> string(10) "text/plain" ["tmp_name"]=> string(14) "/tmp/phpTtaoCz" ["error"]=> int(0) ["size"]=> int(20) } } string(20) "test upload contents" ``` ### See Also * [curl\_setopt()](function.curl-setopt) - Set an option for a cURL transfer php floor floor ===== (PHP 4, PHP 5, PHP 7, PHP 8) floor — Round fractions down ### Description ``` floor(int|float $num): float ``` Returns the next lowest integer value (as float) by rounding down `num` if necessary. ### Parameters `num` The numeric value to round ### Return Values `num` rounded to the next lowest integer. The return value of **floor()** is still of type float. This function returns **`false`** in case of an error (e.g. passing an array). ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `num` no longer accepts internal objects which support numeric conversion. | ### Examples **Example #1 **floor()** example** ``` <?php echo floor(4.3);   // 4 echo floor(9.999); // 9 echo floor(-3.14); // -4 ?> ``` ### See Also * [ceil()](function.ceil) - Round fractions up * [round()](function.round) - Rounds a float php call_user_func_array call\_user\_func\_array ======================= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) call\_user\_func\_array — Call a callback with an array of parameters ### Description ``` call_user_func_array(callable $callback, array $args): mixed ``` Calls the `callback` given by the first parameter with the parameters in `args`. ### Parameters `callback` The [callable](language.types.callable) to be called. `args` The parameters to be passed to the callback, as an indexed array. ### Return Values Returns the return value of the callback, or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `args` keys will now be interpreted as parameter names, instead of being silently ignored. | ### Examples **Example #1 **call\_user\_func\_array()** example** ``` <?php function foobar($arg, $arg2) {     echo __FUNCTION__, " got $arg and $arg2\n"; } class foo {     function bar($arg, $arg2) {         echo __METHOD__, " got $arg and $arg2\n";     } } // Call the foobar() function with 2 arguments call_user_func_array("foobar", array("one", "two")); // Call the $foo->bar() method with 2 arguments $foo = new foo; call_user_func_array(array($foo, "bar"), array("three", "four")); ?> ``` The above example will output something similar to: ``` foobar got one and two foo::bar got three and four ``` **Example #2 **call\_user\_func\_array()** using namespace name** ``` <?php namespace Foobar; class Foo {     static public function test($name) {         print "Hello {$name}!\n";     } } call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes')); call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip')); ?> ``` The above example will output something similar to: ``` Hello Hannes! Hello Philip! ``` **Example #3 Using lambda function** ``` <?php $func = function($arg1, $arg2) {     return $arg1 * $arg2; }; var_dump(call_user_func_array($func, array(2, 4))); ?> ``` The above example will output: ``` int(8) ``` **Example #4 Passing values by reference** ``` <?php function mega(&$a){     $a = 55;     echo "function mega \$a=$a\n"; } $bar = 77; call_user_func_array('mega',array(&$bar)); echo "global \$bar=$bar\n"; ?> ``` The above example will output: ``` function mega $a=55 global $bar=55 ``` ### Notes > > **Note**: > > > Callbacks registered with functions such as [call\_user\_func()](function.call-user-func) and **call\_user\_func\_array()** will not be called if there is an uncaught exception thrown in a previous callback. > > > ### See Also * [call\_user\_func()](function.call-user-func) - Call the callback given by the first parameter * [ReflectionFunction::invokeArgs()](reflectionfunction.invokeargs) - Invokes function args * [ReflectionMethod::invokeArgs()](reflectionmethod.invokeargs) - Invoke args php error_clear_last error\_clear\_last ================== (PHP 7, PHP 8) error\_clear\_last — Clear the most recent error ### Description ``` error_clear_last(): void ``` ### Parameters This function has no parameters. ### Return Values Clears the most recent errors, making it unable to be retrieved with [error\_get\_last()](function.error-get-last). ### Examples **Example #1 An **error\_clear\_last()** example** ``` <?php var_dump(error_get_last()); error_clear_last(); var_dump(error_get_last()); @$a = $b; var_dump(error_get_last()); error_clear_last(); var_dump(error_get_last()); ?> ``` The above example will output something similar to: ``` NULL NULL array(4) { ["type"]=> int(8) ["message"]=> string(21) "Undefined variable: b" ["file"]=> string(9) "%s" ["line"]=> int(6) } NULL ``` ### See Also * [Error constants](https://www.php.net/manual/en/errorfunc.constants.php) php IntlChar::isJavaIDPart IntlChar::isJavaIDPart ====================== (PHP 7, PHP 8) IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier ### Description ``` public static IntlChar::isJavaIDPart(int|string $codepoint): ?bool ``` Determines if the specified character is permissible in a Java identifier. In addition to [IntlChar::isIDPart()](intlchar.isidpart), **`true`** for characters with general category "Sc" (currency symbols). ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` may occur in a Java identifier, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isJavaIDPart("A")); var_dump(IntlChar::isJavaIDPart("$")); var_dump(IntlChar::isJavaIDPart("\n")); var_dump(IntlChar::isJavaIDPart("\u{2603}")); ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) bool(false) ``` ### See Also * [IntlChar::isIDIgnorable()](intlchar.isidignorable) - Check if code point is an ignorable character * [IntlChar::isIDPart()](intlchar.isidpart) - Check if code point is permissible in an identifier * [IntlChar::isJavaIDStart()](intlchar.isjavaidstart) - Check if code point is permissible as the first character in a Java identifier * [IntlChar::isalpha()](intlchar.isalpha) - Check if code point is a letter character * [IntlChar::isdigit()](intlchar.isdigit) - Check if code point is a digit character php mb_encoding_aliases mb\_encoding\_aliases ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) mb\_encoding\_aliases — Get aliases of a known encoding type ### Description ``` mb_encoding_aliases(string $encoding): array ``` Returns an array of aliases for a known `encoding` type. ### Parameters `encoding` The encoding type being checked, for aliases. ### Return Values Returns a numerically indexed array of encoding aliases on success, or **`false`** on failure ### Errors/Exceptions Emits an **`E_WARNING`** level error if `encoding` is unknown. ### Examples **Example #1 **mb\_encoding\_aliases()** example** ``` <?php $encoding        = 'ASCII'; $known_encodings = mb_list_encodings(); if (in_array($encoding, $known_encodings)) {     $aliases = mb_encoding_aliases($encoding);     print_r($aliases); } else {     echo "Unknown ($encoding) encoding.\n"; } ?> ``` The above example will output something similar to: ``` Array ( [0] => ANSI_X3.4-1968 [1] => iso-ir-6 [2] => ANSI_X3.4-1986 [3] => ISO_646.irv:1991 [4] => US-ASCII [5] => ISO646-US [6] => us [7] => IBM367 [8] => cp367 [9] => csASCII ) ``` ### See Also * [mb\_list\_encodings()](function.mb-list-encodings) - Returns an array of all supported encodings php imagecreatefromstring imagecreatefromstring ===================== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) imagecreatefromstring — Create a new image from the image stream in the string ### Description ``` imagecreatefromstring(string $data): GdImage|false ``` **imagecreatefromstring()** returns an image identifier representing the image obtained from the given `data`. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, BMP, WBMP, GD2, and WEBP. ### Parameters `data` A string containing the image data. ### Return Values An image object will be returned on success. **`false`** is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded. ### Errors/Exceptions **imagecreatefromstring()** raises an E\_WARNING level error, if the data is not in a recognized format. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. | | 7.3.0 | WEBP is supported now (if supported by the libgd in use). | ### Examples **Example #1 **imagecreatefromstring()** example** ``` <?php $data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'        . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'        . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'        . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg=='; $data = base64_decode($data); $im = imagecreatefromstring($data); if ($im !== false) {     header('Content-Type: image/png');     imagepng($im);     imagedestroy($im); } else {     echo 'An error occurred.'; } ?> ``` The above example will output something similar to: ### See Also * [imagecreatefromjpeg()](function.imagecreatefromjpeg) - Create a new image from file or URL * [imagecreatefrompng()](function.imagecreatefrompng) - Create a new image from file or URL * [imagecreatefromgif()](function.imagecreatefromgif) - Create a new image from file or URL * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image php The SplMaxHeap class The SplMaxHeap class ==================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top. Class synopsis -------------- class **SplMaxHeap** extends [SplHeap](class.splheap) { /\* Methods \*/ ``` protected compare(mixed $value1, mixed $value2): int ``` /\* Inherited methods \*/ ``` protected SplHeap::compare(mixed $value1, mixed $value2): int ``` ``` public SplHeap::count(): int ``` ``` public SplHeap::current(): mixed ``` ``` public SplHeap::extract(): mixed ``` ``` public SplHeap::insert(mixed $value): bool ``` ``` public SplHeap::isCorrupted(): bool ``` ``` public SplHeap::isEmpty(): bool ``` ``` public SplHeap::key(): int ``` ``` public SplHeap::next(): void ``` ``` public SplHeap::recoverFromCorruption(): bool ``` ``` public SplHeap::rewind(): void ``` ``` public SplHeap::top(): mixed ``` ``` public SplHeap::valid(): bool ``` } Table of Contents ----------------- * [SplMaxHeap::compare](splmaxheap.compare) — Compare elements in order to place them correctly in the heap while sifting up php Gmagick::flipimage Gmagick::flipimage ================== (PECL gmagick >= Unknown) Gmagick::flipimage — Creates a vertical mirror image ### Description ``` public Gmagick::flipimage(): Gmagick ``` Creates a vertical mirror image by reflecting the pixels around the central x-axis. ### Parameters This function has no parameters. ### Return Values The flipped [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. ### See Also * [Gmagick::flopimage()](gmagick.flopimage) - Creates a horizontal mirror image php GearmanTask::isRunning GearmanTask::isRunning ====================== (PECL gearman >= 0.5.0) GearmanTask::isRunning — Test whether the task is currently running ### Description ``` public GearmanTask::isRunning(): bool ``` Indicates whether or not this task is currently running. ### Parameters This function has no parameters. ### Return Values **`true`** if the task is running, **`false`** otherwise. php mb_http_input mb\_http\_input =============== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_http\_input — Detect HTTP input character encoding ### Description ``` mb_http_input(?string $type = null): array|string|false ``` Detects the HTTP input character encoding. ### Parameters `type` Input string specifies the input type. `"G"` for GET, `"P"` for POST, `"C"` for COOKIE, `"S"` for string, `"L"` for list, and `"I"` for the whole list (will return array). If type is omitted, it returns the last input type processed. ### Return Values The character encoding name, as per the `type`, or an array of character encoding names, if `type` is `"I"`. If **mb\_http\_input()** does not process specified HTTP input, it returns **`false`**. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `type` is nullable now. | ### See Also * [mb\_internal\_encoding()](function.mb-internal-encoding) - Set/Get internal character encoding * [mb\_http\_output()](function.mb-http-output) - Set/Get HTTP output character encoding * [mb\_detect\_order()](function.mb-detect-order) - Set/Get character encoding detection order php imap_utf7_encode imap\_utf7\_encode ================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_utf7\_encode — Converts ISO-8859-1 string to modified UTF-7 text ### Description ``` imap_utf7_encode(string $string): string ``` Converts `string` to modified UTF-7 text. This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters. ### Parameters `string` An ISO-8859-1 string. ### Return Values Returns `string` encoded with the modified UTF-7 encoding as defined in [» RFC 2060](http://www.faqs.org/rfcs/rfc2060), section 5.1.3. ### See Also * [imap\_utf7\_decode()](function.imap-utf7-decode) - Decodes a modified UTF-7 encoded string php Yaf_Controller_Abstract::setViewpath Yaf\_Controller\_Abstract::setViewpath ====================================== (Yaf >=1.0.0) Yaf\_Controller\_Abstract::setViewpath — The setViewpath purpose ### Description ``` public Yaf_Controller_Abstract::setViewpath(string $view_directory): void ``` ### Parameters `view_directory` ### Return Values php InternalIterator::next InternalIterator::next ====================== (PHP 8) InternalIterator::next — Move forward to next element ### Description ``` public InternalIterator::next(): void ``` Moves the current position to the next element. ### Parameters This function has no parameters. ### Return Values No value is returned. php IntlCalendar::getGreatestMinimum IntlCalendar::getGreatestMinimum ================================ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field ### Description Object-oriented style ``` public IntlCalendar::getGreatestMinimum(int $field): int|false ``` Procedural style ``` intlcal_get_greatest_minimum(IntlCalendar $calendar, int $field): int|false ``` Returns the largest local minimum for a field. This should be a value larger or equal to that returned by [IntlCalendar::getActualMinimum()](intlcalendar.getactualminimum), which is in its turn larger or equal to that returned by [IntlCalendar::getMinimum()](intlcalendar.getminimum). All these three functions return the same value for the Gregorian calendar. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `field` One of the [IntlCalendar](class.intlcalendar) date/time [field constants](class.intlcalendar#intlcalendar.constants). These are integer values between `0` and **`IntlCalendar::FIELD_COUNT`**. ### Return Values An int representing a field value, in the fieldʼs unit, or **`false`** on failure. php mailparse_msg_create mailparse\_msg\_create ====================== (PECL mailparse >= 0.9.0) mailparse\_msg\_create — Create a mime mail resource ### Description ``` mailparse_msg_create(): resource ``` Create a `MIME` mail resource. ### Parameters This function has no parameters. ### Return Values Returns a handle that can be used to parse a message. ### Notes > > **Note**: > > > It is recommended to call [mailparse\_msg\_free()](function.mailparse-msg-free) on the result of this function, when it is no longer needed, to avoid memory leaks. > > ### See Also * [mailparse\_msg\_free()](function.mailparse-msg-free) - Frees a MIME resource * [mailparse\_msg\_parse\_file()](function.mailparse-msg-parse-file) - Parses a file php ctype_digit ctype\_digit ============ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ctype\_digit — Check for numeric character(s) ### Description ``` ctype_digit(mixed $text): bool ``` Checks if all of the characters in the provided string, `text`, are numerical. ### Parameters `text` The tested string. > > **Note**: > > > If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer. > > > **Warning** As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to [chr()](function.chr) should be made. ### Return Values Returns **`true`** if every character in the string `text` is a decimal digit, **`false`** otherwise. When called with an empty string the result will always be **`false`**. ### Examples **Example #1 A **ctype\_digit()** example** ``` <?php $strings = array('1820.20', '10002', 'wsl!12'); foreach ($strings as $testcase) {     if (ctype_digit($testcase)) {         echo "The string $testcase consists of all digits.\n";     } else {         echo "The string $testcase does not consist of all digits.\n";     } } ?> ``` The above example will output: ``` The string 1820.20 does not consist of all digits. The string 10002 consists of all digits. The string wsl!12 does not consist of all digits. ``` **Example #2 A **ctype\_digit()** example comparing strings with integers** ``` <?php $numeric_string = '42'; $integer        = 42; ctype_digit($numeric_string);  // true ctype_digit($integer);         // false (ASCII 42 is the * character) is_numeric($numeric_string);   // true is_numeric($integer);          // true ?> ``` ### See Also * [ctype\_alnum()](function.ctype-alnum) - Check for alphanumeric character(s) * [ctype\_xdigit()](function.ctype-xdigit) - Check for character(s) representing a hexadecimal digit * [is\_numeric()](function.is-numeric) - Finds whether a variable is a number or a numeric string * [is\_int()](function.is-int) - Find whether the type of a variable is integer * [is\_string()](function.is-string) - Find whether the type of a variable is string
programming_docs
php ImagickPixel::getColorCount ImagickPixel::getColorCount =========================== (PECL imagick 2, PECL imagick 3) ImagickPixel::getColorCount — Returns the color count associated with this color ### Description ``` public ImagickPixel::getColorCount(): int ``` Returns the color count associated with this color. The color count is the number of pixels in the image that have the same color as this ImagickPixel. ImagickPixel::getColorCount appears to only work for ImagickPixel objects created through Imagick::getImageHistogram() ### Parameters This function has no parameters. ### Return Values Returns the color count as an integer on success, throws ImagickPixelException on failure. ### Examples **Example #1 ImagickPixel **getColorCount()**** ``` <?php     $imagick = new \Imagick();     $imagick->newPseudoImage(640, 480, "magick:logo");     $histogramElements = $imagick->getImageHistogram();     $lastColor = array_pop($histogramElements);     echo "Last pixel color count is: ".$lastColor->getColorCount(); ?> ``` The output for this will be similar to: ``` Last pixel color count is: 256244 ``` php imap_clearflag_full imap\_clearflag\_full ===================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_clearflag\_full — Clears flags on messages ### Description ``` imap_clearflag_full( IMAP\Connection $imap, string $sequence, string $flag, int $options = 0 ): bool ``` This function causes a store to delete the specified `flag` to the flags set for the messages in the specified `sequence`. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `sequence` A sequence of message numbers. You can enumerate desired messages with the `X,Y` syntax, or retrieve all messages within an interval with the `X:Y` syntax `flag` The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by [» RFC2060](http://www.faqs.org/rfcs/rfc2060)) `options` `options` are a bit mask and may contain the single option: * **`ST_UID`** - The sequence argument contains UIDs instead of sequence numbers ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_setflag\_full()](function.imap-setflag-full) - Sets flags on messages php Phar::delete Phar::delete ============ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::delete — Delete a file within a phar archive ### Description ``` public Phar::delete(string $localName): bool ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > Delete a file within an archive. This is the functional equivalent of calling [unlink()](function.unlink) on the stream wrapper equivalent, as shown in the example below. ### Parameters `localName` Path within an archive to the file to delete. ### Return Values returns **`true`** on success, but it is better to check for thrown exception, and assume success if none is thrown. ### Errors/Exceptions Throws [PharException](class.pharexception) if errors occur while flushing changes to disk. ### Examples **Example #1 A **Phar::delete()** example** ``` <?php try {     $phar = new Phar('myphar.phar');     $phar->delete('unlink/me.php');     // this is equivalent to:     unlink('phar://myphar.phar/unlink/me.php'); } catch (Exception $e) {     // handle errors } ?> ``` ### See Also * [PharData::delete()](phardata.delete) - Delete a file within a tar/zip archive * [Phar::unlinkArchive()](phar.unlinkarchive) - Completely remove a phar archive from disk and from memory php SolrQuery::getHighlightRegexMaxAnalyzedChars SolrQuery::getHighlightRegexMaxAnalyzedChars ============================================ (PECL solr >= 0.9.2) SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter ### Description ``` public SolrQuery::getHighlightRegexMaxAnalyzedChars(): int ``` Returns the maximum number of characters from a field when using the regex fragmenter ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php GearmanClient::error GearmanClient::error ==================== (PECL gearman >= 0.5.0) GearmanClient::error — Returns an error string for the last error encountered ### Description ``` public GearmanClient::error(): string ``` Returns an error string for the last error encountered. ### Parameters This function has no parameters. ### Return Values A human readable error string. ### See Also * [GearmanClient::getErrno()](gearmanclient.geterrno) - Get an errno value php stream_bucket_prepend stream\_bucket\_prepend ======================= (PHP 5, PHP 7, PHP 8) stream\_bucket\_prepend — Prepend bucket to brigade ### Description ``` stream_bucket_prepend(resource $brigade, object $bucket): void ``` This function can be called to prepend a bucket to a bucket brigade. It is typically called from [php\_user\_filter::filter()](php-user-filter.filter). ### Parameters `brigade` `brigade` is a resource pointing to a `bucket brigade` which contains one or more `bucket` objects. `bucket` A bucket object. ### Return Values No value is returned. ### Examples **Example #1 **stream\_bucket\_prepend()** examples** ``` <?php class foo extends php_user_filter {   protected $calls = 0;   public function filter($in, $out, &$consumed, $closing) {     while ($bucket = stream_bucket_make_writeable($in)) {       $consumed += $bucket->datalen;       if ($this->calls++ == 2) {         // This bucket will appear again before any other bucket.         stream_bucket_prepend($in, $bucket);       }     }     return PSFS_FEED_ME;   } } stream_filter_register('test', 'foo'); print  file_get_contents('php://filter/read=test/resource=foo'); ?> ``` php Imagick::displayImages Imagick::displayImages ====================== (PECL imagick 2, PECL imagick 3) Imagick::displayImages — Displays an image or image sequence ### Description ``` public Imagick::displayImages(string $servername): bool ``` Displays an image or image sequence on a X server. ### Parameters `servername` The X server name ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php sodium_crypto_secretstream_xchacha20poly1305_init_push sodium\_crypto\_secretstream\_xchacha20poly1305\_init\_push =========================================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_secretstream\_xchacha20poly1305\_init\_push — Initialize a secretstream context for encryption ### Description ``` sodium_crypto_secretstream_xchacha20poly1305_init_push(string $key): array ``` Initialize a secretstream context for encryption. ### Parameters `key` Cryptography key. See [sodium\_crypto\_secretstream\_xchacha20poly1305\_keygen()](function.sodium-crypto-secretstream-xchacha20poly1305-keygen). ### Return Values An array with two string values: * The secretstream state, needed for further pushes * The secretstream header, which needs to be provided to the recipient so they can pull data ### Examples **Example #1 **sodium\_crypto\_secretstream\_xchacha20poly1305\_init\_push()** example** ``` <?php function encrypt_file(string $inputFilePath, string $outputFilePath, string $key): void {     [$state, $header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($key);     $inputFile = fopen($inputFilePath, 'rb');     $outputFile = fopen($outputFilePath, 'wb');     // Write the header:     fwrite($outputFile, $header);     $inputFileSize = fstat($inputFile)['size'];     // Encrypt the file and write its contents to the output file:     for ($i = 0; $i < $inputFileSize; $i += 8175) {         $ptxt_chunk = fread($inputFile, 8175);         $ctxt_chunk = sodium_crypto_secretstream_xchacha20poly1305_push($state, $ptxt_chunk);         fwrite($outputFile, $ctxt_chunk);     }     sodium_memzero($state);     fclose($inputFile);     fclose($outputFile); } // sodium_crypto_secretstream_xchacha20poly1305_keygen() $key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL); file_put_contents('hello.txt', 'Hello world!'); encrypt_file('hello.txt', 'hello.txt.encrypted', $key); var_dump(sodium_bin2hex(file_get_contents('hello.txt.encrypted'))); ?> ``` The above example will output something similar to: ``` string(106) "971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c" ``` php Ds\Vector::rotate Ds\Vector::rotate ================= (PECL ds >= 1.0.0) Ds\Vector::rotate — Rotates the vector by a given number of rotations ### Description ``` public Ds\Vector::rotate(int $rotations): void ``` Rotates the vector by a given number of rotations, which is equivalent to successively calling `$vector->push($vector->shift())` if the number of rotations is positive, or `$vector->unshift($vector->pop())` if negative. ### Parameters `rotations` The number of times the vector should be rotated. ### Return Values No value is returned.. The vector of the current instance will be rotated. ### Examples **Example #1 **Ds\Vector::rotate()** example** ``` <?php $vector = new \Ds\Vector(["a", "b", "c", "d"]); $vector->rotate(1);  // "a" is shifted, then pushed. print_r($vector); $vector->rotate(2);  // "b" and "c" are both shifted, the pushed. print_r($vector); ?> ``` The above example will output something similar to: ``` ( [0] => b [1] => c [2] => d [3] => a ) Ds\Vector Object ( [0] => d [1] => a [2] => b [3] => c ) ``` php QuickHashStringIntHash::__construct QuickHashStringIntHash::\_\_construct ===================================== (No version information available, might only be in Git) QuickHashStringIntHash::\_\_construct — Creates a new QuickHashStringIntHash object ### Description ``` public QuickHashStringIntHash::__construct(int $size, int $options = 0) ``` This constructor creates a new [QuickHashStringIntHash](class.quickhashstringinthash). The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported. ### Parameters `size` The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from `64` to `4194304`. `options` The options that you can pass in are: **`QuickHashStringIntHash::CHECK_FOR_DUPES`**, which makes sure no duplicate entries are added to the hash and **`QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC`** to not use PHP's internal memory manager. ### Return Values Returns a new [QuickHashStringIntHash](class.quickhashstringinthash) object. ### Examples **Example #1 **QuickHashStringIntHash::\_\_construct()** example** ``` <?php var_dump( new QuickHashStringIntHash( 1024 ) ); var_dump( new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES ) ); ?> ``` php radius_put_attr radius\_put\_attr ================= (PECL radius >= 1.1.0) radius\_put\_attr — Attaches a binary attribute ### Description ``` radius_put_attr( resource $radius_handle, int $type, string $value, int $options = 0, int $tag = ? ): bool ``` Attaches a binary attribute to the current RADIUS request. > > **Note**: > > > A request must be created via [radius\_create\_request()](function.radius-create-request) before this function can be called. > > > ### Parameters `radius_handle` The RADIUS resource. `type` The attribute type. `value` The attribute value, which will be treated as a raw binary string. `options` A bitmask of the attribute options. The available options include [**`RADIUS_OPTION_TAGGED`**](https://www.php.net/manual/en/radius.constants.options.php#constant.radius-option-tagged) and [**`RADIUS_OPTION_SALT`**](https://www.php.net/manual/en/radius.constants.options.php#constant.radius-option-salt). `tag` The attribute tag. This parameter is ignored unless the [**`RADIUS_OPTION_TAGGED`**](https://www.php.net/manual/en/radius.constants.options.php#constant.radius-option-tagged) option is set. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | PECL radius 1.3.0 | The `options` and `tag` parameters were added. | ### Examples **Example #1 **radius\_put\_attr()** example** ``` <?php mt_srand(time()); $chall = mt_rand(); $chapval = md5(pack('Ca*',1 , 'sepp' . $chall)); $pass = pack('CH*', 1, $chapval); if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {     echo 'RadiusError:' . radius_strerror($res). "\n<br />";     exit; } ?> ``` ### See Also * [radius\_get\_attr()](function.radius-get-attr) - Extracts an attribute * [radius\_get\_vendor\_attr()](function.radius-get-vendor-attr) - Extracts a vendor specific attribute * [radius\_put\_vendor\_attr()](function.radius-put-vendor-attr) - Attaches a vendor specific binary attribute php Imagick::getImageRegion Imagick::getImageRegion ======================= (PECL imagick 2, PECL imagick 3) Imagick::getImageRegion — Extracts a region of the image ### Description ``` public Imagick::getImageRegion( int $width, int $height, int $x, int $y ): Imagick ``` Extracts a region of the image and returns it as a new Imagick object. ### Parameters `width` The width of the extracted region. `height` The height of the extracted region. `x` X-coordinate of the top-left corner of the extracted region. `y` Y-coordinate of the top-left corner of the extracted region. ### Return Values Extracts a region of the image and returns it as a new wand. ### Errors/Exceptions Throws ImagickException on error. php EventBase::gotStop EventBase::gotStop ================== (PECL event >= 1.2.6-beta) EventBase::gotStop — Checks if the event loop was told to exit ### Description ``` public EventBase::gotStop(): bool ``` Checks if the event loop was told to exit by [EventBase::stop()](eventbase.stop) . ### Parameters This function has no parameters. ### Return Values Returns **`true`**, event loop was told to stop by [EventBase::stop()](eventbase.stop) . Otherwise **`false`**. ### See Also * [EventBase::exit()](eventbase.exit) - Stop dispatching events * [EventBase::stop()](eventbase.stop) - Tells event\_base to stop dispatching events * [EventBase::gotExit()](eventbase.gotexit) - Checks if the event loop was told to exit php ZipArchive::isCompressionMethodSupported ZipArchive::isCompressionMethodSupported ======================================== (PHP >= 8.0.0, PECL zip >= 1.19.0) ZipArchive::isCompressionMethodSupported — Check if a compression method is supported by libzip ### Description ``` public static ZipArchive::isCompressionMethodSupported(int $method, bool $enc = true): bool ``` Check if a compression method is supported by libzip. ### Parameters `method` The compression method, one of the **`ZipArchive::CM_*`** constants. `enc` If **`true`** check for compression, else check for decompression. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Notes > > **Note**: > > > This function is only available if built against libzip ≥ 1.7.0. > > ### See Also * [ZipArchive::setCompressionIndex()](ziparchive.setcompressionindex) - Set the compression method of an entry defined by its index * [ZipArchive::setCompressionName()](ziparchive.setcompressionname) - Set the compression method of an entry defined by its name php NoRewindIterator::getInnerIterator NoRewindIterator::getInnerIterator ================================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) NoRewindIterator::getInnerIterator — Get the inner iterator ### Description ``` public NoRewindIterator::getInnerIterator(): iterator ``` Gets the inner iterator, that was passed in to [NoRewindIterator](class.norewinditerator). **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The inner iterator, as passed to [NoRewindIterator::\_\_construct()](norewinditerator.construct). ### See Also * [NoRewindIterator::valid()](norewinditerator.valid) - Validates the iterator php pg_lo_create pg\_lo\_create ============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_lo\_create — Create a large object ### Description ``` pg_lo_create(PgSql\Connection $connection = ?, mixed $object_id = ?): int ``` ``` pg_lo_create(mixed $object_id): int ``` **pg\_lo\_create()** creates a large object and returns the OID of the large object. PostgreSQL access modes **`INV_READ`**, **`INV_WRITE`**, and **`INV_ARCHIVE`** are not supported, the object is created always with both read and write access. **`INV_ARCHIVE`** has been removed from PostgreSQL itself (version 6.3 and above). To use the large object interface, it is necessary to enclose it within a transaction block. Instead of using the large object interface (which has no access controls and is cumbersome to use), try PostgreSQL's bytea column type and [pg\_escape\_bytea()](function.pg-escape-bytea). > > **Note**: > > > This function used to be called **pg\_locreate()**. > > ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `object_id` If an `object_id` is given the function will try to create a large object with this id, else a free object id is assigned by the server. The parameter relies on functionality that first appeared in PostgreSQL 8.1. ### Return Values A large object OID, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_lo\_create()** example** ``` <?php    $database = pg_connect("dbname=jacarta");    pg_query($database, "begin");    $oid = pg_lo_create($database);    echo "$oid\n";    $handle = pg_lo_open($database, $oid, "w");    echo "$handle\n";    pg_lo_write($handle, "large object data");    pg_lo_close($handle);    pg_query($database, "commit"); ?> ``` php streamWrapper::stream_seek streamWrapper::stream\_seek =========================== (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) streamWrapper::stream\_seek — Seeks to specific location in a stream ### Description ``` public streamWrapper::stream_seek(int $offset, int $whence = SEEK_SET): bool ``` This method is called in response to [fseek()](function.fseek). The read/write position of the stream should be updated according to the `offset` and `whence`. ### Parameters `offset` The stream offset to seek to. `whence` Possible values: * **`SEEK_SET`** - Set position equal to `offset` bytes. * **`SEEK_CUR`** - Set position to current location plus `offset`. * **`SEEK_END`** - Set position to end-of-file plus `offset`. > **Note**: The current implementation never sets `whence` to **`SEEK_CUR`**; instead such seeks are internally converted to **`SEEK_SET`** seeks. > > ### Return Values Return **`true`** if the position was updated, **`false`** otherwise. ### Notes > > **Note**: > > > If not implemented, **`false`** is assumed as the return value. > > > > **Note**: > > > Upon success, [streamWrapper::stream\_tell()](streamwrapper.stream-tell) is called directly after calling **streamWrapper::stream\_seek()**. If [streamWrapper::stream\_tell()](streamwrapper.stream-tell) fails, the return value to the caller function will be set to **`false`** > > > > **Note**: > > > Not all seeks operations on the stream will result in this function being called. PHP streams have read buffering enabled by default (see also [stream\_set\_read\_buffer()](function.stream-set-read-buffer)) and seeking may be done by merely moving the buffer pointer. > > ### See Also * [fseek()](function.fseek) - Seeks on a file pointer
programming_docs
php The Collator class The Collator class ================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Provides string comparison capability with support for appropriate locale-sensitive sort orderings. Class synopsis -------------- class **Collator** { /\* Methods \*/ public [\_\_construct](collator.construct)(string `$locale`) ``` public asort(array &$array, int $flags = Collator::SORT_REGULAR): bool ``` ``` public compare(string $string1, string $string2): int|false ``` ``` public static create(string $locale): ?Collator ``` ``` public getAttribute(int $attribute): int|false ``` ``` public getErrorCode(): int|false ``` ``` public getErrorMessage(): string|false ``` ``` public getLocale(int $type): string|false ``` ``` public getSortKey(string $string): string|false ``` ``` public getStrength(): int ``` ``` public setAttribute(int $attribute, int $value): bool ``` ``` public setStrength(int $strength): bool ``` ``` public sortWithSortKeys(array &$array): bool ``` ``` public sort(array &$array, int $flags = Collator::SORT_REGULAR): bool ``` } Predefined Constants -------------------- **`Collator::FRENCH_COLLATION`** (int) Sort strings with different accents from the back of the string. This attribute is automatically set to *On* for the French locales and a few others. Users normally would not need to explicitly set this attribute. There is a string comparison performance cost when it is set *On*, but sort key length is unaffected. Possible values are: * **`Collator::ON`** * **`Collator::OFF`**(default) * **`Collator::DEFAULT_VALUE`** **Example #1 FRENCH\_COLLATION rules** * F=OFF cote < coté < côte < côté * F=ON cote < côte < coté < côté **`Collator::ALTERNATE_HANDLING`** (int) The Alternate attribute is used to control the handling of the so called variable characters in the UCA: whitespace, punctuation and symbols. If Alternate is set to *NonIgnorable* (N), then differences among these characters are of the same importance as differences among letters. If Alternate is set to *Shifted* (S), then these characters are of only minor importance. The *Shifted* value is often used in combination with *Strength* set to Quaternary. In such a case, whitespace, punctuation, and symbols are considered when comparing strings, but only if all other aspects of the strings (base letters, accents, and case) are identical. If Alternate is not set to Shifted, then there is no difference between a Strength of 3 and a Strength of 4. For more information and examples, see Variable\_Weighting in the [» UCA](http://www.unicode.org/reports/tr10/). The reason the Alternate values are not simply *On* and *Off* is that additional Alternate values may be added in the future. The UCA option Blanked is expressed with Strength set to 3, and Alternate set to Shifted. The default for most locales is NonIgnorable. If Shifted is selected, it may be slower if there are many strings that are the same except for punctuation; sort key length will not be affected unless the strength level is also increased. Possible values are: * **`Collator::NON_IGNORABLE`**(default) * **`Collator::SHIFTED`** * **`Collator::DEFAULT_VALUE`** **Example #2 ALTERNATE\_HANDLING rules** * S=3, A=N di Silva < Di Silva < diSilva < U.S.A. < USA * S=3, A=S di Silva = diSilva < Di Silva < U.S.A. = USA * S=4, A=S di Silva < diSilva < Di Silva < U.S.A. < USA **`Collator::CASE_FIRST`** (int) The Case\_First attribute is used to control whether uppercase letters come before lowercase letters or vice versa, in the absence of other differences in the strings. The possible values are *Uppercase\_First* (U) and *Lowercase\_First* (L), plus the standard *Default* and *Off*. There is almost no difference between the Off and Lowercase\_First options in terms of results, so typically users will not use Lowercase\_First: only Off or Uppercase\_First. (People interested in the detailed differences between X and L should consult the `Collation Customization`). Specifying either L or U won't affect string comparison performance, but will affect the sort key length. Possible values are: * **`Collator::OFF`**(default) * **`Collator::LOWER_FIRST`** * **`Collator::UPPER_FIRST`** * **`Collator:DEFAULT`** **Example #3 CASE\_FIRST rules** * C=X or C=L "china" < "China" < "denmark" < "Denmark" * C=U "China" < "china" < "Denmark" < "denmark" **`Collator::CASE_LEVEL`** (int) The Case\_Level attribute is used when ignoring accents but not case. In such a situation, set Strength to be *Primary*, and Case\_Level to be *On*. In most locales, this setting is Off by default. There is a small string comparison performance and sort key impact if this attribute is set to be *On*. Possible values are: * **`Collator::OFF`**(default) * **`Collator::ON`** * **`Collator::DEFAULT_VALUE`** **Example #4 CASE\_LEVEL rules** * S=1, E=X role = Role = rôle * S=1, E=O role = rôle < Role **`Collator::NORMALIZATION_MODE`** (int) The Normalization setting determines whether text is thoroughly normalized or not in comparison. Even if the setting is off (which is the default for many locales), text as represented in common usage will compare correctly (for details, see UTN #5). Only if the accent marks are in noncanonical order will there be a problem. If the setting is *On*, then the best results are guaranteed for all possible text input. There is a medium string comparison performance cost if this attribute is *On*, depending on the frequency of sequences that require normalization. There is no significant effect on sort key length. If the input text is known to be in NFD or NFKD normalization forms, there is no need to enable this Normalization option. Possible values are: * **`Collator::OFF`**(default) * **`Collator::ON`** * **`Collator::DEFAULT_VALUE`** **`Collator::STRENGTH`** (int) The ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions. For more detailed information, see [collator\_set\_strength()](collator.setstrength) chapter. Possible values are: * **`Collator::PRIMARY`** * **`Collator::SECONDARY`** * **`Collator::TERTIARY`**(default) * **`Collator::QUATERNARY`** * **`Collator::IDENTICAL`** * **`Collator::DEFAULT_VALUE`** **`Collator::HIRAGANA_QUATERNARY_MODE`** (int) Compatibility with JIS x 4061 requires the introduction of an additional level to distinguish Hiragana and Katakana characters. If compatibility with that standard is required, then this attribute should be set *On*, and the strength set to Quaternary. This will affect sort key length and string comparison string comparison performance. Possible values are: * **`Collator::OFF`**(default) * **`Collator::ON`** * **`Collator::DEFAULT_VALUE`** **`Collator::NUMERIC_COLLATION`** (int) When turned on, this attribute generates a collation key for the numeric value of substrings of digits. This is a way to get '100' to sort AFTER '2'. Possible values are: * **`Collator::OFF`**(default) * **`Collator::ON`** * **`Collator::DEFAULT_VALUE`** **`Collator::DEFAULT_VALUE`** (int) **`Collator::PRIMARY`** (int) **`Collator::SECONDARY`** (int) **`Collator::TERTIARY`** (int) **`Collator::DEFAULT_STRENGTH`** (int) **`Collator::QUATERNARY`** (int) **`Collator::IDENTICAL`** (int) **`Collator::OFF`** (int) **`Collator::ON`** (int) **`Collator::SHIFTED`** (int) **`Collator::NON_IGNORABLE`** (int) **`Collator::LOWER_FIRST`** (int) **`Collator::UPPER_FIRST`** (int) Table of Contents ----------------- * [Collator::asort](collator.asort) — Sort array maintaining index association * [Collator::compare](collator.compare) — Compare two Unicode strings * [Collator::\_\_construct](collator.construct) — Create a collator * [Collator::create](collator.create) — Create a collator * [Collator::getAttribute](collator.getattribute) — Get collation attribute value * [Collator::getErrorCode](collator.geterrorcode) — Get collator's last error code * [Collator::getErrorMessage](collator.geterrormessage) — Get text for collator's last error code * [Collator::getLocale](collator.getlocale) — Get the locale name of the collator * [Collator::getSortKey](collator.getsortkey) — Get sorting key for a string * [Collator::getStrength](collator.getstrength) — Get current collation strength * [Collator::setAttribute](collator.setattribute) — Set collation attribute * [Collator::setStrength](collator.setstrength) — Set collation strength * [Collator::sortWithSortKeys](collator.sortwithsortkeys) — Sort array using specified collator and sort keys * [Collator::sort](collator.sort) — Sort array using specified collator php ob_end_flush ob\_end\_flush ============== (PHP 4, PHP 5, PHP 7, PHP 8) ob\_end\_flush — Flush (send) the output buffer and turn off output buffering ### Description ``` ob_end_flush(): bool ``` This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call [ob\_get\_contents()](function.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()](function.ob-start) with [PHP\_OUTPUT\_HANDLER\_FLUSHABLE](https://www.php.net/manual/en/outcontrol.constants.php#constant.php-output-handler-flushable) and [PHP\_OUTPUT\_HANDLER\_REMOVABLE](https://www.php.net/manual/en/outcontrol.constants.php#constant.php-output-handler-removable) flags. Otherwise **ob\_end\_flush()** will not work. > **Note**: This function is similar to [ob\_get\_flush()](function.ob-get-flush), except that [ob\_get\_flush()](function.ob-get-flush) returns the buffer as a string. > > ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer). ### Errors/Exceptions If the function fails it generates an **`E_NOTICE`**. ### Examples **Example #1 **ob\_end\_flush()** example** The following example shows an easy way to flush and end all output buffers: ``` <?php   while (@ob_end_flush()); ?> ``` ### See Also * [ob\_start()](function.ob-start) - Turn on output buffering * [ob\_get\_contents()](function.ob-get-contents) - Return the contents of the output buffer * [ob\_get\_flush()](function.ob-get-flush) - Flush the output buffer, return it as a string and turn off output buffering * [ob\_flush()](function.ob-flush) - Flush (send) the output buffer * [ob\_end\_clean()](function.ob-end-clean) - Clean (erase) the output buffer and turn off output buffering php ArrayObject::setFlags ArrayObject::setFlags ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) ArrayObject::setFlags — Sets the behavior flags ### Description ``` public ArrayObject::setFlags(int $flags): void ``` Set the flags that change the behavior of the ArrayObject. ### Parameters `flags` The new ArrayObject behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. The available behavior flags are listed below. The actual meanings of these flags are described in the [predefined constants](class.arrayobject#arrayobject.constants). **ArrayObject behavior flags**| value | constant | | --- | --- | | 1 | [ArrayObject::STD\_PROP\_LIST](class.arrayobject#arrayobject.constants.std-prop-list) | | 2 | [ArrayObject::ARRAY\_AS\_PROPS](class.arrayobject#arrayobject.constants.array-as-props) | ### Return Values No value is returned. ### Examples **Example #1 **ArrayObject::setFlags()** example** ``` <?php // Array of available fruits $fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10); $fruitsArrayObject = new ArrayObject($fruits); // Try to use array key as property var_dump($fruitsArrayObject->lemons); // Set the flag so that the array keys can be used as properties of the ArrayObject $fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS); // Try it again var_dump($fruitsArrayObject->lemons); ?> ``` The above example will output: ``` NULL int(1) ``` php imagepalettetotruecolor imagepalettetotruecolor ======================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) imagepalettetotruecolor — Converts a palette based image to true color ### Description ``` imagepalettetotruecolor(GdImage $image): bool ``` Converts a palette based image, created by functions like [imagecreate()](function.imagecreate) to a true color image, like [imagecreatetruecolor()](function.imagecreatetruecolor). ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). ### Return Values Returns **`true`** if the convertion was complete, or if the source image already is a true color image, otherwise **`false`** is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Converts any image object to true color** ``` <?php // Backwards compatiblity if(!function_exists('imagepalettetotruecolor')) {     function imagepalettetotruecolor(&$src)     {         if(imageistruecolor($src))         {             return(true);         }         $dst = imagecreatetruecolor(imagesx($src), imagesy($src));         imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));         imagedestroy($src);         $src = $dst;         return(true);     } } // Helper closure $typeof = function() use($im) {     echo 'typeof($im) = ' . (imageistruecolor($im) ? 'true color' : 'palette'), PHP_EOL; }; // Create a palette based image $im = imagecreate(100, 100); $typeof(); // Convert it to true color imagepalettetotruecolor($im); $typeof(); // Free the memory imagedestroy($im); ?> ``` The above example will output: ``` typeof($im) = palette typeof($im) = true color ``` ### See Also * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image * [imageistruecolor()](function.imageistruecolor) - Finds whether an image is a truecolor image php SplObjectStorage::offsetGet SplObjectStorage::offsetGet =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplObjectStorage::offsetGet — Returns the data associated with an object ### Description ``` public SplObjectStorage::offsetGet(object $object): mixed ``` Returns the data associated with an object in the storage. ### Parameters `object` The object to look for. ### Return Values The data previously associated with the object in the storage. ### Errors/Exceptions Throws [UnexpectedValueException](class.unexpectedvalueexception) when `object` could not be found. ### Examples **Example #1 **SplObjectStorage::offsetGet()** example** ``` <?php $s = new SplObjectStorage; $o1 = new StdClass; $o2 = new StdClass; $s[$o1] = "hello"; $s->attach($o2); var_dump($s->offsetGet($o1)); // Similar to $s[$o1] var_dump($s->offsetGet($o2)); // Similar to $s[$o2] ?> ``` The above example will output something similar to: ``` string(5) "hello" NULL ``` ### See Also * [SplObjectStorage::offsetSet()](splobjectstorage.offsetset) - Associates data to an object in the storage * [SplObjectStorage::offsetExists()](splobjectstorage.offsetexists) - Checks whether an object exists in the storage * [SplObjectStorage::offsetUnset()](splobjectstorage.offsetunset) - Removes an object from the storage php The StompFrame class The StompFrame class ==================== Introduction ------------ (PECL stomp >= 0.1.0) Represents a message which was sent or received from a Stomp compliant Message Broker. Class synopsis -------------- class **StompFrame** { /\* Properties \*/ public [$command](class.stompframe#stompframe.props.command); public [$headers](class.stompframe#stompframe.props.headers); public [$body](class.stompframe#stompframe.props.body); /\* Methods \*/ [\_\_construct](stompframe.construct)(string `$command` = ?, array `$headers` = ?, string `$body` = ?) } Properties ---------- command Frame command. headers Frame headers (array). body Frame body. Table of Contents ----------------- * [StompFrame::\_\_construct](stompframe.construct) — Constructor php stats_stat_percentile stats\_stat\_percentile ======================= (PECL stats >= 1.0.0) stats\_stat\_percentile — Returns the percentile value ### Description ``` stats_stat_percentile(array $arr, float $perc): float ``` Returns the `perc`-th percentile value of the array `arr`. ### Parameters `arr` The input array `perc` The percentile ### Return Values Returns the percentile values of the input array. php MessageFormatter::setPattern MessageFormatter::setPattern ============================ msgfmt\_set\_pattern ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) MessageFormatter::setPattern -- msgfmt\_set\_pattern — Set the pattern used by the formatter ### Description Object-oriented style ``` public MessageFormatter::setPattern(string $pattern): bool ``` Procedural style ``` msgfmt_set_pattern(MessageFormatter $formatter, string $pattern): bool ``` Set the pattern used by the formatter ### Parameters `formatter` The message formatter `pattern` The pattern string to use in this message formatter. The pattern uses an 'apostrophe-friendly' syntax; see [» Quoting/Escaping](https://unicode-org.github.io/icu/userguide/format_parse/messages/#quotingescaping) for details. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **msgfmt\_set\_pattern()** example** ``` <?php $fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" ); echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n"; echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n"; msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" ); echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n"; echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n"; ?> ``` **Example #2 OO example** ``` <?php $fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" ); echo "Default pattern: '" . $fmt->getPattern() . "'\n"; echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n"; $fmt->setPattern("{0, number} trees hosting {1, number} monkeys" ); echo "New pattern: '" . $fmt->getPattern() . "'\n"; echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n"; ?> ``` The above example will output: ``` Default pattern: '{0,number} monkeys on {1,number} trees' Formatting result: 123 monkeys on 456 trees New pattern: '{0,number} trees hosting {1,number} monkeys' Formatted number: 123 trees hosting 456 monkeys ``` ### See Also * [msgfmt\_create()](messageformatter.create) - Constructs a new Message Formatter * [msgfmt\_get\_pattern()](messageformatter.getpattern) - Get the pattern used by the formatter php Parle\Parser::advance Parle\Parser::advance ===================== (PECL parle >= 0.5.1) Parle\Parser::advance — Process next parser rule ### Description ``` public Parle\Parser::advance(): void ``` Process next parser rule. ### Parameters This function has no parameters. ### Return Values No value is returned.
programming_docs
php wincache_refresh_if_changed wincache\_refresh\_if\_changed ============================== (PECL wincache >= 1.0.0) wincache\_refresh\_if\_changed — Refreshes the cache entries for the cached files ### Description ``` wincache_refresh_if_changed(array $files = NULL): bool ``` Refreshes the cache entries for the files, whose names were passed in the input argument. If no argument is specified then refreshes all the entries in the cache. ### Parameters `files` An array of file names for files that need to be refreshed. An absolute or relative file paths can be used. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples WinCache performs regular checks on the cached files to ensure that if any file has changed then the corresponding entry in the cache is updated. By default this check is performed every 30 seconds. If, for example, a PHP script updates another PHP script where the application's configuration settings are stored, then it may happen that after the configuration settings have been saved to a file, the application is still using old settings for some time until the cache is refreshed. In those cases it may be preferrable to refresh the cache right after the file has been changed. The following example shows how this can be done. **Example #1 A **wincache\_refresh\_if\_changed()** example** ``` <?php  $filename = 'C:\inetpub\wwwroot\config.php'; $handle = fopen($filename, 'w+'); if ($handle === FALSE) die('Failed to open file '.$filename.' for writing'); fwrite($handle, '<?php $setting=something; ?>'); fclose($handle); wincache_refresh_if_changed(array($filename)); ?> ``` ### See Also * [wincache\_fcache\_fileinfo()](function.wincache-fcache-fileinfo) - Retrieves information about files cached in the file cache * [wincache\_fcache\_meminfo()](function.wincache-fcache-meminfo) - Retrieves information about file cache memory usage * [wincache\_ocache\_fileinfo()](function.wincache-ocache-fileinfo) - Retrieves information about files cached in the opcode cache * [wincache\_ocache\_meminfo()](function.wincache-ocache-meminfo) - Retrieves information about opcode cache memory usage * [wincache\_rplist\_fileinfo()](function.wincache-rplist-fileinfo) - Retrieves information about resolve file path cache * [wincache\_rplist\_meminfo()](function.wincache-rplist-meminfo) - Retrieves information about memory usage by the resolve file path cache * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache php ReflectionClass::getProperties ReflectionClass::getProperties ============================== (PHP 5, PHP 7, PHP 8) ReflectionClass::getProperties — Gets properties ### Description ``` public ReflectionClass::getProperties(?int $filter = null): array ``` Retrieves reflected properties. ### Parameters `filter` The optional filter, for filtering desired property types. It's configured using the [ReflectionProperty constants](class.reflectionproperty#reflectionproperty.constants.modifiers), and defaults to all property types. ### Return Values An array of [ReflectionProperty](class.reflectionproperty) objects. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | `filter` is nullable now. | ### Examples **Example #1 **ReflectionClass::getProperties()** filtering example** This example demonstrates usage of the optional `filter` parameter, where it essentially skips private properties. ``` <?php class Foo {     public    $foo  = 1;     protected $bar  = 2;     private   $baz  = 3; } $foo = new Foo(); $reflect = new ReflectionClass($foo); $props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED); foreach ($props as $prop) {     print $prop->getName() . "\n"; } var_dump($props); ?> ``` The above example will output something similar to: ``` foo bar array(2) { [0]=> object(ReflectionProperty)#3 (2) { ["name"]=> string(3) "foo" ["class"]=> string(3) "Foo" } [1]=> object(ReflectionProperty)#4 (2) { ["name"]=> string(3) "bar" ["class"]=> string(3) "Foo" } } ``` ### See Also * [ReflectionClass::getProperty()](reflectionclass.getproperty) - Gets a ReflectionProperty for a class's property * [ReflectionProperty](class.reflectionproperty) * [ReflectionProperty modifier constants](class.reflectionproperty#reflectionproperty.constants.modifiers) php ReflectionFunction::invokeArgs ReflectionFunction::invokeArgs ============================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) ReflectionFunction::invokeArgs — Invokes function args ### Description ``` public ReflectionFunction::invokeArgs(array $args): mixed ``` Invokes the function and pass its arguments as array. ### Parameters `args` The passed arguments to the function as an array, much like [call\_user\_func\_array()](function.call-user-func-array) works. ### Return Values Returns the result of the invoked function ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `args` keys will now be interpreted as parameter names, instead of being silently ignored. | ### Examples **Example #1 **ReflectionFunction::invokeArgs()** example** ``` <?php function title($title, $name) {     return sprintf("%s. %s\r\n", $title, $name); } $function = new ReflectionFunction('title'); echo $function->invokeArgs(array('Dr', 'Phil')); ?> ``` The above example will output: ``` Dr. Phil ``` **Example #2 **ReflectionFunction::invokeArgs()** with references example** ``` <?php function get_false_conditions(array $conditions, array &$false_conditions) {     foreach ($conditions as $condition) {         if (!$condition) {             $false_conditions[] = $condition;         }     } } $function_ref     = new ReflectionFunction('get_false_conditions'); $conditions       = array(true, false, -1, 0, 1); $false_conditions = array(); $function_ref->invokeArgs(array($conditions, &$false_conditions)); var_dump($false_conditions); ?> ``` The above example will output: ``` array(2) { [0]=> bool(false) [1]=> int(0) } ``` ### Notes > > **Note**: > > > If the function has arguments that need to be references, then they must be references in the passed argument list. > > ### See Also * [ReflectionFunction::invoke()](reflectionfunction.invoke) - Invokes function * [ReflectionFunctionAbstract::getNumberOfParameters()](reflectionfunctionabstract.getnumberofparameters) - Gets number of parameters * [\_\_invoke()](language.oop5.magic#object.invoke) * [call\_user\_func\_array()](function.call-user-func-array) - Call a callback with an array of parameters php SplFileInfo::getPerms SplFileInfo::getPerms ===================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getPerms — Gets file permissions ### Description ``` public SplFileInfo::getPerms(): int|false ``` Gets the file permissions for the file. ### Parameters This function has no parameters. ### Return Values Returns the file permissions on success, or **`false`** on failure. ### Examples **Example #1 **SplFileInfo::getPerms()** example** ``` <?php $info = new SplFileInfo('/tmp'); echo substr(sprintf('%o', $info->getPerms()), -4); $info = new SplFileInfo(__FILE__); echo substr(sprintf('%o', $info->getPerms()), -4); ?> ``` The above example will output something similar to: ``` 1777 0644 ``` php InternalIterator::__construct InternalIterator::\_\_construct =============================== (PHP 8) InternalIterator::\_\_construct — Private constructor to disallow direct instantiation ### Description private **InternalIterator::\_\_construct**() ### Parameters This function has no parameters. php ReflectionClass::isFinal ReflectionClass::isFinal ======================== (PHP 5, PHP 7, PHP 8) ReflectionClass::isFinal — Checks if class is final ### Description ``` public ReflectionClass::isFinal(): bool ``` Checks if a class is final. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **ReflectionClass::isFinal()** example** ``` <?php class       TestClass { } final class TestFinalClass { } $normalClass = new ReflectionClass('TestClass'); $finalClass  = new ReflectionClass('TestFinalClass'); var_dump($normalClass->isFinal()); var_dump($finalClass->isFinal()); ?> ``` The above example will output: ``` bool(false) bool(true) ``` ### See Also * [ReflectionClass::isAbstract()](reflectionclass.isabstract) - Checks if class is abstract * [Final Keyword](language.oop5.final) php stats_rand_gen_noncentral_t stats\_rand\_gen\_noncentral\_t =============================== (PECL stats >= 1.0.0) stats\_rand\_gen\_noncentral\_t — Generates a single random deviate from a non-central t-distribution ### Description ``` stats_rand_gen_noncentral_t(float $df, float $xnonc): float ``` Returns a random deviate from the non-central t-distribution with the degrees of freedom, `df`, and the non-centrality parameter, `xnonc`. ### Parameters `df` The degrees of freedom `xnonc` The non-centrality parameter ### Return Values A random deviate php ZipArchive::addPattern ZipArchive::addPattern ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL zip >= 1.9.0) ZipArchive::addPattern — Add files from a directory by PCRE pattern ### Description ``` public ZipArchive::addPattern(string $pattern, string $path = ".", array $options = []): array|false ``` Add files from a directory which match the regular expression `pattern`. The operation is not recursive. The pattern will be matched against the file name only. ### Parameters `pattern` A [PCRE](https://www.php.net/manual/en/book.pcre.php) pattern against which files will be matched. `path` The directory that will be scanned. Defaults to the current working directory. `options` An associative array of options accepted by [ZipArchive::addGlob()](ziparchive.addglob). ### Return Values An array of added files on success or **`false`** on failure ### Examples **Example #1 **ZipArchive::addPattern()** example** Add all php scripts and text files from current directory ``` <?php $zip = new ZipArchive(); $ret = $zip->open('application.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); if ($ret !== TRUE) {     printf('Failed with code %d', $ret); } else {     $directory = realpath('.');     $options = array('add_path' => 'sources/', 'remove_path' => $directory);     $zip->addPattern('/\.(?:php|txt)$/', $directory, $options);     $zip->close(); } ?> ``` ### See Also * [ZipArchive::addFile()](ziparchive.addfile) - Adds a file to a ZIP archive from the given path * [ZipArchive::addGlob()](ziparchive.addglob) - Add files from a directory by glob pattern php Imagick::setCompressionQuality Imagick::setCompressionQuality ============================== (PECL imagick 2, PECL imagick 3) Imagick::setCompressionQuality — Sets the object's default compression quality ### Description ``` public Imagick::setCompressionQuality(int $quality): bool ``` Sets the object's default compression quality. **Caution** This method only works for new images e.g. those created through Imagick::newPseudoImage. For existing images you should use [Imagick::setImageCompressionQuality()](imagick.setimagecompressionquality). ### Parameters `quality` An int between 1 and 100, 1 = high compression, 100 low compression. ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::setCompressionQuality()**** ``` <?php function setCompressionQuality($imagePath, $quality) {     $backgroundImagick = new \Imagick(realpath($imagePath));     $imagick = new \Imagick();     $imagick->setCompressionQuality($quality);     $imagick->newPseudoImage(         $backgroundImagick->getImageWidth(),         $backgroundImagick->getImageHeight(),         'canvas:white'     );     $imagick->compositeImage(         $backgroundImagick,         \Imagick::COMPOSITE_ATOP,         0,         0     );          $imagick->setFormat("jpg");         header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php EventConfig::__construct EventConfig::\_\_construct ========================== (PECL event >= 1.2.6-beta) EventConfig::\_\_construct — Constructs EventConfig object ### Description ``` public EventConfig::__construct() ``` Constructs EventConfig object which could be passed to [EventBase::\_\_construct()](eventbase.construct) constructor. ### Parameters This function has no parameters. ### Return Values Returns [EventConfig](class.eventconfig) object. ### Examples **Example #1 **EventConfig::\_\_construct()** example** ``` <?php // Avoiding "select" method $cfg = new EventConfig(); if ($cfg->avoidMethod("select")) {     echo "'select' method avoided\n"; } // Create event_base associated with the config $base = new EventBase($cfg); /* Now $base is configured to avoid select backend(method) */ ?> ``` ### See Also * [EventBase::\_\_construct()](eventbase.construct) - Constructs EventBase object php curl_multi_init curl\_multi\_init ================= (PHP 5, PHP 7, PHP 8) curl\_multi\_init — Returns a new cURL multi handle ### Description ``` curl_multi_init(): CurlMultiHandle ``` Allows the processing of multiple cURL handles asynchronously. ### Parameters This function has no parameters. ### Return Values Returns a cURL multi handle on success, **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [CurlMultiHandle](class.curlmultihandle) instance now; previously, a resource was returned. | ### Examples **Example #1 **curl\_multi\_init()** example** This example will create two cURL handles, add them to a multi handle, and process them asynchronously. ``` <?php // create both cURL resources $ch1 = curl_init(); $ch2 = curl_init(); // set URL and other appropriate options curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/"); curl_setopt($ch1, CURLOPT_HEADER, 0); curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/"); curl_setopt($ch2, CURLOPT_HEADER, 0); //create the multiple cURL handle $mh = curl_multi_init(); //add the two handles curl_multi_add_handle($mh,$ch1); curl_multi_add_handle($mh,$ch2); //execute the multi handle do {     $status = curl_multi_exec($mh, $active);     if ($active) {         curl_multi_select($mh);     } } while ($active && $status == CURLM_OK); //close the handles curl_multi_remove_handle($mh, $ch1); curl_multi_remove_handle($mh, $ch2); curl_multi_close($mh); ?> ``` ### See Also * [curl\_init()](function.curl-init) - Initialize a cURL session * [curl\_multi\_close()](function.curl-multi-close) - Close a set of cURL handles php enchant_dict_check enchant\_dict\_check ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 ) enchant\_dict\_check — Check whether a word is correctly spelled or not ### Description ``` enchant_dict_check(EnchantDictionary $dictionary, string $word): bool ``` If the word is correctly spelled return **`true`**, otherwise return **`false`** ### Parameters `dictionary` An Enchant dictionary returned by [enchant\_broker\_request\_dict()](function.enchant-broker-request-dict) or [enchant\_broker\_request\_pwl\_dict()](function.enchant-broker-request-pwl-dict). `word` The word to check ### Return Values Returns **`true`** if the word is spelled correctly, **`false`** if not. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `dictionary` expects an [EnchantDictionary](class.enchantdictionary) instance now; previoulsy, a [resource](language.types.resource) was expected. | php Stomp::setReadTimeout Stomp::setReadTimeout ===================== stomp\_set\_read\_timeout ========================= (PECL stomp >= 0.3.0) Stomp::setReadTimeout -- stomp\_set\_read\_timeout — Sets read timeout ### Description Object-oriented style (method): ``` public Stomp::setReadTimeout(int $seconds, int $microseconds = ?): void ``` Procedural style: ``` stomp_set_read_timeout(resource $link, int $seconds, int $microseconds = ?): void ``` Sets read timeout. ### Parameters `link` Procedural style only: The stomp link identifier returned by [stomp\_connect()](stomp.construct). `seconds` The seconds part of the timeout to be set. `microseconds` The microseconds part of the timeout to be set. ### Return Values No value is returned. ### Examples **Example #1 Object-oriented style** ``` <?php /* connection */ try {     $stomp = new Stomp('tcp://localhost:61613'); } catch(StompException $e) {     die('Connection failed: ' . $e->getMessage()); } $stomp->setReadTimeout(10);      /* close connection */ unset($stomp); ?> ``` **Example #2 Procedural style** ``` <?php /* connection */ $link = stomp_connect('ssl://localhost:61612'); /* check connection */ if (!$link) {     die('Connection failed: ' . stomp_connect_error()); } stomp_set_read_timeout($link, 10);      /* close connection */ stomp_close($link); ?> ``` php The OutOfBoundsException class The OutOfBoundsException class ============================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time. Class synopsis -------------- class **OutOfBoundsException** extends [RuntimeException](class.runtimeexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php Ds\Queue::pop Ds\Queue::pop ============= (PECL ds >= 1.0.0) Ds\Queue::pop — Removes and returns the value at the front of the queue ### Description ``` public Ds\Queue::pop(): mixed ``` Removes and returns the value at the front of the queue. ### Parameters This function has no parameters. ### Return Values The removed value which was at the front of the queue. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Queue::pop()** example** ``` <?php $queue = new \Ds\Queue(); $queue->push("a"); $queue->push("b"); $queue->push("c"); var_dump($queue->pop()); var_dump($queue->pop()); var_dump($queue->pop()); ?> ``` The above example will output something similar to: ``` string(1) "a" string(1) "b" string(1) "c" ```
programming_docs
php stats_rand_gen_noncentral_chisquare stats\_rand\_gen\_noncentral\_chisquare ======================================= (PECL stats >= 1.0.0) stats\_rand\_gen\_noncentral\_chisquare — Generates a random deviate from the non-central chi-square distribution ### Description ``` stats_rand_gen_noncentral_chisquare(float $df, float $xnonc): float ``` Returns a random deviate from the non-central chi-square distribution with degrees of freedom, `df`, and non-centrality parameter, `xnonc`. ### Parameters `df` The degrees of freedom `xnonc` The non-centrality parameter ### Return Values A random deviate php pg_fetch_assoc pg\_fetch\_assoc ================ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_fetch\_assoc — Fetch a row as an associative array ### Description ``` pg_fetch_assoc(PgSql\Result $result, ?int $row = null): array|false ``` **pg\_fetch\_assoc()** returns an associative array that corresponds to the fetched row (records). **pg\_fetch\_assoc()** is equivalent to calling [pg\_fetch\_array()](function.pg-fetch-array) with **`PGSQL_ASSOC`** as the optional third parameter. It only returns an associative array. If you need the numeric indices, use [pg\_fetch\_row()](function.pg-fetch-row). > **Note**: This function sets NULL fields to the PHP **`null`** value. > > **pg\_fetch\_assoc()** is NOT significantly slower than using [pg\_fetch\_row()](function.pg-fetch-row), and is significantly easier to use. ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `row` Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or **`null`**, the next row is fetched. ### Return Values An array indexed associatively (by field name). Each value in the array is represented as a string. Database `NULL` values are returned as **`null`**. **`false`** is returned if `row` exceeds the number of rows in the set, there are no more rows, or on any other error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_fetch\_assoc()** example** ``` <?php  $conn = pg_connect("dbname=publisher"); if (!$conn) {   echo "An error occurred.\n";   exit; } $result = pg_query($conn, "SELECT id, author, email FROM authors"); if (!$result) {   echo "An error occurred.\n";   exit; } while ($row = pg_fetch_assoc($result)) {   echo $row['id'];   echo $row['author'];   echo $row['email']; } ?> ``` ### See Also * [pg\_fetch\_row()](function.pg-fetch-row) - Get a row as an enumerated array * [pg\_fetch\_array()](function.pg-fetch-array) - Fetch a row as an array * [pg\_fetch\_object()](function.pg-fetch-object) - Fetch a row as an object * [pg\_fetch\_result()](function.pg-fetch-result) - Returns values from a result instance php SplPriorityQueue::next SplPriorityQueue::next ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplPriorityQueue::next — Move to the next node ### Description ``` public SplPriorityQueue::next(): void ``` Extracts the top node from the queue. ### Parameters This function has no parameters. ### Return Values No value is returned. php ibase_server_info ibase\_server\_info =================== (PHP 5, PHP 7 < 7.4.0) ibase\_server\_info — Request information about a database server ### Description ``` ibase_server_info(resource $service_handle, int $action): string ``` ### Parameters `service_handle` A previously created connection to the database server. `action` A valid constant. ### Return Values Returns mixed types depending on context. ### Examples **Example #1 [ibase\_service\_attach()](function.ibase-service-attach) example** ``` <?php     // Attach to the remote Firebird server     if (($service = ibase_service_attach('10.1.1.254/3050', 'sysdba', 'masterkey')) != FALSE) {         // Successfully attached.         // Output the info         echo "Server version: " . ibase_server_info($service, IBASE_SVC_SERVER_VERSION) . "\n";         echo "Server implementation: " . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION) . "\n";         echo "Server users: " . print_r(ibase_server_info($service, IBASE_SVC_GET_USERS), true) . "\n";         echo "Server directory: " . ibase_server_info($service, IBASE_SVC_GET_ENV) . "\n";         echo "Server lock path: " . ibase_server_info($service, IBASE_SVC_GET_ENV_LOCK) . "\n";         echo "Server lib path: " . ibase_server_info($service, IBASE_SVC_GET_ENV_MSG) . "\n";         echo "Path of user db: " . ibase_server_info($service, IBASE_SVC_USER_DBPATH) . "\n";         echo "Established connections: " . print_r(ibase_server_info($service, IBASE_SVC_SVR_DB_INFO),true) . "\n";         // Detach from server (disconnect)         ibase_service_detach($service);     }     else {         // Output message on error         $conn_error = ibase_errmsg();         die($conn_error);     } ?> ``` The above example will output: ``` Server version: LI-V3.0.4.33054 Firebird 3.0 Server implementation: Firebird/Linux/AMD/Intel/x64 Server users: Array ( [0] => Array ( [user_name] => SYSDBA [first_name] => Sql [middle_name] => Server [last_name] => Administrator [user_id] => 0 [group_id] => 0 ) ) Server directory: /etc/firebird/ Server lock path: /tmp/firebird/ Server lib path: /usr/lib64/firebird/lib/ Path of user db: /var/lib/firebird/secdb/security3.fdb Established connections: Array ( [attachments] => 3 [databases] => 2 [0] => /srv/firebird/poss.fdb [1] => /srv/firebird/employees.fdb ) ``` php ReflectionFunctionAbstract::getNumberOfRequiredParameters ReflectionFunctionAbstract::getNumberOfRequiredParameters ========================================================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters ### Description ``` public ReflectionFunctionAbstract::getNumberOfRequiredParameters(): int ``` Get the number of required parameters that a function defines. ### Parameters This function has no parameters. ### Return Values The number of required parameters. ### See Also * [ReflectionFunctionAbstract::getNumberOfParameters()](reflectionfunctionabstract.getnumberofparameters) - Gets number of parameters php Gmagick::write Gmagick::write ============== (PECL gmagick >= Unknown) Gmagick::write — Alias of [Gmagick::writeimage()](gmagick.writeimage) ### Description This method is an alias of: [Gmagick::writeimage()](gmagick.writeimage). php Yaf_Application::getLastErrorMsg Yaf\_Application::getLastErrorMsg ================================= (Yaf >=2.1.2) Yaf\_Application::getLastErrorMsg — Get message of the last occurred error ### Description ``` public Yaf_Application::getLastErrorMsg(): string ``` ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 **Yaf\_Application::getLastErrorMsg()**example** ``` <?php function error_handler($errno, $errstr, $errfile, $errline) {    var_dump(Yaf_Application::app()->getLastErrorMsg()); } $config = array(                     "application" => array(    "directory" => "/tmp/notexists",      "dispatcher" => array(        "throwException" => 0, //trigger error instead of throw exception when error occure       ),   ), ); $app = new Yaf_Application($config); $app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR); $app->run(); ?> ``` The above example will output something similar to: ``` string(69) "Could not find controller script /tmp/notexists/controllers/Index.php" ``` php Phar::offsetUnset Phar::offsetUnset ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::offsetUnset — Remove a file from a phar ### Description ``` public Phar::offsetUnset(string $localName): void ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > This is an implementation of the [ArrayAccess](class.arrayaccess) interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the [unset()](function.unset) language construct. ### Parameters `localName` The filename (relative path) to modify in a Phar. ### Return Values No value is returned. ### Errors/Exceptions if [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) is `1`, [BadMethodCallException](class.badmethodcallexception) is thrown, as modifying a Phar is only allowed when phar.readonly is set to `0`. Throws [PharException](class.pharexception) if there are any problems flushing changes made to the Phar archive to disk. ### Examples **Example #1 A **Phar::offsetUnset()** example** ``` <?php $p = new Phar('/path/to/my.phar', 0, 'my.phar'); try {     // deletes file.txt from my.phar by calling offsetUnset     unset($p['file.txt']); } catch (Exception $e) {     echo 'Could not delete file.txt: ', $e; } ?> ``` ### See Also * [Phar::offsetExists()](phar.offsetexists) - Determines whether a file exists in the phar * [Phar::offsetGet()](phar.offsetget) - Gets a PharFileInfo object for a specific file * [Phar::offsetSet()](phar.offsetset) - Set the contents of an internal file to those of an external file * [Phar::unlinkArchive()](phar.unlinkarchive) - Completely remove a phar archive from disk and from memory * [Phar::delete()](phar.delete) - Delete a file within a phar archive php PharData::convertToData PharData::convertToData ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) PharData::convertToData — Convert a phar archive to a non-executable tar or zip file ### Description ``` public PharData::convertToData(?int $format = null, ?int $compression = null, ?string $extension = null): ?PharData ``` This method is used to convert a non-executable tar or zip archive to another non-executable format. If no changes are specified, this method throws a [BadMethodCallException](class.badmethodcallexception). This method should be used to convert a tar archive to zip format or vice-versa. Although it is possible to simply change the compression of a tar archive using this method, it is better to use the [PharData::compress()](phardata.compress) method for logical consistency. If successful, the method creates a new archive on disk and returns a [PharData](class.phardata) object. The old archive is not removed from disk, and should be done manually after the process has finished. ### Parameters `format` This should be one of `Phar::TAR` or `Phar::ZIP`. If set to **`null`**, the existing file format will be preserved. `compression` This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression. `extension` This parameter is used to override the default file extension for a converted archive. Note that `.phar` cannot be used anywhere in the filename for a non-executable tar or zip archive. If converting to a tar-based phar archive, the default extensions are `.tar`, `.tar.gz`, and `.tar.bz2` depending on specified compression. For zip-based archives, the default extension is `.zip`. ### Return Values The method returns a [PharData](class.phardata) object on success, or **`null`** on failure. ### Errors/Exceptions This method throws [BadMethodCallException](class.badmethodcallexception) when unable to compress, an unknown compression method has been specified, the requested archive is buffering with [Phar::startBuffering()](phar.startbuffering) and has not concluded with [Phar::stopBuffering()](phar.stopbuffering), and a [PharException](class.pharexception) if any problems are encountered during the phar creation process. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `format`, `compression`, and `extension` are now nullable. | ### Examples **Example #1 A **PharData::convertToData()** example** Using PharData::convertToData(): ``` <?php try {     $tarphar = new PharData('myphar.tar');     // note that myphar.tar is *not* unlinked     // convert it to the non-executable tar file format     // creates myphar.zip     $zip = $tarphar->convertToData(Phar::ZIP);     // create myphar.tbz     $tgz = $zip->convertToData(Phar::TAR, Phar::BZ2, '.tbz');     // creates myphar.phar.tgz     $phar = $tarphar->convertToData(Phar::PHAR); // throws exception } catch (Exception $e) {     // handle the error here } ?> ``` ### See Also * [Phar::convertToExecutable()](phar.converttoexecutable) - Convert a phar archive to another executable phar archive file format * [Phar::convertToData()](phar.converttodata) - Convert a phar archive to a non-executable tar or zip file * [PharData::convertToExecutable()](phardata.converttoexecutable) - Convert a non-executable tar/zip archive to an executable phar archive php Threaded::chunk Threaded::chunk =============== (PECL pthreads >= 2.0.0) Threaded::chunk — Manipulation ### Description ``` public Threaded::chunk(int $size, bool $preserve): array ``` Fetches a chunk of the objects property table of the given size, optionally preserving keys ### Parameters `size` The number of items to fetch `preserve` Preserve the keys of members, by default false ### Return Values An array of items from the objects property table ### Examples **Example #1 Fetch a chunk of the property table** ``` <?php $safe = new Threaded(); while (count($safe) < 10) {     $safe[] = count($safe); } var_dump($safe->chunk(5)); ?> ``` The above example will output: ``` array(5) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) [4]=> int(4) } ``` php atan2 atan2 ===== (PHP 4, PHP 5, PHP 7, PHP 8) atan2 — Arc tangent of two variables ### Description ``` atan2(float $y, float $x): float ``` This function calculates the arc tangent of the two variables `x` and `y`. It is similar to calculating the arc tangent of `y` / `x`, except that the signs of both arguments are used to determine the quadrant of the result. The function returns the result in radians, which is between -PI and PI (inclusive). ### Parameters `y` Dividend parameter `x` Divisor parameter ### Return Values The arc tangent of `y`/`x` in radians. ### See Also * [atan()](function.atan) - Arc tangent php streamWrapper::unlink streamWrapper::unlink ===================== (PHP 5, PHP 7, PHP 8) streamWrapper::unlink — Delete a file ### Description ``` public streamWrapper::unlink(string $path): bool ``` This method is called in response to [unlink()](function.unlink). > > **Note**: > > > In order for the appropriate error message to be returned this method should *not* be defined if the wrapper does not support removing files. > > ### Parameters `path` The file URL which should be deleted. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Emits **`E_WARNING`** if call to this method fails (i.e. not implemented). ### Notes > > **Note**: > > > The streamWrapper::$context property is updated if a valid context is passed to the caller function. > > > ### See Also * [unlink()](function.unlink) - Deletes a file * [streamWrapper::rmdir()](streamwrapper.rmdir) - Removes a directory php svn_cat svn\_cat ======== (PECL svn >= 0.1.0) svn\_cat — Returns the contents of a file in a repository ### Description ``` svn_cat(string $repos_url, int $revision_no = ?): string ``` Returns the contents of the URL `repos_url` to a file in the repository, optionally at revision number `revision_no`. ### Parameters `repos_url` String URL path to item in a repository. `revision_no` Integer revision number of item to retrieve, default is the HEAD revision. ### Return Values Returns the string contents of the item from the repository on success, and **`false`** on failure. ### Examples **Example #1 Basic example** This example retrieves the contents of a file at revision 28: ``` <?php $contents = svn_cat('http://www.example.com/svnroot/calc/gui.c', 28) ?> ``` ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. ### See Also * **svn\_list()** * [» SVN documentation on svn cat](http://svnbook.red-bean.com/en/1.2/svn.ref.svn.c.cat.html) php mysqli_result::fetch_column mysqli\_result::fetch\_column ============================= mysqli\_fetch\_column ===================== (PHP 8 >= 8.1.0) mysqli\_result::fetch\_column -- mysqli\_fetch\_column — Fetch a single column from the next row of a result set ### Description Object-oriented style ``` public mysqli_result::fetch_column(int $column = 0): null|int|float|string|false ``` Procedural style ``` mysqli_fetch_column(mysqli_result $result, int $column = 0): null|int|float|string|false ``` Fetches one row of data from the result set and returns the 0-indexed column. Each subsequent call to this function will return the value from the next row within the result set, or **`false`** if there are no more rows. > **Note**: This function sets NULL fields to the PHP **`null`** value. > > ### Parameters `result` Procedural style only: A [mysqli\_result](class.mysqli-result) object returned by [mysqli\_query()](mysqli.query), [mysqli\_store\_result()](mysqli.store-result), [mysqli\_use\_result()](mysqli.use-result) or [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result). `column` 0-indexed number of the column you wish to retrieve from the row. If no value is supplied, the first column will be returned. ### Return Values Returns a single column from the next row of a result set or **`false`** if there are no more rows. **Warning** There is no way to return another column from the same row if you use this function to retrieve data. ### Examples **Example #1 **mysqli\_result::fetch\_column()** example** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5"; $result = $mysqli->query($query); /* fetch a single value from the second column */ while ($Name = $result->fetch_column(1)) {     printf("%s\n", $Name); } ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = mysqli_connect("localhost", "my_user", "my_password", "world"); $query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5"; $result = mysqli_query($mysqli, $query); /* fetch a single value from the second column */ while ($Name = mysqli_fetch_column($result, 1)) {     printf("%s\n", $Name); } ``` The above examples will output something similar to: ``` Rafah Nablus Jabaliya Hebron Khan Yunis ``` ### See Also * [mysqli\_fetch\_all()](mysqli-result.fetch-all) - Fetch all result rows as an associative array, a numeric array, or both * [mysqli\_fetch\_array()](mysqli-result.fetch-array) - Fetch the next row of a result set as an associative, a numeric array, or both * [mysqli\_fetch\_assoc()](mysqli-result.fetch-assoc) - Fetch the next row of a result set as an associative array * [mysqli\_fetch\_object()](mysqli-result.fetch-object) - Fetch the next row of a result set as an object * [mysqli\_fetch\_row()](mysqli-result.fetch-row) - Fetch the next row of a result set as an enumerated array * [mysqli\_data\_seek()](mysqli-result.data-seek) - Adjusts the result pointer to an arbitrary row in the result
programming_docs
php None Extending Exceptions -------------------- A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class. **Example #1 The Built in Exception class** ``` <?php class Exception implements Throwable {     protected $message = 'Unknown exception';   // exception message     private   $string;                          // __toString cache     protected $code = 0;                        // user defined exception code     protected $file;                            // source filename of exception     protected $line;                            // source line of exception     private   $trace;                           // backtrace     private   $previous;                        // previous exception if nested exception     public function __construct($message = '', $code = 0, Throwable $previous = null);     final private function __clone();           // Inhibits cloning of exceptions.     final public  function getMessage();        // message of exception     final public  function getCode();           // code of exception     final public  function getFile();           // source filename     final public  function getLine();           // source line     final public  function getTrace();          // an array of the backtrace()     final public  function getPrevious();       // previous exception     final public  function getTraceAsString();  // formatted string of trace     // Overrideable     public function __toString();               // formatted string for display } ?> ``` If a class extends the built-in Exception class and re-defines the [constructor](language.oop5.decon), it is highly recommended that it also call [parent::\_\_construct()](language.oop5.paamayim-nekudotayim) to ensure all available data has been properly assigned. The [\_\_toString()](language.oop5.magic) method can be overridden to provide a custom output when the object is presented as a string. > > **Note**: > > > Exceptions cannot be cloned. Attempting to [clone](language.oop5.cloning) an Exception will result in a fatal **`E_ERROR`** error. > > **Example #2 Extending the Exception class** ``` <?php /**  * Define a custom exception class  */ class MyException extends Exception {     // Redefine the exception so message isn't optional     public function __construct($message, $code = 0, Throwable $previous = null) {         // some code         // make sure everything is assigned properly         parent::__construct($message, $code, $previous);     }     // custom string representation of object     public function __toString() {         return __CLASS__ . ": [{$this->code}]: {$this->message}\n";     }     public function customFunction() {         echo "A custom function for this type of exception\n";     } } /**  * Create a class to test the exception  */ class TestException {     public $var;     const THROW_NONE    = 0;     const THROW_CUSTOM  = 1;     const THROW_DEFAULT = 2;     function __construct($avalue = self::THROW_NONE) {         switch ($avalue) {             case self::THROW_CUSTOM:                 // throw custom exception                 throw new MyException('1 is an invalid parameter', 5);                 break;             case self::THROW_DEFAULT:                 // throw default one.                 throw new Exception('2 is not allowed as a parameter', 6);                 break;             default:                 // No exception, object will be created.                 $this->var = $avalue;                 break;         }     } } // Example 1 try {     $o = new TestException(TestException::THROW_CUSTOM); } catch (MyException $e) {      // Will be caught     echo "Caught my exception\n", $e;     $e->customFunction(); } catch (Exception $e) {        // Skipped     echo "Caught Default Exception\n", $e; } // Continue execution var_dump($o); // Null echo "\n\n"; // Example 2 try {     $o = new TestException(TestException::THROW_DEFAULT); } catch (MyException $e) {      // Doesn't match this type     echo "Caught my exception\n", $e;     $e->customFunction(); } catch (Exception $e) {        // Will be caught     echo "Caught Default Exception\n", $e; } // Continue execution var_dump($o); // Null echo "\n\n"; // Example 3 try {     $o = new TestException(TestException::THROW_CUSTOM); } catch (Exception $e) {        // Will be caught     echo "Default Exception caught\n", $e; } // Continue execution var_dump($o); // Null echo "\n\n"; // Example 4 try {     $o = new TestException(); } catch (Exception $e) {        // Skipped, no exception     echo "Default Exception caught\n", $e; } // Continue execution var_dump($o); // TestException echo "\n\n"; ?> ``` php bcsqrt bcsqrt ====== (PHP 4, PHP 5, PHP 7, PHP 8) bcsqrt — Get the square root of an arbitrary precision number ### Description ``` bcsqrt(string $num, ?int $scale = null): string ``` Return the square root of the `num`. ### Parameters `num` The operand, as a string. `scale` This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the [bcscale()](function.bcscale) function, or fallback to `0` if this has not been set. ### Return Values Returns the square root as a string, or **`null`** if `num` is negative. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `scale` is now nullable. | ### Examples **Example #1 **bcsqrt()** example** ``` <?php echo bcsqrt('2', 3); // 1.414 ?> ``` ### See Also * [bcpow()](function.bcpow) - Raise an arbitrary precision number to another php SolrQuery::setTerms SolrQuery::setTerms =================== (PECL solr >= 0.9.2) SolrQuery::setTerms — Enables or disables the TermsComponent ### Description ``` public SolrQuery::setTerms(bool $flag): SolrQuery ``` Enables or disables the TermsComponent ### Parameters `flag` **`true`** enables it. **`false`** turns it off ### Return Values Returns the current SolrQuery object, if the return value is used. php Phar::getStub Phar::getStub ============= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive ### Description ``` public Phar::getStub(): string ``` Phar archives contain a bootstrap loader, or `stub` written in PHP that is executed when the archive is executed in PHP either via include: ``` <?php include 'myphar.phar'; ?> ``` or by simple execution: ``` php myphar.phar ``` ### Parameters This function has no parameters. ### Return Values Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive. ### Errors/Exceptions Throws [RuntimeException](class.runtimeexception) if it is not possible to read the stub from the Phar archive. ### Examples **Example #1 A **Phar::getStub()** example** ``` <?php $p = new Phar('/path/to/my.phar', 0, 'my.phar'); echo $p->getStub(); echo "==NEXT==\n"; $p->setStub("<?php function __autoload($class) {     include 'phar://' . str_replace('_', '/', $class); } Phar::mapPhar('myphar.phar'); include 'phar://myphar.phar/startup.php'; __HALT_COMPILER(); ?>"); echo $p->getStub(); ?> ``` The above example will output: ``` <?php __HALT_COMPILER(); ?> ==NEXT== <?php function __autoload($class) { include 'phar://' . str_replace('_', '/', $class); } Phar::mapPhar('myphar.phar'); include 'phar://myphar.phar/startup.php'; __HALT_COMPILER(); ?> ``` ### See Also * [Phar::setStub()](phar.setstub) - Used to set the PHP loader or bootstrap stub of a Phar archive * [Phar::createDefaultStub()](phar.createdefaultstub) - Create a phar-file format specific stub php The DOMElement class The DOMElement class ==================== Class synopsis -------------- (PHP 5, PHP 7, PHP 8) class **DOMElement** extends [DOMNode](class.domnode) implements [DOMParentNode](class.domparentnode), [DOMChildNode](class.domchildnode) { /\* Properties \*/ public readonly string [$tagName](class.domelement#domelement.props.tagname); public readonly [mixed](language.types.declarations#language.types.declarations.mixed) [$schemaTypeInfo](class.domelement#domelement.props.schematypeinfo) = null; public readonly ?[DOMElement](class.domelement) [$firstElementChild](class.domelement#domelement.props.firstelementchild); public readonly ?[DOMElement](class.domelement) [$lastElementChild](class.domelement#domelement.props.lastelementchild); public readonly int [$childElementCount](class.domelement#domelement.props.childelementcount); public readonly ?[DOMElement](class.domelement) [$previousElementSibling](class.domelement#domelement.props.previouselementsibling); public readonly ?[DOMElement](class.domelement) [$nextElementSibling](class.domelement#domelement.props.nextelementsibling); /\* Inherited properties \*/ public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domelement.construct)(string `$qualifiedName`, ?string `$value` = **`null`**, string `$namespace` = "") ``` public getAttribute(string $qualifiedName): string ``` ``` public getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false ``` ``` public getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null ``` ``` public getAttributeNS(?string $namespace, string $localName): string ``` ``` public getElementsByTagName(string $qualifiedName): DOMNodeList ``` ``` public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList ``` ``` public hasAttribute(string $qualifiedName): bool ``` ``` public hasAttributeNS(?string $namespace, string $localName): bool ``` ``` public removeAttribute(string $qualifiedName): bool ``` ``` public removeAttributeNode(DOMAttr $attr): DOMAttr|false ``` ``` public removeAttributeNS(?string $namespace, string $localName): void ``` ``` public setAttribute(string $qualifiedName, string $value): DOMAttr|bool ``` ``` public setAttributeNode(DOMAttr $attr): DOMAttr|null|false ``` ``` public setAttributeNodeNS(DOMAttr $attr): DOMAttr|null|false ``` ``` public setAttributeNS(?string $namespace, string $qualifiedName, string $value): void ``` ``` public setIdAttribute(string $qualifiedName, bool $isId): void ``` ``` public setIdAttributeNode(DOMAttr $attr, bool $isId): void ``` ``` public setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void ``` /\* Inherited methods \*/ ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Properties ---------- childElementCount The number of child elements. firstElementChild First child element or **`null`**. lastElementChild Last child element or **`null`**. nextElementSibling The next sibling element or **`null`**. previousElementSibling The previous sibling element or **`null`**. schemaTypeInfo Not implemented yet, always return **`null`** tagName The element name Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | The firstElementChild, lastElementChild, childElementCount, previousElementSibling, and nextElementSibling properties have been added. | | 8.0.0 | **DOMElement** implements [DOMParentNode](class.domparentnode) and [DOMChildNode](class.domchildnode) now. | Notes ----- > > **Note**: > > > The DOM extension uses UTF-8 encoding. Use [mb\_convert\_encoding()](function.mb-convert-encoding), [UConverter::transcode()](uconverter.transcode), or [iconv()](function.iconv) to handle other encodings. > > > Table of Contents ----------------- * [DOMElement::\_\_construct](domelement.construct) — Creates a new DOMElement object * [DOMElement::getAttribute](domelement.getattribute) — Returns value of attribute * [DOMElement::getAttributeNode](domelement.getattributenode) — Returns attribute node * [DOMElement::getAttributeNodeNS](domelement.getattributenodens) — Returns attribute node * [DOMElement::getAttributeNS](domelement.getattributens) — Returns value of attribute * [DOMElement::getElementsByTagName](domelement.getelementsbytagname) — Gets elements by tagname * [DOMElement::getElementsByTagNameNS](domelement.getelementsbytagnamens) — Get elements by namespaceURI and localName * [DOMElement::hasAttribute](domelement.hasattribute) — Checks to see if attribute exists * [DOMElement::hasAttributeNS](domelement.hasattributens) — Checks to see if attribute exists * [DOMElement::removeAttribute](domelement.removeattribute) — Removes attribute * [DOMElement::removeAttributeNode](domelement.removeattributenode) — Removes attribute * [DOMElement::removeAttributeNS](domelement.removeattributens) — Removes attribute * [DOMElement::setAttribute](domelement.setattribute) — Adds new or modifies existing attribute * [DOMElement::setAttributeNode](domelement.setattributenode) — Adds new attribute node to element * [DOMElement::setAttributeNodeNS](domelement.setattributenodens) — Adds new attribute node to element * [DOMElement::setAttributeNS](domelement.setattributens) — Adds new attribute * [DOMElement::setIdAttribute](domelement.setidattribute) — Declares the attribute specified by name to be of type ID * [DOMElement::setIdAttributeNode](domelement.setidattributenode) — Declares the attribute specified by node to be of type ID * [DOMElement::setIdAttributeNS](domelement.setidattributens) — Declares the attribute specified by local name and namespace URI to be of type ID php preg_last_error preg\_last\_error ================= (PHP 5 >= 5.2.0, PHP 7, PHP 8) preg\_last\_error — Returns the error code of the last PCRE regex execution ### Description ``` preg_last_error(): int ``` Returns the error code of the last PCRE regex execution. **Example #1 **preg\_last\_error()** example** ``` <?php preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar'); if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {     echo 'Backtrack limit was exhausted!'; } ?> ``` The above example will output: ``` Backtrack limit was exhausted! ``` ### Parameters This function has no parameters. ### Return Values Returns one of the following constants ([explained on their own page](https://www.php.net/manual/en/pcre.constants.php)): * **`PREG_NO_ERROR`** * **`PREG_INTERNAL_ERROR`** * **`PREG_BACKTRACK_LIMIT_ERROR`** (see also [pcre.backtrack\_limit](https://www.php.net/manual/en/pcre.configuration.php#ini.pcre.backtrack-limit)) * **`PREG_RECURSION_LIMIT_ERROR`** (see also [pcre.recursion\_limit](https://www.php.net/manual/en/pcre.configuration.php#ini.pcre.recursion-limit)) * **`PREG_BAD_UTF8_ERROR`** * **`PREG_BAD_UTF8_OFFSET_ERROR`** * **`PREG_JIT_STACKLIMIT_ERROR`** ### See Also * [preg\_last\_error\_msg()](function.preg-last-error-msg) - Returns the error message of the last PCRE regex execution php ImagickPixelIterator::setIteratorRow ImagickPixelIterator::setIteratorRow ==================================== (PECL imagick 2, PECL imagick 3) ImagickPixelIterator::setIteratorRow — Set the pixel iterator row ### Description ``` public ImagickPixelIterator::setIteratorRow(int $row): bool ``` **Warning**This function is currently not documented; only its argument list is available. Set the pixel iterator row. ### Parameters `row` ### Return Values Returns **`true`** on success. ### Examples **Example #1 **ImagickPixelIterator::setIteratorRow()**** ``` <?php function setIteratorRow($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imageIterator = $imagick->getPixelRegionIterator(200, 100, 200, 200);     for ($x = 0; $x < 20; $x++) {                 $imageIterator->setIteratorRow($x * 5);         $pixels = $imageIterator->getCurrentIteratorRow();         /* Loop through the pixels in the row (columns) */         foreach ($pixels as $pixel) {             /** @var $pixel \ImagickPixel */             /* Paint every second pixel black*/             $pixel->setColor("rgba(0, 0, 0, 0)");          }         /* Sync the iterator, this is important to do on each iteration */         $imageIterator->syncIterator();     }     header("Content-Type: image/jpg");     echo $imagick; } ?> ``` php sys_getloadavg sys\_getloadavg =============== (PHP 5 >= 5.1.3, PHP 7, PHP 8) sys\_getloadavg — Gets system load average ### Description ``` sys_getloadavg(): array|false ``` Returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively. Returns **`false`** on failure. ### Parameters This function has no parameters. ### Return Values Returns an array with three samples (last 1, 5 and 15 minutes). ### Examples **Example #1 A **sys\_getloadavg()** example** ``` <?php $load = sys_getloadavg(); if ($load[0] > 0.80) {     header('HTTP/1.1 503 Too busy, try again later');     die('Server too busy. Please try again later.'); } ?> ``` ### Notes > **Note**: This function is not implemented on Windows platforms. > > php APCUIterator::getTotalSize APCUIterator::getTotalSize ========================== (PECL apcu >= 5.0.0) APCUIterator::getTotalSize — Get total cache size ### Description ``` public APCUIterator::getTotalSize(): int ``` Gets the total cache size. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The total cache size. ### See Also * [APCUIterator::getTotalCount()](apcuiterator.gettotalcount) - Get total count * [APCUIterator::getTotalHits()](apcuiterator.gettotalhits) - Get total cache hits * **apc\_cache\_info()**
programming_docs
php stream_context_set_default stream\_context\_set\_default ============================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) stream\_context\_set\_default — Set the default stream context ### Description ``` stream_context_set_default(array $options): resource ``` Set the default stream context which will be used whenever file operations ([fopen()](function.fopen), [file\_get\_contents()](function.file-get-contents), etc...) are called without a context parameter. Uses the same syntax as [stream\_context\_create()](function.stream-context-create). ### Parameters `options` The options to set for the default context. > > **Note**: > > > `options` must be an associative array of associative arrays in the format `$arr['wrapper']['option'] = $value`. > > ### Return Values Returns the default stream context. ### Examples **Example #1 **stream\_context\_set\_default()** example** ``` <?php $default_opts = array(   'http'=>array(     'method'=>"GET",     'header'=>"Accept-language: en\r\n" .               "Cookie: foo=bar",     'proxy'=>"tcp://10.54.1.39:8000"   ) ); $default = stream_context_set_default($default_opts); /* Sends a regular GET request to proxy server at 10.54.1.39  * For www.example.com using context options specified in $default_opts  */ readfile('http://www.example.com'); ?> ``` ### See Also * [stream\_context\_create()](function.stream-context-create) - Creates a stream context * [stream\_context\_get\_default()](function.stream-context-get-default) - Retrieve the default stream context * Listing of supported wrappers with context options ([Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php)). php None Type declarations ----------------- Type declarations can be added to function arguments, return values, and, as of PHP 7.4.0, class properties. They ensure that the value is of the specified type at call time, otherwise a [TypeError](class.typeerror) is thrown. Every single type that PHP supports, with the exception of resource can be used within a user-land type declaration. This page contains a changelog of availability of the different types and documentation about usage of them in type declarations. > > **Note**: > > > When a class implements an interface method or reimplements a method which has already been defined by a parent class, it has to be compatible with the aforementioned definition. A method is compatible if it follows the [variance](language.oop5.variance) rules. > > ### Changelog | Version | Description | | --- | --- | | 8.2.0 | Support for DNF types has been added. | | 8.2.0 | Support for the literal type true has been added. | | 8.2.0 | The types null and false can now be used standalone. | | 8.1.0 | Support for intersection types has been added. | | 8.1.0 | Returning by reference from a void function is now deprecated. | | 8.1.0 | Support for the return only type never has been added. | | 8.0.0 | Support for [mixed](language.types.declarations#language.types.declarations.mixed) has been added. | | 8.0.0 | Support for the return only type static has been added. | | 8.0.0 | Support for union types has been added. | | 7.2.0 | Support for object has been added. | | 7.1.0 | Support for [iterable](language.types.iterable) has been added. | | 7.1.0 | Support for void has been added. | | 7.1.0 | Support for nullable types has been added. | ### Base Types Usage Notes Base types have straight forward behaviour with some minor caveats which are described in this section. #### Scalar types **Warning** Name aliases for scalar types (bool, int, float, string) are not supported. Instead, they are treated as class or interface names. For example, using `boolean` as a type declaration will require the value to be an [`instanceof`](language.operators.type) the class or interface `boolean`, rather than of type bool: ``` <?php     function test(boolean $param) {}     test(true); ?> ``` Output of the above example in PHP 8: ``` Warning: "boolean" will be interpreted as a class name. Did you mean "bool"? Write "\boolean" to suppress this warning in /in/9YrUX on line 2 Fatal error: Uncaught TypeError: test(): Argument #1 ($param) must be of type boolean, bool given, called in - on line 3 and defined in -:2 Stack trace: #0 -(3): test(true) #1 {main} thrown in - on line 2 ``` #### void > > **Note**: > > > Returning by reference from a void function is deprecated as of PHP 8.1.0, because such a function is contradictory. Previously, it already emitted the following **`E_NOTICE`** when called: `Only variable references should be returned by reference`. > > > > ``` > <?php > function &test(): void {} > ?> > ``` > #### Callable types This type cannot be used as a class property type declaration. > **Note**: It is not possible to specify the signature of the function. > > #### Type declarations on pass-by-reference Parameters If a pass-by-reference parameter has a type declaration, the type of the variable is *only* checked on function entry, at the beginning of the call, but not when the function returns. This means that a function can change the type of variable reference. **Example #1 Typed pass-by-reference Parameters** ``` <?php function array_baz(array &$param) {     $param = 1; } $var = []; array_baz($var); var_dump($var); array_baz($var); ?> ``` The above example will output something similar to: ``` int(1) Fatal error: Uncaught TypeError: array_baz(): Argument #1 ($param) must be of type array, int given, called in - on line 9 and defined in -:2 Stack trace: #0 -(9): array_baz(1) #1 {main} thrown in - on line 2 ``` ### Composite Types Usage Notes Composite type declarations are subject to a couple of restrictions and will perform a redundancy check at compile time to prevent simple bugs. **Caution** Prior to PHP 8.2.0, and the introduction of DNF types, it was not possible to combine intersection types with union types. #### Union types **Warning** It is not possible to combine the two literal types `false` and `true` together in a union type. Use bool instead. **Caution** Prior to PHP 8.2.0, as `false` and null could not be used as standalone types, a union type comprised of only these types was not permitted. This comprises the following types: `false`, `false|null`, and `?false`. ##### Nullable type syntactic sugar A single base type declaration can be marked nullable by prefixing the type with a question mark (`?`). Thus `?T` and `T|null` are identical. > **Note**: This syntax is supported as of PHP 7.1.0, and predates generalized union types support. > > > > **Note**: > > > It is also possible to achieve nullable arguments by making `null` the default value. This is not recommended as if the default value is changed in a child class a type compatibility violation will be raised as the null type will need to be added to the type declaration. > > **Example #2 Old way to make arguments nullable** > > > ``` > <?php > class C {} > > function f(C $c = null) { >     var_dump($c); > } > > f(new C); > f(null); > ?> > ``` > The above example will output: > > > ``` > > object(C)#1 (0) { > } > NULL > > ``` > #### Duplicate and redundant types To catch simple bugs in composite type declarations, redundant types that can be detected without performing class loading will result in a compile-time error. This includes: * Each name-resolved type may only occur once. Types such as `int|string|INT` or `Countable&Traversable&COUNTABLE` result in an error. * Using [mixed](language.types.declarations#language.types.declarations.mixed) results in an error. * For union types: + If bool is used, false or true cannot be used additionally. + If object is used, class types cannot be used additionally. + If [iterable](language.types.iterable) is used, array and [Traversable](class.traversable) cannot be used additionally. * For intersection types: + Using a type which is not a class-type results in an error. + Using either self, parent, or static results in an error. * For DNF types: + If a more generic type is used, the more restrictive one is redundant. + Using two identical intersection types. > **Note**: This does not guarantee that the type is “minimal”, because doing so would require loading all used class types. > > For example, if `A` and `B` are class aliases, then `A|B` remains a legal union type, even though it could be reduced to either `A` or `B`. Similarly, if class `B extends A {}`, then `A|B` is also a legal union type, even though it could be reduced to just `A`. ``` <?php function foo(): int|INT {} // Disallowed function foo(): bool|false {} // Disallowed function foo(): int&Traversable {} // Disallowed function foo(): self&Traversable {} // Disallowed use A as B; function foo(): A|B {} // Disallowed ("use" is part of name resolution) function foo(): A&B {} // Disallowed ("use" is part of name resolution) class_alias('X', 'Y'); function foo(): X|Y {} // Allowed (redundancy is only known at runtime) function foo(): X&Y {} // Allowed (redundancy is only known at runtime) ?> ``` ### Examples **Example #3 Basic class type declaration** ``` <?php class C {} class D extends C {} // This doesn't extend C. class E {} function f(C $c) {     echo get_class($c)."\n"; } f(new C); f(new D); f(new E); ?> ``` Output of the above example in PHP 8: ``` C D Fatal error: Uncaught TypeError: f(): Argument #1 ($c) must be of type C, E given, called in /in/gLonb on line 14 and defined in /in/gLonb:8 Stack trace: #0 -(14): f(Object(E)) #1 {main} thrown in - on line 8 ``` **Example #4 Basic interface type declaration** ``` <?php interface I { public function f(); } class C implements I { public function f() {} } // This doesn't implement I. class E {} function f(I $i) {     echo get_class($i)."\n"; } f(new C); f(new E); ?> ``` Output of the above example in PHP 8: ``` C Fatal error: Uncaught TypeError: f(): Argument #1 ($i) must be of type I, E given, called in - on line 13 and defined in -:8 Stack trace: #0 -(13): f(Object(E)) #1 {main} thrown in - on line 8 ``` **Example #5 Basic return type declaration** ``` <?php function sum($a, $b): float {     return $a + $b; } // Note that a float will be returned. var_dump(sum(1, 2)); ?> ``` The above example will output: ``` float(3) ``` **Example #6 Returning an object** ``` <?php class C {} function getC(): C {     return new C; } var_dump(getC()); ?> ``` The above example will output: ``` object(C)#1 (0) { } ``` **Example #7 Nullable argument type declaration** ``` <?php class C {} function f(?C $c) {     var_dump($c); } f(new C); f(null); ?> ``` The above example will output: ``` object(C)#1 (0) { } NULL ``` **Example #8 Nullable return type declaration** ``` <?php function get_item(): ?string {     if (isset($_GET['item'])) {         return $_GET['item'];     } else {         return null;     } } ?> ``` ### Strict typing By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string. It is possible to enable strict mode on a per-file basis. In strict mode, only a value corresponding exactly to the type declaration will be accepted, otherwise a [TypeError](class.typeerror) will be thrown. The only exception to this rule is that an int value will pass a float type declaration. **Warning** Function calls from within internal functions will not be affected by the `strict_types` declaration. To enable strict mode, the [`declare`](control-structures.declare) statement is used with the `strict_types` declaration: > > **Note**: > > > Strict typing applies to function calls made from *within* the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (coercive typing) will be respected, and the value will be coerced. > > > > **Note**: > > > Strict typing is only defined for scalar type declarations. > > **Example #9 Strict typing for arguments values** ``` <?php declare(strict_types=1); function sum(int $a, int $b) {     return $a + $b; } var_dump(sum(1, 2)); var_dump(sum(1.5, 2.5)); ?> ``` Output of the above example in PHP 8: ``` int(3) Fatal error: Uncaught TypeError: sum(): Argument #1 ($a) must be of type int, float given, called in - on line 9 and defined in -:4 Stack trace: #0 -(9): sum(1.5, 2.5) #1 {main} thrown in - on line 4 ``` **Example #10 Coercive typing for argument values** ``` <?php function sum(int $a, int $b) {     return $a + $b; } var_dump(sum(1, 2)); // These will be coerced to integers: note the output below! var_dump(sum(1.5, 2.5)); ?> ``` The above example will output: ``` int(3) int(3) ``` **Example #11 Strict typing for return values** ``` <?php declare(strict_types=1); function sum($a, $b): int {     return $a + $b; } var_dump(sum(1, 2)); var_dump(sum(1, 2.5)); ?> ``` The above example will output: ``` int(3) Fatal error: Uncaught TypeError: sum(): Return value must be of type int, float returned in -:5 Stack trace: #0 -(9): sum(1, 2.5) #1 {main} thrown in - on line 5 ``` php stream_wrapper_register stream\_wrapper\_register ========================= (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) stream\_wrapper\_register — Register a URL wrapper implemented as a PHP class ### Description ``` stream_wrapper_register(string $protocol, string $class, int $flags = 0): bool ``` Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as [fopen()](function.fopen), [fread()](function.fread) etc.). ### Parameters `protocol` The wrapper name to be registered. Valid protocol names must contain alphanumerics, dots (.), plusses (+), or hyphens (-) only. `class` The classname which implements the `protocol`. `flags` Should be set to **`STREAM_IS_URL`** if `protocol` is a URL protocol. Default is 0, local stream. ### Return Values Returns **`true`** on success or **`false`** on failure. **stream\_wrapper\_register()** will return **`false`** if the `protocol` already has a handler. ### Examples **Example #1 How to register a stream wrapper** ``` <?php $existed = in_array("var", stream_get_wrappers()); if ($existed) {     stream_wrapper_unregister("var"); } stream_wrapper_register("var", "VariableStream"); $myvar = ""; $fp = fopen("var://myvar", "r+"); fwrite($fp, "line1\n"); fwrite($fp, "line2\n"); fwrite($fp, "line3\n"); rewind($fp); while (!feof($fp)) {     echo fgets($fp); } fclose($fp); var_dump($myvar); if ($existed) {     stream_wrapper_restore("var"); } ?> ``` The above example will output: ``` line1 line2 line3 string(18) "line1 line2 line3 " ``` ### See Also * The [streamWrapper](class.streamwrapper) prototype class * [Example class registered as stream wrapper](https://www.php.net/manual/en/stream.streamwrapper.example-1.php) * [stream\_wrapper\_unregister()](function.stream-wrapper-unregister) - Unregister a URL wrapper * [stream\_wrapper\_restore()](function.stream-wrapper-restore) - Restores a previously unregistered built-in wrapper * [stream\_get\_wrappers()](function.stream-get-wrappers) - Retrieve list of registered streams php ImagickPixel::getColor ImagickPixel::getColor ====================== (PECL imagick 2, PECL imagick 3) ImagickPixel::getColor — Returns the color ### Description ``` public ImagickPixel::getColor(int $normalized = 0): array ``` Returns the color described by the ImagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list. ### Parameters `normalized` Normalize the color values. Possible values are `0`, `1` or `2`. **List of possible values for `normalized`** | `normalized` | Description | | --- | --- | | **`0`** | The RGB values are returned as ints in the range `0` to `255` (inclusive.) The alpha value is returned as int and is either `0` or `1`. | | **`1`** | The RGBA values are returned as floats in the range `0` to `1` (inclusive.) | | **`2`** | The RGBA values are returned as ints in the range `0` to `255` (inclusive.) | ### Return Values An array of channel values. Throws ImagickPixelException on error. ### Examples **Example #1 Basic **Imagick::getColor()** usage** ``` <?php //Create an ImagickPixel with the predefined color 'brown' $color = new ImagickPixel('brown'); //Set the color to have an alpha of 25% $color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0); $colorInfo = $color->getColor(); echo "Standard values".PHP_EOL; print_r($colorInfo); $colorInfo = $color->getColor(1); echo "Normalized values:".PHP_EOL; print_r($colorInfo); ?> ``` The above example will output: ``` Standard values Array ( [r] => 165 [g] => 42 [b] => 42 [a] => 0 ) Normalized values: Array ( [r] => 0.64705882352941 [g] => 0.16470588235294 [b] => 0.16470588235294 [a] => 0.25000381475547 ) ``` php None Internal option setting ----------------------- The settings of [PCRE\_CASELESS](reference.pcre.pattern.modifiers), [PCRE\_MULTILINE](reference.pcre.pattern.modifiers), [PCRE\_DOTALL](reference.pcre.pattern.modifiers), [PCRE\_UNGREEDY](reference.pcre.pattern.modifiers), [PCRE\_EXTRA](reference.pcre.pattern.modifiers), [PCRE\_EXTENDED](reference.pcre.pattern.modifiers) and PCRE\_DUPNAMES can be changed from within the pattern by a sequence of Perl option letters enclosed between "(?" and ")". The option letters are: **Internal option letters**| `i` | for [PCRE\_CASELESS](reference.pcre.pattern.modifiers) | | `m` | for [PCRE\_MULTILINE](reference.pcre.pattern.modifiers) | | `s` | for [PCRE\_DOTALL](reference.pcre.pattern.modifiers) | | `x` | for [PCRE\_EXTENDED](reference.pcre.pattern.modifiers) | | `U` | for [PCRE\_UNGREEDY](reference.pcre.pattern.modifiers) | | `X` | for [PCRE\_EXTRA](reference.pcre.pattern.modifiers) (no longer supported as of PHP 7.3.0) | | `J` | for [PCRE\_INFO\_JCHANGED](reference.pcre.pattern.modifiers) | For example, (?im) sets case-insensitive (caseless), multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which sets [PCRE\_CASELESS](reference.pcre.pattern.modifiers) and [PCRE\_MULTILINE](reference.pcre.pattern.modifiers) while unsetting [PCRE\_DOTALL](reference.pcre.pattern.modifiers) and [PCRE\_EXTENDED](reference.pcre.pattern.modifiers), is also permitted. If a letter appears both before and after the hyphen, the option is unset. When an option change occurs at top level (that is, not inside subpattern parentheses), the change applies to the remainder of the pattern that follows. So `/ab(?i)c/` matches only "abc" and "abC". If an option change occurs inside a subpattern, the effect is different. This is a change of behaviour in Perl 5.005. An option change inside a subpattern affects only that part of the subpattern that follows it, so `(a(?i)b)c` matches abc and aBc and no other strings (assuming [PCRE\_CASELESS](reference.pcre.pattern.modifiers) is not used). By this means, options can be made to have different settings in different parts of the pattern. Any changes made in one alternative do carry on into subsequent branches within the same subpattern. For example, `(a(?i)b|c)` matches "ab", "aB", "c", and "C", even though when matching "C" the first branch is abandoned before the option setting. This is because the effects of option settings happen at compile time. There would be some very weird behaviour otherwise. The PCRE-specific options [PCRE\_UNGREEDY](reference.pcre.pattern.modifiers) and [PCRE\_EXTRA](reference.pcre.pattern.modifiers) can be changed in the same way as the Perl-compatible options by using the characters U and X respectively. The (?X) flag setting is special in that it must always occur earlier in the pattern than any of the additional features it turns on, even when it is at top level. It is best put at the start.
programming_docs
php Imagick::colorFloodfillImage Imagick::colorFloodfillImage ============================ (PECL imagick 2, PECL imagick 3) Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::colorFloodfillImage( mixed $fill, float $fuzz, mixed $bordercolor, int $x, int $y ): bool ``` Changes the color value of any pixel that matches target and is an immediate neighbor. ### Parameters `fill` ImagickPixel object containing the fill color `fuzz` The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill. `bordercolor` ImagickPixel object containing the border color `x` X start position of the floodfill `y` Y start position of the floodfill ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as first and third parameter. Previous versions allow only an ImagickPixel object. | php EvCheck::__construct EvCheck::\_\_construct ====================== (PECL ev >= 0.2.0) EvCheck::\_\_construct — Constructs the EvCheck watcher object ### Description public **EvCheck::\_\_construct**( [callable](language.types.callable) `$callback` , [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = ?, int `$priority` = ?) Constructs the [EvCheck](class.evcheck) watcher object. ### Parameters `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### See Also * [EvPrepare](class.evprepare) * [EvLoop::check()](evloop.check) - Creates EvCheck object associated with the current event loop instance php imagecropauto imagecropauto ============= (PHP 5 >= 5.5.0, PHP 7, PHP 8) imagecropauto — Crop an image automatically using one of the available modes ### Description ``` imagecropauto( GdImage $image, int $mode = IMG_CROP_DEFAULT, float $threshold = 0.5, int $color = -1 ): GdImage|false ``` Automatically crops an image according to the given `mode`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `mode` One of the following constants: **`IMG_CROP_DEFAULT`** Same as **`IMG_CROP_TRANSPARENT`**. Before PHP 7.4.0, the bundled libgd fell back to **`IMG_CROP_SIDES`**, if the image had no transparent color. **`IMG_CROP_TRANSPARENT`** Crops out a transparent background. **`IMG_CROP_BLACK`** Crops out a black background. **`IMG_CROP_WHITE`** Crops out a white background. **`IMG_CROP_SIDES`** Uses the 4 corners of the image to attempt to detect the background to crop. **`IMG_CROP_THRESHOLD`** Crops an image using the given `threshold` and `color`. `threshold` Specifies the tolerance in percent to be used while comparing the image color and the color to crop. The method used to calculate the color difference is based on the color distance in the RGB(a) cube. Used only in **`IMG_CROP_THRESHOLD`** mode. > **Note**: Before PHP 7.4.0, the bundled libgd used a somewhat different algorithm, so the same `threshold` yielded different results for system and bundled libgd. > > `color` Either an RGB color value or a palette index. Used only in **`IMG_CROP_THRESHOLD`** mode. ### Return Values Returns a cropped image object on success or **`false`** on failure. If the complete image was cropped, [imagecrop()](function.imagecrop) returns **`false`**. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | | 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. | | 7.4.0 | The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd: **`IMG_CROP_DEFAULT`** no longer falls back to **`IMG_CROP_SIDES`** and threshold-cropping now uses the same algorithm as system libgd. | | 7.4.0 | The default value of `mode` has been changed to **`IMG_CROP_AUTO`**. Formerly, the default value has been `-1` which corresponds to **`IMG_CROP_DEFAULT`**, but passing `-1` is now deprecated. | ### Examples **Example #1 Proper handling of auto-cropping** As noted in the return value section, **imagecropauto()** returns **`false`** if the whole image was cropped. In this example we have an image object `$im` which should be automatically cropped only if there is something to crop; otherwise we want to proceed with the original image. ``` <?php $cropped = imagecropauto($im, IMG_CROP_DEFAULT); if ($cropped !== false) { // in case a new image object was returned     imagedestroy($im);    // we destroy the original image     $im = $cropped;       // and assign the cropped image to $im } ?> ``` ### See Also * [imagecrop()](function.imagecrop) - Crop an image to the given rectangle php Yaf_Dispatcher::flushInstantly Yaf\_Dispatcher::flushInstantly =============================== (Yaf >=1.0.0) Yaf\_Dispatcher::flushInstantly — Switch on/off the instant flushing ### Description ``` public Yaf_Dispatcher::flushInstantly(bool $flag = ?): Yaf_Dispatcher ``` ### Parameters `flag` bool > > **Note**: > > > since 2.2.0, if this parameter is not given, then the current state will be returned > > ### Return Values php fbird_blob_import fbird\_blob\_import =================== (PHP 5, PHP 7 < 7.4.0) fbird\_blob\_import — Alias of [ibase\_blob\_import()](function.ibase-blob-import) ### Description This function is an alias of: [ibase\_blob\_import()](function.ibase-blob-import). ### See Also * [fbird\_blob\_add()](function.fbird-blob-add) - Alias of ibase\_blob\_add * [fbird\_blob\_cancel()](function.fbird-blob-cancel) - Cancel creating blob * [fbird\_blob\_close()](function.fbird-blob-close) - Alias of ibase\_blob\_close * [fbird\_blob\_create()](function.fbird-blob-create) - Alias of ibase\_blob\_create php NumberFormatter::formatCurrency NumberFormatter::formatCurrency =============================== numfmt\_format\_currency ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::formatCurrency -- numfmt\_format\_currency — Format a currency value ### Description Object-oriented style ``` public NumberFormatter::formatCurrency(float $amount, string $currency): string|false ``` Procedural style ``` numfmt_format_currency(NumberFormatter $formatter, float $amount, string $currency): string|false ``` Format the currency value according to the formatter rules. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. `amount` The numeric currency value. `currency` The 3-letter ISO 4217 currency code indicating the currency to use. ### Return Values String representing the formatted currency value, or **`false`** on failure. ### Examples **Example #1 **numfmt\_format\_currency()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY ); echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n"; echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n"; $fmt = numfmt_create( 'ru_RU', NumberFormatter::CURRENCY ); echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n"; echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n"; ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY ); echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n"; echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n"; $fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY ); echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n"; echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n"; ?> ``` The above example will output: ``` 1.234.567,89 € 1.234.567,89 RUR 1 234 567,89€ 1 234 567,89р. ``` ### Notes > > **Note**: > > > Formats achievable by this method of formatting cannot fully use the possibilities of underlying ICU library, such as to format currency with narrow currency symbol. > > To fully utilize them use [msgfmt\_format\_message()](messageformatter.formatmessage). > > ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [numfmt\_format()](numberformatter.format) - Format a number * [numfmt\_parse\_currency()](numberformatter.parsecurrency) - Parse a currency number * [msgfmt\_format\_message()](messageformatter.formatmessage) - Quick format message php RecursiveDirectoryIterator::getChildren RecursiveDirectoryIterator::getChildren ======================================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory ### Description ``` public RecursiveDirectoryIterator::getChildren(): RecursiveDirectoryIterator ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The filename, file information, or $this depending on the set flags. See the [FilesystemIterator constants](class.filesystemiterator#filesystemiterator.constants). php pspell_config_repl pspell\_config\_repl ==================== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) pspell\_config\_repl — Set a file that contains replacement pairs ### Description ``` pspell_config_repl(PSpell\Config $config, string $filename): bool ``` Set a file that contains replacement pairs. The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, [pspell\_store\_replacement()](function.pspell-store-replacement) can be used to store a replacement pair and then [pspell\_save\_wordlist()](function.pspell-save-wordlist) to save the wordlist along with the replacement pairs. **pspell\_config\_repl()** should be used on a config before calling [pspell\_new\_config()](function.pspell-new-config). ### Parameters `config` An [PSpell\Config](class.pspell-config) instance. `filename` The file should be writable by whoever PHP runs as (e.g. nobody). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `config` parameter expects an [PSpell\Config](class.pspell-config) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pspell\_config\_repl()**** ``` <?php $pspell_config = pspell_config_create("en"); pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws"); pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl"); $pspell = pspell_new_config($pspell_config); pspell_check($pspell, "thecat"); ?> ``` ### Notes > > **Note**: > > > This function will not work unless you have pspell .11.2 and aspell .32.5 or later. > > php ImagickDraw::pathCurveToRelative ImagickDraw::pathCurveToRelative ================================ (PECL imagick 2, PECL imagick 3) ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve ### Description ``` public ImagickDraw::pathCurveToRelative( float $x1, float $y1, float $x2, float $y2, float $x, float $y ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. ### Parameters `x1` x coordinate of starting control point `y1` y coordinate of starting control point `x2` x coordinate of ending control point `y2` y coordinate of ending control point `x` ending x coordinate `y` ending y coordinate ### Return Values No value is returned. php XMLReader::isValid XMLReader::isValid ================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::isValid — Indicates if the parsed document is valid ### Description ``` public XMLReader::isValid(): bool ``` Returns a boolean indicating if the document being parsed is currently valid. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Validating XML** ``` <?php $xml = XMLReader::open('test.xml'); // The validate parser option must be enabled for  // this method to work properly $xml->setParserProperty(XMLReader::VALIDATE, true); var_dump($xml->isValid()); ?> ``` ### Notes > **Note**: This checks the current node, not the entire document. > > ### See Also * [XMLReader::setParserProperty()](xmlreader.setparserproperty) - Set parser options * [XMLReader::setRelaxNGSchema()](xmlreader.setrelaxngschema) - Set the filename or URI for a RelaxNG Schema * [XMLReader::setRelaxNGSchemaSource()](xmlreader.setrelaxngschemasource) - Set the data containing a RelaxNG Schema * [XMLReader::setSchema()](xmlreader.setschema) - Validate document against XSD php The SessionHandler class The SessionHandler class ======================== Introduction ------------ (PHP 5 >= 5.4.0, PHP 7, PHP 8) **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](https://www.php.net/manual/en/session.configuration.php#ini.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()](function.session-set-save-handler) it will wrap the current save handlers. A class extending from **SessionHandler** allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the internal PHP session handlers. This allows you, for example, to intercept the `read` and `write` methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback `gc`. Because the **SessionHandler** wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers. To use this class, first set the save handler you wish to expose using [session.save\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.save-handler) and then pass an instance of **SessionHandler** or one extending it to [session\_set\_save\_handler()](function.session-set-save-handler). Please note that the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer to [session\_set\_save\_handler()](function.session-set-save-handler). Class synopsis -------------- class **SessionHandler** implements [SessionHandlerInterface](class.sessionhandlerinterface), [SessionIdInterface](class.sessionidinterface) { /\* Methods \*/ ``` public close(): bool ``` ``` public create_sid(): string ``` ``` public destroy(string $id): bool ``` ``` public gc(int $max_lifetime): int|false ``` ``` public open(string $path, string $name): bool ``` ``` public read(string $id): string|false ``` ``` public write(string $id, string $data): bool ``` } **Warning** This class is designed to expose the current internal PHP session save handler, if you want to write your own custom save handlers, please implement the [SessionHandlerInterface](class.sessionhandlerinterface) interface instead of extending from **SessionHandler**. **Example #1 Using **SessionHandler** to add encryption to internal PHP save handlers.** ``` <?php  /**   * decrypt AES 256   *   * @param data $edata   * @param string $password   * @return decrypted data   */ function decrypt($edata, $password) {     $data = base64_decode($edata);     $salt = substr($data, 0, 16);     $ct = substr($data, 16);     $rounds = 3; // depends on key length     $data00 = $password.$salt;     $hash = array();     $hash[0] = hash('sha256', $data00, true);     $result = $hash[0];     for ($i = 1; $i < $rounds; $i++) {         $hash[$i] = hash('sha256', $hash[$i - 1].$data00, true);         $result .= $hash[$i];     }     $key = substr($result, 0, 32);     $iv  = substr($result, 32,16);     return openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv);   } /**  * crypt AES 256  *  * @param data $data  * @param string $password  * @return base64 encrypted data  */ function encrypt($data, $password) {     // Generate a cryptographically secure random salt using random_bytes()     $salt = random_bytes(16);     $salted = '';     $dx = '';     // Salt the key(32) and iv(16) = 48     while (strlen($salted) < 48) {       $dx = hash('sha256', $dx.$password.$salt, true);       $salted .= $dx;     }     $key = substr($salted, 0, 32);     $iv  = substr($salted, 32,16);     $encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv);     return base64_encode($salt . $encrypted_data); } class EncryptedSessionHandler extends SessionHandler {     private $key;     public function __construct($key)     {         $this->key = $key;     }     public function read($id)     {         $data = parent::read($id);         if (!$data) {             return "";         } else {             return decrypt($data, $this->key);         }     }     public function write($id, $data)     {         $data = encrypt($data, $this->key);         return parent::write($id, $data);     } } // we'll intercept the native 'files' handler, but will equally work // with other internal native handlers like 'sqlite', 'memcache' or 'memcached' // which are provided by PHP extensions. ini_set('session.save_handler', 'files'); $key = 'secret_string'; $handler = new EncryptedSessionHandler($key); session_set_save_handler($handler, true); session_start(); // proceed to set and retrieve values by key from $_SESSION ``` > > **Note**: > > > Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return **`false`** unless the session has actually been started (either automatically, or by explicit [session\_start()](function.session-start)). This is important to consider when writing unit tests where the class methods might be invoked manually. > > Table of Contents ----------------- * [SessionHandler::close](sessionhandler.close) — Close the session * [SessionHandler::create\_sid](sessionhandler.create-sid) — Return a new session ID * [SessionHandler::destroy](sessionhandler.destroy) — Destroy a session * [SessionHandler::gc](sessionhandler.gc) — Cleanup old sessions * [SessionHandler::open](sessionhandler.open) — Initialize session * [SessionHandler::read](sessionhandler.read) — Read session data * [SessionHandler::write](sessionhandler.write) — Write session data
programming_docs
php ImagickDraw::getStrokeLineCap ImagickDraw::getStrokeLineCap ============================= (PECL imagick 2, PECL imagick 3) ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked ### Description ``` public ImagickDraw::getStrokeLineCap(): int ``` **Warning**This function is currently not documented; only its argument list is available. Returns the shape to be used at the end of open subpaths when they are stroked. ### Return Values Returns a [LINECAP](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.linecap) constant (`imagick::LINECAP_*`), or 0 if stroke linecap is not set. php SplFixedArray::valid SplFixedArray::valid ==================== (PHP 5 >= 5.3.0, PHP 7) SplFixedArray::valid — Check whether the array contains more elements ### Description ``` public SplFixedArray::valid(): bool ``` Checks if the array contains any more elements. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the array contains any more elements, **`false`** otherwise. php PDO::rollBack PDO::rollBack ============= (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0) PDO::rollBack — Rolls back a transaction ### Description ``` public PDO::rollBack(): bool ``` Rolls back the current transaction, as initiated by [PDO::beginTransaction()](pdo.begintransaction). If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction. Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Throws a [PDOException](class.pdoexception) if there is no active transaction. > **Note**: An exception is raised even when the **`PDO::ATTR_ERRMODE`** attribute is not **`PDO::ERRMODE_EXCEPTION`**. > > ### Examples **Example #1 Roll back a transaction** The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back. ``` <?php /* Begin a transaction, turning off autocommit */ $dbh->beginTransaction(); /* Change the database schema and data */ $sth = $dbh->exec("DROP TABLE fruit"); $sth = $dbh->exec("UPDATE dessert     SET name = 'hamburger'"); /* Recognize mistake and roll back changes */ $dbh->rollBack(); /* Database connection is now back in autocommit mode */ ?> ``` ### See Also * [PDO::beginTransaction()](pdo.begintransaction) - Initiates a transaction * [PDO::commit()](pdo.commit) - Commits a transaction * [Transactions and auto-commit](https://www.php.net/manual/en/pdo.transactions.php) php The SolrIllegalOperationException class The SolrIllegalOperationException class ======================================= Introduction ------------ (PECL solr >= 0.9.2) This object is thrown when an illegal or unsupported operation is performed on an object. Class synopsis -------------- class **SolrIllegalOperationException** extends [SolrException](class.solrexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; protected int [$sourceline](class.solrexception#solrexception.props.sourceline); protected string [$sourcefile](class.solrexception#solrexception.props.sourcefile); protected string [$zif\_name](class.solrexception#solrexception.props.zif-name); /\* Methods \*/ ``` public getInternalInfo(): array ``` /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` ``` public SolrException::getInternalInfo(): array ``` } Table of Contents ----------------- * [SolrIllegalOperationException::getInternalInfo](solrillegaloperationexception.getinternalinfo) — Returns internal information where the Exception was thrown php prev prev ==== (PHP 4, PHP 5, PHP 7, PHP 8) prev — Rewind the internal array pointer ### Description ``` prev(array|object &$array): mixed ``` Rewind the internal array pointer. **prev()** behaves just like [next()](function.next), except it rewinds the internal array pointer one place instead of advancing it. ### Parameters `array` The input array. ### Return Values Returns the array value in the previous place that's pointed to by the internal array pointer, or **`false`** if there are no more elements. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Calling this function on objects is deprecated. Either use [get\_mangled\_object\_vars()](function.get-mangled-object-vars) on the object first, or use [ArrayIterator](class.arrayiterator). | ### Examples **Example #1 Example use of **prev()** and friends** ``` <?php $transport = array('foot', 'bike', 'car', 'plane'); $mode = current($transport); // $mode = 'foot'; $mode = next($transport);    // $mode = 'bike'; $mode = next($transport);    // $mode = 'car'; $mode = prev($transport);    // $mode = 'bike'; $mode = end($transport);     // $mode = 'plane'; ?> ``` ### Notes > **Note**: The beginning of an array is indistinguishable from a bool **`false`** element. To make the distinction, check that the [key()](function.key) of the **prev()** element is not **`null`**. > > ### See Also * [current()](function.current) - Return the current element in an array * [end()](function.end) - Set the internal pointer of an array to its last element * [next()](function.next) - Advance the internal pointer of an array * [reset()](function.reset) - Set the internal pointer of an array to its first element * [each()](function.each) - Return the current key and value pair from an array and advance the array cursor php xml_set_processing_instruction_handler xml\_set\_processing\_instruction\_handler ========================================== (PHP 4, PHP 5, PHP 7, PHP 8) xml\_set\_processing\_instruction\_handler — Set up processing instruction (PI) handler ### Description ``` xml_set_processing_instruction_handler(XMLParser $parser, callable $handler): bool ``` Sets the processing instruction (PI) handler function for the XML parser `parser`. A processing instruction has the following format: ``` <? ``` target data ``` ?> ``` You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (`?>`) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents.If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data. ### Parameters `parser` A reference to the XML parser to set up processing instruction (PI) handler function. `handler` `handler` is a string containing the name of a function that must exist when [xml\_parse()](function.xml-parse) is called for `parser`. The function named by `handler` must accept three parameters: ``` handler(XMLParser $parser, string $target, string $data) ``` `parser` The first parameter, parser, is a reference to the XML parser calling the handler. `target` The second parameter, `target`, contains the PI target. `data` The third parameter, `data`, contains the PI data. If a handler function is set to an empty string, or **`false`**, the handler in question is disabled. > **Note**: Instead of a function name, an array containing an object reference and a method name can also be supplied. > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `parser` expects an [XMLParser](class.xmlparser) instance now; previously, a resource was expected. | php Yaf_Config_Ini::readonly Yaf\_Config\_Ini::readonly ========================== (Yaf >=1.0.0) Yaf\_Config\_Ini::readonly — The readonly purpose ### Description ``` public Yaf_Config_Ini::readonly(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php The mysqli_result class The mysqli\_result class ======================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Represents the result set obtained from a query against the database. Class synopsis -------------- class **mysqli\_result** implements [IteratorAggregate](class.iteratoraggregate) { /\* Properties \*/ public readonly int [$current\_field](mysqli-result.current-field); public readonly int [$field\_count](mysqli-result.field-count); public readonly ?array [$lengths](mysqli-result.lengths); public readonly int|string [$num\_rows](mysqli-result.num-rows); public int [$type](class.mysqli-result#mysqli-result.props.type); /\* Methods \*/ public [\_\_construct](mysqli-result.construct)([mysqli](class.mysqli) `$mysql`, int `$result_mode` = **`MYSQLI_STORE_RESULT`**) ``` public data_seek(int $offset): bool ``` ``` public fetch_all(int $mode = MYSQLI_NUM): array ``` ``` public fetch_array(int $mode = MYSQLI_BOTH): array|null|false ``` ``` public fetch_assoc(): array|null|false ``` ``` public fetch_column(int $column = 0): null|int|float|string|false ``` ``` public fetch_field_direct(int $index): object|false ``` ``` public fetch_field(): object|false ``` ``` public fetch_fields(): array ``` ``` public fetch_object(string $class = "stdClass", array $constructor_args = []): object|null|false ``` ``` public fetch_row(): array|null|false ``` ``` public field_seek(int $index): bool ``` ``` public free(): void ``` ``` public close(): void ``` ``` public free_result(): void ``` ``` public getIterator(): Iterator ``` } Properties ---------- type Stores whether the result is buffered or unbuffered as an int (**`MYSQLI_STORE_RESULT`** or **`MYSQLI_USE_RESULT`**, respectively). Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | **mysqli\_result** implements [IteratorAggregate](class.iteratoraggregate) now. Previously, [Traversable](class.traversable) was implemented instead. | Table of Contents ----------------- * [mysqli\_result::\_\_construct](mysqli-result.construct) — Constructs a mysqli\_result object * [mysqli\_result::$current\_field](mysqli-result.current-field) — Get current field offset of a result pointer * [mysqli\_result::data\_seek](mysqli-result.data-seek) — Adjusts the result pointer to an arbitrary row in the result * [mysqli\_result::fetch\_all](mysqli-result.fetch-all) — Fetch all result rows as an associative array, a numeric array, or both * [mysqli\_result::fetch\_array](mysqli-result.fetch-array) — Fetch the next row of a result set as an associative, a numeric array, or both * [mysqli\_result::fetch\_assoc](mysqli-result.fetch-assoc) — Fetch the next row of a result set as an associative array * [mysqli\_result::fetch\_column](mysqli-result.fetch-column) — Fetch a single column from the next row of a result set * [mysqli\_result::fetch\_field\_direct](mysqli-result.fetch-field-direct) — Fetch meta-data for a single field * [mysqli\_result::fetch\_field](mysqli-result.fetch-field) — Returns the next field in the result set * [mysqli\_result::fetch\_fields](mysqli-result.fetch-fields) — Returns an array of objects representing the fields in a result set * [mysqli\_result::fetch\_object](mysqli-result.fetch-object) — Fetch the next row of a result set as an object * [mysqli\_result::fetch\_row](mysqli-result.fetch-row) — Fetch the next row of a result set as an enumerated array * [mysqli\_result::$field\_count](mysqli-result.field-count) — Gets the number of fields in the result set * [mysqli\_result::field\_seek](mysqli-result.field-seek) — Set result pointer to a specified field offset * [mysqli\_result::free](mysqli-result.free) — Frees the memory associated with a result * [mysqli\_result::getIterator](mysqli-result.getiterator) — Retrieve an external iterator * [mysqli\_result::$lengths](mysqli-result.lengths) — Returns the lengths of the columns of the current row in the result set * [mysqli\_result::$num\_rows](mysqli-result.num-rows) — Gets the number of rows in the result set php php_ini_loaded_file php\_ini\_loaded\_file ====================== (PHP 5 >= 5.2.4, PHP 7, PHP 8) php\_ini\_loaded\_file — Retrieve a path to the loaded php.ini file ### Description ``` php_ini_loaded_file(): string|false ``` Check if a php.ini file is loaded, and retrieve its path. ### Parameters This function has no parameters. ### Return Values The loaded php.ini path, or **`false`** if one is not loaded. ### Examples **Example #1 **php\_ini\_loaded\_file()** example** ``` <?php $inipath = php_ini_loaded_file(); if ($inipath) {     echo 'Loaded php.ini: ' . $inipath; } else {     echo 'A php.ini file is not loaded'; } ?> ``` The above example will output something similar to: ``` Loaded php.ini: /usr/local/php/php.ini ``` ### See Also * [php\_ini\_scanned\_files()](function.php-ini-scanned-files) - Return a list of .ini files parsed from the additional ini dir * [phpinfo()](function.phpinfo) - Outputs information about PHP's configuration * [The configuration file](https://www.php.net/manual/en/configuration.file.php) php OAuthProvider::addRequiredParameter OAuthProvider::addRequiredParameter =================================== (PECL OAuth >= 1.0.0) OAuthProvider::addRequiredParameter — Add required parameters ### Description ``` final public OAuthProvider::addRequiredParameter(string $req_params): bool ``` Add required oauth provider parameters. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `req_params` The required parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [OAuthProvider::removeRequiredParameter()](oauthprovider.removerequiredparameter) - Remove a required parameter php preg_filter preg\_filter ============ (PHP 5 >= 5.3.0, PHP 7, PHP 8) preg\_filter — Perform a regular expression search and replace ### Description ``` preg_filter( string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null ): string|array|null ``` **preg\_filter()** is identical to [preg\_replace()](function.preg-replace) except it only returns the (possibly transformed) subjects where there was a match. For details about how this function works, read the [preg\_replace()](function.preg-replace) documentation. ### Parameters Parameters are described in the documentation for [preg\_replace()](function.preg-replace). ### Return Values Returns an array if the `subject` parameter is an array, or a string otherwise. If no matches are found or an error occurred, an empty array is returned when `subject` is an array or **`null`** otherwise. ### Errors/Exceptions If the regex pattern passed does not compile to a valid regex, an **`E_WARNING`** is emitted. ### Examples **Example #1 Example comparing **preg\_filter()** with [preg\_replace()](function.preg-replace)** ``` <?php $subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');  $pattern = array('/\d/', '/[a-z]/', '/[1a]/');  $replace = array('A:$0', 'B:$0', 'C:$0');  echo "preg_filter returns\n"; print_r(preg_filter($pattern, $replace, $subject));  echo "preg_replace returns\n"; print_r(preg_replace($pattern, $replace, $subject));  ?> ``` The above example will output: ``` preg_filter returns Array ( [0] => A:C:1 [1] => B:C:a [2] => A:2 [3] => B:b [4] => A:3 [7] => A:4 ) preg_replace returns Array ( [0] => A:C:1 [1] => B:C:a [2] => A:2 [3] => B:b [4] => A:3 [5] => A [6] => B [7] => A:4 ) ``` ### See Also * [PCRE Patterns](https://www.php.net/manual/en/pcre.pattern.php) * [preg\_quote()](function.preg-quote) - Quote regular expression characters * [preg\_replace()](function.preg-replace) - Perform a regular expression search and replace * [preg\_replace\_callback()](function.preg-replace-callback) - Perform a regular expression search and replace using a callback * [preg\_grep()](function.preg-grep) - Return array entries that match the pattern * [preg\_last\_error()](function.preg-last-error) - Returns the error code of the last PCRE regex execution php stats_cdf_uniform stats\_cdf\_uniform =================== (PECL stats >= 1.0.0) stats\_cdf\_uniform — Calculates any one parameter of the uniform distribution given values for the others ### Description ``` stats_cdf_uniform( float $par1, float $par2, float $par3, int $which ): float ``` Returns the cumulative distribution function, its inverse, or one of its parameters, of the uniform distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`. The following table lists the return value and parameters by `which`. CDF, x, a, and b denotes cumulative distribution function, the value of the random variable, the lower bound and the higher bound of the uniform distribution, respectively. **Return value and parameters**| `which` | Return value | `par1` | `par2` | `par3` | | --- | --- | --- | --- | --- | | 1 | CDF | x | a | b | | 2 | x | CDF | a | b | | 3 | a | x | CDF | b | | 4 | b | x | CDF | a | ### Parameters `par1` The first parameter `par2` The second parameter `par3` The third parameter `which` The flag to determine what to be calculated ### Return Values Returns CDF, x, a, or b, determined by `which`. php strtr strtr ===== (PHP 4, PHP 5, PHP 7, PHP 8) strtr — Translate characters or replace substrings ### Description ``` strtr(string $string, string $from, string $to): string ``` Alternative signature (not supported with named arguments): ``` strtr(string $string, array $replace_pairs): string ``` If given three arguments, this function returns a copy of `string` 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 `string` 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 `string`. However, this function will be the most efficient when all the keys have the same size. ### Parameters `string` 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', ...)`. If `replace_pairs` contains a key which is an empty string (`""`), the element is ignored; as of PHP 8.0.0 **`E_WARNING`** is raised in this case. ### Return Values Returns the translated string. ### Examples **Example #1 **strtr()** example** ``` <?php //In this form, strtr() does byte-by-byte translation //Therefore, we are assuming a single-byte encoding here: $addr = strtr($addr, "äåö", "aao"); ?> ``` The next example shows the behavior of **strtr()** when called with only two arguments. Note the preference of the replacements (`"h"` is not picked because there are longer matches) and how replaced text was not searched again. **Example #2 **strtr()** example with two arguments** ``` <?php $trans = array("h" => "-", "hello" => "hi", "hi" => "hello"); echo strtr("hi all, I said hello", $trans); ?> ``` The above example will output: ``` hello all, I said hi ``` The two modes of behavior are substantially different. With three arguments, **strtr()** will replace bytes; with two, it may replace longer substrings. **Example #3 **strtr()** behavior comparison** ``` <?php echo strtr("baab", "ab", "01"),"\n"; $trans = array("ab" => "01"); echo strtr("baab", $trans); ?> ``` The above example will output: ``` 1001 ba01 ``` ### See Also * [str\_replace()](function.str-replace) - Replace all occurrences of the search string with the replacement string * [preg\_replace()](function.preg-replace) - Perform a regular expression search and replace
programming_docs
php Gmagick::blurimage Gmagick::blurimage ================== (PECL gmagick >= Unknown) Gmagick::blurimage — Adds blur filter to image ### Description ``` public Gmagick::blurimage(float $radius, float $sigma, int $channel = ?): Gmagick ``` Adds blur filter to image. ### Parameters `radius` Blur radius `sigma` Standard deviation ### Return Values The blurred [Gmagick](class.gmagick) object ### Errors/Exceptions Throws an **GmagickException** on error. php None Dot --- Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the [PCRE\_DOTALL](reference.pcre.pattern.modifiers) option is set, then dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class. *\C* can be used to match single byte. It makes sense in *UTF-8 mode* where full stop matches the whole character which can consist of multiple bytes. php EventListener::setCallback EventListener::setCallback ========================== (PECL event >= 1.2.6-beta) EventListener::setCallback — The setCallback purpose ### Description ``` public EventListener::setCallback( callable $cb , mixed $arg = null ): void ``` Adjust event connect listener's callback and optionally the callback argument. ### Parameters `cb` The new callback for new connections. Ignored if **`null`**. Should match the following prototype: ``` callback( EventListener $listener = null , mixed $fd = null , array $address = null , mixed $arg = null ): void ``` `listener` The [EventListener](class.eventlistener) object. `fd` The file descriptor or a resource associated with the listener. `address` Array of two elements: IP address and the *server* port. `arg` User custom data attached to the callback. `arg` Custom user data attached to the callback. Ignored if **`null`**. ### Return Values No value is returned. php The SolrClient class The SolrClient class ==================== Introduction ------------ (PECL solr >= 0.9.2) Used to send requests to a Solr server. Currently, cloning and serialization of SolrClient instances is not supported. Class synopsis -------------- final class **SolrClient** { /\* Constants \*/ const int [SEARCH\_SERVLET\_TYPE](class.solrclient#solrclient.constants.search-servlet-type) = 1; const int [UPDATE\_SERVLET\_TYPE](class.solrclient#solrclient.constants.update-servlet-type) = 2; const int [THREADS\_SERVLET\_TYPE](class.solrclient#solrclient.constants.threads-servlet-type) = 4; const int [PING\_SERVLET\_TYPE](class.solrclient#solrclient.constants.ping-servlet-type) = 8; const int [TERMS\_SERVLET\_TYPE](class.solrclient#solrclient.constants.terms-servlet-type) = 16; const int [SYSTEM\_SERVLET\_TYPE](class.solrclient#solrclient.constants.system-servlet-type) = 32; const string [DEFAULT\_SEARCH\_SERVLET](class.solrclient#solrclient.constants.default-search-servlet) = select; const string [DEFAULT\_UPDATE\_SERVLET](class.solrclient#solrclient.constants.default-update-servlet) = update; const string [DEFAULT\_THREADS\_SERVLET](class.solrclient#solrclient.constants.default-threads-servlet) = admin/threads; const string [DEFAULT\_PING\_SERVLET](class.solrclient#solrclient.constants.default-ping-servlet) = admin/ping; const string [DEFAULT\_TERMS\_SERVLET](class.solrclient#solrclient.constants.default-terms-servlet) = terms; const string [DEFAULT\_SYSTEM\_SERVLET](class.solrclient#solrclient.constants.default-system-servlet) = admin/system; /\* Methods \*/ public [\_\_construct](solrclient.construct)(array `$clientOptions`) ``` public addDocument(SolrInputDocument $doc, bool $overwrite = true, int $commitWithin = 0): SolrUpdateResponse ``` ``` public addDocuments(array $docs, bool $overwrite = true, int $commitWithin = 0): void ``` ``` public commit(bool $softCommit = false, bool $waitSearcher = true, bool $expungeDeletes = false): SolrUpdateResponse ``` ``` public deleteById(string $id): SolrUpdateResponse ``` ``` public deleteByIds(array $ids): SolrUpdateResponse ``` ``` public deleteByQueries(array $queries): SolrUpdateResponse ``` ``` public deleteByQuery(string $query): SolrUpdateResponse ``` ``` public getById(string $id): SolrQueryResponse ``` ``` public getByIds(array $ids): SolrQueryResponse ``` ``` public getDebug(): string ``` ``` public getOptions(): array ``` ``` public optimize(int $maxSegments = 1, bool $softCommit = true, bool $waitSearcher = true): SolrUpdateResponse ``` ``` public ping(): SolrPingResponse ``` ``` public query(SolrParams $query): SolrQueryResponse ``` ``` public request(string $raw_request): SolrUpdateResponse ``` ``` public rollback(): SolrUpdateResponse ``` ``` public setResponseWriter(string $responseWriter): void ``` ``` public setServlet(int $type, string $value): bool ``` ``` public system(): void ``` ``` public threads(): void ``` public [\_\_destruct](solrclient.destruct)() } Predefined Constants -------------------- **`SolrClient::SEARCH_SERVLET_TYPE`** Used when updating the search servlet. **`SolrClient::UPDATE_SERVLET_TYPE`** Used when updating the update servlet. **`SolrClient::THREADS_SERVLET_TYPE`** Used when updating the threads servlet. **`SolrClient::PING_SERVLET_TYPE`** Used when updating the ping servlet. **`SolrClient::TERMS_SERVLET_TYPE`** Used when updating the terms servlet. **`SolrClient::SYSTEM_SERVLET_TYPE`** Used when retrieving system information from the system servlet. **`SolrClient::DEFAULT_SEARCH_SERVLET`** This is the initial value for the search servlet. **`SolrClient::DEFAULT_UPDATE_SERVLET`** This is the initial value for the update servlet. **`SolrClient::DEFAULT_THREADS_SERVLET`** This is the initial value for the threads servlet. **`SolrClient::DEFAULT_PING_SERVLET`** This is the initial value for the ping servlet. **`SolrClient::DEFAULT_TERMS_SERVLET`** This is the initial value for the terms servlet used for the TermsComponent **`SolrClient::DEFAULT_SYSTEM_SERVLET`** This is the initial value for the system servlet used to obtain Solr Server information Table of Contents ----------------- * [SolrClient::addDocument](solrclient.adddocument) — Adds a document to the index * [SolrClient::addDocuments](solrclient.adddocuments) — Adds a collection of SolrInputDocument instances to the index * [SolrClient::commit](solrclient.commit) — Finalizes all add/deletes made to the index * [SolrClient::\_\_construct](solrclient.construct) — Constructor for the SolrClient object * [SolrClient::deleteById](solrclient.deletebyid) — Delete by Id * [SolrClient::deleteByIds](solrclient.deletebyids) — Deletes by Ids * [SolrClient::deleteByQueries](solrclient.deletebyqueries) — Removes all documents matching any of the queries * [SolrClient::deleteByQuery](solrclient.deletebyquery) — Deletes all documents matching the given query * [SolrClient::\_\_destruct](solrclient.destruct) — Destructor for SolrClient * [SolrClient::getById](solrclient.getbyid) — Get Document By Id. Utilizes Solr Realtime Get (RTG) * [SolrClient::getByIds](solrclient.getbyids) — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG) * [SolrClient::getDebug](solrclient.getdebug) — Returns the debug data for the last connection attempt * [SolrClient::getOptions](solrclient.getoptions) — Returns the client options set internally * [SolrClient::optimize](solrclient.optimize) — Defragments the index * [SolrClient::ping](solrclient.ping) — Checks if Solr server is still up * [SolrClient::query](solrclient.query) — Sends a query to the server * [SolrClient::request](solrclient.request) — Sends a raw update request * [SolrClient::rollback](solrclient.rollback) — Rollbacks all add/deletes made to the index since the last commit * [SolrClient::setResponseWriter](solrclient.setresponsewriter) — Sets the response writer used to prepare the response from Solr * [SolrClient::setServlet](solrclient.setservlet) — Changes the specified servlet type to a new value * [SolrClient::system](solrclient.system) — Retrieve Solr Server information * [SolrClient::threads](solrclient.threads) — Checks the threads status php NumberFormatter::setPattern NumberFormatter::setPattern =========================== numfmt\_set\_pattern ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::setPattern -- numfmt\_set\_pattern — Set formatter pattern ### Description Object-oriented style ``` public NumberFormatter::setPattern(string $pattern): bool ``` Procedural style ``` numfmt_set_pattern(NumberFormatter $formatter, string $pattern): bool ``` Set the pattern used by the formatter. Can not be used on a rule-based formatter. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. `pattern` Pattern in syntax described in [» ICU DecimalFormat documentation](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#details). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **numfmt\_set\_pattern()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL ); echo "Pattern: ".numfmt_get_pattern($fmt)."\n"; echo numfmt_format($fmt, 1234567.891234567890000)."\n"; numfmt_set_pattern($fmt, "#0.# kg"); echo "Pattern: ".numfmt_get_pattern($fmt)."\n"; echo numfmt_format($fmt, 1234567.891234567890000)."\n"; ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL ); echo "Pattern: ".$fmt->getPattern()."\n"; echo $fmt->format(1234567.891234567890000)."\n"; $fmt->setPattern("#0.# kg"); echo "Pattern: ".$fmt->getPattern()."\n"; echo $fmt->format(1234567.891234567890000)."\n"; ?> ``` The above example will output: ``` Pattern: #,##0.### 1.234.567,891 Pattern: #0.# kg 1234567,9 kg ``` ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [numfmt\_create()](numberformatter.create) - Create a number formatter * [numfmt\_get\_pattern()](numberformatter.getpattern) - Get formatter pattern php The PgSql\Lob class The PgSql\Lob class =================== Introduction ------------ (PHP 8 >= 8.1.0) A fully opaque class which replaces a `pgsql large object` resource as of PHP 8.1.0. Class synopsis -------------- final class **PgSql\Lob** { } php DOMDocument::__construct DOMDocument::\_\_construct ========================== (PHP 5, PHP 7, PHP 8) DOMDocument::\_\_construct — Creates a new DOMDocument object ### Description public **DOMDocument::\_\_construct**(string `$version` = "1.0", string `$encoding` = "") Creates a new [DOMDocument](class.domdocument) object. ### Parameters `version` The version number of the document as part of the XML declaration. `encoding` The encoding of the document as part of the XML declaration. ### Examples **Example #1 Creating a new DOMDocument** ``` <?php $dom = new DOMDocument('1.0', 'iso-8859-1'); echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */ ?> ``` ### See Also * [DOMImplementation::createDocument()](domimplementation.createdocument) - Creates a DOMDocument object of the specified type with its document element php odbc_data_source odbc\_data\_source ================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) odbc\_data\_source — Returns information about available DSNs ### Description ``` odbc_data_source(resource $odbc, int $fetch_type): array|false ``` This function will return the list of available DSN (after calling it several times). ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `fetch_type` The `fetch_type` can be one of two constant types: **`SQL_FETCH_FIRST`**, **`SQL_FETCH_NEXT`**. Use **`SQL_FETCH_FIRST`** the first time this function is called, thereafter use the **`SQL_FETCH_NEXT`**. ### Return Values Returns **`false`** on error, an array upon success, and **`null`** after fetching the last available DSN. ### Examples **Example #1 List available DSNs** ``` <?php $conn = odbc_connect('dsn', 'user', 'pass'); $dsn_info = odbc_data_source($conn, SQL_FETCH_FIRST); while ($dsn_info) {     print_r($dsn_info);     $dsn_info = odbc_data_source($conn, SQL_FETCH_NEXT); } ?> ``` The above example will output something similar to: ``` Array ( [server] => dsn [description] => ODBC Driver 17 for SQL Server ) Array ( [server] => other_dsn [description] => Microsoft Access Driver (*.mdb, *.accdb) ) ``` php ImagickDraw::getStrokeDashArray ImagickDraw::getStrokeDashArray =============================== (PECL imagick 2, PECL imagick 3) ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths ### Description ``` public ImagickDraw::getStrokeDashArray(): array ``` **Warning**This function is currently not documented; only its argument list is available. Returns an array representing the pattern of dashes and gaps used to stroke paths. ### Return Values Returns an array on success and empty array if not set. php OAuth::__construct OAuth::\_\_construct ==================== (PECL OAuth >= 0.99.1) OAuth::\_\_construct — Create a new OAuth object ### Description public **OAuth::\_\_construct**( string `$consumer_key`, string `$consumer_secret`, string `$signature_method` = **`OAUTH_SIG_METHOD_HMACSHA1`**, int `$auth_type` = 0 ) Creates a new OAuth object ### Parameters `consumer_key` The consumer key provided by the service provider. `consumer_secret` The consumer secret provided by the service provider. `signature_method` This optional parameter defines which signature method to use, by default it is **`OAUTH_SIG_METHOD_HMACSHA1`** (HMAC-SHA1). `auth_type` This optional parameter defines how to pass the OAuth parameters to a consumer, by default it is **`OAUTH_AUTH_TYPE_AUTHORIZATION`** (in the `Authorization` header). php SolrObject::__destruct SolrObject::\_\_destruct ======================== (PECL solr >= 0.9.2) SolrObject::\_\_destruct — Destructor ### Description public **SolrObject::\_\_destruct**() The destructor ### Parameters This function has no parameters. ### Return Values None. php eio_get_last_error eio\_get\_last\_error ===================== (PECL eio >= 1.0.0) eio\_get\_last\_error — Returns string describing the last error associated with a request resource ### Description ``` eio_get_last_error(resource $req): string ``` **eio\_get\_last\_error()** returns string describing the last error associated with `req`. ### Parameters `req` The request resource ### Return Values **eio\_get\_last\_error()** returns string describing the last error associated with the request resource specified by `req`. **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php Yaf_Route_Regex::route Yaf\_Route\_Regex::route ======================== (Yaf >=1.0.0) Yaf\_Route\_Regex::route — The route purpose ### Description ``` public Yaf_Route_Regex::route(Yaf_Request_Abstract $request): bool ``` Route a incoming request. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `request` ### Return Values If the pattern given by the first parameter of **Yaf\_Route\_Regex::\_construct()** matche the request uri, return **`true`**, otherwise return **`false`**. php xml_parser_get_option xml\_parser\_get\_option ======================== (PHP 4, PHP 5, PHP 7, PHP 8) xml\_parser\_get\_option — Get options from an XML parser ### Description ``` xml_parser_get_option(XMLParser $parser, int $option): string|int ``` Gets an option value from an XML parser. ### Parameters `parser` A reference to the XML parser to get an option from. `option` Which option to fetch. **`XML_OPTION_CASE_FOLDING`**, **`XML_OPTION_SKIP_TAGSTART`**, **`XML_OPTION_SKIP_WHITE`** and **`XML_OPTION_TARGET_ENCODING`** are available. See [xml\_parser\_set\_option()](function.xml-parser-set-option) for their description. ### Return Values This function returns **`false`** if `parser` does not refer to a valid parser or if `option` isn't valid (generates also a **`E_WARNING`**). Else the option's value is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `parser` expects an [XMLParser](class.xmlparser) instance now; previously, a resource was expected. | | 7.1.24, 7.2.12, 7.3.0 | `options` now supports **`XML_OPTION_SKIP_TAGSTART`** and **`XML_OPTION_SKIP_WHITE`**. | php QuickHashStringIntHash::update QuickHashStringIntHash::update ============================== (No version information available, might only be in Git) QuickHashStringIntHash::update — This method updates an entry in the hash with a new value ### Description ``` public QuickHashStringIntHash::update(string $key, int $value): bool ``` This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK\_FOR\_DUPES during hash creation to prevent duplicate keys from being part of the hash. ### Parameters `key` The key of the entry to update. `value` The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible. ### Return Values **`true`** when the entry was found and updated, and **`false`** if the entry was not part of the hash already. ### Examples **Example #1 **QuickHashStringIntHash::update()** example** ``` <?php $hash = new QuickHashStringIntHash( 1024 ); $hash->add( 'six', 314159265 ); $hash->add( "a lot", 314159265 ); echo $hash->get( 'six' ), "\n"; echo $hash->get( 'a lot' ), "\n"; var_dump( $hash->update( 'a lot', 314159266 ) ); var_dump( $hash->update( "a lot plus one", 314159999 ) ); echo $hash->get( 'six' ), "\n"; echo $hash->get( 'a lot' ), "\n"; ?> ``` The above example will output something similar to: ``` 314159265 314159265 bool(true) bool(false) 314159265 314159266 ``` php ftp_rename ftp\_rename =========== (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_rename — Renames a file or a directory on the FTP server ### Description ``` ftp_rename(FTP\Connection $ftp, string $from, string $to): bool ``` **ftp\_rename()** renames a file or a directory on the FTP server. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `from` The old file/directory name. `to` The new name. ### Return Values Returns **`true`** on success or **`false`** on failure. Upon failure (such as attempting to rename a non-existent file), an `E_WARNING` error will be emitted. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_rename()** example** ``` <?php $old_file = 'somefile.txt.bak'; $new_file = 'somefile.txt'; // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); // try to rename $old_file to $new_file if (ftp_rename($ftp, $old_file, $new_file)) {  echo "successfully renamed $old_file to $new_file\n"; } else {  echo "There was a problem while renaming $old_file to $new_file\n"; } // close the connection ftp_close($ftp); ?> ```
programming_docs
php The Closure class The Closure class ================= Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) Class used to represent [anonymous functions](functions.anonymous). Anonymous functions yield objects of this type. This class has methods that allow further control of the anonymous function after it has been created. Besides the methods listed here, this class also has an `__invoke` method. This is for consistency with other classes that implement [calling magic](language.oop5.magic#language.oop5.magic.invoke), as this method is not used for calling the function. Class synopsis -------------- final class **Closure** { /\* Methods \*/ private [\_\_construct](closure.construct)() ``` public static bind(Closure $closure, ?object $newThis, object|string|null $newScope = "static"): ?Closure ``` ``` public bindTo(?object $newThis, object|string|null $newScope = "static"): ?Closure ``` ``` public call(object $newThis, mixed ...$args): mixed ``` ``` public static fromCallable(callable $callback): Closure ``` } Table of Contents ----------------- * [Closure::\_\_construct](closure.construct) — Constructor that disallows instantiation * [Closure::bind](closure.bind) — Duplicates a closure with a specific bound object and class scope * [Closure::bindTo](closure.bindto) — Duplicates the closure with a new bound object and class scope * [Closure::call](closure.call) — Binds and calls the closure * [Closure::fromCallable](closure.fromcallable) — Converts a callable into a closure php SimpleXMLIterator::next SimpleXMLIterator::next ======================= (PHP 5, PHP 7, PHP 8) SimpleXMLIterator::next — Move to next element ### Description ``` public SimpleXMLIterator::next(): void ``` This method moves the [SimpleXMLIterator](class.simplexmliterator) to the next element. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 Move to the next element** ``` <?php $xmlIterator = new SimpleXMLIterator('<books><book>PHP Basics</book><book>XML basics</book></books>'); $xmlIterator->rewind(); // rewind to the first element $xmlIterator->next(); var_dump($xmlIterator->current()); ?> ``` The above example will output: ``` object(SimpleXMLIterator)#2 (1) { [0]=> string(10) "XML basics" } ``` php EventBufferEvent::read EventBufferEvent::read ====================== (PECL event >= 1.2.6-beta) EventBufferEvent::read — Read buffer's data ### Description ``` public EventBufferEvent::read( int $size ): string ``` Removes up to `size` bytes from the input buffer. Returns a string of data read from the input buffer. ### Parameters `size` Maximum number of bytes to read ### Return Values Returns string of data read from the input buffer. ### See Also * [EventBufferEvent::readBuffer()](eventbufferevent.readbuffer) - Drains the entire contents of the input buffer and places them into buf php is_executable is\_executable ============== (PHP 4, PHP 5, PHP 7, PHP 8) is\_executable — Tells whether the filename is executable ### Description ``` is_executable(string $filename): bool ``` Tells whether the filename is executable. ### Parameters `filename` Path to the file. ### Return Values Returns **`true`** if the filename exists and is executable, or **`false`** on error. On POSIX systems, a file is executable if the executable bit of the file permissions is set. For Windows, see the note below. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 **is\_executable()** example** ``` <?php $file = '/home/vincent/somefile.sh'; if (is_executable($file)) {     echo $file.' is executable'; } else {     echo $file.' is not executable'; } ?> ``` ### Notes > **Note**: The results of this function are cached. See [clearstatcache()](function.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](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality. > **Note**: On Windows, a file is considered executable, if it is a properly executable file as reported by the Win API `GetBinaryType()`; for BC reasons, files with a .bat or .cmd extension are also considered executable. Prior to PHP 7.4.0, any non-empty file with a .exe or .com extension was considered executable. Note that PATHEXT is irrelevant for **is\_executable()**. > > ### See Also * [is\_file()](function.is-file) - Tells whether the filename is a regular file * [is\_link()](function.is-link) - Tells whether the filename is a symbolic link php xattr_get xattr\_get ========== (PECL xattr >= 0.9.0) xattr\_get — Get an extended attribute ### Description ``` xattr_get(string $filename, string $name, int $flags = 0): string ``` This function gets the value of an extended attribute of a file. Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter. ### Parameters `filename` The file from which we get the attribute. `name` The name of the attribute. `flags` **Supported xattr flags**| **`XATTR_DONTFOLLOW`** | Do not follow the symbolic link but operate on symbolic link itself. | | **`XATTR_ROOT`** | Set attribute in root (trusted) namespace. Requires root privileges. | ### Return Values Returns a string containing the value or **`false`** if the attribute doesn't exist. ### Examples **Example #1 Checks if system administrator has signed the file** ``` <?php $file = '/usr/local/sbin/some_binary'; $signature = xattr_get($file, 'Root signature', XATTR_ROOT); /* ... check if $signature is valid ... */ ?> ``` ### See Also * [xattr\_list()](function.xattr-list) - Get a list of extended attributes * [xattr\_set()](function.xattr-set) - Set an extended attribute * [xattr\_remove()](function.xattr-remove) - Remove an extended attribute php openssl_pkcs7_encrypt openssl\_pkcs7\_encrypt ======================= (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) openssl\_pkcs7\_encrypt — Encrypt an S/MIME message ### Description ``` openssl_pkcs7_encrypt( string $input_filename, string $output_filename, OpenSSLCertificate|array|string $certificate, ?array $headers, int $flags = 0, int $cipher_algo = OPENSSL_CIPHER_AES_128_CBC ): bool ``` **openssl\_pkcs7\_encrypt()** takes the contents of the file named `input_filename` and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by `certificate`. ### Parameters `input_filename` `output_filename` `certificate` Either a lone X.509 certificate, or an array of X.509 certificates. `headers` `headers` is an array of headers that will be prepended to the data after it has been encrypted. `headers` can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line. `flags` `flags` can be used to specify options that affect the encoding process - see [PKCS7 constants](https://www.php.net/manual/en/openssl.pkcs7.flags.php). `cipher_algo` One of [cipher constants](https://www.php.net/manual/en/openssl.ciphers.php). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The default cipher algorithm (`cipher_algo`) is now AES-128-CBC (**`OPENSSL_CIPHER_AES_128_CBC`**). Previously, PKCS7/CMS was used (**`OPENSSL_CIPHER_RC2_40`**). | | 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509 CSR` was accepted. | ### Examples **Example #1 **openssl\_pkcs7\_encrypt()** example** ``` <?php // the message you want to encrypt and send to your secret agent // in the field, known as nighthawk.  You have his certificate // in the file nighthawk.pem $data = <<<EOD Nighthawk, Top secret, for your eyes only! The enemy is closing in! Meet me at the cafe at 8.30am to collect your forged passport! HQ EOD; // load key $key = file_get_contents("nighthawk.pem"); // save message to file $fp = fopen("msg.txt", "w"); fwrite($fp, $data); fclose($fp); // encrypt it if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,     array("To" => "[email protected]", // keyed syntax           "From: HQ <[email protected]>", // indexed syntax           "Subject" => "Eyes only"))) {     // message encrypted - send it!     exec(ini_get("sendmail_path") . " < enc.txt"); } ?> ``` php The XSLTProcessor class The XSLTProcessor class ======================= Introduction ------------ (PHP 5, PHP 7, PHP 8) Class synopsis -------------- class **XSLTProcessor** { /\* Methods \*/ public [\_\_construct](xsltprocessor.construct)() ``` public getParameter(string $namespace, string $name): string|false ``` ``` public getSecurityPrefs(): int ``` ``` public hasExsltSupport(): bool ``` ``` public importStylesheet(object $stylesheet): bool ``` ``` public registerPHPFunctions(array|string|null $functions = null): void ``` ``` public removeParameter(string $namespace, string $name): bool ``` ``` public setParameter(string $namespace, string $name, string $value): bool ``` ``` public setParameter(string $namespace, array $options): bool ``` ``` public setProfiling(?string $filename): bool ``` ``` public setSecurityPrefs(int $preferences): int ``` ``` public transformToDoc(object $document, ?string $returnClass = null): DOMDocument|false ``` ``` public transformToUri(DOMDocument $doc, string $uri): int ``` ``` public transformToXml(object $document): string|null|false ``` } Table of Contents ----------------- * [XSLTProcessor::\_\_construct](xsltprocessor.construct) — Creates a new XSLTProcessor object * [XSLTProcessor::getParameter](xsltprocessor.getparameter) — Get value of a parameter * [XSLTProcessor::getSecurityPrefs](xsltprocessor.getsecurityprefs) — Get security preferences * [XSLTProcessor::hasExsltSupport](xsltprocessor.hasexsltsupport) — Determine if PHP has EXSLT support * [XSLTProcessor::importStylesheet](xsltprocessor.importstylesheet) — Import stylesheet * [XSLTProcessor::registerPHPFunctions](xsltprocessor.registerphpfunctions) — Enables the ability to use PHP functions as XSLT functions * [XSLTProcessor::removeParameter](xsltprocessor.removeparameter) — Remove parameter * [XSLTProcessor::setParameter](xsltprocessor.setparameter) — Set value for a parameter * [XSLTProcessor::setProfiling](xsltprocessor.setprofiling) — Sets profiling output file * [XSLTProcessor::setSecurityPrefs](xsltprocessor.setsecurityprefs) — Set security preferences * [XSLTProcessor::transformToDoc](xsltprocessor.transformtodoc) — Transform to a DOMDocument * [XSLTProcessor::transformToUri](xsltprocessor.transformtouri) — Transform to URI * [XSLTProcessor::transformToXml](xsltprocessor.transformtoxml) — Transform to XML php session_abort session\_abort ============== (PHP 5 >= 5.6.0, PHP 7, PHP 8) session\_abort — Discard session array changes and finish session ### Description ``` session_abort(): bool ``` **session\_abort()** finishes session without saving data. Thus the original values in session data are kept. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | The return type of this function is bool now. Formerly, it has been void. | ### See Also * [$\_SESSION](reserved.variables.session) * The [session.auto\_start](https://www.php.net/manual/en/session.configuration.php#ini.session.auto-start) configuration directive * [session\_start()](function.session-start) - Start new or resume existing session * [session\_reset()](function.session-reset) - Re-initialize session array with original values * [session\_commit()](function.session-commit) - Alias of session\_write\_close php register_shutdown_function register\_shutdown\_function ============================ (PHP 4, PHP 5, PHP 7, PHP 8) register\_shutdown\_function — Register a function for execution on shutdown ### Description ``` register_shutdown_function(callable $callback, mixed ...$args): void ``` Registers a `callback` to be executed after script execution finishes or [exit()](function.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()](function.exit) within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called. Shutdown functions may also call **register\_shutdown\_function()** themselves to add a shutdown function to the end of the queue. ### 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. `args` It is possible to pass parameters to the shutdown function by passing additional parameters. ### Return Values No value is returned. ### Examples **Example #1 **register\_shutdown\_function()** example** ``` <?php function shutdown() {     // This is our shutdown function, in      // here we can do any last operations     // before the script is complete.     echo 'Script executed with success', PHP_EOL; } register_shutdown_function('shutdown'); ?> ``` ### Notes > > **Note**: > > > The 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()](function.pcntl-signal) to install a handler for a SIGTERM which uses [exit()](function.exit) to end cleanly. > > > > **Note**: > > > Shutdown functions run separately from the time tracked by [max\_execution\_time](https://www.php.net/manual/en/info.configuration.php#ini.max-execution-time). That means even if a process is terminated for running too long, shutdown functions will still be called. Additionally, if the `max_execution_time` runs out while a shutdown function is running it will not be terminated. > > ### See Also * [auto\_append\_file](https://www.php.net/manual/en/ini.core.php#ini.auto-append-file) * [exit()](function.exit) - Output a message and terminate the current script * [fastcgi\_finish\_request()](function.fastcgi-finish-request) - Flushes all response data to the client * The section on [connection handling](https://www.php.net/manual/en/features.connection-handling.php) php Fiber::isSuspended Fiber::isSuspended ================== (PHP 8 >= 8.1.0) Fiber::isSuspended — Determines if the fiber is suspended ### Description ``` public Fiber::isSuspended(): bool ``` ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the fiber is currently suspended; otherwise **`false`** is returned. php ReflectionClass::getShortName ReflectionClass::getShortName ============================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) ReflectionClass::getShortName — Gets short name ### Description ``` public ReflectionClass::getShortName(): string ``` Gets the short name of the class, the part without the namespace. ### Parameters This function has no parameters. ### Return Values The class short name. ### Examples **Example #1 **ReflectionClass::getShortName()** example** ``` <?php namespace A\B; class Foo { } $function = new \ReflectionClass('stdClass'); var_dump($function->inNamespace()); var_dump($function->getName()); var_dump($function->getNamespaceName()); var_dump($function->getShortName()); $function = new \ReflectionClass('A\\B\\Foo'); var_dump($function->inNamespace()); var_dump($function->getName()); var_dump($function->getNamespaceName()); var_dump($function->getShortName()); ?> ``` The above example will output: ``` bool(false) string(8) "stdClass" string(0) "" string(8) "stdClass" bool(true) string(7) "A\B\Foo" string(3) "A\B" string(3) "Foo" ``` ### See Also * [ReflectionClass::getName()](reflectionclass.getname) - Gets class name php Imagick::setImageAttribute Imagick::setImageAttribute ========================== (PECL imagick 2, PECL imagick 3) Imagick::setImageAttribute — Description **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::setImageAttribute(string $key, string $value): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `key` `value` ### Return Values Returns **`true`** on success. php openssl_cms_decrypt openssl\_cms\_decrypt ===================== (PHP 8) openssl\_cms\_decrypt — Decrypt a CMS message ### Description ``` openssl_cms_decrypt( string $input_filename, string $output_filename, OpenSSLCertificate|string $certificate, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string|null $private_key = null, int $encoding = OPENSSL_ENCODING_SMIME ): bool ``` Decrypts a CMS message. ### Parameters `input_filename` The name of a file containing encrypted content. `output_filename` The name of the file to deposit the decrypted content. `certificate` The name of the file containing a certificate of the recipient. `private_key` The name of the file containing a PKCS#8 key. `encoding` The encoding of the input file. One of **`OPENSSL_ENCODING_SMIME`**, **`OPENSSL_ENCODING_DER`** or **`OPENSSL_ENCODING_PEM`**. ### Return Values Returns **`true`** on success or **`false`** on failure. php ImagickDraw::pathCurveToQuadraticBezierRelative ImagickDraw::pathCurveToQuadraticBezierRelative =============================================== (PECL imagick 2, PECL imagick 3) ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve ### Description ``` public ImagickDraw::pathCurveToQuadraticBezierRelative( float $x1, float $y1, float $x, float $y ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. ### Parameters `x1` starting x coordinate `y1` starting y coordinate `x` ending x coordinate `y` ending y coordinate ### Return Values No value is returned. php SplHeap::rewind SplHeap::rewind =============== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplHeap::rewind — Rewind iterator back to the start (no-op) ### Description ``` public SplHeap::rewind(): void ``` This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap. ### Parameters This function has no parameters. ### Return Values No value is returned.
programming_docs
php sodium_memzero sodium\_memzero =============== (PHP 7 >= 7.2.0, PHP 8) sodium\_memzero — Overwrite a string with NUL characters ### Description ``` sodium_memzero(string &$string): void ``` **sodium\_memzero()** zeroes out the string that is passed by reference. ### Parameters `string` String. ### Return Values No value is returned. php None Meta-characters --------------- The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of *meta-characters*, which do not stand for themselves but instead are interpreted in some special way. There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows: **Meta-characters outside square brackets**| Meta-character | Description | | --- | --- | | \ | general escape character with several uses | | ^ | assert start of subject (or line, in multiline mode) | | $ | assert end of subject or before a terminating newline (or end of line, in multiline mode) | | . | match any character except newline (by default) | | [ | start character class definition | | ] | end character class definition | | | | start of alternative branch | | ( | start subpattern | | ) | end subpattern | | ? | extends the meaning of (, also 0 or 1 quantifier, also makes greedy quantifiers lazy (see [repetition](regexp.reference.repetition)) | | \* | 0 or more quantifier | | + | 1 or more quantifier | | { | start min/max quantifier | | } | end min/max quantifier | Part of a pattern that is in square brackets is called a [character class](regexp.reference.character-classes). In a character class the only meta-characters are: **Meta-characters inside square brackets (*character classes*)**| Meta-character | Description | | --- | --- | | \ | general escape character | | ^ | negate the class, but only if the first character | | - | indicates character range | The following sections describe the use of each of the meta-characters. php ReflectionZendExtension::getURL ReflectionZendExtension::getURL =============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionZendExtension::getURL — Gets URL ### Description ``` public ReflectionZendExtension::getURL(): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php IntlCalendar::getTimeZone IntlCalendar::getTimeZone ========================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getTimeZone — Get the objectʼs timezone ### Description Object-oriented style ``` public IntlCalendar::getTimeZone(): IntlTimeZone|false ``` Procedural style ``` intlcal_get_time_zone(IntlCalendar $calendar): IntlTimeZone|false ``` Returns the [IntlTimeZone](class.intltimezone) object associated with this calendar. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. ### Return Values An [IntlTimeZone](class.intltimezone) object corresponding to the one used internally in this object. Returns **`false`** on failure. ### Examples **Example #1 **IntlCalendar::getTimeZone()**** ``` <?php ini_set('date.timezone', 'Europe/Lisbon'); ini_set('intl.default_locale', 'en_US'); $cal = IntlCalendar::createInstance(); print_r($cal->getTimeZone()); $cal->setTimeZone('UTC'); print_r($cal->getTimeZone()); $cal = IntlCalendar::fromDateTime('2012-01-01 00:00:00 GMT+03:33'); print_r($cal->getTimeZone()); ``` The above example will output: ``` IntlTimeZone Object ( [valid] => 1 [id] => Europe/Lisbon [rawOffset] => 0 [currentOffset] => 3600000 ) IntlTimeZone Object ( [valid] => 1 [id] => UTC [rawOffset] => 0 [currentOffset] => 0 ) IntlTimeZone Object ( [valid] => 1 [id] => GMT+03:33 [rawOffset] => 12780000 [currentOffset] => 12780000 ) ``` ### See Also * [IntlCalendar::setTimeZone()](intlcalendar.settimezone) - Set the timezone used by this calendar * [IntlCalendar::createInstance()](intlcalendar.createinstance) - Create a new IntlCalendar * [IntlGregorianCalendar::\_\_construct()](intlgregoriancalendar.construct) - Create the Gregorian Calendar class php EmptyIterator::rewind EmptyIterator::rewind ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) EmptyIterator::rewind — The rewind() method ### Description ``` public EmptyIterator::rewind(): void ``` No operation, nothing to do. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php The EvPrepare class The EvPrepare class =================== Introduction ------------ (PECL ev >= 0.2.0) **EvPrepare** and [EvCheck](class.evcheck) watchers are usually used in pairs. **EvPrepare** watchers get invoked before the process blocks, [EvCheck](class.evcheck) afterwards. It is not allowed to call [EvLoop::run()](evloop.run) or similar methods or functions that enter the current event loop from either **EvPrepare** or [EvCheck](class.evcheck) watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: **EvPrepare** -> blocking -> [EvCheck](class.evcheck) , so having a watcher of each kind they will always be called in pairs bracketing the blocking call. The main purpose is to integrate other event mechanisms into *libev* and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking. It is recommended to give [EvCheck](class.evcheck) watchers highest( **`Ev::MAXPRI`** ) priority, to ensure that they are being run before any other watchers after the poll (this doesn’t matter for **EvPrepare** watchers). Also, [EvCheck](class.evcheck) watchers should not activate/feed events. While *libev* fully supports this, they might get executed before other [EvCheck](class.evcheck) watchers did their job. Class synopsis -------------- class **EvPrepare** extends [EvWatcher](class.evwatcher) { /\* Inherited properties \*/ public [$is\_active](class.evwatcher#evwatcher.props.is-active); public [$data](class.evwatcher#evwatcher.props.data); public [$is\_pending](class.evwatcher#evwatcher.props.is-pending); public [$priority](class.evwatcher#evwatcher.props.priority); /\* Methods \*/ public [\_\_construct](evprepare.construct)( string `$callback` , string `$data` = ?, string `$priority` = ?) ``` final public static createStopped( callable $callback , mixed $data = null , int $priority = 0 ): EvPrepare ``` /\* Inherited methods \*/ ``` public EvWatcher::clear(): int ``` ``` public EvWatcher::feed( int $revents ): void ``` ``` public EvWatcher::getLoop(): EvLoop ``` ``` public EvWatcher::invoke( int $revents ): void ``` ``` public EvWatcher::keepalive( bool $value = ?): bool ``` ``` public EvWatcher::setCallback( callable $callback ): void ``` ``` public EvWatcher::start(): void ``` ``` public EvWatcher::stop(): void ``` } Table of Contents ----------------- * [EvPrepare::\_\_construct](evprepare.construct) — Constructs EvPrepare watcher object * [EvPrepare::createStopped](evprepare.createstopped) — Creates a stopped instance of EvPrepare watcher php forward_static_call_array forward\_static\_call\_array ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) forward\_static\_call\_array — Call a static method and pass the arguments as array ### Description ``` forward_static_call_array(callable $callback, array $args): mixed ``` Calls a user defined function or method given by the `callback` parameter. This function must be called within a method context, it can't be used outside a class. It uses the [late static binding](language.oop5.late-static-bindings). All arguments of the forwarded method are passed as values, and as an array, similarly to [call\_user\_func\_array()](function.call-user-func-array). ### Parameters `callback` The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name. `parameter` One parameter, gathering all the method parameter in one array. > > **Note**: > > > Note that the parameters for **forward\_static\_call\_array()** are not passed by reference. > > ### Return Values Returns the function result, or **`false`** on error. ### Examples **Example #1 **forward\_static\_call\_array()** example** ``` <?php class A {     const NAME = 'A';     public static function test() {         $args = func_get_args();         echo static::NAME, " ".join(',', $args)." \n";     } } class B extends A {     const NAME = 'B';     public static function test() {         echo self::NAME, "\n";         forward_static_call_array(array('A', 'test'), array('more', 'args'));         forward_static_call_array( 'test', array('other', 'args'));     } } B::test('foo'); function test() {         $args = func_get_args();         echo "C ".join(',', $args)." \n";     } ?> ``` The above example will output: ``` B B more,args C other,args ``` ### See Also * [forward\_static\_call()](function.forward-static-call) - Call a static method * [call\_user\_func()](function.call-user-func) - Call the callback given by the first parameter * [call\_user\_func\_array()](function.call-user-func-array) - Call a callback with an array of parameters * [is\_callable()](function.is-callable) - Verify that a value can be called as a function from the current scope. php Phar::convertToData Phar::convertToData =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::convertToData — Convert a phar archive to a non-executable tar or zip file ### Description ``` public Phar::convertToData(?int $format = null, ?int $compression = null, ?string $extension = null): ?PharData ``` This method is used to convert an executable phar archive to either a tar or zip file. To make the tar or zip non-executable, the phar stub and phar alias files are removed from the newly created archive. If no changes are specified, this method throws a [BadMethodCallException](class.badmethodcallexception) if the archive is in phar file format. For archives in tar or zip file format, this method converts the archive to a non-executable archive. If successful, the method creates a new archive on disk and returns a [PharData](class.phardata) object. The old archive is not removed from disk, and should be done manually after the process has finished. ### Parameters `format` This should be one of `Phar::TAR` or `Phar::ZIP`. If set to **`null`**, the existing file format will be preserved. `compression` This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression. `extension` This parameter is used to override the default file extension for a converted archive. Note that `.phar` cannot be used anywhere in the filename for a non-executable tar or zip archive. If converting to a tar-based phar archive, the default extensions are `.tar`, `.tar.gz`, and `.tar.bz2` depending on specified compression. For zip-based archives, the default extension is `.zip`. ### Return Values The method returns a [PharData](class.phardata) object on success, or **`null`** on failure. ### Errors/Exceptions This method throws [BadMethodCallException](class.badmethodcallexception) when unable to compress, an unknown compression method has been specified, the requested archive is buffering with [Phar::startBuffering()](phar.startbuffering) and has not concluded with [Phar::stopBuffering()](phar.stopbuffering), and a [PharException](class.pharexception) if any problems are encountered during the phar creation process. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `format`, `compression`, and `extension` are now nullable. | ### Examples **Example #1 A **Phar::convertToData()** example** Using Phar::convertToData(): ``` <?php try {     $tarphar = new Phar('myphar.phar.tar');     // note that myphar.phar.tar is *not* unlinked     // convert it to the non-executable tar file format     // creates myphar.tar     $tar = $tarphar->convertToData();     // convert to non-executable zip format, creates myphar.zip     $zip = $tarphar->convertToData(Phar::ZIP);     // create myphar.tbz     $tgz = $tarphar->convertToData(Phar::TAR, Phar::BZ2, '.tbz');     // creates myphar.phar.tgz     $phar = $tarphar->convertToData(Phar::PHAR); // throws exception } catch (Exception $e) {     // handle the error here } ?> ``` ### See Also * [Phar::convertToExecutable()](phar.converttoexecutable) - Convert a phar archive to another executable phar archive file format * [PharData::convertToExecutable()](phardata.converttoexecutable) - Convert a non-executable tar/zip archive to an executable phar archive * [PharData::convertToData()](phardata.converttodata) - Convert a phar archive to a non-executable tar or zip file php VarnishStat::getSnapshot VarnishStat::getSnapshot ======================== (PECL varnish >= 0.3) VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot ### Description ``` public VarnishStat::getSnapshot(): array ``` ### Parameters This function has no parameters. ### Return Values Array with the varnish statistic snapshot. The array keys are identical to that in the varnishstat tool. php Imagick::compareImageLayers Imagick::compareImageLayers =========================== (PECL imagick 2, PECL imagick 3) Imagick::compareImageLayers — Returns the maximum bounding region between images ### Description ``` public Imagick::compareImageLayers(int $method): Imagick ``` Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `method` One of the [layer method constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.layermethod). ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::compareImageLayers()**** Comparing image layers ``` <?php /* create new imagick object */ $im = new Imagick("test.gif"); /* optimize the image layers */ $result = $im->compareImageLayers(imagick::LAYERMETHOD_COALESCE); /* work on the $result */ ?> ``` ### See Also * [Imagick::optimizeImageLayers()](imagick.optimizeimagelayers) - Removes repeated portions of images to optimize * [Imagick::writeImages()](imagick.writeimages) - Writes an image or image sequence * [Imagick::writeImage()](imagick.writeimage) - Writes an image to the specified filename php Yaf_View_Interface::render Yaf\_View\_Interface::render ============================ (Yaf >=1.0.0) Yaf\_View\_Interface::render — Render a template ### Description ``` abstract public Yaf_View_Interface::render(string $tpl, array $tpl_vars = ?): string ``` Render a template and return the result. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `tpl` `tpl_vars` ### Return Values php DOMDocument::saveXML DOMDocument::saveXML ==================== (PHP 5, PHP 7, PHP 8) DOMDocument::saveXML — Dumps the internal XML tree back into a string ### Description ``` public DOMDocument::saveXML(?DOMNode $node = null, int $options = 0): string|false ``` Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below. ### Parameters `node` Use this parameter to output only a specific node without XML declaration rather than the entire document. `options` Additional Options. Currently only [LIBXML\_NOEMPTYTAG](https://www.php.net/manual/en/libxml.constants.php) is supported. ### Return Values Returns the XML, or **`false`** if an error occurred. ### Errors/Exceptions **`DOM_WRONG_DOCUMENT_ERR`** Raised if `node` is from another document. ### Examples **Example #1 Saving a DOM tree into a string** ``` <?php $doc = new DOMDocument('1.0'); // we want a nice output $doc->formatOutput = true; $root = $doc->createElement('book'); $root = $doc->appendChild($root); $title = $doc->createElement('title'); $title = $root->appendChild($title); $text = $doc->createTextNode('This is the title'); $text = $title->appendChild($text); echo "Saving all the document:\n"; echo $doc->saveXML() . "\n"; echo "Saving only the title part:\n"; echo $doc->saveXML($title); ?> ``` The above example will output: ``` Saving all the document: <?xml version="1.0"?> <book> <title>This is the title</title> </book> Saving only the title part: <title>This is the title</title> ``` ### See Also * [DOMDocument::save()](domdocument.save) - Dumps the internal XML tree back into a file * [DOMDocument::load()](domdocument.load) - Load XML from a file * [DOMDocument::loadXML()](domdocument.loadxml) - Load XML from a string php DateTimeInterface::format DateTimeInterface::format ========================= DateTimeImmutable::format ========================= DateTime::format ================ date\_format ============ (PHP 5 >= 5.2.0, PHP 7, PHP 8) DateTimeInterface::format -- DateTimeImmutable::format -- DateTime::format -- date\_format — Returns date formatted according to given format ### Description Object-oriented style ``` public DateTimeInterface::format(string $format): string ``` ``` public DateTimeImmutable::format(string $format): string ``` ``` public DateTime::format(string $format): string ``` Procedural style ``` date_format(DateTimeInterface $object, string $format): string ``` Returns date formatted according to given format. ### Parameters `object` Procedural style only: A [DateTime](class.datetime) object returned by [date\_create()](function.date-create) `format` The format of the outputted date string. See the formatting options below. There are also several [predefined date constants](class.datetimeinterface#datetimeinterface.constants.types) that may be used instead, so for example **`DATE_RSS`** contains the format string `'D, d M Y H:i:s'`. **The following characters are recognized in the `format` parameter string**| `format` character | Description | Example returned values | | --- | --- | --- | | *Day* | --- | --- | | `d` | Day of the month, 2 digits with leading zeros | `01` to `31` | | `D` | A textual representation of a day, three letters | `Mon` through `Sun` | | `j` | Day of the month without leading zeros | `1` to `31` | | `l` (lowercase 'L') | A full textual representation of the day of the week | `Sunday` through `Saturday` | | `N` | ISO 8601 numeric representation of the day of the week | `1` (for Monday) through `7` (for Sunday) | | `S` | English ordinal suffix for the day of the month, 2 characters | `st`, `nd`, `rd` or `th`. Works well with `j` | | `w` | Numeric representation of the day of the week | `0` (for Sunday) through `6` (for Saturday) | | `z` | The day of the year (starting from 0) | `0` through `365` | | *Week* | --- | --- | | `W` | ISO 8601 week number of year, weeks starting on Monday | Example: `42` (the 42nd week in the year) | | *Month* | --- | --- | | `F` | A full textual representation of a month, such as January or March | `January` through `December` | | `m` | Numeric representation of a month, with leading zeros | `01` through `12` | | `M` | A short textual representation of a month, three letters | `Jan` through `Dec` | | `n` | Numeric representation of a month, without leading zeros | `1` through `12` | | `t` | Number of days in the given month | `28` through `31` | | *Year* | --- | --- | | `L` | Whether it's a leap year | `1` if it is a leap year, `0` otherwise. | | `o` | ISO 8601 week-numbering year. This has the same value as `Y`, except that if the ISO week number (`W`) belongs to the previous or next year, that year is used instead. | Examples: `1999` or `2003` | | `X` | An expanded full numeric representation of a year, at least 4 digits, with `-` for years BCE, and `+` for years CE. | Examples: `-0055`, `+0787`, `+1999`, `+10191` | | `x` | An expanded full numeric representation if requried, or a standard full numeral representation if possible (like `Y`). At least four digits. Years BCE are prefixed with a `-`. Years beyond (and including) `10000` are prefixed by a `+`. | Examples: `-0055`, `0787`, `1999`, `+10191` | | `Y` | A full numeric representation of a year, at least 4 digits, with `-` for years BCE. | Examples: `-0055`, `0787`, `1999`, `2003`, `10191` | | `y` | A two digit representation of a year | Examples: `99` or `03` | | *Time* | --- | --- | | `a` | Lowercase Ante meridiem and Post meridiem | `am` or `pm` | | `A` | Uppercase Ante meridiem and Post meridiem | `AM` or `PM` | | `B` | Swatch Internet time | `000` through `999` | | `g` | 12-hour format of an hour without leading zeros | `1` through `12` | | `G` | 24-hour format of an hour without leading zeros | `0` through `23` | | `h` | 12-hour format of an hour with leading zeros | `01` through `12` | | `H` | 24-hour format of an hour with leading zeros | `00` through `23` | | `i` | Minutes with leading zeros | `00` to `59` | | `s` | Seconds with leading zeros | `00` through `59` | | `u` | Microseconds. Note that [date()](function.date) will always generate `000000` since it takes an int parameter, whereas **DateTime::format()** does support microseconds if [DateTime](class.datetime) was created with microseconds. | Example: `654321` | | `v` | Milliseconds. Same note applies as for `u`. | Example: `654` | | *Timezone* | --- | --- | | `e` | Timezone identifier | Examples: `UTC`, `GMT`, `Atlantic/Azores` | | `I` (capital i) | Whether or not the date is in daylight saving time | `1` if Daylight Saving Time, `0` otherwise. | | `O` | Difference to Greenwich time (GMT) without colon between hours and minutes | Example: `+0200` | | `P` | Difference to Greenwich time (GMT) with colon between hours and minutes | Example: `+02:00` | | `p` | The same as `P`, but returns `Z` instead of `+00:00` (available as of PHP 8.0.0) | Examples: `Z` or `+02:00` | | `T` | Timezone abbreviation, if known; otherwise the GMT offset. | Examples: `EST`, `MDT`, `+05` | | `Z` | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | `-43200` through `50400` | | *Full Date/Time* | --- | --- | | `c` | ISO 8601 date | 2004-02-12T15:19:21+00:00 | | `r` | [» RFC 2822](http://www.faqs.org/rfcs/rfc2822)/[» RFC 5322](http://www.faqs.org/rfcs/rfc5322) formatted date | Example: `Thu, 21 Dec 2000 16:01:07 +0200` | | `U` | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also [time()](function.time) | Unrecognized characters in the format string will be printed as-is. The `Z` format will always return `0` when using [gmdate()](function.gmdate). > > **Note**: > > > Since this function only accepts int timestamps the `u` format character is only useful when using the [date\_format()](function.date-format) function with user based timestamps created with [date\_create()](function.date-create). > > ### Return Values Returns the formatted date string on success. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | The format characters `X` and `x` have been added. | | 8.0.0 | Prior to this version, **`false`** was returned on failure. | | 8.0.0 | The format character `p` has been added. | ### Examples **Example #1 **DateTimeInterface::format()** example** Object-oriented style ``` <?php $date = new DateTimeImmutable('2000-01-01'); echo $date->format('Y-m-d H:i:s'); ?> ``` Procedural style ``` <?php $date = date_create('2000-01-01'); echo date_format($date, 'Y-m-d H:i:s'); ?> ``` The above example will output: ``` 2000-01-01 00:00:00 ``` **Example #2 More examples** ``` <?php // set the default timezone to use. date_default_timezone_set('UTC'); // now $date = new DateTimeImmutable(); // Prints something like: Wednesday echo $date->format('l'), "\n"; // Prints something like: Wednesday 19th of October 2022 08:40:48 AM echo $date->format('l jS \o\f F Y h:i:s A'), "\n"; /* use the constants in the format parameter */ // prints something like: Wed, 19 Oct 2022 08:40:48 +0000 echo $date->format(DateTimeInterface::RFC2822), "\n"; ?> ``` You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash. **Example #3 Escaping characters while formatting** ``` <?php $date = new DateTimeImmutable(); // prints something like: Wednesday the 19th echo $date->format('l \t\h\e jS'); ?> ``` To format dates in other languages, [IntlDateFormatter::format()](intldateformatter.format) can be used instead of **DateTimeInterface::format()**. ### Notes This method does not use locales. All output is in English. ### See Also * [IntlDateFormatter::format()](intldateformatter.format) - Format the date/time value as a string
programming_docs
php IntlDateFormatter::create IntlDateFormatter::create ========================= datefmt\_create =============== IntlDateFormatter::\_\_construct ================================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) IntlDateFormatter::create -- datefmt\_create -- IntlDateFormatter::\_\_construct — Create a date formatter ### Description Object-oriented style ``` public static IntlDateFormatter::create( ?string $locale, int $dateType = IntlDateFormatter::FULL, int $timeType = IntlDateFormatter::FULL, IntlTimeZone|DateTimeZone|string|null $timezone = null, IntlCalendar|int|null $calendar = null, ?string $pattern = null ): ?IntlDateFormatter ``` Object-oriented style (constructor) public **IntlDateFormatter::\_\_construct**( ?string `$locale`, int `$dateType` = IntlDateFormatter::FULL, int `$timeType` = IntlDateFormatter::FULL, [IntlTimeZone](class.intltimezone)|[DateTimeZone](class.datetimezone)|string|null `$timezone` = **`null`**, [IntlCalendar](class.intlcalendar)|int|null `$calendar` = **`null`**, ?string `$pattern` = **`null`** ) Procedural style ``` datefmt_create( ?string $locale, int $dateType = IntlDateFormatter::FULL, int $timeType = IntlDateFormatter::FULL, IntlTimeZone|DateTimeZone|string|null $timezone = null, IntlCalendar|int|null $calendar = null, ?string $pattern = null ): ?IntlDateFormatter ``` Create a date formatter. ### Parameters `locale` Locale to use when formatting or parsing or **`null`** to use the value specified in the ini setting [intl.default\_locale](https://www.php.net/manual/en/intl.configuration.php#ini.intl.default-locale). `dateType` Date type to use (**`none`**, **`short`**, **`medium`**, **`long`**, **`full`**). This is one of the [IntlDateFormatter constants](class.intldateformatter#intl.intldateformatter-constants). `timeType` Time type to use (**`none`**, **`short`**, **`medium`**, **`long`**, **`full`**). This is one of the [IntlDateFormatter constants](class.intldateformatter#intl.intldateformatter-constants). `timezone` Time zone ID. The default (and the one used if **`null`** is given) is the one returned by [date\_default\_timezone\_get()](function.date-default-timezone-get) or, if applicable, that of the [IntlCalendar](class.intlcalendar) object passed for the `calendar` parameter. This ID must be a valid identifier on ICUʼs database or an ID representing an explicit offset, such as `GMT-05:30`. This can also be an [IntlTimeZone](class.intltimezone) or a [DateTimeZone](class.datetimezone) object. `calendar` Calendar to use for formatting or parsing. The default value is **`null`**, which corresponds to **`IntlDateFormatter::GREGORIAN`**. This can either be one of the [IntlDateFormatter calendar constants](class.intldateformatter#intl.intldateformatter-constants.calendartypes) or an [IntlCalendar](class.intlcalendar). Any [IntlCalendar](class.intlcalendar) object passed will be clone; it will not be changed by the [IntlDateFormatter](class.intldateformatter). This will determine the calendar type used (gregorian, islamic, persian, etc.) and, if **`null`** is given for the `timezone` parameter, also the timezone used. `pattern` Optional pattern to use when formatting or parsing. Possible patterns are documented at [» https://unicode-org.github.io/icu/userguide/format\_parse/datetime/](https://unicode-org.github.io/icu/userguide/format_parse/datetime/). ### Return Values The created [IntlDateFormatter](class.intldateformatter) or **`null`** in case of failure. ### Changelog | Version | Description | | --- | --- | | 5.5.0/PECL 3.0.0 | An [IntlCalendar](class.intlcalendar) object is allowed for `calendar`. Objects of type [IntlTimeZone](class.intltimezone) and [DateTimeZone](class.datetimezone) are allowed for `timezone`. Invalid timezone identifiers (including empty strings) are no longer allowed for `timezone`. If **`null`** is given for `timezone`, the timezone identifier given by [date\_default\_timezone\_get()](function.date-default-timezone-get) will be used instead of ICUʼs default. | ### Examples **Example #1 **datefmt\_create()** example** ``` <?php $fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,     'America/Los_Angeles', IntlDateFormatter::GREGORIAN  ); echo "First Formatted output is ".datefmt_format( $fmt , 0); $fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ); echo "Second Formatted output is ".datefmt_format( $fmt , 0); $fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,      'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy"); echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0); $fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,      'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy"); echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0); ?> ``` **Example #2 OO example** ``` <?php $fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ); echo "First Formatted output is ".$fmt->format(0); $fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ); echo "Second Formatted output is ".$fmt->format(0); $fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,      'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy"); echo "First Formatted output with pattern is ".$fmt->format(0); $fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,       'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy"); echo "Second Formatted output with pattern is ".$fmt->format(0); ?> ``` The above example will output: ``` First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00 First Formatted output with pattern is 12/31/1969 Second Formatted output with pattern is 12/31/1969 ``` ### See Also * [datefmt\_format()](intldateformatter.format) - Format the date/time value as a string * [datefmt\_parse()](intldateformatter.parse) - Parse string to a timestamp value * [datefmt\_get\_error\_code()](intldateformatter.geterrorcode) - Get the error code from last operation * [datefmt\_get\_error\_message()](intldateformatter.geterrormessage) - Get the error text from the last operation php openal_source_play openal\_source\_play ==================== (PECL openal >= 0.1.0) openal\_source\_play — Start playing the source ### Description ``` openal_source_play(resource $source): bool ``` ### Parameters `source` An [Open AL(Source)](https://www.php.net/manual/en/openal.resources.php) resource (previously created by [openal\_source\_create()](function.openal-source-create)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [openal\_source\_stop()](function.openal-source-stop) - Stop playing the source * [openal\_source\_pause()](function.openal-source-pause) - Pause the source * [openal\_source\_rewind()](function.openal-source-rewind) - Rewind the source php mysqli::set_charset mysqli::set\_charset ==================== mysqli\_set\_charset ==================== (PHP 5 >= 5.0.5, PHP 7, PHP 8) mysqli::set\_charset -- mysqli\_set\_charset — Sets the client character set ### Description Object-oriented style ``` public mysqli::set_charset(string $charset): bool ``` Procedural style ``` mysqli_set_charset(mysqli $mysql, string $charset): bool ``` Sets the character set to be used when sending data from and to the database server. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `charset` The desired character set. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **mysqli::set\_charset()** example** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "test"); printf("Initial character set: %s\n", $mysqli->character_set_name()); /* change character set to utf8mb4 */ $mysqli->set_charset("utf8mb4"); printf("Current character set: %s\n", $mysqli->character_set_name()); ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect('localhost', 'my_user', 'my_password', 'test'); printf("Initial character set: %s\n", mysqli_character_set_name($link)); /* change character set to utf8mb4 */ mysqli_set_charset($link, "utf8mb4"); printf("Current character set: %s\n", mysqli_character_set_name($link)); ``` The above examples will output something similar to: ``` Initial character set: latin1 Current character set: utf8mb4 ``` ### Notes > > **Note**: > > > To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above). > > > > **Note**: > > > This is the preferred way to change the charset. Using [mysqli\_query()](mysqli.query) to set it (such as `SET NAMES utf8`) is not recommended. See the [MySQL character set concepts](https://www.php.net/manual/en/mysqlinfo.concepts.charset.php) section for more information. > > ### See Also * [mysqli\_character\_set\_name()](mysqli.character-set-name) - Returns the current character set of the database connection * [mysqli\_real\_escape\_string()](mysqli.real-escape-string) - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection * [MySQL character set concepts](https://www.php.net/manual/en/mysqlinfo.concepts.charset.php) * [» List of character sets that MySQL supports](http://dev.mysql.com/doc/mysql/en/charset-charsets.html) php The SoapServer class The SoapServer class ==================== Introduction ------------ (PHP 5, PHP 7, PHP 8) The SoapServer class provides a server for the [» SOAP 1.1](http://www.w3.org/TR/soap11/) and [» SOAP 1.2](http://www.w3.org/TR/soap12/) protocols. It can be used with or without a WSDL service description. Class synopsis -------------- class **SoapServer** { /\* Properties \*/ private resource [$service](class.soapserver#soapserver.props.service); private ?[SoapFault](class.soapfault) [$\_\_soap\_fault](class.soapserver#soapserver.props.--soap-fault) = null; /\* Methods \*/ public [\_\_construct](soapserver.construct)(?string `$wsdl`, array `$options` = []) ``` public addFunction(array|string|int $functions): void ``` ``` public addSoapHeader(SoapHeader $header): void ``` ``` public fault( string $code, string $string, string $actor = "", mixed $details = null, string $name = "" ): void ``` ``` public getFunctions(): array ``` ``` public handle(?string $request = null): void ``` ``` public setClass(string $class, mixed ...$args): void ``` ``` public setObject(object $object): void ``` ``` public setPersistence(int $mode): void ``` } Properties ---------- service \_\_soap\_fault Table of Contents ----------------- * [SoapServer::addFunction](soapserver.addfunction) — Adds one or more functions to handle SOAP requests * [SoapServer::addSoapHeader](soapserver.addsoapheader) — Add a SOAP header to the response * [SoapServer::\_\_construct](soapserver.construct) — SoapServer constructor * [SoapServer::fault](soapserver.fault) — Issue SoapServer fault indicating an error * [SoapServer::getFunctions](soapserver.getfunctions) — Returns list of defined functions * [SoapServer::handle](soapserver.handle) — Handles a SOAP request * [SoapServer::setClass](soapserver.setclass) — Sets the class which handles SOAP requests * [SoapServer::setObject](soapserver.setobject) — Sets the object which will be used to handle SOAP requests * [SoapServer::setPersistence](soapserver.setpersistence) — Sets SoapServer persistence mode php imagefilledellipse imagefilledellipse ================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) imagefilledellipse — Draw a filled ellipse ### Description ``` imagefilledellipse( GdImage $image, int $center_x, int $center_y, int $width, int $height, int $color ): bool ``` Draws an ellipse centered at the specified coordinate on the given `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `center_x` x-coordinate of the center. `center_y` y-coordinate of the center. `width` The ellipse width. `height` The ellipse height. `color` The fill color. A color identifier created with [imagecolorallocate()](function.imagecolorallocate). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagefilledellipse()** example** ``` <?php // create a blank image $image = imagecreatetruecolor(400, 300); // fill the background color $bg = imagecolorallocate($image, 0, 0, 0); // choose a color for the ellipse $col_ellipse = imagecolorallocate($image, 255, 255, 255); // draw the white ellipse imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse); // output the picture header("Content-type: image/png"); imagepng($image); ?> ``` The above example will output something similar to: ### Notes > > **Note**: > > > **imagefilledellipse()** ignores [imagesetthickness()](function.imagesetthickness). > > ### See Also * [imageellipse()](function.imageellipse) - Draw an ellipse * [imagefilledarc()](function.imagefilledarc) - Draw a partial arc and fill it php Yaf_Config_Abstract::toArray Yaf\_Config\_Abstract::toArray ============================== (Yaf >=1.0.0) Yaf\_Config\_Abstract::toArray — Cast to array ### Description ``` abstract public Yaf_Config_Abstract::toArray(): array ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php fbird_blob_open fbird\_blob\_open ================= (PHP 5, PHP 7 < 7.4.0) fbird\_blob\_open — Alias of [ibase\_blob\_open()](function.ibase-blob-open) ### Description This function is an alias of: [ibase\_blob\_open()](function.ibase-blob-open). ### See Also * [fbird\_blob\_close()](function.fbird-blob-close) - Alias of ibase\_blob\_close * [fbird\_blob\_echo()](function.fbird-blob-echo) - Alias of ibase\_blob\_echo * [fbird\_blob\_get()](function.fbird-blob-get) - Alias of ibase\_blob\_get php CachingIterator::count CachingIterator::count ====================== (PHP 5 >= 5.2.2, PHP 7, PHP 8) CachingIterator::count — The number of elements in the iterator ### Description ``` public CachingIterator::count(): int ``` **Warning**This function is currently not documented; only its argument list is available. May return the number of elements in the iterator. ### Parameters This function has no parameters. ### Return Values The count of the elements iterated over. php SolrClient::request SolrClient::request =================== (PECL solr >= 0.9.2) SolrClient::request — Sends a raw update request ### Description ``` public SolrClient::request(string $raw_request): SolrUpdateResponse ``` Sends a raw XML update request to the server ### Parameters `raw_request` An XML string with the raw request to the server. ### Return Values Returns a [SolrUpdateResponse](class.solrupdateresponse) on success. Throws an exception on failure. ### Errors/Exceptions Throws [SolrIllegalArgumentException](class.solrillegalargumentexception) if `raw_request` was an empty string Throws [SolrClientException](class.solrclientexception) if the client had failed, or there was a connection issue. Throws [SolrServerException](class.solrserverexception) if the Solr Server had failed to satisfy the query. ### Examples **Example #1 **SolrClient::request()** example** ``` <?php $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT, ); $client = new SolrClient($options); $update_response = $client->request("<commit/>"); $response = $update_response->getResponse(); print_r($response); ?> ``` The above example will output something similar to: ``` ... ``` php strftime strftime ======== (PHP 4, PHP 5, PHP 7, PHP 8) strftime — Format a local time/date according to locale settings **Warning**This function has been *DEPRECATED* as of PHP 8.1.0. Relying on this function is highly discouraged. Alternatives to this function include: * [date()](function.date) * [IntlDateFormatter::format()](intldateformatter.format) ### Description ``` strftime(string $format, ?int $timestamp = null): string|false ``` Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with [setlocale()](function.setlocale). **Warning** Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's **strftime()**. Additionally, not all platforms support negative timestamps, so your date range may be limited to no earlier than the Unix epoch. This means that %e, %T, %R and, %D (and possibly others) - as well as dates prior to `Jan 1, 1970` - will not work on Windows, some Linux distributions, and a few other operating systems. For Windows systems, a complete overview of supported conversion specifiers can be found at [» MSDN](http://msdn.microsoft.com/en-us/library/fe06s4ak.aspx). Instead use the [IntlDateFormatter::format()](intldateformatter.format) method. ### Parameters `format` **The following characters are recognized in the `format` parameter string**| `format` | Description | Example returned values | | --- | --- | --- | | *Day* | --- | --- | | `%a` | An abbreviated textual representation of the day | `Sun` through `Sat` | | `%A` | A full textual representation of the day | `Sunday` through `Saturday` | | `%d` | Two-digit day of the month (with leading zeros) | `01` to `31` | | `%e` | Day of the month, with a space preceding single digits. Not implemented as described on Windows. See below for more information. | `1` to `31` | | `%j` | Day of the year, 3 digits with leading zeros | `001` to `366` | | `%u` | ISO-8601 numeric representation of the day of the week | `1` (for Monday) through `7` (for Sunday) | | `%w` | Numeric representation of the day of the week | `0` (for Sunday) through `6` (for Saturday) | | *Week* | --- | --- | | `%U` | Week number of the given year, starting with the first Sunday as the first week | `13` (for the 13th full week of the year) | | `%V` | ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week | `01` through `53` (where 53 accounts for an overlapping week) | | `%W` | A numeric representation of the week of the year, starting with the first Monday as the first week | `46` (for the 46th week of the year beginning with a Monday) | | *Month* | --- | --- | | `%b` | Abbreviated month name, based on the locale | `Jan` through `Dec` | | `%B` | Full month name, based on the locale | `January` through `December` | | `%h` | Abbreviated month name, based on the locale (an alias of %b) | `Jan` through `Dec` | | `%m` | Two digit representation of the month | `01` (for January) through `12` (for December) | | *Year* | --- | --- | | `%C` | Two digit representation of the century (year divided by 100, truncated to an integer) | `19` for the 20th Century | | `%g` | Two digit representation of the year going by ISO-8601:1988 standards (see %V) | Example: `09` for the week of January 6, 2009 | | `%G` | The full four-digit version of %g | Example: `2008` for the week of January 3, 2009 | | `%y` | Two digit representation of the year | Example: `09` for 2009, `79` for 1979 | | `%Y` | Four digit representation for the year | Example: `2038` | | *Time* | --- | --- | | `%H` | Two digit representation of the hour in 24-hour format | `00` through `23` | | `%k` | Hour in 24-hour format, with a space preceding single digits | `0` through `23` | | `%I` | Two digit representation of the hour in 12-hour format | `01` through `12` | | `%l (lower-case 'L')` | Hour in 12-hour format, with a space preceding single digits | `1` through `12` | | `%M` | Two digit representation of the minute | `00` through `59` | | `%p` | UPPER-CASE 'AM' or 'PM' based on the given time | Example: `AM` for 00:31, `PM` for 22:23. The exact result depends on the Operating System, and they can also return lower-case variants, or variants with dots (such as `a.m.`). | | `%P` | lower-case 'am' or 'pm' based on the given time | Example: `am` for 00:31, `pm` for 22:23. Not supported by all Operating Systems. | | `%r` | Same as "%I:%M:%S %p" | Example: `09:34:17 PM` for 21:34:17 | | `%R` | Same as "%H:%M" | Example: `00:35` for 12:35 AM, `16:44` for 4:44 PM | | `%S` | Two digit representation of the second | `00` through `59` | | `%T` | Same as "%H:%M:%S" | Example: `21:34:17` for 09:34:17 PM | | `%X` | Preferred time representation based on locale, without the date | Example: `03:59:16` or `15:59:16` | | `%z` | The time zone offset. Not implemented as described on Windows. See below for more information. | Example: `-0500` for US Eastern Time | | `%Z` | The time zone abbreviation. Not implemented as described on Windows. See below for more information. | Example: `EST` for Eastern Time | | *Time and Date Stamps* | --- | --- | | `%c` | Preferred date and time stamp based on locale | Example: `Tue Feb 5 00:45:10 2009` for February 5, 2009 at 12:45:10 AM | | `%D` | Same as "%m/%d/%y" | Example: `02/05/09` for February 5, 2009 | | `%F` | Same as "%Y-%m-%d" (commonly used in database datestamps) | Example: `2009-02-05` for February 5, 2009 | | `%s` | Unix Epoch Time timestamp (same as the [time()](function.time) function) | Example: `305815200` for September 10, 1979 08:40:00 AM | | `%x` | Preferred date representation based on locale, without the time | Example: `02/05/09` for February 5, 2009 | | *Miscellaneous* | --- | --- | | `%n` | A newline character ("\n") | --- | | `%t` | A Tab character ("\t") | --- | | `%%` | A literal percentage character ("%") | --- | **Warning** Contrary to ISO-9899:1999, Sun Solaris starts with Sunday as 1. As a result, `%u` may not function as described in this manual. **Warning** *Windows only:* The `%e` modifier is not supported in the Windows implementation of this function. To achieve this value, the `%#d` modifier can be used instead. The example below illustrates how to write a cross platform compatible function. The `%z` and `%Z` modifiers both return the time zone name instead of the offset or abbreviation. **Warning** *macOS and musl only:* The `%P` modifier is not supported in the macOS implementation of this function. `timestamp` The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or **`null`**. In other words, it defaults to the value of [time()](function.time). ### Return Values Returns a string formatted according `format` using the given `timestamp` or the current local time if no timestamp is given. Month and weekday names and other language-dependent strings respect the current locale set with [setlocale()](function.setlocale). The function returns **`false`** if `format` is empty, contains unsupported conversion specifiers, or if the length of the returned string would be greater than `4095`. ### Errors/Exceptions Every call to a date/time function will generate a **`E_WARNING`** if the time zone is not valid. See also [date\_default\_timezone\_set()](function.date-default-timezone-set) As the output is dependent upon the underlying C library, some conversion specifiers are not supported. On Windows, supplying unknown conversion specifiers will result in 5 **`E_WARNING`** messages and return **`false`**. On other operating systems you may not get any **`E_WARNING`** messages and the output may contain the conversion specifiers unconverted. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `timestamp` is nullable now. | ### Examples This example will work if you have the respective locales installed in your system. **Example #1 **strftime()** locale examples** ``` <?php setlocale(LC_TIME, "C"); echo strftime("%A"); setlocale(LC_TIME, "fi_FI"); echo strftime(" in Finnish is %A,"); setlocale(LC_TIME, "fr_FR"); echo strftime(" in French %A and"); setlocale(LC_TIME, "de_DE"); echo strftime(" in German %A.\n"); ?> ``` **Example #2 ISO 8601:1988 week number example** ``` <?php /*     December 2002 / January 2003 ISOWk  M   Tu  W   Thu F   Sa  Su ----- ---------------------------- 51     16  17  18  19  20  21  22 52     23  24  25  26  27  28  29 1      30  31   1   2   3   4   5 2       6   7   8   9  10  11  12 3      13  14  15  16  17  18  19   */ // Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002 echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n"; // Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002 echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n"; // Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003 echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n"; // Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003 echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n"; /*     December 2004 / January 2005 ISOWk  M   Tu  W   Thu F   Sa  Su ----- ---------------------------- 51     13  14  15  16  17  18  19 52     20  21  22  23  24  25  26 53     27  28  29  30  31   1   2 1       3   4   5   6   7   8   9 2      10  11  12  13  14  15  16   */ // Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004 echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n"; // Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004 echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n"; // Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005 echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n"; // Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005 echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n"; ?> ``` **Example #3 Cross platform compatible example using the `%e` modifier** ``` <?php // Jan 1: results in: '%e%1%' (%%, e, %%, %e, %%) $format = '%%e%%%e%%'; // Check for Windows to find and replace the %e  // modifier correctly if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {     $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format); } echo strftime($format); ?> ``` **Example #4 Display all known and unknown formats.** ``` <?php // Describe the formats. $strftimeFormats = array(     'A' => 'A full textual representation of the day',     'B' => 'Full month name, based on the locale',     'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',     'D' => 'Same as "%m/%d/%y"',     'E' => '',     'F' => 'Same as "%Y-%m-%d"',     'G' => 'The full four-digit version of %g',     'H' => 'Two digit representation of the hour in 24-hour format',     'I' => 'Two digit representation of the hour in 12-hour format',     'J' => '',     'K' => '',     'L' => '',     'M' => 'Two digit representation of the minute',     'N' => '',     'O' => '',     'P' => 'lower-case "am" or "pm" based on the given time',     'Q' => '',     'R' => 'Same as "%H:%M"',     'S' => 'Two digit representation of the second',     'T' => 'Same as "%H:%M:%S"',     'U' => 'Week number of the given year, starting with the first Sunday as the first week',     'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',     'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',     'X' => 'Preferred time representation based on locale, without the date',     'Y' => 'Four digit representation for the year',     'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',     'a' => 'An abbreviated textual representation of the day',     'b' => 'Abbreviated month name, based on the locale',     'c' => 'Preferred date and time stamp based on local',     'd' => 'Two-digit day of the month (with leading zeros)',     'e' => 'Day of the month, with a space preceding single digits',     'f' => '',     'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',     'h' => 'Abbreviated month name, based on the locale (an alias of %b)',     'i' => '',     'j' => 'Day of the year, 3 digits with leading zeros',     'k' => 'Hour in 24-hour format, with a space preceding single digits',     'l' => 'Hour in 12-hour format, with a space preceding single digits',     'm' => 'Two digit representation of the month',     'n' => 'A newline character ("\n")',     'o' => '',     'p' => 'UPPER-CASE "AM" or "PM" based on the given time',     'q' => '',     'r' => 'Same as "%I:%M:%S %p"',     's' => 'Unix Epoch Time timestamp',     't' => 'A Tab character ("\t")',     'u' => 'ISO-8601 numeric representation of the day of the week',     'v' => '',     'w' => 'Numeric representation of the day of the week',     'x' => 'Preferred date representation based on locale, without the time',     'y' => 'Two digit representation of the year',     'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',     '%' => 'A literal percentage character ("%")', ); // Results. $strftimeValues = array(); // Evaluate the formats whilst suppressing any errors. foreach($strftimeFormats as $format => $description){     if (False !== ($value = @strftime("%{$format}"))){         $strftimeValues[$format] = $value;     } } // Find the longest value. $maxValueLength = 2 + max(array_map('strlen', $strftimeValues)); // Report known formats. foreach($strftimeValues as $format => $value){     echo "Known format   : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n"; } // Report unknown formats. foreach(array_diff_key($strftimeFormats, $strftimeValues) as $format => $description){     echo "Unknown format : '{$format}'   ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n"; } ?> ``` The above example will output something similar to: ``` Known format : 'A' = 'Friday' ( A full textual representation of the day ) Known format : 'B' = 'December' ( Full month name, based on the locale ) Known format : 'H' = '11' ( Two digit representation of the hour in 24-hour format ) Known format : 'I' = '11' ( Two digit representation of the hour in 12-hour format ) Known format : 'M' = '24' ( Two digit representation of the minute ) Known format : 'S' = '44' ( Two digit representation of the second ) Known format : 'U' = '48' ( Week number of the given year, starting with the first Sunday as the first week ) Known format : 'W' = '48' ( A numeric representation of the week of the year, starting with the first Monday as the first week ) Known format : 'X' = '11:24:44' ( Preferred time representation based on locale, without the date ) Known format : 'Y' = '2010' ( Four digit representation for the year ) Known format : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) ) Known format : 'a' = 'Fri' ( An abbreviated textual representation of the day ) Known format : 'b' = 'Dec' ( Abbreviated month name, based on the locale ) Known format : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local ) Known format : 'd' = '03' ( Two-digit day of the month (with leading zeros) ) Known format : 'j' = '337' ( Day of the year, 3 digits with leading zeros ) Known format : 'm' = '12' ( Two digit representation of the month ) Known format : 'p' = 'AM' ( UPPER-CASE "AM" or "PM" based on the given time ) Known format : 'w' = '5' ( Numeric representation of the day of the week ) Known format : 'x' = '12/03/10' ( Preferred date representation based on locale, without the time ) Known format : 'y' = '10' ( Two digit representation of the year ) Known format : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) ) Known format : '%' = '%' ( A literal percentage character ("%") ) Unknown format : 'C' ( Two digit representation of the century (year divided by 100, truncated to an integer) ) Unknown format : 'D' ( Same as "%m/%d/%y" ) Unknown format : 'E' Unknown format : 'F' ( Same as "%Y-%m-%d" ) Unknown format : 'G' ( The full four-digit version of %g ) Unknown format : 'J' Unknown format : 'K' Unknown format : 'L' Unknown format : 'N' Unknown format : 'O' Unknown format : 'P' ( lower-case "am" or "pm" based on the given time ) Unknown format : 'Q' Unknown format : 'R' ( Same as "%H:%M" ) Unknown format : 'T' ( Same as "%H:%M:%S" ) Unknown format : 'V' ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week ) Unknown format : 'e' ( Day of the month, with a space preceding single digits ) Unknown format : 'f' Unknown format : 'g' ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) ) Unknown format : 'h' ( Abbreviated month name, based on the locale (an alias of %b) ) Unknown format : 'i' Unknown format : 'k' ( Hour in 24-hour format, with a space preceding single digits ) Unknown format : 'l' ( Hour in 12-hour format, with a space preceding single digits ) Unknown format : 'n' ( A newline character ("\n") ) Unknown format : 'o' Unknown format : 'q' Unknown format : 'r' ( Same as "%I:%M:%S %p" ) Unknown format : 's' ( Unix Epoch Time timestamp ) Unknown format : 't' ( A Tab character ("\t") ) Unknown format : 'u' ( ISO-8601 numeric representation of the day of the week ) Unknown format : 'v' ``` ### Notes > **Note**: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page. > > ### See Also * [IntlDateFormatter::format()](intldateformatter.format) - Format the date/time value as a string * [DateTimeInterface::format()](datetime.format) - Returns date formatted according to given format * [» Online strftime() format design tool](http://strftime.net/) * [setlocale()](function.setlocale) - Set locale information * [mktime()](function.mktime) - Get Unix timestamp for a date * [strptime()](function.strptime) - Parse a time/date generated with strftime * [gmstrftime()](function.gmstrftime) - Format a GMT/UTC time/date according to locale settings * [» Open Group specification of **strftime()**](http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html)
programming_docs
php None Syntax ------ Constants can be defined using the `const` keyword, or by using the [define()](function.define)-function. While [define()](function.define) allows a constant to be defined to an arbitrary expression, the `const` keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined. When using the `const` keyword, only scalar (bool, int, float and string) expressions and constant arrays containing only scalar expressions are accepted. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results. The value of a constant is accessed simply by specifying its name. Unlike variables, a constant is *not* prepended with a `$`. It is also possible to use the [constant()](function.constant) function to read a constant's value if the constant's name is obtained dynamically. Use [get\_defined\_constants()](function.get-defined-constants) to get a list of all defined constants. > **Note**: Constants and (global) variables are in a different namespace. This implies that for example **`true`** and $TRUE are generally different. > > If an undefined constant is used an [Error](class.error) is thrown. Prior to PHP 8.0.0, undefined constants would be interpreted as a bare word string, i.e. (CONSTANT vs "CONSTANT"). This fallback is deprecated as of PHP 7.2.0, and an error of level **`E_WARNING`** is issued when it happens. Prior to PHP 7.2.0, an error of level [E\_NOTICE](https://www.php.net/manual/en/ref.errorfunc.php) has been issued instead. See also the manual entry on why [$foo[bar]](language.types.array#language.types.array.foo-bar) is wrong (unless `bar` is a constant). This does not apply to [(fully) qualified constants](language.namespaces.rules), which will always raise a [Error](class.error) if undefined. > **Note**: To check if a constant is set, use the [defined()](function.defined) function. > > These are the differences between constants and variables: * Constants do not have a dollar sign (`$`) before them; * Constants may be defined and accessed anywhere without regard to variable scoping rules; * Constants may not be redefined or undefined once they have been set; and * Constants may only evaluate to scalar values or arrays. **Example #1 Defining Constants** ``` <?php define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // Emits an Error: Undefined constant "Constant"                // Prior to PHP 8.0.0, outputs "Constant" and issues a warning. ?> ``` **Example #2 Defining Constants using the `const` keyword** ``` <?php // Simple scalar value const CONSTANT = 'Hello World'; echo CONSTANT; // Scalar expression const ANOTHER_CONST = CONSTANT.'; Goodbye World'; echo ANOTHER_CONST; const ANIMALS = array('dog', 'cat', 'bird'); echo ANIMALS[1]; // outputs "cat" // Constant arrays define('ANIMALS', array(     'dog',     'cat',     'bird' )); echo ANIMALS[1]; // outputs "cat" ?> ``` > > **Note**: > > > As opposed to defining constants using [define()](function.define), constants defined using the `const` keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, `if` statements or `try`/`catch` blocks. > > ### See Also * [Class Constants](language.oop5.constants) php Memcached::set Memcached::set ============== (PECL memcached >= 0.1.0) Memcached::set — Store an item ### Description ``` public Memcached::set(string $key, mixed $value, int $expiration = ?): bool ``` **Memcached::set()** stores the `value` on a memcache server under the specified `key`. The `expiration` parameter can be used to control when the value is considered expired. The value can be any valid PHP type except for resources, because those cannot be represented in a serialized form. If the **`Memcached::OPT_COMPRESSION`** option is turned on, the serialized value will also be compressed before storage. ### Parameters `key` The key under which to store the value. `value` The value to store. `expiration` The expiration time, defaults to 0. See [Expiration Times](https://www.php.net/manual/en/memcached.expiration.php) for more info. ### Return Values Returns **`true`** on success or **`false`** on failure. Use [Memcached::getResultCode()](memcached.getresultcode) if necessary. ### Examples **Example #1 **Memcached::set()** example** ``` <?php $m = new Memcached(); $m->addServer('localhost', 11211); $m->set('int', 99); $m->set('string', 'a simple string'); $m->set('array', array(11, 12)); /* expire 'object' key in 5 minutes */ $m->set('object', new stdclass, time() + 300); var_dump($m->get('int')); var_dump($m->get('string')); var_dump($m->get('array')); var_dump($m->get('object')); ?> ``` The above example will output something similar to: ``` int(99) string(15) "a simple string" array(2) { [0]=> int(11) [1]=> int(12) } object(stdClass)#1 (0) { } ``` ### See Also * [Memcached::setByKey()](memcached.setbykey) - Store an item on a specific server * [Memcached::add()](memcached.add) - Add an item under a new key * [Memcached::replace()](memcached.replace) - Replace the item under an existing key php ImagickPixel::setColorCount ImagickPixel::setColorCount =========================== (PECL imagick 2, PECL imagick 3) ImagickPixel::setColorCount — Description ### Description ``` public ImagickPixel::setcolorcount(int $colorCount): bool ``` Sets the color count associated with this color. ### Parameters `colorCount` ### Return Values Returns **`true`** on success. php mb_check_encoding mb\_check\_encoding =================== (PHP 4 >= 4.4.3, PHP 5 >= 5.1.3, PHP 7, PHP 8) mb\_check\_encoding — Check if strings are valid for the specified encoding ### Description ``` mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool ``` Checks if the specified byte stream is valid for the specified encoding. If `value` is of type array, all keys and values are validated recursively. It is useful to prevent so-called "Invalid Encoding Attack". ### Parameters `value` The byte stream or array to check. If it is omitted, this function checks all the input from the beginning of the request. **Warning** As of PHP 8.1.0, omitting this parameter or passing **`null`** is deprecated. `encoding` The expected encoding. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Calling this function with **`null`** as `value` or without argument is deprecated. | | 8.0.0 | `value` and `encoding` are nullable now. | | 7.2.0 | This function now also accepts an array as `value`. Formerly, only strings have been supported. | php SolrQuery::removeFacetQuery SolrQuery::removeFacetQuery =========================== (PECL solr >= 0.9.2) SolrQuery::removeFacetQuery — Removes one of the facet.query parameters ### Description ``` public SolrQuery::removeFacetQuery(string $value): SolrQuery ``` Removes one of the facet.query parameters. ### Parameters `value` The value ### Return Values Returns the current SolrQuery object, if the return value is used. php fwrite fwrite ====== (PHP 4, PHP 5, PHP 7, PHP 8) fwrite — Binary-safe file write ### Description ``` fwrite(resource $stream, string $data, ?int $length = null): int|false ``` **fwrite()** writes the contents of `data` to the file stream pointed to by `stream`. ### Parameters `stream` A file system pointer resource that is typically created using [fopen()](function.fopen). `data` The string that is to be written. `length` If `length` is an int, writing will stop after `length` bytes have been written or the end of `data` is reached, whichever comes first. ### Return Values **fwrite()** returns the number of bytes written, or **`false`** on failure. ### Errors/Exceptions **fwrite()** raises **`E_WARNING`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `length` is nullable now. | ### Examples **Example #1 A simple **fwrite()** example** ``` <?php $filename = 'test.txt'; $somecontent = "Add this to the file\n"; // Let's make sure the file exists and is writable first. if (is_writable($filename)) {     // In our example we're opening $filename in append mode.     // The file pointer is at the bottom of the file hence     // that's where $somecontent will go when we fwrite() it.     if (!$fp = fopen($filename, 'a')) {          echo "Cannot open file ($filename)";          exit;     }     // Write $somecontent to our opened file.     if (fwrite($fp, $somecontent) === FALSE) {         echo "Cannot write to file ($filename)";         exit;     }     echo "Success, wrote ($somecontent) to file ($filename)";     fclose($fp); } else {     echo "The file $filename is not writable"; } ?> ``` ### Notes > > **Note**: > > > Writing to a network stream may end before the whole string is written. Return value of **fwrite()** may be checked: > > > > ``` > <?php > function fwrite_stream($fp, $string) { >     for ($written = 0; $written < strlen($string); $written += $fwrite) { >         $fwrite = fwrite($fp, substr($string, $written)); >         if ($fwrite === false) { >             return $written; >         } >     } >     return $written; > } > ?> > ``` > > > **Note**: > > > On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in [fopen()](function.fopen) mode parameter. > > > > **Note**: > > > If `stream` was [fopen()](function.fopen)ed in append mode, **fwrite()**s are atomic (unless the size of `data` exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to [flock()](function.flock) a resource before calling **fwrite()**; all of the data will be written without interruption. > > > > **Note**: > > > If writing twice to the file pointer, then the data will be appended to the end of the file content: > > > > ``` > <?php > $fp = fopen('data.txt', 'w'); > fwrite($fp, '1'); > fwrite($fp, '23'); > fclose($fp); > > // the content of 'data.txt' is now 123 and not 23! > ?> > ``` > ### See Also * [fread()](function.fread) - Binary-safe file read * [fopen()](function.fopen) - Opens file or URL * [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection * [popen()](function.popen) - Opens process file pointer * [file\_get\_contents()](function.file-get-contents) - Reads entire file into a string * [pack()](function.pack) - Pack data into binary string php SimpleXMLIterator::hasChildren SimpleXMLIterator::hasChildren ============================== (PHP 5, PHP 7, PHP 8) SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements ### Description ``` public SimpleXMLIterator::hasChildren(): bool ``` This method checks whether the current [SimpleXMLIterator](class.simplexmliterator) element has sub-elements. ### Parameters This function has no parameters. ### Return Values **`true`** if the current element has sub-elements, otherwise **`false`** ### Examples **Example #1 Check whether the current element has sub-elements** ``` <?php $xml = <<<XML <books>     <book>         <title>PHP Basics</title>         <author>Jim Smith</author>     </book>     <book>XML basics</book> </books> XML; $xmlIterator = new SimpleXMLIterator( $xml ); for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {     if($xmlIterator->hasChildren()) {         var_dump($xmlIterator->current());     } } ?> ``` The above example will output: ``` object(SimpleXMLIterator)#2 (2) { ["title"]=> string(10) "PHP Basics" ["author"]=> string(9) "Jim Smith" } ``` php PDO::prepare PDO::prepare ============ (PHP 5 >= 5.1.0, PHP 7, PHP 8, PHP 8,PECL pdo >= 0.1.0) PDO::prepare — Prepares a statement for execution and returns a statement object ### Description ``` public PDO::prepare(string $query, array $options = []): PDOStatement|false ``` Prepares an SQL statement to be executed by the [PDOStatement::execute()](pdostatement.execute) method. The statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. Both named and question mark parameter markers cannot be used within the same statement template; only one or the other parameter style. Use these parameters to bind any user-input, do not include the user-input directly in the query. You must include a unique parameter marker for each value you wish to pass in to the statement when you call [PDOStatement::execute()](pdostatement.execute). You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on. > > **Note**: > > > Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters. For example, you cannot bind multiple values to a single parameter in the IN() clause of an SQL statement. > > Calling **PDO::prepare()** and [PDOStatement::execute()](pdostatement.execute) for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information. Also, calling **PDO::prepare()** and [PDOStatement::execute()](pdostatement.execute) helps to prevent SQL injection attacks by eliminating the need to manually quote and escape the parameters. PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other. > **Note**: The parser used for emulated prepared statements and for rewriting named or question mark style parameters supports the non standard backslash escapes for single- and double quotes. That means that terminating quotes immediately preceeded by a backslash are not recognized as such, which may result in wrong detection of parameters causing the prepared statement to fail when it is executed. A work-around is to not use emulated prepares for such SQL queries, and to avoid rewriting of parameters by using a parameter style which is natively supported by the driver. > > As of PHP 7.4.0, question marks can be escaped by doubling them. That means that the `??` string will be translated to `?` when sending the query to the database. ### Parameters `query` This must be a valid SQL statement template for the target database server. `options` This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the `PDO::ATTR_CURSOR` value to `PDO::CURSOR_SCROLL` to request a scrollable cursor. Some drivers have driver-specific options that may be set at prepare-time. ### Return Values If the database server successfully prepares the statement, **PDO::prepare()** returns a [PDOStatement](class.pdostatement) object. If the database server cannot successfully prepare the statement, **PDO::prepare()** returns **`false`** or emits [PDOException](class.pdoexception) (depending on [error handling](https://www.php.net/manual/en/pdo.error-handling.php)). > > **Note**: > > > Emulated prepared statements does not communicate with the database server so **PDO::prepare()** does not check the statement. > > ### Examples **Example #1 SQL statement template with named parameters** ``` <?php /* Execute a prepared statement by passing an array of values */ $sql = 'SELECT name, colour, calories     FROM fruit     WHERE calories < :calories AND colour = :colour'; $sth = $dbh->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]); $sth->execute(['calories' => 150, 'colour' => 'red']); $red = $sth->fetchAll(); /* Array keys can be prefixed with colons ":" too (optional) */ $sth->execute([':calories' => 175, ':colour' => 'yellow']); $yellow = $sth->fetchAll(); ?> ``` **Example #2 SQL statement template with question mark parameters** ``` <?php /* Execute a prepared statement by passing an array of values */ $sth = $dbh->prepare('SELECT name, colour, calories     FROM fruit     WHERE calories < ? AND colour = ?'); $sth->execute([150, 'red']); $red = $sth->fetchAll(); $sth->execute([175, 'yellow']); $yellow = $sth->fetchAll(); ?> ``` **Example #3 SQL statement template with question mark escaped** ``` <?php /* note: this is only valid on PostgreSQL databases */ $sth = $dbh->prepare('SELECT * FROM issues WHERE tag::jsonb ?? ?'); $sth->execute(['feature']); $featureIssues = $sth->fetchAll(); $sth->execute(['performance']); $performanceIssues = $sth->fetchAll(); ?> ``` ### See Also * [PDO::exec()](pdo.exec) - Execute an SQL statement and return the number of affected rows * [PDO::query()](pdo.query) - Prepares and executes an SQL statement without placeholders * [PDOStatement::execute()](pdostatement.execute) - Executes a prepared statement php EvLoop::now EvLoop::now =========== (PECL ev >= 0.2.0) EvLoop::now — Returns the current "event loop time" ### Description ``` public EvLoop::now(): float ``` Returns the current "event loop time", which is the time the event loop received events and started processing them. This timestamp does not change as long as callbacks are being processed, and this is also the base time used for relative timers. You can treat it as the timestamp of the event occurring(or more correctly, libev finding out about it). ### Parameters This function has no parameters. ### Return Values Returns time of the event loop in (fractional) seconds. ### See Also * [Ev::now()](ev.now) - Returns the time when the last iteration of the default event loop has started php inflate_init inflate\_init ============= (PHP 7, PHP 8) inflate\_init — Initialize an incremental inflate context ### Description ``` inflate_init(int $encoding, array $options = []): InflateContext|false ``` Initialize an incremental inflate context with the specified `encoding`. ### Parameters `encoding` One of the **`ZLIB_ENCODING_*`** constants. `options` An associative array which may contain the following elements: level The compression level in range -1..9; defaults to -1. memory The compression memory level in range 1..9; defaults to 8. window The zlib window size (logarithmic) in range 8..15; defaults to 15. strategy One of **`ZLIB_FILTERED`**, **`ZLIB_HUFFMAN_ONLY`**, **`ZLIB_RLE`**, **`ZLIB_FIXED`** or **`ZLIB_DEFAULT_STRATEGY`** (the default). dictionary A string or an array of strings of the preset dictionary (default: no preset dictionary). ### Return Values Returns an inflate context resource (`zlib.inflate`) on success, or **`false`** on failure. ### Errors/Exceptions If an invalid encoding or option is passed to `options`, or the context couldn't be created, an error of level **`E_WARNING`** is generated. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns an [InflateContext](class.inflatecontext) instance now; previously, a resource was returned. | ### Notes **Caution** Unlike [gzinflate()](function.gzinflate), incremental inflate contexts do not constrain the length of the decoded data, so provide no automatic protection against Zip bombs. ### See Also * [inflate\_add()](function.inflate-add) - Incrementally inflate encoded data * [deflate\_init()](function.deflate-init) - Initialize an incremental deflate context
programming_docs
php DOMDocument::loadHTMLFile DOMDocument::loadHTMLFile ========================= (PHP 5, PHP 7, PHP 8) DOMDocument::loadHTMLFile — Load HTML from a file ### Description ``` public DOMDocument::loadHTMLFile(string $filename, int $options = 0): DOMDocument|bool ``` The function parses the HTML document in the file named `filename`. Unlike loading XML, HTML does not have to be well-formed to load. ### Parameters `filename` The path to the HTML file. `options` Since Libxml 2.6.0, you may also use the `options` parameter to specify [additional Libxml parameters](https://www.php.net/manual/en/libxml.constants.php). ### Return Values Returns **`true`** on success or **`false`** on failure. If called statically, returns a [DOMDocument](class.domdocument) or **`false`** on failure. ### Errors/Exceptions If an empty string is passed as the `filename` or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using [libxml's error handling functions](function.libxml-use-internal-errors). Prior to PHP 8.0.0 this method *could* be called statically, but would issue an **`E_DEPRECATED`** error. As of PHP 8.0.0 calling this method statically throws an [Error](class.error) exception While malformed HTML should load successfully, this function may generate **`E_WARNING`** errors when it encounters bad markup. [libxml's error handling functions](function.libxml-use-internal-errors) may be used to handle these errors. ### Examples **Example #1 Creating a Document** ``` <?php $doc = new DOMDocument(); $doc->loadHTMLFile("filename.html"); echo $doc->saveHTML(); ?> ``` ### See Also * [DOMDocument::loadHTML()](domdocument.loadhtml) - Load HTML from a string * [DOMDocument::saveHTML()](domdocument.savehtml) - Dumps the internal document into a string using HTML formatting * [DOMDocument::saveHTMLFile()](domdocument.savehtmlfile) - Dumps the internal document into a file using HTML formatting php chr chr === (PHP 4, PHP 5, PHP 7, PHP 8) chr — Generate a single-byte string from a number ### Description ``` chr(int $codepoint): string ``` Returns a one-character string containing the character specified by interpreting `codepoint` as an unsigned integer. This can be used to create a one-character string in a single-byte encoding such as ASCII, ISO-8859, or Windows 1252, by passing the position of a desired character in the encoding's mapping table. However, note that this function is not aware of any string encoding, and in particular cannot be passed a Unicode code point value to generate a string in a multibyte encoding like UTF-8 or UTF-16. This function complements [ord()](function.ord). ### Parameters `codepoint` An integer between 0 and 255. Values outside the valid range (0..255) will be bitwise and'ed with 255, which is equivalent to the following algorithm: ``` while ($bytevalue < 0) {     $bytevalue += 256; } $bytevalue %= 256; ``` ### Return Values A single-character string containing the specified byte. ### Changelog | Version | Description | | --- | --- | | 7.4.0 | The function no longer silently accepts unsupported `codepoint`s, and casts these to `0`. | ### Examples **Example #1 **chr()** example** ``` <?php // Assumes the string will be used as ASCII or an ASCII-compatible encoding $str = "The string ends in escape: "; $str .= chr(27); /* add an escape character at the end of $str */ /* Often this is more useful */ $str = sprintf("The string ends in escape: %c", 27); ?> ``` **Example #2 Overflow behavior** ``` <?php echo chr(-159), chr(833), PHP_EOL; ?> ``` The above example will output: ``` aA ``` **Example #3 Building a UTF-8 string from individual bytes** ``` <?php $str = chr(240) . chr(159) . chr(144) . chr(152); echo $str; ?> ``` The above example will output: 🐘 ### See Also * [sprintf()](function.sprintf) - Return a formatted string with a format string of `%c` * [ord()](function.ord) * An [» ASCII-table](https://www.man7.org/linux/man-pages/man7/ascii.7.html) * [mb\_chr()](function.mb-chr) * [IntlChar::chr()](intlchar.chr) php SolrCollapseFunction::getMin SolrCollapseFunction::getMin ============================ (PECL solr >= 2.2.0) SolrCollapseFunction::getMin — Returns min parameter ### Description ``` public SolrCollapseFunction::getMin(): string ``` Returns min parameter ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrCollapseFunction::setMin()](solrcollapsefunction.setmin) - Sets the initial size of the collapse data structures when collapsing on a numeric field only php SolrObject::offsetSet SolrObject::offsetSet ===================== (PECL solr >= 0.9.2) SolrObject::offsetSet — Sets the value for a property ### Description ``` public SolrObject::offsetSet(string $property_name, string $property_value): void ``` Sets the value for a property. This is used when the object is treated as an array. This object is read-only. This should never be attempted. ### Parameters `property_name` The name of the property. `property_value` The new value. ### Return Values None. php SolrDocument::merge SolrDocument::merge =================== (PECL solr >= 0.9.2) SolrDocument::merge — Merges source to the current SolrDocument ### Description ``` public SolrDocument::merge(SolrDocument $sourceDoc, bool $overwrite = true): bool ``` Merges source to the current SolrDocument. ### Parameters `sourceDoc` The source document. `overwrite` If this is **`true`** then fields with the same name in the destination document will be overwritten. ### Return Values Returns **`true`** on success or **`false`** on failure. php ImagickDraw::skewX ImagickDraw::skewX ================== (PECL imagick 2, PECL imagick 3) ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction ### Description ``` public ImagickDraw::skewX(float $degrees): bool ``` **Warning**This function is currently not documented; only its argument list is available. Skews the current coordinate system in the horizontal direction. ### Parameters `degrees` degrees to skew ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::skewX()** example** ``` <?php function skewX($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,                 $startX, $startY, $endX, $endY, $skew) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setStrokeWidth(2);     $draw->setFillColor($fillColor);     $draw->rectangle($startX, $startY, $endX, $endY);     $draw->setFillColor($fillModifiedColor);     $draw->skewX($skew);     $draw->rectangle($startX, $startY, $endX, $endY);     $image = new \Imagick();     $image->newImage(500, 500, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php dgettext dgettext ======== (PHP 4, PHP 5, PHP 7, PHP 8) dgettext — Override the current domain ### Description ``` dgettext(string $domain, string $message): string ``` The **dgettext()** function allows you to override the current `domain` for a single message lookup. ### Parameters `domain` The domain `message` The message ### Return Values A string on success. ### See Also * [gettext()](function.gettext) - Lookup a message in the current domain php SeekableIterator::seek SeekableIterator::seek ====================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SeekableIterator::seek — Seeks to a position ### Description ``` public SeekableIterator::seek(int $offset): void ``` Seeks to a given position in the iterator. ### Parameters `offset` The position to seek to. ### Return Values No value is returned. ### Errors/Exceptions Implementations should throw an [OutOfBoundsException](class.outofboundsexception) if the `offset` is not seekable. ### Examples **Example #1 **SeekableIterator::seek()** example** Seek to the item at position 3 in the iterator ([ArrayIterator](class.arrayiterator) implements [SeekableIterator](class.seekableiterator)). ``` <?php $array = array("apple", "banana", "cherry", "damson", "elderberry"); $iterator = new ArrayIterator($array); $iterator->seek(3); echo $iterator->current(); ?> ``` The above example will output something similar to: ``` damson ``` ### See Also * [SeekableIterator](class.seekableiterator) * [Iterator](class.iterator) php mailparse_msg_extract_part_file mailparse\_msg\_extract\_part\_file =================================== (PECL mailparse >= 0.9.0) mailparse\_msg\_extract\_part\_file — Extracts/decodes a message section ### Description ``` mailparse_msg_extract_part_file(resource $mimemail, mixed $filename, callable $callbackfunc = ?): string ``` Extracts/decodes a message section from the supplied filename. The contents of the section will be decoded according to their transfer encoding - base64, quoted-printable and uuencoded text are supported. ### Parameters `mimemail` A valid `MIME` resource, created with [mailparse\_msg\_create()](function.mailparse-msg-create). `filename` Can be a file name or a valid stream resource. `callbackfunc` If set, this must be either a valid callback that will be passed the extracted section, or **`null`** to make this function return the extracted section. If not specified, the contents will be sent to "stdout". ### Return Values If `callbackfunc` is not **`null`** returns **`true`** on success. If `callbackfunc` is set to **`null`**, returns the extracted section as a string. Returns **`false`** on error. ### See Also * [mailparse\_msg\_extract\_part()](function.mailparse-msg-extract-part) - Extracts/decodes a message section * [mailparse\_msg\_extract\_whole\_part\_file()](function.mailparse-msg-extract-whole-part-file) - Extracts a message section including headers without decoding the transfer encoding php ZipArchive::deleteIndex ZipArchive::deleteIndex ======================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0) ZipArchive::deleteIndex — Delete an entry in the archive using its index ### Description ``` public ZipArchive::deleteIndex(int $index): bool ``` Delete an entry in the archive using its index. ### Parameters `index` Index of the entry to delete. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Delete file from archive using its index** ``` <?php $zip = new ZipArchive; if ($zip->open('test.zip') === TRUE) {     $zip->deleteIndex(2);     $zip->close();     echo 'ok'; } else {     echo 'failed'; } ?> ``` php The ReflectionZendExtension class The ReflectionZendExtension class ================================= Introduction ------------ (PHP 5 >= 5.4.0, PHP 7, PHP 8) Class synopsis -------------- class **ReflectionZendExtension** implements [Reflector](class.reflector) { /\* Properties \*/ public string [$name](class.reflectionzendextension#reflectionzendextension.props.name); /\* Methods \*/ public [\_\_construct](reflectionzendextension.construct)(string `$name`) ``` private __clone(): void ``` ``` public static export(string $name, bool $return = ?): string ``` ``` public getAuthor(): string ``` ``` public getCopyright(): string ``` ``` public getName(): string ``` ``` public getURL(): string ``` ``` public getVersion(): string ``` ``` public __toString(): string ``` } Properties ---------- name Name of the extension. Read-only, throws [ReflectionException](class.reflectionexception) in attempt to write. Table of Contents ----------------- * [ReflectionZendExtension::\_\_clone](reflectionzendextension.clone) — Clone handler * [ReflectionZendExtension::\_\_construct](reflectionzendextension.construct) — Constructor * [ReflectionZendExtension::export](reflectionzendextension.export) — Export * [ReflectionZendExtension::getAuthor](reflectionzendextension.getauthor) — Gets author * [ReflectionZendExtension::getCopyright](reflectionzendextension.getcopyright) — Gets copyright * [ReflectionZendExtension::getName](reflectionzendextension.getname) — Gets name * [ReflectionZendExtension::getURL](reflectionzendextension.geturl) — Gets URL * [ReflectionZendExtension::getVersion](reflectionzendextension.getversion) — Gets version * [ReflectionZendExtension::\_\_toString](reflectionzendextension.tostring) — To string handler php PharData::offsetUnset PharData::offsetUnset ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) PharData::offsetUnset — Remove a file from a tar/zip archive ### Description ``` public PharData::offsetUnset(string $localName): void ``` This is an implementation of the [ArrayAccess](class.arrayaccess) interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the [unset()](function.unset) language construct. ### Parameters `localName` The filename (relative path) to modify in the tar/zip archive. ### Return Values No value is returned. ### Errors/Exceptions Throws [PharException](class.pharexception) if there are any problems flushing changes made to the tar/zip archive to disk. ### Examples **Example #1 A **PharData::offsetUnset()** example** ``` <?php $p = new PharData('/path/to/my.zip'); try {     // deletes file.txt from my.zip by calling offsetUnset     unset($p['file.txt']); } catch (Exception $e) {     echo 'Could not delete file.txt: ', $e; } ?> ``` ### See Also * [Phar::offsetUnset()](phar.offsetunset) - Remove a file from a phar php wordwrap wordwrap ======== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) wordwrap — Wraps a string to a given number of characters ### Description ``` wordwrap( string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false ): string ``` Wraps a string to a given number of characters using a string break character. ### Parameters `string` 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_long_words` If the `cut_long_words` is set to **`true`**, the string is always wrapped at or before the specified `width`. So if you have a word that is larger than the given width, it is broken apart. (See second example). When **`false`** the function does not split the word even if the `width` is smaller than the word width. ### Return Values Returns the given string wrapped at the specified length. ### Examples **Example #1 **wordwrap()** example** ``` <?php $text = "The quick brown fox jumped over the lazy dog."; $newtext = wordwrap($text, 20, "<br />\n"); echo $newtext; ?> ``` The above example will output: ``` The quick brown fox<br /> jumped over the lazy<br /> dog. ``` **Example #2 **wordwrap()** example** ``` <?php $text = "A very long woooooooooooord."; $newtext = wordwrap($text, 8, "\n", true); echo "$newtext\n"; ?> ``` The above example will output: ``` A very long wooooooo ooooord. ``` **Example #3 **wordwrap()** example** ``` <?php $text = "A very long woooooooooooooooooord. and something"; $newtext = wordwrap($text, 8, "\n", false); echo "$newtext\n"; ?> ``` The above example will output: ``` A very long woooooooooooooooooord. and something ``` ### See Also * [nl2br()](function.nl2br) - Inserts HTML line breaks before all newlines in a string * [chunk\_split()](function.chunk-split) - Split a string into smaller chunks php QuickHashStringIntHash::loadFromFile QuickHashStringIntHash::loadFromFile ==================================== (No version information available, might only be in Git) QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file ### Description ``` public static QuickHashStringIntHash::loadFromFile(string $filename, int $size = 0, int $options = 0): QuickHashStringIntHash ``` This factory method creates a new hash from a definition file on disk. The file format consists of a signature `'QH\0x21\0'`, the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. The follows another signed 32 bit integer containing the number of bucket lists. After the header and the strings, the elements follow. They are ordered by bucket list so that the keys don't have to be hashed in order to restore the hash. For each bucket list, the following information is stored (all as 32 bit integers): the bucket list index, the number of elements in that list, and then in pairs of two unsigned 32 bit integers the elements, where the first one is the index into the string list containing the keys, and the second one the value. An example could be: **Example #1 QuickHash StringIntHash file format** ``` 00000000 51 48 21 00 02 00 00 00 09 00 00 00 40 00 00 00 |QH!.........@...| 00000010 4f 4e 45 00 4e 49 4e 45 00 07 00 00 00 01 00 00 |ONE.NINE........| 00000020 00 00 00 00 00 01 00 00 00 2f 00 00 00 01 00 00 |........./......| 00000030 00 04 00 00 00 03 00 00 00 |.........| 00000039 ``` **Example #2 QuickHash IntHash file format** ``` header signature ('QH'; key type: 2; value type: 1; filler: \0x00) 00000000 51 48 21 00 number of elements: 00000004 02 00 00 00 length of string values (9 characters): 00000008 09 00 00 00 number of hash bucket lists (this is configured for hashes as argument to the constructor normally, 64 in this case): 0000000C 40 00 00 00 string values: 00000010 4f 4e 45 00 4e 49 4e 45 00 bucket lists: bucket list 1 (with key 7, and 1 element): header: 07 00 00 00 01 00 00 00 elements (key index: 0 ('ONE'), value = 0): 00 00 00 00 01 00 00 00 bucket list 2 (with key 0x2f, and 1 element): header: 2f 00 00 00 01 00 00 00 elements (key index: 4 ('NINE'), value = 3): 04 00 00 00 03 00 00 00 ``` ### Parameters `filename` The filename of the file to read the hash from. `size` The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from `4` to `4194304`. `options` The same options that the class' constructor takes; except that the size option is ignored. It is read from the file format (unlike the [QuickHashIntHash](class.quickhashinthash) and [QuickHashIntStringHash](class.quickhashintstringhash) classes, where it is automatically calculated from the number of entries in the hash.) ### Return Values Returns a new [QuickHashStringIntHash](class.quickhashstringinthash). ### Examples **Example #3 **QuickHashStringIntHash::loadFromFile()** example** ``` <?php $file = dirname( __FILE__ ) . "/simple.hash.string"; $hash = QuickHashStringIntHash::loadFromFile(     $file,     QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC ); foreach( range( 0, 0x0f ) as $key ) {     $i = 48712 + $key * 1631;     $k = base_convert( $i, 10, 36 );     echo $k, ' => ', $hash->get( $k ), "\n"; } ?> ``` The above example will output something similar to: ``` 11l4 => 48712 12uf => 50343 143q => 51974 15d1 => 53605 16mc => 55236 17vn => 56867 194y => 58498 1ae9 => 60129 1bnk => 61760 1cwv => 63391 1e66 => 65022 1ffh => 66653 1gos => 68284 1hy3 => 69915 1j7e => 71546 1kgp => 73177 ```
programming_docs
php date_sunrise date\_sunrise ============= (PHP 5, PHP 7, PHP 8) date\_sunrise — Returns time of sunrise for a given day and location **Warning** This function has been *DEPRECATED* as of PHP 8.1.0. Relying on this function is highly discouraged. Use [date\_sun\_info()](function.date-sun-info) instead. ### Description ``` date_sunrise( int $timestamp, int $returnFormat = SUNFUNCS_RET_STRING, ?float $latitude = null, ?float $longitude = null, ?float $zenith = null, ?float $utcOffset = null ): string|int|float|false ``` **date\_sunrise()** returns the sunrise time for a given day (specified as a `timestamp`) and location. ### Parameters `timestamp` The `timestamp` of the day from which the sunrise time is taken. `returnFormat` **`returnFormat` constants**| constant | description | example | | --- | --- | --- | | SUNFUNCS\_RET\_STRING | returns the result as string | 16:46 | | SUNFUNCS\_RET\_DOUBLE | returns the result as float | 16.78243132 | | SUNFUNCS\_RET\_TIMESTAMP | returns the result as int (timestamp) | 1095034606 | `latitude` Defaults to North, pass in a negative value for South. See also: [date.default\_latitude](https://www.php.net/manual/en/datetime.configuration.php#ini.date.default-latitude) `longitude` Defaults to East, pass in a negative value for West. See also: [date.default\_longitude](https://www.php.net/manual/en/datetime.configuration.php#ini.date.default-longitude) `zenith` `zenith` is the angle between the center of the sun and a line perpendicular to earth's surface. It defaults to [date.sunrise\_zenith](https://www.php.net/manual/en/datetime.configuration.php#ini.date.sunrise-zenith) **Common `zenith` angles**| Angle | Description | | --- | --- | | 90°50' | Sunrise: the point where the sun becomes visible. | | 96° | Civil twilight: conventionally used to signify the start of dawn. | | 102° | Nautical twilight: the point at which the horizon starts being visible at sea. | | 108° | Astronomical twilight: the point at which the sun starts being the source of any illumination. | `utcOffset` Specified in hours. The `utcOffset` is ignored, if `returnFormat` is **`SUNFUNCS_RET_TIMESTAMP`**. ### Return Values Returns the sunrise time in a specified `returnFormat` on success or **`false`** on failure. One potential reason for failure is that the sun does not rise at all, which happens inside the polar circles for part of the year. ### Errors/Exceptions Every call to a date/time function will generate a **`E_WARNING`** if the time zone is not valid. See also [date\_default\_timezone\_set()](function.date-default-timezone-set) ### Changelog | Version | Description | | --- | --- | | 8.1.0 | This function has been deprecated in favor of [date\_sun\_info()](function.date-sun-info). | | 8.0.0 | `latitude`, `longitude`, `zenith` and `utcOffset` are nullable now. | ### Examples **Example #1 **date\_sunrise()** example** ``` <?php /* calculate the sunrise time for Lisbon, Portugal Latitude: 38.4 North Longitude: 9 West Zenith ~= 90 offset: +1 GMT */ echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1); ?> ``` The above example will output something similar to: ``` Mon Dec 20 2004, sunrise time : 08:54 ``` **Example #2 No sunrise** ``` <?php $solstice = strtotime('2017-12-21'); var_dump(date_sunrise($solstice, SUNFUNCS_RET_STRING, 69.245833, -53.537222)); ?> ``` The above example will output: ``` bool(false) ``` ### See Also * [date\_sun\_info()](function.date-sun-info) - Returns an array with information about sunset/sunrise and twilight begin/end php Ds\Set::capacity Ds\Set::capacity ================ (PECL ds >= 1.0.0) Ds\Set::capacity — Returns the current capacity ### Description ``` public Ds\Set::capacity(): int ``` Returns the current capacity. ### Parameters This function has no parameters. ### Return Values The current capacity. ### Examples **Example #1 **Ds\Set::capacity()** example** ``` <?php $set = new \Ds\Set(); var_dump($set->capacity()); $set->push(...range(1, 50)); var_dump($set->capacity()); ?> ``` The above example will output something similar to: ``` int(16) int(64) ``` php Yaf_Router::route Yaf\_Router::route ================== (Yaf >=1.0.0) Yaf\_Router::route — The route purpose ### Description ``` public Yaf_Router::route(Yaf_Request_Abstract $request): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php GearmanClient::wait GearmanClient::wait =================== (PECL gearman >= 0.6.0) GearmanClient::wait — Wait for I/O activity on all connections in a client ### Description ``` public GearmanClient::wait(): bool ``` This waits for activity from any one of the connected servers. ### Parameters This function has no parameters. ### Return Values **`true`** on success **`false`** on an error. ### See Also * [GearmanWorker::wait()](gearmanworker.wait) - Wait for activity from one of the job servers php The SoapVar class The SoapVar class ================= Introduction ------------ (PHP 5, PHP 7, PHP 8) A class representing a variable or object for use with SOAP services. Class synopsis -------------- class **SoapVar** { /\* Properties \*/ public int [$enc\_type](class.soapvar#soapvar.props.enc-type); public [mixed](language.types.declarations#language.types.declarations.mixed) [$enc\_value](class.soapvar#soapvar.props.enc-value) = null; public ?string [$enc\_stype](class.soapvar#soapvar.props.enc-stype) = null; public ?string [$enc\_ns](class.soapvar#soapvar.props.enc-ns) = null; public ?string [$enc\_name](class.soapvar#soapvar.props.enc-name) = null; public ?string [$enc\_namens](class.soapvar#soapvar.props.enc-namens) = null; /\* Methods \*/ public [\_\_construct](soapvar.construct)( [mixed](language.types.declarations#language.types.declarations.mixed) `$data`, ?int `$encoding`, ?string `$typeName` = **`null`**, ?string `$typeNamespace` = **`null`**, ?string `$nodeName` = **`null`**, ?string `$nodeNamespace` = **`null`** ) } Properties ---------- enc\_name enc\_namens enc\_ns enc\_type enc\_stype enc\_value Table of Contents ----------------- * [SoapVar::\_\_construct](soapvar.construct) — SoapVar constructor php mktime mktime ====== (PHP 4, PHP 5, PHP 7, PHP 8) mktime — Get Unix timestamp for a date ### Description ``` mktime( int $hour, ?int $minute = null, ?int $second = null, ?int $month = null, ?int $day = null, ?int $year = null ): int|false ``` Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Any arguments omitted or **`null`** will be set to the current value according to the local date and time. **Warning** Please note that the ordering of arguments is in an odd order: `month`, `day`, `year`, and not in the more reasonable order of `year`, `month`, `day`. Calling **mktime()** without arguments is deprecated. [time()](function.time) can be used to get the current timestamp. ### Parameters `hour` The number of the hour relative to the start of the day determined by `month`, `day` and `year`. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s). `minute` The number of the minute relative to the start of the `hour`. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s). `second` The number of seconds relative to the start of the `minute`. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s). `month` The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s). `day` The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s). `year` The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time\_t is a 32bit signed integer, as most common today, the valid range for `year` is somewhere between 1901 and 2038. ### Return Values **mktime()** returns the Unix timestamp of the arguments given. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `hour` is no longer optional. | | 8.0.0 | `minute`, `second`, `month`, `day` and `year` are nullable now. | ### Examples **Example #1 **mktime()** basic example** ``` <?php // Set the default timezone to use. date_default_timezone_set('UTC'); // Prints: July 1, 2000 is on a Saturday echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000)); // Prints something like: 2006-04-05T01:02:03+00:00 echo date('c', mktime(1, 2, 3, 4, 5, 2006)); ?> ``` **Example #2 **mktime()** example** **mktime()** is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998". ``` <?php echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997)); echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997)); echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998)); echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98)); ?> ``` **Example #3 Last day of a month** The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29". ``` <?php $lastday = mktime(0, 0, 0, 3, 0, 2000); echo strftime("Last day in Feb 2000 is: %d", $lastday); $lastday = mktime(0, 0, 0, 4, -31, 2000); echo strftime("Last day in Feb 2000 is: %d", $lastday); ?> ``` ### See Also * The [DateTimeImmutable](class.datetimeimmutable) class * [checkdate()](function.checkdate) - Validate a Gregorian date * [gmmktime()](function.gmmktime) - Get Unix timestamp for a GMT date * [date()](function.date) - Format a Unix timestamp * [time()](function.time) - Return current Unix timestamp php Yac::add Yac::add ======== (PECL yac >= 1.0.0) Yac::add — Store into cache ### Description ``` public Yac::add(string $keys, mixed $value, int $ttl = 0): bool ``` ``` public Yac::add(array $key_vals): bool ``` Added a item into cache. ### Parameters `keys` string key `value` mixed value, All php value type could be stored except [resource](language.types.resource) `ttl` expire time ### Return Values bool, **`true`** on success, **`false`** on failure > > **Note**: > > > **Yac::add()** may fail if cas lock could not obtain, so, if you need the value to be stored properly, you may write codes like: > > > **Example #1 Make sure the item is stored** > > > ``` > while(!$yac->set("key", "vale)); > ``` > php openssl_csr_sign openssl\_csr\_sign ================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) openssl\_csr\_sign — Sign a CSR with another certificate (or itself) and generate a certificate ### Description ``` openssl_csr_sign( OpenSSLCertificateSigningRequest|string $csr, OpenSSLCertificate|string|null $ca_certificate, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key, int $days, ?array $options = null, int $serial = 0 ): OpenSSLCertificate|false ``` **openssl\_csr\_sign()** generates an x509 certificate from the given CSR. > **Note**: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under [the installation section](https://www.php.net/manual/en/openssl.installation.php) for more information. > > ### Parameters `csr` A CSR previously generated by [openssl\_csr\_new()](function.openssl-csr-new). It can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by [openssl\_csr\_export()](function.openssl-csr-export). `ca_certificate` The generated certificate will be signed by `ca_certificate`. If `ca_certificate` is **`null`**, the generated certificate will be a self-signed certificate. `private_key` `private_key` is the private key that corresponds to `ca_certificate`. `days` `days` specifies the length of time for which the generated certificate will be valid, in days. `options` You can finetune the CSR signing by `options`. See [openssl\_csr\_new()](function.openssl-csr-new) for more information about `options`. `serial` An optional the serial number of issued certificate. If not specified it will default to 0. ### Return Values Returns an [OpenSSLCertificate](class.opensslcertificate) on success, **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was returned. | | 8.0.0 | `csr` accepts an [OpenSSLCertificateSigningRequest](class.opensslcertificatesigningrequest) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509 CSR` was accepted. | | 8.0.0 | `ca_certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was accepted. | | 8.0.0 | `private_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) or [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` or `OpenSSL X.509` was accepted. | ### Examples **Example #1 **openssl\_csr\_sign()** example - signing a CSR (how to implement your own CA)** ``` <?php // Let's assume that this script is set to receive a CSR that has // been pasted into a textarea from another page $csrdata = $_POST["CSR"]; // We will sign the request using our own "certificate authority" // certificate.  You can use any certificate to sign another, but // the process is worthless unless the signing certificate is trusted // by the software/users that will deal with the newly signed certificate // We need our CA cert and its private key $cacert = "file://path/to/ca.crt"; $privkey = array("file://path/to/ca.key", "your_ca_key_passphrase"); $usercert = openssl_csr_sign($csrdata, $cacert, $privkey, 365, array('digest_alg'=>'sha256') ); // Now display the generated certificate so that the user can // copy and paste it into their local configuration (such as a file // to hold the certificate for their SSL server) openssl_x509_export($usercert, $certout); echo $certout; // Show any errors that occurred here while (($e = openssl_error_string()) !== false) {     echo $e . "\n"; } ?> ``` php pg_meta_data pg\_meta\_data ============== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_meta\_data — Get meta data for table ### Description ``` pg_meta_data(PgSql\Connection $connection, string $table_name, bool $extended = false): array|false ``` **pg\_meta\_data()** returns table definition for `table_name` as an array. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. `table_name` The name of the table. `extended` Flag for returning extended meta data. Default to **`false`**. ### Return Values An array of the table definition, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Getting table metadata** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   $meta = pg_meta_data($dbconn, 'authors');   if (is_array($meta)) {       echo '<pre>';       var_dump($meta);       echo '</pre>';   } ?> ``` The above example will output: ``` array(3) { ["author"]=> array(5) { ["num"]=> int(1) ["type"]=> string(7) "varchar" ["len"]=> int(-1) ["not null"]=> bool(false) ["has default"]=> bool(false) } ["year"]=> array(5) { ["num"]=> int(2) ["type"]=> string(4) "int2" ["len"]=> int(2) ["not null"]=> bool(false) ["has default"]=> bool(false) } ["title"]=> array(5) { ["num"]=> int(3) ["type"]=> string(7) "varchar" ["len"]=> int(-1) ["not null"]=> bool(false) ["has default"]=> bool(false) } } ``` ### See Also * [pg\_convert()](function.pg-convert) - Convert associative array values into forms suitable for SQL statements php DOMParentNode::prepend DOMParentNode::prepend ====================== (PHP 8) DOMParentNode::prepend — Prepends nodes before the first child node ### Description ``` public DOMParentNode::prepend(DOMNode|string ...$nodes): void ``` Prepends one or many `nodes` to the list of children before the first child node. ### Parameters `nodes` The nodes to prepend. ### Return Values No value is returned. ### See Also * [DOMParentNode::append()](domparentnode.append) - Appends nodes after the last child node php pg_copy_to pg\_copy\_to ============ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_copy\_to — Copy a table to an array ### Description ``` pg_copy_to( PgSql\Connection $connection, string $table_name, string $separator = "\t", string $null_as = "\\\\N" ): array|false ``` **pg\_copy\_to()** copies a table to an array. It issues `COPY TO` SQL command internally to retrieve records. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. `table_name` Name of the table from which to copy the data into `rows`. `separator` The token that separates values for each field in each element of `rows`. Default is `\t`. `null_as` How SQL `NULL` values are represented in the `rows`. Default is `\\N` (`"\\\\N"`). ### Return Values An array with one element for each line of `COPY` data, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_copy\_to()** example** ``` <?php    $db = pg_connect("dbname=publisher") or die("Could not connect");        $rows = pg_copy_to($db, $table_name);        pg_query($db, "DELETE FROM $table_name");        pg_copy_from($db, $table_name, $rows); ?> ``` ### See Also * [pg\_copy\_from()](function.pg-copy-from) - Insert records into a table from an array php imap_create imap\_create ============ (PHP 4, PHP 5, PHP 7, PHP 8) imap\_create — Alias of [imap\_createmailbox()](function.imap-createmailbox) ### Description This function is an alias of: [imap\_createmailbox()](function.imap-createmailbox).
programming_docs
php curl_exec curl\_exec ========== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) curl\_exec — Perform a cURL session ### Description ``` curl_exec(CurlHandle $handle): string|bool ``` Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set. ### Parameters `handle` A cURL handle returned by [curl\_init()](function.curl-init). ### Return Values Returns **`true`** on success or **`false`** on failure. However, if the **`CURLOPT_RETURNTRANSFER`** option is [set](function.curl-setopt), it will return the result on success, **`false`** on failure. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. > > **Note**: > > > Note that response status codes which indicate errors (such as `404 > Not found`) are not regarded as failure. [curl\_getinfo()](function.curl-getinfo) can be used to check for these. > > ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `handle` expects a [CurlHandle](class.curlhandle) instance now; previously, a resource was expected. | ### Examples **Example #1 Fetching a web page** ``` <?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); ?> ``` ### See Also * [curl\_multi\_exec()](function.curl-multi-exec) - Run the sub-connections of the current cURL handle php streamWrapper::stream_eof streamWrapper::stream\_eof ========================== (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) streamWrapper::stream\_eof — Tests for end-of-file on a file pointer ### Description ``` public streamWrapper::stream_eof(): bool ``` This method is called in response to [feof()](function.feof). ### Parameters This function has no parameters. ### Return Values Should return **`true`** if the read/write position is at the end of the stream and if no more data is available to be read, or **`false`** otherwise. ### Notes **Warning** When reading the whole file (for example, with [file\_get\_contents()](function.file-get-contents)), PHP will call [streamWrapper::stream\_read()](streamwrapper.stream-read) followed by **streamWrapper::stream\_eof()** in a loop but as long as [streamWrapper::stream\_read()](streamwrapper.stream-read) returns a non-empty string, the return value of **streamWrapper::stream\_eof()** is ignored. ### See Also * [feof()](function.feof) - Tests for end-of-file on a file pointer php Imagick::implodeImage Imagick::implodeImage ===================== (PECL imagick 2, PECL imagick 3) Imagick::implodeImage — Creates a new image as a copy ### Description ``` public Imagick::implodeImage(float $radius): bool ``` Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage. ### Parameters `radius` The radius of the implode ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::implodeImage()**** ``` <?php function implodeImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->implodeImage(0.0001);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php socket_getpeername socket\_getpeername =================== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type ### Description ``` socket_getpeername(Socket $socket, string &$address, int &$port = null): bool ``` Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type. ### Parameters `socket` A [Socket](class.socket) instance created with [socket\_create()](function.socket-create) or [socket\_accept()](function.socket-accept). `address` If the given socket is of type **`AF_INET`** or **`AF_INET6`**, **socket\_getpeername()** will return the peers (remote) *IP address* in appropriate notation (e.g. `127.0.0.1` or `fe80::1`) in the `address` parameter and, if the optional `port` parameter is present, also the associated port. If the given socket is of type **`AF_UNIX`**, **socket\_getpeername()** will return the Unix filesystem path (e.g. `/var/run/daemon.sock`) in the `address` parameter. `port` If given, this will hold the port associated to `address`. ### Return Values Returns **`true`** on success or **`false`** on failure. **socket\_getpeername()** may also return **`false`** if the socket type is not any of **`AF_INET`**, **`AF_INET6`**, or **`AF_UNIX`**, in which case the last socket error code is *not* updated. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | ### Notes > > **Note**: > > > **socket\_getpeername()** should not be used with **`AF_UNIX`** sockets created with [socket\_accept()](function.socket-accept). Only sockets created with [socket\_connect()](function.socket-connect) or a primary server socket following a call to [socket\_bind()](function.socket-bind) will return meaningful values. > > > > **Note**: > > > For having **socket\_getpeername()** to return a meaningful value, the socket it is applied upon must of course be one for which the concept of "peer" makes sense. > > ### See Also * [socket\_getsockname()](function.socket-getsockname) - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type * [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error php V8JsException::getJsTrace V8JsException::getJsTrace ========================= (PECL v8js >= 0.1.0) V8JsException::getJsTrace — The getJsTrace purpose ### Description ``` final public V8JsException::getJsTrace(): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php PDOStatement::columnCount PDOStatement::columnCount ========================= (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0) PDOStatement::columnCount — Returns the number of columns in the result set ### Description ``` public PDOStatement::columnCount(): int ``` Use **PDOStatement::columnCount()** to return the number of columns in the result set represented by the PDOStatement object. If the PDOStatement object was returned from [PDO::query()](pdo.query), the column count is immediately available. If the PDOStatement object was returned from [PDO::prepare()](pdo.prepare), an accurate column count will not be available until you invoke [PDOStatement::execute()](pdostatement.execute). ### Parameters This function has no parameters. ### Return Values Returns the number of columns in the result set represented by the PDOStatement object, even if the result set is empty. If there is no result set, **PDOStatement::columnCount()** returns `0`. ### Examples **Example #1 Counting columns** This example demonstrates how **PDOStatement::columnCount()** operates with and without a result set. ``` <?php $dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2'); $sth = $dbh->prepare("SELECT name, colour FROM fruit"); /* Count the number of columns in the (non-existent) result set */ $colcount = $sth->columnCount(); print("Before execute(), result set has $colcount columns (should be 0)\n"); $sth->execute(); /* Count the number of columns in the result set */ $colcount = $sth->columnCount(); print("After execute(), result set has $colcount columns (should be 2)\n"); ?> ``` The above example will output: ``` Before execute(), result set has 0 columns (should be 0) After execute(), result set has 2 columns (should be 2) ``` ### See Also * [PDO::prepare()](pdo.prepare) - Prepares a statement for execution and returns a statement object * [PDOStatement::execute()](pdostatement.execute) - Executes a prepared statement * [PDOStatement::rowCount()](pdostatement.rowcount) - Returns the number of rows affected by the last SQL statement php ArrayIterator::key ArrayIterator::key ================== (PHP 5, PHP 7, PHP 8) ArrayIterator::key — Return current array key ### Description ``` public ArrayIterator::key(): string|int|null ``` This function returns the current array key ### Parameters This function has no parameters. ### Return Values The current array key. ### Examples **Example #1 **ArrayIterator::key()** example** ``` <?php $array = array('key' => 'value'); $arrayobject = new ArrayObject($array); $iterator = $arrayobject->getIterator(); echo $iterator->key(); //key ?> ``` php pg_num_fields pg\_num\_fields =============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_num\_fields — Returns the number of fields in a result ### Description ``` pg_num_fields(PgSql\Result $result): int ``` **pg\_num\_fields()** returns the number of fields (columns) in the [PgSql\Result](class.pgsql-result) instance. > > **Note**: > > > This function used to be called **pg\_numfields()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). ### Return Values The number of fields (columns) in the result. On error, -1 is returned. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_num\_fields()** example** ``` <?php $result = pg_query($conn, "SELECT 1, 2"); $num = pg_num_fields($result); echo $num . " field(s) returned.\n"; ?> ``` The above example will output: ``` 2 field(s) returned. ``` ### See Also * [pg\_num\_rows()](function.pg-num-rows) - Returns the number of rows in a result * [pg\_affected\_rows()](function.pg-affected-rows) - Returns number of affected records (tuples) php apcu_clear_cache apcu\_clear\_cache ================== (PECL apcu >= 4.0.0) apcu\_clear\_cache — Clears the APCu cache ### Description ``` apcu_clear_cache(): bool ``` Clears the cache. ### Parameters This function has no parameters. ### Return Values Returns **`true`** always ### See Also * [apcu\_cache\_info()](function.apcu-cache-info) - Retrieves cached information from APCu's data store php get_parent_class get\_parent\_class ================== (PHP 4, PHP 5, PHP 7, PHP 8) get\_parent\_class — Retrieves the parent class name for object or class ### Description ``` get_parent_class(object|string $object_or_class = ?): string|false ``` Retrieves the parent class name for object or class. ### Parameters `object_or_class` The tested object or class name. This parameter is optional if called from the object's method. ### Return Values Returns the name of the parent class of the class of which `object_or_class` is an instance or the name. > > **Note**: > > > If the object does not have a parent or the class given does not exist **`false`** will be returned. > > If called without parameter outside object, this function returns **`false`**. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | The `object_or_class` parameter now only accepts objects or valid class names. | ### Examples **Example #1 Using **get\_parent\_class()**** ``` <?php class Dad {     function __construct()     {     // implements some logic     } } class Child extends Dad {     function __construct()     {         echo "I'm " , get_parent_class($this) , "'s son\n";     } } class Child2 extends Dad {     function __construct()     {         echo "I'm " , get_parent_class('child2') , "'s son too\n";     } } $foo = new child(); $bar = new child2(); ?> ``` The above example will output: ``` I'm Dad's son I'm Dad's son too ``` ### See Also * [get\_class()](function.get-class) - Returns the name of the class of an object * [is\_subclass\_of()](function.is-subclass-of) - Checks if the object has this class as one of its parents or implements it * [class\_parents()](function.class-parents) - Return the parent classes of the given class php gzseek gzseek ====== (PHP 4, PHP 5, PHP 7, PHP 8) gzseek — Seek on a gz-file pointer ### Description ``` gzseek(resource $stream, int $offset, int $whence = SEEK_SET): int ``` Sets the file position indicator for the given file pointer to the given offset byte into the file stream. Equivalent to calling (in C) `gzseek(zp, offset, SEEK_SET)`. If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; **gzseek()** then compresses a sequence of zeroes up to the new starting position. ### Parameters `stream` The gz-file pointer. It must be valid, and must point to a file successfully opened by [gzopen()](function.gzopen). `offset` The seeked offset. `whence` `whence` values are: * **`SEEK_SET`** - Set position equal to `offset` bytes. * **`SEEK_CUR`** - Set position to current location plus `offset`. If `whence` is not specified, it is assumed to be **`SEEK_SET`**. ### Return Values Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error. ### Examples **Example #1 **gzseek()** example** ``` <?php $gz = gzopen('somefile.gz', 'r'); gzseek($gz,2); echo gzgetc($gz); gzclose($gz); ?> ``` ### See Also * [gztell()](function.gztell) - Tell gz-file pointer read/write position * [gzrewind()](function.gzrewind) - Rewind the position of a gz-file pointer php The Pair class The Pair class ============== Introduction ------------ (No version information available, might only be in Git) A pair is used by **Ds\Map** to pair keys with values. Class synopsis -------------- class **Ds\Pair** implements [JsonSerializable](class.jsonserializable) { /\* Methods \*/ public [\_\_construct](ds-pair.construct)([mixed](language.types.declarations#language.types.declarations.mixed) `$key` = ?, [mixed](language.types.declarations#language.types.declarations.mixed) `$value` = ?) ``` public clear(): void ``` ``` public copy(): Ds\Pair ``` ``` public isEmpty(): bool ``` ``` public toArray(): array ``` } Table of Contents ----------------- * [Ds\Pair::clear](ds-pair.clear) — Removes all values * [Ds\Pair::\_\_construct](ds-pair.construct) — Creates a new instance * [Ds\Pair::copy](ds-pair.copy) — Returns a shallow copy of the pair * [Ds\Pair::isEmpty](ds-pair.isempty) — Returns whether the pair is empty * [Ds\Pair::jsonSerialize](ds-pair.jsonserialize) — Returns a representation that can be converted to JSON * [Ds\Pair::toArray](ds-pair.toarray) — Converts the pair to an array php The PgSql\Result class The PgSql\Result class ====================== Introduction ------------ (PHP 8 >= 8.1.0) A fully opaque class which replaces a `pgsql result` resource as of PHP 8.1.0. Class synopsis -------------- final class **PgSql\Result** { } php Yaf_Response_Abstract::response Yaf\_Response\_Abstract::response ================================= (Yaf >=1.0.0) Yaf\_Response\_Abstract::response — Send response ### Description ``` public Yaf_Response_Abstract::response(): void ``` send response ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 **Yaf\_Response\_Abstract::response()**example** ``` <?php $response = new Yaf_Response_Http(); $response->setBody("Hello")->setBody(" World", "footer"); $response->response(); ?> ``` The above example will output something similar to: ``` Hello World ``` ### See Also * [Yaf\_Response\_Abstract::setBody()](yaf-response-abstract.setbody) - Set content to response * [Yaf\_Response\_Abstract::clearBody()](yaf-response-abstract.clearbody) - Discard all exists response body php SplPriorityQueue::extract SplPriorityQueue::extract ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplPriorityQueue::extract — Extracts a node from top of the heap and sift up ### Description ``` public SplPriorityQueue::extract(): mixed ``` ### Parameters This function has no parameters. ### Return Values The value or priority (or both) of the extracted node, depending on the extract flag. php Pool::collect Pool::collect ============= (PECL pthreads >= 2.0.0) Pool::collect — Collect references to completed tasks ### Description ``` public Pool::collect(Callable $collector = ?): int ``` Allows the pool to collect references determined to be garbage by the optionally given collector. ### Parameters `collector` A Callable collector that returns a boolean on whether the task can be collected or not. Only in rare cases should a custom collector need to be used. ### Return Values The number of remaining tasks in the pool to be collected. ### Changelog | Version | Description | | --- | --- | | v3 | An integer is now returned, and the `collector` parameter is now optional. | ### Examples **Example #1 A basic example of **Pool::collect()**** ``` <?php $pool = new Pool(4); for ($i = 0; $i < 15; ++$i) {     $pool->submit(new class extends Threaded {}); } while ($pool->collect()); // blocks until all tasks have finished executing $pool->shutdown(); ``` php date_interval_format date\_interval\_format ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) date\_interval\_format — Alias of [DateInterval::format()](dateinterval.format) ### Description This function is an alias of: [DateInterval::format()](dateinterval.format) php Ds\Sequence::sorted Ds\Sequence::sorted =================== (PECL ds >= 1.0.0) Ds\Sequence::sorted — Returns a sorted copy ### Description ``` abstract public Ds\Sequence::sorted(callable $comparator = ?): Ds\Sequence ``` Returns a sorted copy, using an optional `comparator` function. ### Parameters `comparator` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` **Caution** Returning *non-integer* values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ### Return Values Returns a sorted copy of the sequence. ### Examples **Example #1 **Ds\Sequence::sorted()** example** ``` <?php $sequence = new \Ds\Vector([4, 5, 1, 3, 2]); print_r($sequence->sorted()); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) ``` **Example #2 **Ds\Sequence::sorted()** example using a comparator** ``` <?php $sequence = new \Ds\Vector([4, 5, 1, 3, 2]); $sorted = $sequence->sorted(function($a, $b) {     return $b <=> $a; }); print_r($sorted); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 ) ```
programming_docs
php RecursiveDirectoryIterator::rewind RecursiveDirectoryIterator::rewind ================================== (PHP 5, PHP 7, PHP 8) RecursiveDirectoryIterator::rewind — Rewind dir back to the start ### Description ``` public RecursiveDirectoryIterator::rewind(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php session_cache_limiter session\_cache\_limiter ======================= (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) session\_cache\_limiter — Get and/or set the current cache limiter ### Description ``` session_cache_limiter(?string $value = null): string|false ``` **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](https://www.php.net/manual/en/session.configuration.php#ini.session.cache-limiter) at request startup time. Thus, you need to call **session\_cache\_limiter()** for every request (and before [session\_start()](function.session-start) is called). ### Parameters `value` If `value` is specified and not **`null`**, 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. On failure to change the value, **`false`** is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `value` is nullable now. | ### Examples **Example #1 **session\_cache\_limiter()** example** ``` <?php /* set the cache limiter to 'private' */ session_cache_limiter('private'); $cache_limiter = session_cache_limiter(); echo "The cache limiter is now set to $cache_limiter<br />"; ?> ``` ### See Also * [session.cache\_limiter](https://www.php.net/manual/en/session.configuration.php#ini.session.cache-limiter) php RecursiveTreeIterator::callHasChildren RecursiveTreeIterator::callHasChildren ====================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::callHasChildren — Has children ### Description ``` public RecursiveTreeIterator::callHasChildren(): bool ``` Called for each element to test whether it has children. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values **`true`** if there are children, otherwise **`false`** php DateTimeImmutable::modify DateTimeImmutable::modify ========================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) DateTimeImmutable::modify — Creates a new object with modified timestamp ### Description ``` public DateTimeImmutable::modify(string $modifier): DateTimeImmutable|false ``` Creates a new [DateTimeImmutable](class.datetimeimmutable) object with modified timestamp. The original object is not modified. ### Parameters `modifier` A date/time string. Valid formats are explained in [Date and Time Formats](https://www.php.net/manual/en/datetime.formats.php). ### Return Values Returns a new modified DateTimeImmutable object or **`false`** on failure. ### Examples **Example #1 **DateTimeImmutable::modify()** example** Object-oriented style ``` <?php $date = new DateTimeImmutable('2006-12-12'); $newDate = $date->modify('+1 day'); echo $newDate->format('Y-m-d'); ?> ``` The above examples will output: ``` 2006-12-13 ``` **Example #2 Beware when adding or subtracting months** ``` <?php $date = new DateTimeImmutable('2000-12-31'); $newDate1 = $date->modify('+1 month'); echo $newDate1->format('Y-m-d') . "\n"; $newDate2 = $newDate1->modify('+1 month'); echo $newDate2->format('Y-m-d') . "\n"; ?> ``` The above example will output: ``` 2001-01-31 2001-03-03 ``` ### See Also * [DateTimeImmutable::add()](datetimeimmutable.add) - Returns a new object, with added amount of days, months, years, hours, minutes and seconds * [DateTimeImmutable::sub()](datetimeimmutable.sub) - Subtracts an amount of days, months, years, hours, minutes and seconds * [DateTimeImmutable::setDate()](datetimeimmutable.setdate) - Sets the date * [DateTimeImmutable::setISODate()](datetimeimmutable.setisodate) - Sets the ISO date * [DateTimeImmutable::setTime()](datetimeimmutable.settime) - Sets the time * [DateTimeImmutable::setTimestamp()](datetimeimmutable.settimestamp) - Sets the date and time based on a Unix timestamp php socket_listen socket\_listen ============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_listen — Listens for a connection on a socket ### Description ``` socket_listen(Socket $socket, int $backlog = 0): bool ``` After the socket `socket` has been created using [socket\_create()](function.socket-create) and bound to a name with [socket\_bind()](function.socket-bind), it may be told to listen for incoming connections on `socket`. **socket\_listen()** is applicable only to sockets of type **`SOCK_STREAM`** or **`SOCK_SEQPACKET`**. ### Parameters `socket` A [Socket](class.socket) instance created with [socket\_create()](function.socket-create) or [socket\_addrinfo\_bind()](function.socket-addrinfo-bind) `backlog` A maximum of `backlog` incoming connections will be queued for processing. If a connection request arrives with the queue full the client may receive an error with an indication of `ECONNREFUSED`, or, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed. > > **Note**: > > > The maximum number passed to the `backlog` parameter highly depends on the underlying platform. On Linux, it is silently truncated to **`SOMAXCONN`**. On win32, if passed **`SOMAXCONN`**, the underlying service provider responsible for the socket will set the backlog to a maximum *reasonable* value. There is no standard provision to find out the actual backlog value on this platform. > > ### Return Values Returns **`true`** on success or **`false`** on failure. The error code can be retrieved with [socket\_last\_error()](function.socket-last-error). This code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual explanation of the error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | ### See Also * [socket\_accept()](function.socket-accept) - Accepts a connection on a socket * [socket\_bind()](function.socket-bind) - Binds a name to a socket * [socket\_connect()](function.socket-connect) - Initiates a connection on a socket * [socket\_create()](function.socket-create) - Create a socket (endpoint for communication) * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error * [socket\_addrinfo\_bind()](function.socket-addrinfo-bind) - Create and bind to a socket from a given addrinfo php SolrQuery::setHighlightSimplePre SolrQuery::setHighlightSimplePre ================================ (PECL solr >= 0.9.2) SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term ### Description ``` public SolrQuery::setHighlightSimplePre(string $simplePre, string $field_override = ?): SolrQuery ``` Sets the text which appears before a highlighted term ``` The default is <em> ``` ### Parameters `simplePre` The text which appears before a highlighted term `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php NumberFormatter::getTextAttribute NumberFormatter::getTextAttribute ================================= numfmt\_get\_text\_attribute ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::getTextAttribute -- numfmt\_get\_text\_attribute — Get a text attribute ### Description Object-oriented style ``` public NumberFormatter::getTextAttribute(int $attribute): string|false ``` Procedural style ``` numfmt_get_text_attribute(NumberFormatter $formatter, int $attribute): string|false ``` Get a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, **`U_UNSUPPORTED_ERROR`** error is produced. Rule-based formatters only understand **`NumberFormatter::DEFAULT_RULESET`** and **`NumberFormatter::PUBLIC_RULESETS`**. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. `attribute` Attribute specifier - one of the [text attribute](class.numberformatter#intl.numberformatter-constants.unumberformattextattribute) constants. ### Return Values Return attribute value on success, or **`false`** on error. ### Examples **Example #1 **numfmt\_get\_text\_attribute()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL ); echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n"; echo numfmt_format($fmt, -1234567.891234567890000)."\n"; numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS"); echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n"; echo numfmt_format($fmt, -1234567.891234567890000)."\n"; ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL ); echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n"; echo $fmt->format(-1234567.891234567890000)."\n"; $fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS"); echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n"; echo $fmt->format(-1234567.891234567890000)."\n"; ?> ``` The above example will output: ``` Prefix: - -1.234.567,891 Prefix: MINUS MINUS1.234.567,891 ``` ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [numfmt\_get\_attribute()](numberformatter.getattribute) - Get an attribute * [numfmt\_set\_text\_attribute()](numberformatter.settextattribute) - Set a text attribute php Yaf_Application::environ Yaf\_Application::environ ========================= (Yaf >=1.0.0) Yaf\_Application::environ — Retrive environ ### Description ``` public Yaf_Application::environ(): void ``` Retrive environ which was defined in yaf.environ which has a default value "product". ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 **Yaf\_Application::environ()**example** ``` <?php $config = array(     "application" => array(         "directory" => realpath(dirname(__FILE__)) . "/application",     ), ); /** Yaf_Application */ $application = new Yaf_Application($config); print_r($application->environ()); ?> ``` The above example will output something similar to: ``` product ``` php The SolrIllegalArgumentException class The SolrIllegalArgumentException class ====================================== Introduction ------------ (PECL solr >= 0.9.2) This object is thrown when an illegal or invalid argument is passed to a method. Class synopsis -------------- class **SolrIllegalArgumentException** extends [SolrException](class.solrexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; protected int [$sourceline](class.solrexception#solrexception.props.sourceline); protected string [$sourcefile](class.solrexception#solrexception.props.sourcefile); protected string [$zif\_name](class.solrexception#solrexception.props.zif-name); /\* Methods \*/ ``` public getInternalInfo(): array ``` /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` ``` public SolrException::getInternalInfo(): array ``` } Table of Contents ----------------- * [SolrIllegalArgumentException::getInternalInfo](solrillegalargumentexception.getinternalinfo) — Returns internal information where the Exception was thrown php XMLWriter::writeDtdEntity XMLWriter::writeDtdEntity ========================= xmlwriter\_write\_dtd\_entity ============================= (PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::writeDtdEntity -- xmlwriter\_write\_dtd\_entity — Write full DTD Entity tag ### Description Object-oriented style ``` public XMLWriter::writeDtdEntity( string $name, string $content, bool $isParam = false, ?string $publicId = null, ?string $systemId = null, ?string $notationData = null ): bool ``` Procedural style ``` xmlwriter_write_dtd_entity( XMLWriter $writer, string $name, string $content, bool $isParam = false, ?string $publicId = null, ?string $systemId = null, ?string $notationData = null ): bool ``` Writes a full DTD entity. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `name` The name of the entity. `content` The content of the entity. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | | 8.0.0 | `publicId`, `systemId` and `notationData` are nullable now. | ### See Also * [XMLWriter::startDtdEntity()](xmlwriter.startdtdentity) - Create start DTD Entity * [XMLWriter::endDtdEntity()](xmlwriter.enddtdentity) - End current DTD Entity php None The Basics ---------- ### class Basic class definitions begin with the keyword `class`, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label, provided it is not a PHP [reserved word](https://www.php.net/manual/en/reserved.php). A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: `^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$`. A class may contain its own [constants](language.oop5.constants), [variables](language.oop5.properties) (called "properties"), and functions (called "methods"). **Example #1 Simple Class definition** ``` <?php class SimpleClass {     // property declaration     public $var = 'a default value';     // method declaration     public function displayVar() {         echo $this->var;     } } ?> ``` The pseudo-variable $this is available when a method is called from within an object context. $this is the value of the calling object. **Warning** Calling a non-static method statically throws an [Error](class.error). Prior to PHP 8.0.0, this would generate a deprecation notice, and $this would be undefined. **Example #2 Some examples of the $this pseudo-variable** ``` <?php class A {     function foo()     {         if (isset($this)) {             echo '$this is defined (';             echo get_class($this);             echo ")\n";         } else {             echo "\$this is not defined.\n";         }     } } class B {     function bar()     {         A::foo();     } } $a = new A(); $a->foo(); A::foo(); $b = new B(); $b->bar(); B::bar(); ?> ``` Output of the above example in PHP 7: ``` $this is defined (A) Deprecated: Non-static method A::foo() should not be called statically in %s on line 27 $this is not defined. Deprecated: Non-static method A::foo() should not be called statically in %s on line 20 $this is not defined. Deprecated: Non-static method B::bar() should not be called statically in %s on line 32 Deprecated: Non-static method A::foo() should not be called statically in %s on line 20 $this is not defined. ``` Output of the above example in PHP 8: ``` $this is defined (A) Fatal error: Uncaught Error: Non-static method A::foo() cannot be called statically in %s :27 Stack trace: #0 {main} thrown in %s on line 27 ``` #### Readonly classes As of PHP 8.2.0, a class can be marked with the readonly modifier. Marking a class as readonly will add the [readonly modifier](language.oop5.properties#language.oop5.properties.readonly-properties) to every declared property, and prevent the creation of [dynamic properties](language.oop5.properties#language.oop5.properties.dynamic-properties). Moreover, it is impossible to add support for them by using the [AllowDynamicProperties](class.allow-dynamic-properties) attribute. Attempting to do so will trigger a compile-time error. ``` <?php #[AllowDynamicProperties] readonly class Foo { } // Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo ?> ``` As neither untyped, nor static properties can be marked with the `readonly` modifier, readonly classes cannot declare them either: ``` <?php readonly class Foo {     public $bar; } // Fatal error: Readonly property Foo::$bar must have type ?> ``` ``` <?php readonly class Foo {     public static int $bar; } // Fatal error: Readonly class Foo cannot declare static properties ?> ``` A readonly class can be [extended](language.oop5.basic#language.oop5.basic.extends) if, and only if, the child class is also a readonly class. ### new To create an instance of a class, the `new` keyword must be used. An object will always be created unless the object has a [constructor](language.oop5.decon) defined that throws an [exception](language.exceptions) on error. Classes should be defined before instantiation (and in some cases this is a requirement). If a string containing the name of a class is used with `new`, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this. > > **Note**: > > > If there are no arguments to be passed to the class's constructor, parentheses after the class name may be omitted. > > **Example #3 Creating an instance** ``` <?php $instance = new SimpleClass(); // This can also be done with a variable: $className = 'SimpleClass'; $instance = new $className(); // new SimpleClass() ?> ``` As of PHP 8.0.0, using `new` with arbitrary expressions is supported. This allows more complex instantiation if the expression produces a string. The expressions must be wrapped in parentheses. **Example #4 Creating an instance using an arbitrary expression** In the given example we show multiple examples of valid arbitrary expressions that produce a class name. This shows a call to a function, string concatenation, and the **`::class`** constant. ``` <?php class ClassA extends \stdClass {} class ClassB extends \stdClass {} class ClassC extends ClassB {} class ClassD extends ClassA {} function getSomeClass(): string {     return 'ClassA'; } var_dump(new (getSomeClass())); var_dump(new ('Class' . 'B')); var_dump(new ('Class' . 'C')); var_dump(new (ClassD::class)); ?> ``` Output of the above example in PHP 8: ``` object(ClassA)#1 (0) { } object(ClassB)#1 (0) { } object(ClassC)#1 (0) { } object(ClassD)#1 (0) { } ``` In the class context, it is possible to create a new object by `new self` and `new parent`. When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by [cloning](language.oop5.cloning) it. **Example #5 Object Assignment** ``` <?php $instance = new SimpleClass(); $assigned   =  $instance; $reference  =& $instance; $instance->var = '$assigned will have this value'; $instance = null; // $instance and $reference become null var_dump($instance); var_dump($reference); var_dump($assigned); ?> ``` The above example will output: ``` NULL NULL object(SimpleClass)#1 (1) { ["var"]=> string(30) "$assigned will have this value" } ``` It's possible to create instances of an object in a couple of ways: **Example #6 Creating new objects** ``` <?php class Test {     static public function getNew()     {         return new static;     } } class Child extends Test {} $obj1 = new Test(); $obj2 = new $obj1; var_dump($obj1 !== $obj2); $obj3 = Test::getNew(); var_dump($obj3 instanceof Test); $obj4 = Child::getNew(); var_dump($obj4 instanceof Child); ?> ``` The above example will output: ``` bool(true) bool(true) bool(true) ``` It is possible to access a member of a newly created object in a single expression: **Example #7 Access member of newly created object** ``` <?php echo (new DateTime())->format('Y'); ?> ``` The above example will output something similar to: ``` 2016 ``` > **Note**: Prior to PHP 7.1, the arguments are not evaluated if there is no constructor function defined. > > ### Properties and methods Class properties and methods live in separate "namespaces", so it is possible to have a property and a method with the same name. Referring to both a property and a method has the same notation, and whether a property will be accessed or a method will be called, solely depends on the context, i.e. whether the usage is a variable access or a function call. **Example #8 Property access vs. method call** ``` <?php class Foo {     public $bar = 'property';          public function bar() {         return 'method';     } } $obj = new Foo(); echo $obj->bar, PHP_EOL, $obj->bar(), PHP_EOL; ``` The above example will output: ``` property method ``` That means that calling an [anonymous function](functions.anonymous) which has been assigned to a property is not directly possible. Instead the property has to be assigned to a variable first, for instance. It is possible to call such a property directly by enclosing it in parentheses. **Example #9 Calling an anonymous function stored in a property** ``` <?php class Foo {     public $bar;          public function __construct() {         $this->bar = function() {             return 42;         };     } } $obj = new Foo(); echo ($obj->bar)(), PHP_EOL; ``` The above example will output: ``` 42 ``` ### extends A class can inherit the constants, methods, and properties of another class by using the keyword `extends` in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class. The inherited constants, methods, and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method or constant as [final](language.oop5.final), they may not be overridden. It is possible to access the overridden methods or static properties by referencing them with [parent::](language.oop5.paamayim-nekudotayim). > **Note**: As of PHP 8.1.0, constants may be declared as final. > > **Example #10 Simple Class Inheritance** ``` <?php class ExtendClass extends SimpleClass {     // Redefine the parent method     function displayVar()     {         echo "Extending class\n";         parent::displayVar();     } } $extended = new ExtendClass(); $extended->displayVar(); ?> ``` The above example will output: ``` Extending class a default value ``` #### Signature compatibility rules When overriding a method, its signature must be compatible with the parent method. Otherwise, a fatal error is emitted, or, prior to PHP 8.0.0, an **`E_WARNING`** level error is generated. A signature is compatible if it respects the [variance](language.oop5.variance) rules, makes a mandatory parameter optional, and if any new parameters are optional. This is known as the Liskov Substitution Principle, or LSP for short. The [constructor](language.oop5.decon#language.oop5.decon.constructor), and `private` methods are exempt from these signature compatibility rules, and thus won't emit a fatal error in case of a signature mismatch. **Example #11 Compatible child methods** ``` <?php class Base {     public function foo(int $a) {         echo "Valid\n";     } } class Extend1 extends Base {     function foo(int $a = 5)     {         parent::foo($a);     } } class Extend2 extends Base {     function foo(int $a, $b = 5)     {         parent::foo($a);     } } $extended1 = new Extend1(); $extended1->foo(); $extended2 = new Extend2(); $extended2->foo(1); ``` The above example will output: ``` Valid Valid ``` The following examples demonstrate that a child method which removes a parameter, or makes an optional parameter mandatory, is not compatible with the parent method. **Example #12 Fatal error when a child method removes a parameter** ``` <?php class Base {     public function foo(int $a = 5) {         echo "Valid\n";     } } class Extend extends Base {     function foo()     {         parent::foo(1);     } } ``` Output of the above example in PHP 8 is similar to: ``` Fatal error: Declaration of Extend::foo() must be compatible with Base::foo(int $a = 5) in /in/evtlq on line 13 ``` **Example #13 Fatal error when a child method makes an optional parameter mandatory** ``` <?php class Base {     public function foo(int $a = 5) {         echo "Valid\n";     } } class Extend extends Base {     function foo(int $a)     {         parent::foo($a);     } } ``` Output of the above example in PHP 8 is similar to: ``` Fatal error: Declaration of Extend::foo(int $a) must be compatible with Base::foo(int $a = 5) in /in/qJXVC on line 13 ``` **Warning** Renaming a method's parameter in a child class is not a signature incompatibility. However, this is discouraged as it will result in a runtime [Error](class.error) if [named arguments](functions.arguments#functions.named-arguments) are used. **Example #14 Error when using named arguments and parameters were renamed in a child class** ``` <?php class A {     public function test($foo, $bar) {} } class B extends A {     public function test($a, $b) {} } $obj = new B; // Pass parameters according to A::test() contract $obj->test(foo: "foo", bar: "bar"); // ERROR! ``` The above example will output something similar to: ``` Fatal error: Uncaught Error: Unknown named parameter $foo in /in/XaaeN:14 Stack trace: #0 {main} thrown in /in/XaaeN on line 14 ``` ### ::class The `class` keyword is also used for class name resolution. To obtain the fully qualified name of a class `ClassName` use `ClassName::class`. This is particularly useful with [namespaced](https://www.php.net/manual/en/language.namespaces.php) classes. **Example #15 Class name resolution** ``` <?php namespace NS {     class ClassName {     }          echo ClassName::class; } ?> ``` The above example will output: ``` NS\ClassName ``` > > **Note**: > > > The class name resolution using `::class` is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case. > > **Example #16 Missing class name resolution** > > > ``` > <?php > print Does\Not\Exist::class; > ?> > ``` > The above example will output: > > > ``` > > Does\Not\Exist > > ``` > As of PHP 8.0.0, the `::class` constant may also be used on objects. This resolution happens at runtime, not compile time. Its effect is the same as calling [get\_class()](function.get-class) on the object. **Example #17 Object name resolution** ``` <?php namespace NS {     class ClassName {     } } $c = new ClassName(); print $c::class; ?> ``` The above example will output: ``` NS\ClassName ``` ### Nullsafe methods and properties As of PHP 8.0.0, properties and methods may also be accessed with the "nullsafe" operator instead: `?->`. The nullsafe operator works the same as property or method access as above, except that if the object being dereferenced is **`null`** then **`null`** will be returned rather than an exception thrown. If the dereference is part of a chain, the rest of the chain is skipped. The effect is similar to wrapping each access in an [is\_null()](function.is-null) check first, but more compact. **Example #18 Nullsafe Operator** ``` <?php // As of PHP 8.0.0, this line: $result = $repository?->getUser(5)?->name; // Is equivalent to the following code block: if (is_null($repository)) {     $result = null; } else {     $user = $repository->getUser(5);     if (is_null($user)) {         $result = null;     } else {         $result = $user->name;     } } ?> ``` > > **Note**: > > > The nullsafe operator is best used when null is considered a valid and expected possible value for a property or method return. For indicating an error, a thrown exception is preferable. > >
programming_docs
php The SimpleXMLElement class The SimpleXMLElement class ========================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Represents an element in an XML document. Class synopsis -------------- class **SimpleXMLElement** implements [Stringable](class.stringable), [Countable](class.countable), [RecursiveIterator](class.recursiveiterator) { /\* Methods \*/ public [\_\_construct](simplexmlelement.construct)( string `$data`, int `$options` = 0, bool `$dataIsURL` = **`false`**, string `$namespaceOrPrefix` = "", bool `$isPrefix` = **`false`** ) ``` public addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void ``` ``` public addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement ``` ``` public asXML(?string $filename = null): string|bool ``` ``` public attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement ``` ``` public children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement ``` ``` public count(): int ``` ``` public getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false ``` ``` public getName(): string ``` ``` public getNamespaces(bool $recursive = false): array ``` ``` public registerXPathNamespace(string $prefix, string $namespace): bool ``` ``` public __toString(): string ``` ``` public xpath(string $expression): array|null|false ``` } Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | **SimpleXMLElement** implements [Stringable](class.stringable), [Countable](class.countable), and [RecursiveIterator](class.recursiveiterator) now. | Table of Contents ----------------- * [SimpleXMLElement::addAttribute](simplexmlelement.addattribute) — Adds an attribute to the SimpleXML element * [SimpleXMLElement::addChild](simplexmlelement.addchild) — Adds a child element to the XML node * [SimpleXMLElement::asXML](simplexmlelement.asxml) — Return a well-formed XML string based on SimpleXML element * [SimpleXMLElement::attributes](simplexmlelement.attributes) — Identifies an element's attributes * [SimpleXMLElement::children](simplexmlelement.children) — Finds children of given node * [SimpleXMLElement::\_\_construct](simplexmlelement.construct) — Creates a new SimpleXMLElement object * [SimpleXMLElement::count](simplexmlelement.count) — Counts the children of an element * [SimpleXMLElement::getDocNamespaces](simplexmlelement.getdocnamespaces) — Returns namespaces declared in document * [SimpleXMLElement::getName](simplexmlelement.getname) — Gets the name of the XML element * [SimpleXMLElement::getNamespaces](simplexmlelement.getnamespaces) — Returns namespaces used in document * [SimpleXMLElement::registerXPathNamespace](simplexmlelement.registerxpathnamespace) — Creates a prefix/ns context for the next XPath query * [SimpleXMLElement::saveXML](simplexmlelement.savexml) — Alias of SimpleXMLElement::asXML * [SimpleXMLElement::\_\_toString](simplexmlelement.tostring) — Returns the string content * [SimpleXMLElement::xpath](simplexmlelement.xpath) — Runs XPath query on XML data php Ds\Stack::clear Ds\Stack::clear =============== (PECL ds >= 1.0.0) Ds\Stack::clear — Removes all values ### Description ``` public Ds\Stack::clear(): void ``` Removes all values from the stack. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Stack::clear()** example** ``` <?php $stack = new \Ds\Stack([1, 2, 3]); print_r($stack); $stack->clear(); print_r($stack); ?> ``` The above example will output something similar to: ``` Ds\Stack Object ( [0] => 3 [1] => 2 [2] => 1 ) Ds\Stack Object ( ) ``` php IntlChar::getIntPropertyValue IntlChar::getIntPropertyValue ============================= (PHP 7, PHP 8) IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point ### Description ``` public static IntlChar::getIntPropertyValue(int|string $codepoint, int $property): ?int ``` Gets the property value for an enumerated or integer Unicode property for a code point. Also returns binary and mask property values. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) `property` The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants). ### Return Values Returns the numeric value that is directly the property value or, for enumerated properties, corresponds to the numeric value of the enumerated constant of the respective property value enumeration type. Returns **`null`** on failure. Returns `0` or `1` (for **`false`**/**`true`**) for binary Unicode properties. Returns a bit-mask for mask properties. Returns `0` if `property` is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point. ### Examples **Example #1 Testing different properties** ``` <?php var_dump(IntlChar::getIntPropertyValue("A", IntlChar::PROPERTY_ALPHABETIC) === 1); var_dump(IntlChar::getIntPropertyValue("[", IntlChar::PROPERTY_BIDI_MIRRORED) === 1); var_dump(IntlChar::getIntPropertyValue("Φ", IntlChar::PROPERTY_BLOCK) === IntlChar::BLOCK_CODE_GREEK); ?> ``` The above example will output: ``` bool(true) bool(true) bool(true) ``` ### See Also * [IntlChar::hasBinaryProperty()](intlchar.hasbinaryproperty) - Check a binary Unicode property for a code point * [IntlChar::getIntPropertyMinValue()](intlchar.getintpropertyminvalue) - Get the min value for a Unicode property * [IntlChar::getIntPropertyMaxValue()](intlchar.getintpropertymaxvalue) - Get the max value for a Unicode property * [IntlChar::getUnicodeVersion()](intlchar.getunicodeversion) - Get the Unicode version php Gmagick::readimage Gmagick::readimage ================== (PECL gmagick >= Unknown) Gmagick::readimage — Reads image from filename ### Description ``` public Gmagick::readimage(string $filename): Gmagick ``` Reads image from filename. ### Parameters `filename` The image filename. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php class_uses class\_uses =========== (PHP 5 >= 5.4.0, PHP 7, PHP 8) class\_uses — Return the traits used by the given class ### Description ``` class_uses(object|string $object_or_class, bool $autoload = true): array|false ``` This function returns an array with the names of the traits that the given `object_or_class` uses. This does however not include any traits used by a parent class. ### Parameters `object_or_class` An object (class instance) or a string (class name). `autoload` Whether to call [\_\_autoload](language.oop5.autoload) by default. ### Return Values An array on success, or **`false`** when the given class doesn't exist. ### Examples **Example #1 **class\_uses()** example** ``` <?php trait foo { } class bar {   use foo; } print_r(class_uses(new bar)); print_r(class_uses('bar')); spl_autoload_register(); // use autoloading to load the 'not_loaded' class print_r(class_uses('not_loaded', true)); ?> ``` The above example will output something similar to: ``` Array ( [foo] => foo ) Array ( [foo] => foo ) Array ( [trait_of_not_loaded] => trait_of_not_loaded ) ``` ### See Also * [class\_parents()](function.class-parents) - Return the parent classes of the given class * [get\_declared\_traits()](function.get-declared-traits) - Returns an array of all declared traits php convert_cyr_string convert\_cyr\_string ==================== (PHP 4, PHP 5, PHP 7) convert\_cyr\_string — Convert from one Cyrillic character set to another **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` convert_cyr_string(string $str, string $from, string $to): string ``` Converts from one Cyrillic character set to another. ### Parameters `str` The string to be converted. `from` The source Cyrillic character set, as a single character. `to` The target Cyrillic character set, as a single character. Supported characters are: * k - koi8-r * w - windows-1251 * i - iso8859-5 * a - x-cp866 * d - x-cp866 * m - x-mac-cyrillic ### Return Values Returns the converted string. ### Notes > **Note**: This function is binary-safe. > > ### See Also * [mb\_convert\_encoding()](function.mb-convert-encoding) - Convert a string from one character encoding to another * [iconv()](function.iconv) - Convert a string from one character encoding to another php IntlDateFormatter::getErrorMessage IntlDateFormatter::getErrorMessage ================================== datefmt\_get\_error\_message ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) IntlDateFormatter::getErrorMessage -- datefmt\_get\_error\_message — Get the error text from the last operation ### Description Object-oriented style ``` public IntlDateFormatter::getErrorMessage(): string ``` Procedural style ``` datefmt_get_error_message(IntlDateFormatter $formatter): string ``` Get the error text from the last operation. ### Parameters `formatter` The formatter resource. ### Return Values Description of the last error. ### Examples **Example #1 **datefmt\_get\_error\_message()** example** ``` <?php $fmt = datefmt_create(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); $str = datefmt_format($fmt); if (!$str) {     printf(         "ERROR: %s (%d)\n",         datefmt_get_error_message($fmt),         datefmt_get_error_code($fmt)     ); } ?> ``` **Example #2 OO example** ``` <?php $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); $str = $fmt->format(); if(!$str) {     printf(         "ERROR: %s (%d)\n",         $fmt->getErrorMessage(),         $fmt->getErrorCode()     ); } ?> ``` The above example will output: ``` ERROR: U_ZERO_ERROR (0) ``` ### See Also * [datefmt\_get\_error\_code()](intldateformatter.geterrorcode) - Get the error code from last operation * [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code * [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure php DateTime::add DateTime::add ============= date\_add ========= (PHP 5 >= 5.3.0, PHP 7, PHP 8) DateTime::add -- date\_add — Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds ### Description Object-oriented style ``` public DateTime::add(DateInterval $interval): DateTime ``` Procedural style ``` date_add(DateTime $object, DateInterval $interval): DateTime ``` Adds the specified [DateInterval](class.dateinterval) object to the specified [DateTime](class.datetime) object. Like [DateTimeImmutable::add()](datetimeimmutable.add) but works with [DateTime](class.datetime). The procedural version takes the [DateTime](class.datetime) object as its first argument. ### Parameters `object` Procedural style only: A [DateTime](class.datetime) object returned by [date\_create()](function.date-create). The function modifies this object. `interval` A [DateInterval](class.dateinterval) object ### Return Values Returns the modified [DateTime](class.datetime) object for method chaining. ### See Also * [DateTimeImmutable::add()](datetimeimmutable.add) - Returns a new object, with added amount of days, months, years, hours, minutes and seconds php GmagickDraw::gettextdecoration GmagickDraw::gettextdecoration ============================== (PECL gmagick >= Unknown) GmagickDraw::gettextdecoration — Returns the text decoration ### Description ``` public GmagickDraw::gettextdecoration(): int ``` Returns the decoration applied when annotating with text. ### Parameters This function has no parameters. ### Return Values Returns one of the DECORATION\_ constants and 0 if no decoration is set. php SolrDocument::offsetExists SolrDocument::offsetExists ========================== (PECL solr >= 0.9.2) SolrDocument::offsetExists — Checks if a particular field exists ### Description ``` public SolrDocument::offsetExists(string $fieldName): bool ``` Checks if a particular field exists. This is used when the object is treated as an array. ### Parameters `fieldName` The name of the field. ### Return Values Returns **`true`** on success or **`false`** on failure. php Ds\Vector::slice Ds\Vector::slice ================ (PECL ds >= 1.0.0) Ds\Vector::slice — Returns a sub-vector of a given range ### Description ``` public Ds\Vector::slice(int $index, int $length = ?): Ds\Vector ``` Creates a sub-vector of a given range. ### Parameters `index` The index at which the sub-vector starts. If positive, the vector will start at that index in the vector. If negative, the vector will start that far from the end. `length` If a length is given and is positive, the resulting vector will have up to that many values in it. If the length results in an overflow, only values up to the end of the vector will be included. If a length is given and is negative, the vector will stop that many values from the end. If a length is not provided, the resulting vector will contain all values between the index and the end of the vector. ### Return Values A sub-vector of the given range. ### Examples **Example #1 **Ds\Vector::slice()** example** ``` <?php $vector = new \Ds\Vector(["a", "b", "c", "d", "e"]); // Slice from 2 onwards print_r($vector->slice(2)); // Slice from 1, for a length of 3 print_r($vector->slice(1, 3)); // Slice from 1 onwards print_r($vector->slice(1)); // Slice from 2 from the end onwards print_r($vector->slice(-2)); // Slice from 1 to 1 from the end print_r($vector->slice(1, -1)); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => c [1] => d [2] => e ) Ds\Vector Object ( [0] => b [1] => c [2] => d ) Ds\Vector Object ( [0] => b [1] => c [2] => d [3] => e ) Ds\Vector Object ( [0] => d [1] => e ) Ds\Vector Object ( [0] => b [1] => c [2] => d ) ``` php fgetcsv fgetcsv ======= (PHP 4, PHP 5, PHP 7, PHP 8) fgetcsv — Gets line from file pointer and parse for CSV fields ### Description ``` fgetcsv( resource $stream, ?int $length = null, string $separator = ",", string $enclosure = "\"", string $escape = "\\" ): array|false ``` Similar to [fgets()](function.fgets) except that **fgetcsv()** parses the line it reads for fields in CSV format and returns an array containing the fields read. > > **Note**: > > > The locale settings are taken into account by this function. If `LC_CTYPE` is e.g. `en_US.UTF-8`, files in one-byte encodings may be read wrongly by this function. > > ### Parameters `stream` A valid file pointer to a file successfully opened by [fopen()](function.fopen), [popen()](function.popen), or [fsockopen()](function.fsockopen). `length` Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). Otherwise the line is split in chunks of `length` characters, unless the split would occur inside an enclosure. Omitting this parameter (or setting it to 0, or **`null`** in PHP 8.0.0 or later) the maximum line length is not limited, which is slightly slower. `separator` The optional `separator` parameter sets the field separator (one single-byte character only). `enclosure` The optional `enclosure` parameter sets the field enclosure character (one single-byte character only). `escape` The optional `escape` parameter sets the escape character (at most one single-byte character). An empty string (`""`) disables the proprietary escape mechanism. > **Note**: Usually an `enclosure` character is escaped inside a field by doubling it; however, the `escape` character can be used as an alternative. So for the default parameter values `""` and `\"` have the same meaning. Other than allowing to escape the `enclosure` character the `escape` character has no special meaning; it isn't even meant to escape itself. > > ### Return Values Returns an indexed array containing the fields read on success, or **`false`** on failure. > > **Note**: > > > A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error. > > > **Note**: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the [auto\_detect\_line\_endings](https://www.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings) run-time configuration option may help resolve the problem. > > ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `length` is now nullable. | | 7.4.0 | The `escape` parameter now also accepts an empty string to disable the proprietary escape mechanism. | ### Examples **Example #1 Read and print the entire contents of a CSV file** ``` <?php $row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) {     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {         $num = count($data);         echo "<p> $num fields in line $row: <br /></p>\n";         $row++;         for ($c=0; $c < $num; $c++) {             echo $data[$c] . "<br />\n";         }     }     fclose($handle); } ?> ``` ### See Also * [str\_getcsv()](function.str-getcsv) - Parse a CSV string into an array * [explode()](function.explode) - Split a string by a string * [file()](function.file) - Reads entire file into an array * [pack()](function.pack) - Pack data into binary string * [fputcsv()](function.fputcsv) - Format line as CSV and write to file pointer php Imagick::clipImagePath Imagick::clipImagePath ====================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::clipImagePath — Description ### Description ``` public Imagick::clipImagePath(string $pathname, string $inside): void ``` Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. Id may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `pathname` `inside` ### Return Values php pcntl_wifstopped pcntl\_wifstopped ================= (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) pcntl\_wifstopped — Checks whether the child process is currently stopped ### Description ``` pcntl_wifstopped(int $status): bool ``` Checks whether the child process which caused the return is currently stopped; this is only possible if the call to [pcntl\_waitpid()](function.pcntl-waitpid) was done using the option `WUNTRACED`. ### Parameters `status` The `status` parameter is the status parameter supplied to a successful call to [pcntl\_waitpid()](function.pcntl-waitpid). ### Return Values Returns **`true`** if the child process which caused the return is currently stopped, **`false`** otherwise. ### See Also * [pcntl\_waitpid()](function.pcntl-waitpid) - Waits on or returns the status of a forked child
programming_docs
php odbc_procedures odbc\_procedures ================ (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_procedures — Get the list of procedures stored in a specific data source ### Description ``` odbc_procedures( resource $odbc, ?string $catalog = null, ?string $schema = null, ?string $procedure = null ): resource|false ``` Lists all procedures in the requested range. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `catalog` The catalog ('qualifier' in ODBC 2 parlance). `schema` The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character. `procedure` The name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character. ### Return Values Returns an ODBC result identifier containing the information or **`false`** on failure. The result set has the following columns: * `PROCEDURE_CAT` * `PROCEDURE_SCHEM` * `PROCEDURE_NAME` * `NUM_INPUT_PARAMS` * `NUM_OUTPUT_PARAMS` * `NUM_RESULT_SETS` * `REMARKS` * `PROCEDURE_TYPE` Drivers can report additional columns. The result set is ordered by `PROCEDURE_CAT`, `PROCEDURE_SCHEMA` and `PROCEDURE_NAME`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Prior to this version, the function could only be called with either one or four arguments. | ### Examples **Example #1 List stored Procedures of a Database** ``` <?php $conn = odbc_connect($dsn, $user, $pass); $procedures = odbc_procedures($conn, $catalog, $schema, '%'); while (($row = odbc_fetch_array($procedures))) {     print_r($row);     break; // further rows omitted for brevity } ?> ``` The above example will output something similar to: ``` Array ( [PROCEDURE_CAT] => TutorialDB [PROCEDURE_SCHEM] => dbo [PROCEDURE_NAME] => GetEmployeeSalesYTD;1 [NUM_INPUT_PARAMS] => -1 [NUM_OUTPUT_PARAMS] => -1 [NUM_RESULT_SETS] => -1 [REMARKS] => [PROCEDURE_TYPE] => 2 ) ``` ### See Also * [odbc\_procedurecolumns()](function.odbc-procedurecolumns) - Retrieve information about parameters to procedures * [odbc\_tables()](function.odbc-tables) - Get the list of table names stored in a specific data source php Yaf_Registry::__construct Yaf\_Registry::\_\_construct ============================ (Yaf >=1.0.0) Yaf\_Registry::\_\_construct — Yaf\_Registry implements singleton ### Description private **Yaf\_Registry::\_\_construct**() ### Parameters This function has no parameters. ### Return Values php xmlrpc_server_create xmlrpc\_server\_create ====================== (PHP 4 >= 4.1.0, PHP 5, PHP 7) xmlrpc\_server\_create — Creates an xmlrpc server ### Description ``` xmlrpc_server_create(): resource ``` **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. **Warning**This function is currently not documented; only its argument list is available. php LimitIterator::rewind LimitIterator::rewind ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) LimitIterator::rewind — Rewind the iterator to the specified starting offset ### Description ``` public LimitIterator::rewind(): void ``` Rewinds the iterator to the starting offset specified in [LimitIterator::\_\_construct()](limititerator.construct). ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [LimitIterator::current()](limititerator.current) - Get current element * [LimitIterator::key()](limititerator.key) - Get current key * [LimitIterator::next()](limititerator.next) - Move the iterator forward * [LimitIterator::seek()](limititerator.seek) - Seek to the given position * [LimitIterator::valid()](limititerator.valid) - Check whether the current element is valid php V8Js::getExtensions V8Js::getExtensions =================== (PECL v8js >= 0.1.0) V8Js::getExtensions — Return an array of registered extensions ### Description ``` public static V8Js::getExtensions(): array ``` This function returns array of Javascript extensions registered using [V8Js::registerExtension()](v8js.registerextension). ### Parameters This function has no parameters. ### Return Values Returns an array of registered extensions or an empty array if there are none. php Ev::depth Ev::depth ========= (PECL ev >= 0.2.0) Ev::depth — Returns recursion depth ### Description ``` final public static Ev::depth(): int ``` The number of times [Ev::run()](ev.run) was entered minus the number of times [Ev::run()](ev.run) was exited normally, in other words, the recursion depth. Outside [Ev::run()](ev.run) , this number is **`0`** . In a callback, this number is **`1`** , unless [Ev::run()](ev.run) was invoked recursively (or from another thread), in which case it is higher. ### Parameters This function has no parameters. ### Return Values **ev\_depth()** returns recursion depth of the default loop. ### See Also * [Ev::iteration()](ev.iteration) - Return the number of times the default event loop has polled for new events php Phar::isBuffering Phar::isBuffering ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk ### Description ``` public Phar::isBuffering(): bool ``` This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to [Phar::stopBuffering()](phar.stopbuffering) is needed to enable saving changes. Phar write buffering is per-archive, buffering active for the `foo.phar` Phar archive does not affect changes to the `bar.phar` Phar archive. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the write operations are being buffer, **`false`** otherwise. ### Examples **Example #1 A **Phar::isBuffering()** example** ``` <?php $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar'); $p2 = new Phar('existingphar.phar'); $p['file1.txt'] = 'hi'; var_dump($p->isBuffering()); var_dump($p2->isBuffering()); ?> =2= <?php $p->startBuffering(); var_dump($p->isBuffering()); var_dump($p2->isBuffering()); $p->stopBuffering(); ?> =3= <?php var_dump($p->isBuffering()); var_dump($p2->isBuffering()); ?> ``` The above example will output: ``` bool(false) bool(false) =2= bool(true) bool(false) =3= bool(false) bool(false) ``` ### See Also * [Phar::startBuffering()](phar.startbuffering) - Start buffering Phar write operations, do not modify the Phar object on disk * [Phar::stopBuffering()](phar.stopbuffering) - Stop buffering write requests to the Phar archive, and save changes to disk php SplFileInfo::getExtension SplFileInfo::getExtension ========================= (PHP 5 >= 5.3.6, PHP 7, PHP 8) SplFileInfo::getExtension — Gets the file extension ### Description ``` public SplFileInfo::getExtension(): string ``` Retrieves the file extension. ### Parameters This function has no parameters. ### Return Values Returns a string containing the file extension, or an empty string if the file has no extension. ### Examples **Example #1 **SplFileInfo::getExtension()** example** ``` <?php $info = new SplFileInfo('foo.txt'); var_dump($info->getExtension()); $info = new SplFileInfo('photo.jpg'); var_dump($info->getExtension()); $info = new SplFileInfo('something.tar.gz'); var_dump($info->getExtension()); ?> ``` The above example will output: ``` string(3) "txt" string(3) "jpg" string(2) "gz" ``` ### Notes > > **Note**: > > > Another way of getting the extension is to use the [pathinfo()](function.pathinfo) function. > > > ``` > <?php > $extension = pathinfo($info->getFilename(), PATHINFO_EXTENSION); > ?> > ``` > ### See Also * [SplFileInfo::getFilename()](splfileinfo.getfilename) - Gets the filename * [SplFileInfo::getBasename()](splfileinfo.getbasename) - Gets the base name of the file * [pathinfo()](function.pathinfo) - Returns information about a file path php LuaClosure::__invoke LuaClosure::\_\_invoke ====================== (PECL lua >=0.9.0) LuaClosure::\_\_invoke — Invoke luaclosure ### Description ``` public LuaClosure::__invoke(mixed ...$args): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `args` ### Return Values ### Examples **Example #1 **LuaClosure::\_\_invoke()**example** ``` <?php $lua = new Lua(); $closure = $lua->eval(<<<CODE     return (function ()         print("hello world")     end) CODE ); $lua->call($closure); $closure(); ?> ``` The above example will output: ``` hello worldhello world ``` php Exception::__construct Exception::\_\_construct ======================== (PHP 5, PHP 7, PHP 8) Exception::\_\_construct — Construct the exception ### Description public **Exception::\_\_construct**(string `$message` = "", int `$code` = 0, ?[Throwable](class.throwable) `$previous` = **`null`**) Constructs the Exception. ### Parameters `message` The Exception message to throw. `code` The Exception code. `previous` The previous exception used for the exception chaining. > **Note**: Calling the constructor of class Exception from a subclass ignores the default arguments, if the properties $code and $message are already set. > > ### Notes > > **Note**: > > > The `message` is *NOT* binary safe. > > php Ds\Set::sorted Ds\Set::sorted ============== (PECL ds >= 1.0.0) Ds\Set::sorted — Returns a sorted copy ### Description ``` public Ds\Set::sorted(callable $comparator = ?): Ds\Set ``` Returns a sorted copy, using an optional `comparator` function. ### Parameters `comparator` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` **Caution** Returning *non-integer* values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ### Return Values Returns a sorted copy of the set. ### Examples **Example #1 **Ds\Set::sorted()** example** ``` <?php $set = new \Ds\Set([4, 5, 1, 3, 2]); print_r($set->sorted()); ?> ``` The above example will output something similar to: ``` Ds\Set Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) ``` **Example #2 **Ds\Set::sorted()** example using a comparator** ``` <?php $set = new \Ds\Set([4, 5, 1, 3, 2]); $sorted = $set->sorted(function($a, $b) {     return $b <=> $a; }); print_r($sorted); ?> ``` The above example will output something similar to: ``` Ds\Set Object ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 ) ``` php ibase_blob_add ibase\_blob\_add ================ (PHP 5, PHP 7 < 7.4.0) ibase\_blob\_add — Add data into a newly created blob ### Description ``` ibase_blob_add(resource $blob_handle, string $data): void ``` **ibase\_blob\_add()** adds data into a blob created with [ibase\_blob\_create()](function.ibase-blob-create). ### Parameters `blob_handle` A blob handle opened with [ibase\_blob\_create()](function.ibase-blob-create). `data` The data to be added. ### Return Values No value is returned. ### See Also * [ibase\_blob\_cancel()](function.ibase-blob-cancel) - Cancel creating blob * [ibase\_blob\_close()](function.ibase-blob-close) - Close blob * [ibase\_blob\_create()](function.ibase-blob-create) - Create a new blob for adding data * [ibase\_blob\_import()](function.ibase-blob-import) - Create blob, copy file in it, and close it php SolrDisMaxQuery::addBigramPhraseField SolrDisMaxQuery::addBigramPhraseField ===================================== (No version information available, might only be in Git) SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter) ### Description ``` public SolrDisMaxQuery::addBigramPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery ``` Adds a Phrase Bigram Field (pf2 parameter) output format: field~slop^boost OR field^boost Slop is optional ### Parameters `field` `boost` `slop` ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::addBigramPhraseField()** example** ``` <?php $dismaxQuery = new SolrDisMaxQuery("lucene"); $dismaxQuery     ->addBigramPhraseField('cat', 2, 5.1)     ->addBigramPhraseField('feature', 4.5) ; echo $dismaxQuery; ?> ``` The above example will output something similar to: ``` q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5 ``` ### See Also * [SolrDisMaxQuery::removeBigramPhraseField()](solrdismaxquery.removebigramphrasefield) - Removes phrase bigram field (pf2 parameter) * [SolrDisMaxQuery::setBigramPhraseFields()](solrdismaxquery.setbigramphrasefields) - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter * [SolrDisMaxQuery::setBigramPhraseSlop()](solrdismaxquery.setbigramphraseslop) - Sets Bigram Phrase Slop (ps2 parameter) php GmagickDraw::polyline GmagickDraw::polyline ===================== (PECL gmagick >= Unknown) GmagickDraw::polyline — Draws a polyline ### Description ``` public GmagickDraw::polyline(array $coordinate_array): GmagickDraw ``` Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates. ### Parameters `coordinate_array` The array of coordinates ### Return Values The [GmagickDraw](class.gmagickdraw) object. php AppendIterator::__construct AppendIterator::\_\_construct ============================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) AppendIterator::\_\_construct — Constructs an AppendIterator ### Description public **AppendIterator::\_\_construct**() Constructs an AppendIterator. ### Parameters This function has no parameters. ### Examples **Example #1 Iterating AppendIterator with foreach** ``` <?php $pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii')); $toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham')); $appendIterator = new AppendIterator; $appendIterator->append($pizzas); $appendIterator->append($toppings); foreach ($appendIterator as $key => $item) {     echo $key . ' => ' . $item . PHP_EOL; } ?> ``` The above example will output: ``` 0 => Margarita 1 => Siciliana 2 => Hawaii 0 => Cheese 1 => Anchovies 2 => Olives 3 => Pineapple 4 => Ham ``` **Example #2 Iterating AppendIterator with the AppendIterator API** ``` <?php $pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii')); $toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham')); $appendIterator = new AppendIterator; $appendIterator->append($pizzas); $appendIterator->append($toppings); while ($appendIterator->valid()) {     printf(         '%s => %s => %s%s',         $appendIterator->getIteratorIndex(),         $appendIterator->key(),         $appendIterator->current(),         PHP_EOL     );     $appendIterator->next(); } ?> ``` The above example will output: ``` 0 => 0 => Margarita 0 => 1 => Siciliana 0 => 2 => Hawaii 1 => 0 => Cheese 1 => 1 => Anchovies 1 => 2 => Olives 1 => 3 => Pineapple 1 => 4 => Ham ``` ### Notes **Caution** When using [iterator\_to\_array()](function.iterator-to-array) to copy the values of the AppendIterator into an array, you have to set the optional `use_key` argument to **`false`**. When `use_key` is not **`false`** any keys reoccurring in inner iterators will get overwritten in the returned array. There is no way to preserve the original keys. ### See Also * [AppendIterator::append()](appenditerator.append) - Appends an iterator php svn_fs_file_contents svn\_fs\_file\_contents ======================= (PECL svn >= 0.1.0) svn\_fs\_file\_contents — Returns a stream to access the contents of a file from a given version of the fs ### Description ``` svn_fs_file_contents(resource $fsroot, string $path): resource ``` **Warning**This function is currently not documented; only its argument list is available. Returns a stream to access the contents of a file from a given version of the fs ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php getimagesize getimagesize ============ (PHP 4, PHP 5, PHP 7, PHP 8) getimagesize — Get the size of an image ### Description ``` getimagesize(string $filename, array &$image_info = null): array|false ``` The **getimagesize()** function will determine the size of any supported given image file and return the dimensions along with the file type and a `height/width` text string to be used inside a normal HTML `IMG` tag and the correspondent HTTP content type. **getimagesize()** can also return some more information in `image_info` parameter. **Caution** This function expects `filename` to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values. Do not use **getimagesize()** to check that a given file is a valid image. Use a purpose-built solution such as the [Fileinfo](https://www.php.net/manual/en/book.fileinfo.php) extension instead. > **Note**: Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain `multiple JPEG 2000 codestreams`. In this case, **getimagesize()** returns the values for the first codestream it encounters in the root of the file. > > > **Note**: The information about icons are retrieved from the icon with the highest bitrate. > > > **Note**: GIF images consist of one or more frames, where each frame may only occupy part of the image. The size of the image which is reported by **getimagesize()** is the overall size (read from the logical screen descriptor). > > ### Parameters `filename` This parameter specifies the file you wish to retrieve information about. It can reference a local file or (configuration permitting) a remote file using one of the [supported streams](https://www.php.net/manual/en/wrappers.php). `image_info` This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed [» IPTC](http://www.iptc.org/) information in the APP13 marker. You can use the [iptcparse()](function.iptcparse) function to parse the binary APP13 marker into something readable. > > **Note**: > > > The `image_info` only supports JFIF files. > > ### Return Values Returns an array with up to 7 elements. Not all image types will include the `channels` and `bits` elements. Index 0 and 1 contains respectively the width and the height of the image. > > **Note**: > > > Some formats may contain no image or may contain multiple images. In these cases, **getimagesize()** might not be able to properly determine the image size. **getimagesize()** will return zero for width and height in these cases. > > Index 2 is one of the [IMAGETYPE\_XXX constants](https://www.php.net/manual/en/image.constants.php) indicating the type of the image. Index 3 is a text string with the correct `height="yyy" width="xxx"` string that can be used directly in an IMG tag. `mime` is the correspondant MIME type of the image. This information can be used to deliver images with the correct HTTP `Content-type` header: **Example #1 **getimagesize()** and MIME types** ``` <?php $size = getimagesize($filename); $fp = fopen($filename, "rb"); if ($size && $fp) {     header("Content-type: {$size['mime']}");     fpassthru($fp);     exit; } else {     // error } ?> ``` `channels` will be 3 for RGB pictures and 4 for CMYK pictures. `bits` is the number of bits for each color. For some image types, the presence of `channels` and `bits` values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table. On failure, **`false`** is returned. ### Errors/Exceptions If accessing the `filename` image is impossible **getimagesize()** will generate an error of level **`E_WARNING`**. On read error, **getimagesize()** will generate an error of level **`E_NOTICE`**. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | Now returns the actual image dimensions, bits and channels of AVIF images; previously, the dimensions were reported as `0x0`, and bits and channels were not reported at all. | | 7.1.0 | Added WebP support. | ### Examples **Example #2 **getimagesize()** example** ``` <?php list($width, $height, $type, $attr) = getimagesize("img/flag.jpg"); echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />"; ?> ``` **Example #3 getimagesize (URL)** ``` <?php $size = getimagesize("http://www.example.com/gifs/logo.gif"); // if the file name has space in it, encode it properly $size = getimagesize("http://www.example.com/gifs/lo%20go.gif"); ?> ``` **Example #4 getimagesize() returning IPTC** ``` <?php $size = getimagesize("testimg.jpg", $info); if (isset($info["APP13"])) {     $iptc = iptcparse($info["APP13"]);     var_dump($iptc); } ?> ``` ### Notes > > **Note**: > > > This function does not require the GD image library. > > > ### See Also * [image\_type\_to\_mime\_type()](function.image-type-to-mime-type) - Get Mime-Type for image-type returned by getimagesize, exif\_read\_data, exif\_thumbnail, exif\_imagetype * [exif\_imagetype()](function.exif-imagetype) - Determine the type of an image * [exif\_read\_data()](function.exif-read-data) - Reads the EXIF headers from an image file * [exif\_thumbnail()](function.exif-thumbnail) - Retrieve the embedded thumbnail of an image * [imagesx()](function.imagesx) - Get image width * [imagesy()](function.imagesy) - Get image height
programming_docs
php apcu_add apcu\_add ========= (PECL apcu >= 4.0.0) apcu\_add — Cache a new variable in the data store ### Description ``` apcu_add(string $key, mixed $var, int $ttl = 0): bool ``` ``` apcu_add(array $values, mixed $unused = NULL, int $ttl = 0): array ``` Caches a variable in the data store, only if it's not already stored. > **Note**: Unlike many other mechanisms in PHP, variables stored using **apcu\_add()** will persist between requests (until the value is removed from the cache). > > ### Parameters `key` Store the variable using this name. `key`s are cache-unique, so attempting to use **apcu\_add()** to store data with a key that already exists will not overwrite the existing data, and will instead return **`false`**. (This is the only difference between **apcu\_add()** and [apcu\_store()](function.apcu-store).) `var` The variable to store `ttl` Time To Live; store `var` in the cache for `ttl` seconds. After the `ttl` has passed, the stored variable will be expunged from the cache (on the next request). If no `ttl` is supplied (or if the `ttl` is `0`), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.). `values` Names in key, variables in value. ### Return Values Returns TRUE if something has effectively been added into the cache, FALSE otherwise. Second syntax returns array with error keys. ### Examples **Example #1 A **apcu\_add()** example** ``` <?php $bar = 'BAR'; apcu_add('foo', $bar); var_dump(apcu_fetch('foo')); echo "\n"; $bar = 'NEVER GETS SET'; apcu_add('foo', $bar); var_dump(apcu_fetch('foo')); echo "\n"; ?> ``` The above example will output: ``` string(3) "BAR" string(3) "BAR" ``` ### See Also * [apcu\_store()](function.apcu-store) - Cache a variable in the data store * [apcu\_fetch()](function.apcu-fetch) - Fetch a stored variable from the cache * [apcu\_delete()](function.apcu-delete) - Removes a stored variable from the cache php dba_open dba\_open ========= (PHP 4, PHP 5, PHP 7, PHP 8) dba\_open — Open database ### Description ``` dba_open( string $path, string $mode, ?string $handler = null, int $permission = 0644, int $map_size = 0, ?int $flags = null ): resource|false ``` **dba\_open()** establishes a database instance for `path` with `mode` using `handler`. ### Parameters `path` Commonly a regular path in your filesystem. `mode` It is `r` for read access, `w` for read/write access to an already existing database, `c` for read/write access and database creation if it doesn't currently exist, and `n` for create, truncate and read/write access. The database is created in BTree mode, other modes (like Hash or Queue) are not supported. Additionally you can set the database lock method with the next char. Use `l` to lock the database with a .lck file or `d` to lock the databasefile itself. It is important that all of your applications do this consistently. If you want to test the access and do not want to wait for the lock you can add `t` as third character. When you are absolutely sure that you do not require database locking you can do so by using `-` instead of `l` or `d`. When none of `d`, `l` or `-` is used, dba will lock on the database file as it would with `d`. > > **Note**: > > > There can only be one writer for one database file. When you use dba on a web server and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table: > > > > > **DBA locking**| already open | `mode` = "rl" | `mode` = "rlt" | `mode` = "wl" | `mode` = "wlt" | `mode` = "rd" | `mode` = "rdt" | `mode` = "wd" | `mode` = "wdt" | > | --- | --- | --- | --- | --- | --- | --- | --- | --- | > | not open | ok | ok | ok | ok | ok | ok | ok | ok | > | `mode` = "rl" | ok | ok | wait | false | illegal | illegal | illegal | illegal | > | `mode` = "wl" | wait | false | wait | false | illegal | illegal | illegal | illegal | > | `mode` = "rd" | illegal | illegal | illegal | illegal | ok | ok | wait | false | > | `mode` = "wd" | illegal | illegal | illegal | illegal | wait | false | wait | false | > > * ok: the second call will be successful. > * wait: the second call waits until [dba\_close()](function.dba-close) is called for the first. > * false: the second call returns false. > * illegal: you must not mix `"l"` and `"d"` modifiers for `mode` parameter. > > `handler` The name of the [handler](https://www.php.net/manual/en/dba.requirements.php) which shall be used for accessing `path`. It is passed all optional parameters given to **dba\_open()** and can act on behalf of them. If `handler` is **`null`**, then the default handler is invoked. `permission` Optional int parameter which is passed to the driver. It has the same meaning as the `permissions` parameter of [chmod()](function.chmod), and defaults to `0644`. The `db1`, `db2`, `db3`, `db4`, `dbm`, `gdbm`, `ndbm`, and `lmdb` drivers support the `permission` parameter. `map_size` Optional int parameter which is passed to the driver. Its value should be a multiple of the page size of the OS, or zero, to use the default map size. Only the `lmdb` driver accepts the `map_size` parameter. `flags` Flags to pass to the database drivers. If **`null`** the default flags will be provided. Currently, only the LMDB driver supports the following flags **`DBA_LMDB_USE_SUB_DIR`** and **`DBA_LMDB_NO_SUB_DIR`**. ### Return Values Returns a positive handle on success or **`false`** on failure. ### Errors/Exceptions **`false`** is returned and an **`E_WARNING`** level error is issued when `handler` is **`null`**, but there is no default handler. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | `flags` is added. | | 8.1.0 | `handler` is now nullable. | | 7.3.14, 7.4.2 | The `lmdb` driver now supports an additional `map_size` parameter. | ### See Also * [dba\_popen()](function.dba-popen) - Open database persistently * [dba\_close()](function.dba-close) - Close a DBA database php mb_str_split mb\_str\_split ============== (PHP 7 >= 7.4.0, PHP 8) mb\_str\_split — Given a multibyte string, return an array of its characters ### Description ``` mb_str_split(string $string, int $length = 1, ?string $encoding = null): array ``` This function will return an array of strings, it is a version of [str\_split()](function.str-split) with support for encodings of variable character size as well as fixed-size encodings of 1,2 or 4 byte characters. If the `length` parameter is specified, the string is broken down into chunks of the specified length in characters (not bytes). The `encoding` parameter can be optionally specified and it is good practice to do so. ### Parameters `string` The string to split into characters or chunks. `length` If specified, each element of the returned array will be composed of multiple characters instead of a single character. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. A string specifying one of the supported encodings. ### Return Values **mb\_str\_split()** returns an array of strings. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | | 8.0.0 | This function no longer returns **`false`** on failure. | ### See Also * [str\_split()](function.str-split) - Convert a string to an array php Ds\Stack::jsonSerialize Ds\Stack::jsonSerialize ======================= (PECL ds >= 1.0.0) Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON See [JsonSerializable::jsonSerialize()](jsonserializable.jsonserialize) > > **Note**: > > > You should never need to call this directly. > > php svn_fs_check_path svn\_fs\_check\_path ==================== (PECL svn >= 0.1.0) svn\_fs\_check\_path — Determines what kind of item lives at path in a given repository fsroot ### Description ``` svn_fs_check_path(resource $fsroot, string $path): int ``` **Warning**This function is currently not documented; only its argument list is available. Determines what kind of item lives at path in a given repository fsroot ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php ob_gzhandler ob\_gzhandler ============= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ob\_gzhandler — ob\_start callback function to gzip output buffer ### Description ``` ob_gzhandler(string $data, int $flags): string|false ``` **ob\_gzhandler()** is intended to be used as a callback function for [ob\_start()](function.ob-start) to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before **ob\_gzhandler()** actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages. If a browser doesn't support compressed pages this function returns **`false`**. ### Parameters `data` `flags` ### Return Values ### Examples **Example #1 **ob\_gzhandler()** example** ``` <?php ob_start("ob_gzhandler"); ?> <html> <body> <p>This should be a compressed page.</p> </body> </html> ``` ### Notes > > **Note**: > > > **ob\_gzhandler()** requires the [zlib](https://www.php.net/manual/en/ref.zlib.php) extension. > > > > **Note**: > > > You cannot use both **ob\_gzhandler()** and [zlib.output\_compression](https://www.php.net/manual/en/zlib.configuration.php#ini.zlib.output-compression). Also note that using [zlib.output\_compression](https://www.php.net/manual/en/zlib.configuration.php#ini.zlib.output-compression) is preferred over **ob\_gzhandler()**. > > ### See Also * [ob\_start()](function.ob-start) - Turn on output buffering * [ob\_end\_flush()](function.ob-end-flush) - Flush (send) the output buffer and turn off output buffering php Worker::shutdown Worker::shutdown ================ (PECL pthreads >= 2.0.0) Worker::shutdown — Shutdown the worker ### Description ``` public Worker::shutdown(): bool ``` Shuts down the worker after executing all of the stacked tasks. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Shutdown the referenced worker** ``` <?php $my = new Worker(); $my->start(); /* stack/execute tasks */ var_dump($my->shutdown()); ``` The above example will output: ``` bool(true) ``` php ReflectionProperty::isPrivate ReflectionProperty::isPrivate ============================= (PHP 5, PHP 7, PHP 8) ReflectionProperty::isPrivate — Checks if property is private ### Description ``` public ReflectionProperty::isPrivate(): bool ``` Checks whether the property is private. ### Parameters This function has no parameters. ### Return Values **`true`** if the property is private, **`false`** otherwise. ### See Also * [ReflectionProperty::isPublic()](reflectionproperty.ispublic) - Checks if property is public * [ReflectionProperty::isProtected()](reflectionproperty.isprotected) - Checks if property is protected * [ReflectionProperty::isReadOnly()](reflectionproperty.isreadonly) - Checks if property is readonly * [ReflectionProperty::isStatic()](reflectionproperty.isstatic) - Checks if property is static php SolrDocument::__unset SolrDocument::\_\_unset ======================= (PECL solr >= 0.9.2) SolrDocument::\_\_unset — Removes a field from the document ### Description ``` public SolrDocument::__unset(string $fieldName): bool ``` Removes a field from the document when the field is access as an object property. ### Parameters `fieldName` The name of the field. ### Return Values Returns **`true`** on success or **`false`** on failure. php enchant_dict_add_to_personal enchant\_dict\_add\_to\_personal ================================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 ) enchant\_dict\_add\_to\_personal — Alias of [enchant\_dict\_add()](function.enchant-dict-add) **Warning**This alias is *DEPRECATED* as of PHP 8.0.0. ### Description This function is an alias of: [enchant\_dict\_add()](function.enchant-dict-add). php assert assert ====== (PHP 4, PHP 5, PHP 7, PHP 8) assert — Checks if assertion is **`false`** ### Description PHP 5 and 7 ``` assert(mixed $assertion, string $description = ?): bool ``` PHP 7 ``` assert(mixed $assertion, Throwable $exception = ?): bool ``` **assert()** will check the given `assertion` and take appropriate action if its result is **`false`**. #### Traditional assertions (PHP 5 and 7) If the `assertion` is given as a string it will be evaluated as PHP code by **assert()**. If you pass a boolean condition as `assertion`, this condition will not show up as parameter to the assertion function which you may have defined with [assert\_options()](function.assert-options). The condition is converted to a string before calling that handler function, and the boolean **`false`** is converted as the empty string. Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be **`true`** and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features. Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated. The behavior of **assert()** may be configured by [assert\_options()](function.assert-options) or by .ini-settings described in that functions manual page. The [assert\_options()](function.assert-options) function and/or **`ASSERT_CALLBACK`** configuration directive allow a callback function to be set to handle failed assertions. **assert()** callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier! The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any — literal values such as 1 or "two" will not be passed via this argument). Users of PHP 5.4.8 and later may also provide a fourth optional argument, which will contain the `description` given to **assert()**, if it was set. #### Expectations (PHP 7 only) **assert()** is a language construct in PHP 7, allowing for the definition of expectations: assertions that take effect in development and testing environments, but are optimised away to have zero cost in production. While [assert\_options()](function.assert-options) can still be used to control behaviour as described above for backward compatibility reasons, PHP 7 only code should use the two new configuration directives to control the behaviour of **assert()** and not call [assert\_options()](function.assert-options). **PHP 7 configuration directives for **assert()**** | Directive | Default value | Possible values | | --- | --- | --- | | [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) | `1` | * `1`: generate and execute code (development mode) * `0`: generate code but jump around it at runtime * `-1`: do not generate code (production mode) | | [assert.exception](https://www.php.net/manual/en/info.configuration.php#ini.assert.exception) | `0` | * `1`: throw when the assertion fails, either by throwing the object provided as the `exception` or by throwing a new [AssertionError](class.assertionerror) object if `exception` wasn't provided * `0`: use or generate a [Throwable](class.throwable) as described above, but only generate a warning based on that object rather than throwing it (compatible with PHP 5 behaviour) | ### Parameters `assertion` The assertion. In PHP 5, this must be either a string to be evaluated or a bool to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result used to indicate whether the assertion succeeded or failed. **Warning** Using string as the `assertion` is *DEPRECATED* as of PHP 7.2.0 and *REMOVED* as of PHP 8.0.0. `description` An optional description that will be included in the failure message if the `assertion` fails. From PHP 7, if no description is provided, a default description equal to the source code for the invocation of **assert()** is provided. `exception` In PHP 7, the second parameter can be a [Throwable](class.throwable) object instead of a descriptive string, in which case this is the object that will be thrown if the assertion fails and the [assert.exception](https://www.php.net/manual/en/info.configuration.php#ini.assert.exception) configuration directive is enabled. ### Return Values **`false`** if the assertion is false, **`true`** otherwise. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | **assert()** will no longer evaluate string arguments, instead they will be treated like any other argument. `assert($a == $b)` should be used instead of `assert('$a == $b')`. The `assert.quiet_eval` php.ini directive and the **`ASSERT_QUIET_EVAL`** constant have also been removed, as they would no longer have any effect. | | 8.0.0 | Declaring a function called `assert()` inside a namespace is no longer allowed, and issues **`E_COMPILE_ERROR`**. | | 7.3.0 | Declaring a function called `assert()` inside a namespace became deprecated. Such declaration now emits an **`E_DEPRECATED`**. | | 7.2.0 | Usage of a string as the `assertion` became deprecated. It now emits an **`E_DEPRECATED`** notice when both [assert.active](https://www.php.net/manual/en/info.configuration.php#ini.assert.active) and [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) are set to `1`. | | 7.0.0 | **assert()** is now a language construct and not a function. `assertion` can now be an expression. The second parameter is now interpreted either as an `exception` (if a [Throwable](class.throwable) object is given), or as the `description` supported from PHP 5.4.8 onwards. | ### Examples #### Traditional assertions (PHP 5 and 7) **Example #1 Handle a failed assertion with a custom handler** ``` <?php // Active assert and make it quiet assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); // Create a handler function function my_assert_handler($file, $line, $code) {     echo "<hr>Assertion Failed:         File '$file'<br />         Line '$line'<br />         Code '$code'<br /><hr />"; } // Set up the callback assert_options(ASSERT_CALLBACK, 'my_assert_handler'); // Make an assertion that should fail assert('mysql_query("")'); ?> ``` **Example #2 Using a custom handler to print a description** ``` <?php // Active assert and make it quiet assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); // Create a handler function function my_assert_handler($file, $line, $code, $desc = null) {     echo "Assertion failed at $file:$line: $code";     if ($desc) {         echo ": $desc";     }     echo "\n"; } // Set up the callback assert_options(ASSERT_CALLBACK, 'my_assert_handler'); // Make an assertion that should fail assert('2 < 1'); assert('2 < 1', 'Two is less than one'); ?> ``` The above example will output: ``` Assertion failed at test.php:21: 2 < 1 Assertion failed at test.php:22: 2 < 1: Two is less than one ``` #### Expectations (PHP 7 only) **Example #3 Expectations without a custom exception** ``` <?php assert(true == false); echo 'Hi!'; ?> ``` With [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) set to 0, the above example will output: ``` Hi! ``` With [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) set to 1 and [assert.exception](https://www.php.net/manual/en/info.configuration.php#ini.assert.exception) set to 0, the above example will output: ``` Warning: assert(): assert(true == false) failed in - on line 2 Hi! ``` With [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) set to 1 and [assert.exception](https://www.php.net/manual/en/info.configuration.php#ini.assert.exception) set to 1, the above example will output: ``` Fatal error: Uncaught AssertionError: assert(true == false) in -:2 Stack trace: #0 -(2): assert(false, 'assert(true == ...') #1 {main} thrown in - on line 2 ``` **Example #4 Expectations with a custom exception** ``` <?php class CustomError extends AssertionError {} assert(true == false, new CustomError('True is not false!')); echo 'Hi!'; ?> ``` With [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) set to 0, the above example will output: ``` Hi! ``` With [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) set to 1 and [assert.exception](https://www.php.net/manual/en/info.configuration.php#ini.assert.exception) set to 0, the above example will output: ``` Warning: assert(): CustomError: True is not false! in -:4 Stack trace: #0 {main} failed in - on line 4 Hi! ``` With [zend.assertions](https://www.php.net/manual/en/ini.core.php#ini.zend.assertions) set to 1 and [assert.exception](https://www.php.net/manual/en/info.configuration.php#ini.assert.exception) set to 1, the above example will output: ``` Fatal error: Uncaught CustomError: True is not false! in -:4 Stack trace: #0 {main} thrown in - on line 4 ``` ### See Also * [assert\_options()](function.assert-options) - Set/get the various assert flags
programming_docs
php GlobIterator::count GlobIterator::count =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) GlobIterator::count — Get the number of directories and files ### Description ``` public GlobIterator::count(): int ``` Gets the number of directories and files found by the glob expression. ### Parameters This function has no parameters. ### Return Values The number of returned directories and files, as an int. ### Examples **Example #1 **GlobIterator::count()** example** ``` <?php $iterator = new GlobIterator('*.xml'); printf("Matched %d item(s)\r\n", $iterator->count()); ?> ``` The above example will output something similar to: ``` Matched 8 item(s) ``` ### See Also * [GlobIterator::\_\_construct()](globiterator.construct) - Construct a directory using glob * [count()](function.count) - Counts all elements in an array or in a Countable object * [glob()](function.glob) - Find pathnames matching a pattern php ReflectionProperty::getDefaultValue ReflectionProperty::getDefaultValue =================================== (PHP 8) ReflectionProperty::getDefaultValue — Returns the default value declared for a property ### Description ``` public ReflectionProperty::getDefaultValue(): mixed ``` Gets the implicit or explicitly declared default value for a property. ### Parameters This function has no parameters. ### Return Values The default value if the property has any default value (including **`null`**). If there is no default value, then **`null`** is returned. It is not possible to differentiate between a **`null`** default value and an unitialized typed property. Use [ReflectionProperty::hasDefaultValue()](reflectionproperty.hasdefaultvalue) to detect the difference. ### Examples **Example #1 **ReflectionProperty::getDefaultValue()** example** ``` <?php class Foo {     public $bar = 1;     public ?int $baz;     public int $boing = 0; } $ro = new ReflectionClass(Foo::class); var_dump($ro->getProperty('bar')->getDefaultValue()); var_dump($ro->getProperty('baz')->getDefaultValue()); var_dump($ro->getProperty('boing')->getDefaultValue()); ?> ``` The above example will output: ``` int(1) NULL int(0) ``` ### See Also * [ReflectionProperty::hasDefaultValue()](reflectionproperty.hasdefaultvalue) - Checks if property has a default value declared php ImagickDraw::skewY ImagickDraw::skewY ================== (PECL imagick 2, PECL imagick 3) ImagickDraw::skewY — Skews the current coordinate system in the vertical direction ### Description ``` public ImagickDraw::skewY(float $degrees): bool ``` **Warning**This function is currently not documented; only its argument list is available. Skews the current coordinate system in the vertical direction. ### Parameters `degrees` degrees to skew ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::skewY()** example** ``` <?php function skewY($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,                 $startX, $startY, $endX, $endY, $skew) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setStrokeWidth(2);     $draw->setFillColor($fillColor);     $draw->rectangle($startX, $startY, $endX, $endY);     $draw->setFillColor($fillModifiedColor);     $draw->skewY($skew);     $draw->rectangle($startX, $startY, $endX, $endY);     $image = new \Imagick();     $image->newImage(500, 500, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php decoct decoct ====== (PHP 4, PHP 5, PHP 7, PHP 8) decoct — Decimal to octal ### Description ``` decoct(int $num): string ``` Returns a string containing an octal representation of the given `num` argument. The largest number that can be converted depends on the platform in use. For 32-bit platforms this is usually `4294967295` in decimal resulting in `37777777777`. For 64-bit platforms this is usually `9223372036854775807` in decimal resulting in `777777777777777777777`. ### Parameters `num` Decimal value to convert ### Return Values Octal string representation of `num` ### Examples **Example #1 **decoct()** example** ``` <?php echo decoct(15) . "\n"; echo decoct(264); ?> ``` The above example will output: ``` 17 410 ``` ### See Also * [octdec()](function.octdec) - Octal to decimal * [decbin()](function.decbin) - Decimal to binary * [dechex()](function.dechex) - Decimal to hexadecimal * [base\_convert()](function.base-convert) - Convert a number between arbitrary bases php gnupg_addsignkey gnupg\_addsignkey ================= (PECL gnupg >= 0.5) gnupg\_addsignkey — Add a key for signing ### Description ``` gnupg_addsignkey(resource $identifier, string $fingerprint, string $passphrase = ?): bool ``` ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. `fingerprint` The fingerprint key. `passphrase` The pass phrase. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Procedural **gnupg\_addsignkey()** example** ``` <?php $res = gnupg_init(); gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test"); ?> ``` **Example #2 OO **gnupg\_addsignkey()** example** ``` <?php $gpg = new gnupg(); $gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test"); ?> ``` php SolrQuery::getMlt SolrQuery::getMlt ================= (PECL solr >= 0.9.2) SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled ### Description ``` public SolrQuery::getMlt(): bool ``` Returns whether or not MoreLikeThis results should be enabled ### Parameters This function has no parameters. ### Return Values Returns a boolean on success and **`null`** if not set. php EventHttp::setMaxHeadersSize EventHttp::setMaxHeadersSize ============================ (PECL event >= 1.4.0-beta) EventHttp::setMaxHeadersSize — Sets maximum HTTP header size ### Description ``` public EventHttp::setMaxHeadersSize( int $value ): void ``` Sets maximum HTTP header size. ### Parameters `value` The header size in bytes. ### Return Values No value is returned. ### See Also * **EventHttp::setMaxHeadersSize()** php ImagickDraw::getVectorGraphics ImagickDraw::getVectorGraphics ============================== (PECL imagick 2, PECL imagick 3) ImagickDraw::getVectorGraphics — Returns a string containing vector graphics ### Description ``` public ImagickDraw::getVectorGraphics(): string ``` **Warning**This function is currently not documented; only its argument list is available. Returns a string which specifies the vector graphics generated by any graphics calls made since the [ImagickDraw](class.imagickdraw) object was instantiated. ### Return Values Returns a string containing the vector graphics. php filter_input filter\_input ============= (PHP 5 >= 5.2.0, PHP 7, PHP 8) filter\_input — Gets a specific external variable by name and optionally filters it ### Description ``` filter_input( int $type, string $var_name, int $filter = FILTER_DEFAULT, array|int $options = 0 ): mixed ``` ### Parameters `type` One of **`INPUT_GET`**, **`INPUT_POST`**, **`INPUT_COOKIE`**, **`INPUT_SERVER`**, or **`INPUT_ENV`**. `var_name` Name of a variable to get. `filter` The ID of the filter to apply. The [Types of filters](https://www.php.net/manual/en/filter.filters.php) manual page lists the available filters. If omitted, **`FILTER_DEFAULT`** will be used, which is equivalent to [**`FILTER_UNSAFE_RAW`**](https://www.php.net/manual/en/filter.filters.sanitize.php). This will result in no filtering taking place by default. `options` Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. ### Return Values Value of the requested variable on success, **`false`** if the filter fails, or **`null`** if the `var_name` variable is not set. If the flag **`FILTER_NULL_ON_FAILURE`** is used, it returns **`false`** if the variable is not set and **`null`** if the filter fails. ### Examples **Example #1 A **filter\_input()** example** ``` <?php $search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS); $search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED); echo "You have searched for $search_html.\n"; echo "<a href='?search=$search_url'>Search again.</a>"; ?> ``` The above example will output something similar to: ``` You have searched for Me &#38; son. <a href='?search=Me%20%26%20son'>Search again.</a> ``` ### See Also * [filter\_var()](function.filter-var) - Filters a variable with a specified filter * [filter\_input\_array()](function.filter-input-array) - Gets external variables and optionally filters them * [filter\_var\_array()](function.filter-var-array) - Gets multiple variables and optionally filters them * [Types of filters](https://www.php.net/manual/en/filter.filters.php) php The Yaf_Route_Regex class The Yaf\_Route\_Regex class =========================== Introduction ------------ (Yaf >=1.0.0) **Yaf\_Route\_Regex** is the most flexible route among the Yaf built-in routes. Class synopsis -------------- class **Yaf\_Route\_Regex** extends [Yaf\_Route\_Interface](class.yaf-route-interface) implements [Yaf\_Route\_Interface](class.yaf-route-interface) { /\* Properties \*/ protected [$\_route](class.yaf-route-regex#yaf-route-regex.props.route); protected [$\_default](class.yaf-route-regex#yaf-route-regex.props.default); protected [$\_maps](class.yaf-route-regex#yaf-route-regex.props.maps); protected [$\_verify](class.yaf-route-regex#yaf-route-regex.props.verify); /\* Methods \*/ public [\_\_construct](yaf-route-regex.construct)( string `$match`, array `$route`, array `$map` = ?, array `$verify` = ?, string `$reverse` = ? ) ``` public assemble(array $info, array $query = ?): ?string ``` ``` public route(Yaf_Request_Abstract $request): bool ``` /\* Inherited methods \*/ ``` abstract public Yaf_Route_Interface::assemble(array $info, array $query = ?): string ``` ``` abstract public Yaf_Route_Interface::route(Yaf_Request_Abstract $request): bool ``` } Properties ---------- \_route \_default \_maps \_verify Table of Contents ----------------- * [Yaf\_Route\_Regex::assemble](yaf-route-regex.assemble) — Assemble a url * [Yaf\_Route\_Regex::\_\_construct](yaf-route-regex.construct) — Yaf\_Route\_Regex constructor * [Yaf\_Route\_Regex::route](yaf-route-regex.route) — The route purpose php Imagick::getPointSize Imagick::getPointSize ===================== (PECL imagick 2 >= 2.1.0, PECL imagick 3) Imagick::getPointSize — Gets point size ### Description ``` public Imagick::getPointSize(): float ``` Returns the objects point size property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer. ### Parameters This function has no parameters. ### Return Values Returns a float containing the point size. ### See Also * [Imagick::setPointSize()](imagick.setpointsize) - Sets point size php SoapServer::__construct SoapServer::\_\_construct ========================= (PHP 5, PHP 7, PHP 8) SoapServer::\_\_construct — SoapServer constructor ### Description public **SoapServer::\_\_construct**(?string `$wsdl`, array `$options` = []) This constructor allows the creation of [SoapServer](class.soapserver) objects in WSDL or non-WSDL mode. ### Parameters `wsdl` To use the SoapServer in WSDL mode, pass the URI of a WSDL file. Otherwise, pass **`null`** and set the `uri` option to the target namespace for the server. `options` Allow setting a default SOAP version (`soap_version`), internal character encoding (`encoding`), and actor URI (`actor`). The `classmap` option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values. The `typemap` option is an array of type mappings. Type mapping is an array with keys `type_name`, `type_ns` (namespace URI), `from_xml` (callback accepting one string parameter) and `to_xml` (callback accepting one object parameter). The `cache_wsdl` option is one of **`WSDL_CACHE_NONE`**, **`WSDL_CACHE_DISK`**, **`WSDL_CACHE_MEMORY`** or **`WSDL_CACHE_BOTH`**. There is also a `features` option which can be set to **`SOAP_WAIT_ONE_WAY_CALLS`**, **`SOAP_SINGLE_ELEMENT_ARRAYS`**, **`SOAP_USE_XSI_ARRAY_TYPE`**. The `send_errors` option can be set to **`false`** to sent a generic error message ("Internal error") instead of the specific error message sent otherwise. ### Examples **Example #1 **SoapServer::\_\_construct()** example** ``` <?php $server = new SoapServer("some.wsdl"); $server = new SoapServer("some.wsdl", array('soap_version' => SOAP_1_2)); $server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C")); $server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1')); $server = new SoapServer(null, array('uri' => "http://test-uri/")); class MyBook {     public $title;     public $author; } $server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook"))); ?> ``` ### See Also * [SoapClient::\_\_construct()](soapclient.construct) - SoapClient constructor php GearmanTask::jobHandle GearmanTask::jobHandle ====================== gearman\_job\_handle ==================== (PECL gearman >= 0.5.0) GearmanTask::jobHandle -- gearman\_job\_handle — Get the job handle ### Description ``` public GearmanTask::jobHandle(): string ``` Returns the job handle for this task. ### Parameters This function has no parameters. ### Return Values The opaque job handle. ### See Also * [GearmanClient::doJobHandle()](gearmanclient.dojobhandle) - Get the job handle for the running task php SplFileInfo::getOwner SplFileInfo::getOwner ===================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getOwner — Gets the owner of the file ### Description ``` public SplFileInfo::getOwner(): int|false ``` Gets the file owner. The owner ID is returned in numerical format. ### Parameters This function has no parameters. ### Return Values The owner id in numerical format on success, or **`false`** on failure. ### Errors/Exceptions Throws [RuntimeException](class.runtimeexception) on error. ### Examples **Example #1 **SplFileInfo::getOwner()** example** ``` <?php $info = new SplFileInfo('file.txt'); print_r(posix_getpwuid($info->getOwner())); ?> ``` ### See Also * [posix\_getpwuid()](function.posix-getpwuid) - Return info about a user by user id * [SplFileInfo::getGroup()](splfileinfo.getgroup) - Gets the file group php None 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](language.types.string#language.types.string.details). > **Note**: On 32-bit builds, a string can be as large as up to 2GB (2147483647 bytes maximum) > > ### Syntax A string literal can be specified in four different ways: * [single quoted](language.types.string#language.types.string.syntax.single) * [double quoted](language.types.string#language.types.string.syntax.double) * [heredoc syntax](language.types.string#language.types.string.syntax.heredoc) * [nowdoc syntax](language.types.string#language.types.string.syntax.nowdoc) #### 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](language.types.string#language.types.string.syntax.double) and [heredoc](language.types.string#language.types.string.syntax.heredoc) syntaxes, [variables](https://www.php.net/manual/en/language.variables.php) and escape sequences for special characters will *not* be expanded when they occur in single quoted strings. > > ``` <?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?> ``` #### Double quoted If the string is enclosed in double-quotes ("), PHP will interpret the following escape sequences for special characters: **Escaped characters**| Sequence | Meaning | | --- | --- | | `\n` | linefeed (LF or 0x0A (10) in ASCII) | | `\r` | carriage return (CR or 0x0D (13) in ASCII) | | `\t` | horizontal tab (HT or 0x09 (9) in ASCII) | | `\v` | vertical tab (VT or 0x0B (11) in ASCII) | | `\e` | escape (ESC or 0x1B (27) in ASCII) | | `\f` | form feed (FF or 0x0C (12) in ASCII) | | `\\` | backslash | | `\$` | dollar sign | | `\"` | double-quote | | `\[0-7]{1,3}` | 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 | As in single quoted strings, escaping any other character will result in the backslash being printed too. The most important feature of double-quoted strings is the fact that variable names will be expanded. See [string parsing](language.types.string#language.types.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 may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Prior to PHP 7.3.0, the closing identifier *must* begin in the first column of the line. Also, the closing identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. **Example #1 Basic Heredoc example as of PHP 7.3.0** ``` <?php // no indentation echo <<<END       a      b     c \n END; // 4 spaces of indentation echo <<<END       a      b     c     END; ``` Output of the above example in PHP 7.3: ``` a b c a b c ``` If the closing identifier is indented further than any lines of the body, then a [ParseError](class.parseerror) will be thrown: **Example #2 Closing identifier must not be indented further than any lines of the body** ``` <?php echo <<<END   a  b c    END; ``` Output of the above example in PHP 7.3: ``` PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4 ``` If the closing identifier is indented, tabs can be used as well, however, tabs and spaces *must not* be intermixed regarding the indentation of the closing identifier and the indentation of the body (up to the closing identifier). In any of these cases, a [ParseError](class.parseerror) will be thrown. These whitespace constraints have been included because mixing tabs and spaces for indentation is harmful to legibility. **Example #3 Different indentation for body (spaces) closing identifier** ``` <?php // All the following code do not work. // different indentation for body (spaces) ending marker (tabs) {     echo <<<END      a         END; } // mixing spaces and tabs in body {     echo <<<END         a      END; } // mixing spaces and tabs in ending marker {     echo <<<END           a          END; } ``` Output of the above example in PHP 7.3: ``` PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8 ``` The closing identifier for the body string is not required to be followed by a semicolon or newline. For example, the following code is allowed as of PHP 7.3.0: **Example #4 Continuing an expression after a closing identifier** ``` <?php $values = [<<<END a   b     c END, 'd e f']; var_dump($values); ``` Output of the above example in PHP 7.3: ``` array(2) { [0] => string(11) "a b c" [1] => string(5) "d e f" } ``` **Warning** If the closing identifier was found at the start of a line, then regardless of whether it was a part of another word, it may be considered as the closing identifier and causes a [ParseError](class.parseerror). **Example #5 Closing identifier in body of the string tends to cause ParseError** ``` <?php $values = [<<<END a b END ING END, 'd e f']; ``` Output of the above example in PHP 7.3: ``` PHP Parse error: syntax error, unexpected identifier "ING", expecting "]" in example.php on line 6 ``` To avoid this problem, it is safe for you to follow the simple rule: *do not choose the closing identifier that appears in the body of the text*. **Warning** Prior to PHP 7.3.0, it is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (`;`). That means especially that the identifier *may not be indented*, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is `\n` on UNIX systems, including macOS. The closing delimiter must also be followed by a newline. If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line. **Example #6 Invalid example, prior to PHP 7.3.0** ``` <?php class foo {     public $bar = <<<EOT bar     EOT; } // Identifier must not be indented ?> ``` **Example #7 Valid example, even if prior to PHP 7.3.0** ``` <?php class foo {     public $bar = <<<EOT bar EOT; } ?> ``` Heredocs containing variables can not be used for initializing class properties. Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings. **Example #8 Heredoc string quoting example** ``` <?php $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD; /* More complex example, with variables. */ class foo {     var $foo;     var $bar;     function __construct()     {         $this->foo = 'Foo';         $this->bar = array('Bar1', 'Bar2', 'Bar3');     } } $foo = new foo(); $name = 'MyName'; echo <<<EOT My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT; ?> ``` The above example will output: ``` My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A ``` It is also possible to use the Heredoc syntax to pass data to function arguments: **Example #9 Heredoc in arguments example** ``` <?php var_dump(array(<<<EOD foobar! EOD )); ?> ``` It's possible to initialize static variables and class properties/constants using the Heredoc syntax: **Example #10 Using Heredoc to initialize static values** ``` <?php // Static variables function foo() {     static $bar = <<<LABEL Nothing in here... LABEL; } // Class properties/constants class foo {     const BAR = <<<FOOBAR Constant example FOOBAR;     public $baz = <<<FOOBAR Property example FOOBAR; } ?> ``` The opening Heredoc identifier may optionally be enclosed in double quotes: **Example #11 Using double quotes in Heredoc** ``` <?php echo <<<"FOOBAR" Hello World! FOOBAR; ?> ``` #### Nowdoc Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but *no parsing is done* inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML `<![CDATA[ ]]>` construct, in that it declares a block of text which is not for parsing. A nowdoc is identified with the same `<<<` sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. `<<<'EOT'`. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier. **Example #12 Nowdoc string quoting example** ``` <?php echo <<<'EOD' Example of string spanning multiple lines using nowdoc syntax. Backslashes are always treated literally, e.g. \\ and \'. EOD; ``` The above example will output: ``` Example of string spanning multiple lines using nowdoc syntax. Backslashes are always treated literally, e.g. \\ and \'. ``` **Example #13 Nowdoc string quoting example with variables** ``` <?php class foo {     public $foo;     public $bar;     function __construct()     {         $this->foo = 'Foo';         $this->bar = array('Bar1', 'Bar2', 'Bar3');     } } $foo = new foo(); $name = 'MyName'; echo <<<'EOT' My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': \x41 EOT; ?> ``` The above example will output: ``` My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': \x41 ``` **Example #14 Static data example** ``` <?php class foo {     public $bar = <<<'EOT' bar EOT; } ?> ``` #### Variable parsing When a string is specified in double quotes or with heredoc, [variables](https://www.php.net/manual/en/language.variables.php) are parsed within it. There are two types of syntax: a [simple](language.types.string#language.types.string.parsing.simple) one and a [complex](language.types.string#language.types.string.parsing.complex) one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort. The complex syntax can be recognised by the curly braces surrounding the expression. ##### Simple syntax If a dollar sign (`$`) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name. ``` <?php $juice = "apple"; echo "He drank some $juice juice.".PHP_EOL; // Invalid. "s" is a valid character for a variable name, but the variable is $juice. echo "He drank some juice made of $juices."; // Valid. Explicitly specify the end of the variable name by enclosing it in braces: echo "He drank some juice made of ${juice}s."; ?> ``` The above example will output: ``` He drank some apple juice. He drank some juice made of . He drank some juice made of apples. ``` Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (`]`) marks the end of the index. The same rules apply to object properties as to simple variables. **Example #15 Simple syntax example** ``` <?php $juices = array("apple", "orange", "koolaid1" => "purple"); echo "He drank some $juices[0] juice.".PHP_EOL; echo "He drank some $juices[1] juice.".PHP_EOL; echo "He drank some $juices[koolaid1] juice.".PHP_EOL; class people {     public $john = "John Smith";     public $jane = "Jane Smith";     public $robert = "Robert Paulsen";     public $smith = "Smith"; } $people = new people(); echo "$people->john drank some $juices[0] juice.".PHP_EOL; echo "$people->john then said hello to $people->jane.".PHP_EOL; echo "$people->john's wife greeted $people->robert.".PHP_EOL; echo "$people->robert greeted the two $people->smiths."; // Won't work ?> ``` The above example will output: ``` He drank some apple juice. He drank some orange juice. He drank some purple juice. John Smith drank some apple juice. John Smith then said hello to Jane Smith. John Smith's wife greeted Robert Paulsen. Robert Paulsen greeted the two . ``` As of PHP 7.1.0 also *negative* numeric indices are supported. **Example #16 Negative numeric indices** ``` <?php $string = 'string'; echo "The character at index -2 is $string[-2].", PHP_EOL; $string[-3] = 'o'; echo "Changing the character at index -3 to o gives $string.", PHP_EOL; ?> ``` The above example will output: ``` The character at index -2 is n. Changing the character at index -3 to o gives strong. ``` For anything more complex, you should use the complex syntax. ##### Complex (curly) syntax This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions. Any scalar variable, array element or object property with a string representation can be included via this syntax. The expression is written the same way as it would appear outside the string, and then wrapped in `{` and `}`. Since `{` can not be escaped, this syntax will only be recognised when the `$` immediately follows the `{`. Use `{\$` to get a literal `{$`. Some examples to make it clear: ``` <?php // Show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: {$arr['key']}"; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong  outside a string. // In other words, it will still work, but only because PHP first looks for a // constant named foo; an error of level E_NOTICE (undefined constant) will be // thrown. echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "This works too: {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; echo "This is the value of the var named by the return value of getName(): {${getName()}}"; echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}"; // Won't work, outputs: This is the return value of getName(): {getName()} echo "This is the return value of getName(): {getName()}"; // Won't work, outputs: C:\folder\{fantastic}.txt echo "C:\folder\{$great}.txt" // Works, outputs: C:\folder\fantastic.txt echo "C:\\folder\\{$great}.txt" ?> ``` It is also possible to access class properties using variables within strings using this syntax. ``` <?php class foo {     var $bar = 'I am bar.'; } $foo = new foo(); $bar = 'bar'; $baz = array('foo', 'bar', 'baz', 'quux'); echo "{$foo->$bar}\n"; echo "{$foo->{$baz[1]}}\n"; ?> ``` The above example will output: ``` I am bar. I am bar. ``` > > **Note**: > > > The value accessed from functions, method calls, static class variables, and class constants inside `{$}` will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces (`{}`) will not work for accessing the return values of functions or methods or the values of class constants or static class variables. > > ``` <?php // Show all errors. error_reporting(E_ALL); class beers {     const softdrink = 'rootbeer';     public static $ale = 'ipa'; } $rootbeer = 'A & W'; $ipa = 'Alexander Keith\'s'; // This works; outputs: I'd like an A & W echo "I'd like an {${beers::softdrink}}\n"; // This works too; outputs: I'd like an Alexander Keith's echo "I'd like an {${beers::$ale}}\n"; ?> ``` #### String access and modification by character Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions [substr()](function.substr) and [substr\_replace()](function.substr-replace) can be used when you want to extract or replace more than 1 character. > **Note**: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted **`E_NOTICE`** for reading (yielding an empty string) and **`E_WARNING`** for writing (leaving the string untouched). > > > **Note**: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0. > > **Warning** Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits **`E_WARNING`**. Only the first character of an assigned string is used. As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly, it assigned a NULL byte. **Warning** Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1. > **Note**: As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal error. Formerly, the empty string was silently converted to an array. > > **Example #17 Some string examples** ``` <?php // Get the first character of a string $str = 'This is a test.'; $first = $str[0]; // Get the third character of a string $third = $str[2]; // Get the last character of a string. $str = 'This is still a test.'; $last = $str[strlen($str)-1]; // Modify the last character of a string $str = 'Look at the sea'; $str[strlen($str)-1] = 'e'; ?> ``` String offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. **Example #18 Example of Illegal String Offsets** ``` <?php $str = 'abc'; var_dump($str['1']); var_dump(isset($str['1'])); var_dump($str['1.0']); var_dump(isset($str['1.0'])); var_dump($str['x']); var_dump(isset($str['x'])); var_dump($str['1x']); var_dump(isset($str['1x'])); ?> ``` The above example will output: ``` 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**: > > > Characters within string literals can be accessed using `[]` or `{}`. > > > > **Note**: > > > Accessing characters within string literals using the `{}` syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0. > > ### Useful functions and operators Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will *not* work for this. See [String operators](language.operators.string) for more information. There are a number of useful functions for string manipulation. See the [string functions section](https://www.php.net/manual/en/ref.strings.php) for general functions, and the [Perl-compatible regular expression functions](https://www.php.net/manual/en/ref.pcre.php) for advanced find & replace functionality. There are also [functions for URL strings](https://www.php.net/manual/en/ref.url.php), and functions to encrypt/decrypt strings ([Sodium](https://www.php.net/manual/en/ref.sodium.php) and [Hash](https://www.php.net/manual/en/ref.hash.php)). Finally, see also the [character type functions](https://www.php.net/manual/en/ref.ctype.php). ### Converting to string A value can be converted to a string using the `(string)` cast or the [strval()](function.strval) function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the [echo](function.echo) or [print](function.print) functions, or when a variable is compared to a string. The sections on [Types](https://www.php.net/manual/en/language.types.php) and [Type Juggling](language.types.type-juggling) will make the following clearer. See also the [settype()](function.settype) function. A bool **`true`** value is converted to the string `"1"`. bool **`false`** is converted to `""` (the empty string). This allows conversion back and forth between bool and string values. An int or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (`4.1E+6`). > > **Note**: > > > As of PHP 8.0.0, the decimal point character is always `.`. Prior to PHP 8.0.0, the decimal point character is defined in the script's locale (category LC\_NUMERIC). See the [setlocale()](function.setlocale) function. > > Arrays are always converted to the string `"Array"`; because of this, [echo](function.echo) and [print](function.print) can not by themselves show the contents of an array. To view a single element, use a construction such as `echo $arr['foo']`. See below for tips on viewing the entire contents. In order to convert objects to string, the magic method [\_\_toString](language.oop5.magic) 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.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()](function.print-r) and [var\_dump()](function.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.serialize) function. ### Details of the String Type The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value `0` (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.) This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings. Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string `"á"` equivalent to `"\xE1"` (ISO-8859-1), `"\xC3\xA1"` (UTF-8, C form), `"\x61\xCC\x81"` (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicitly declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic. Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions: * Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, [substr()](function.substr), [strpos()](function.strpos), [strlen()](function.strlen) or [strcmp()](function.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()](function.htmlentities) and the majority of the functions in the [mbstring](https://www.php.net/manual/en/book.mbstring.php) extension. * Others use the current locale (see [setlocale()](function.setlocale)), but operate byte-by-byte. * Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the [intl](https://www.php.net/manual/en/book.intl.php) extension and in the [PCRE](https://www.php.net/manual/en/book.pcre.php) extension (in the last case, only when the `u` modifier is used). Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the [intl](https://www.php.net/manual/en/book.intl.php) and [mbstring](https://www.php.net/manual/en/book.mbstring.php) 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.
programming_docs
php Imagick::getHomeURL Imagick::getHomeURL =================== (PECL imagick 2, PECL imagick 3) Imagick::getHomeURL — Returns the ImageMagick home URL ### Description ``` public static Imagick::getHomeURL(): string ``` Returns the ImageMagick home URL. ### Parameters This function has no parameters. ### Return Values Returns a link to the imagemagick homepage. php DirectoryIterator::__toString DirectoryIterator::\_\_toString =============================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::\_\_toString — Get file name as a string ### Description ``` public DirectoryIterator::__toString(): string ``` Get the file name of the current [DirectoryIterator](class.directoryiterator) item. ### Parameters This function has no parameters. ### Return Values Returns the file name of the current [DirectoryIterator](class.directoryiterator) item. ### Examples **Example #1 A **DirectoryIterator::\_\_toString()** example** This example will list the contents of the directory containing the script. ``` <?php $dir = new DirectoryIterator(dirname(__FILE__)); foreach ($dir as $fileinfo) {     echo $fileinfo; } ?> ``` The above example will output something similar to: ``` . .. apple.jpg banana.jpg index.php pear.jpg ``` ### See Also * [DirectoryIterator::getFilename()](directoryiterator.getfilename) - Return file name of current DirectoryIterator item * The [\_\_toString()](language.oop5.magic#object.tostring) magic method php The AllowDynamicProperties class The AllowDynamicProperties class ================================ Introduction ------------ (PHP 8 >= 8.2.0) This attribute is used to mark classes that allow [dynamic properties](language.oop5.properties#language.oop5.properties.dynamic-properties). Class synopsis -------------- final class **AllowDynamicProperties** { } Examples -------- Dynamic properties are deprecated as of PHP 8.2.0, thus using them without marking the class with this attribute will emit a deprecation notice. ``` <?php class DefaultBehaviour { } #[AllowDynamicProperties] class ClassAllowsDynamicProperties { } $o1 = new DefaultBehaviour(); $o2 = new ClassAllowsDynamicProperties(); $o1->nonExistingProp = true; $o2->nonExistingProp = true; ?> ``` Output of the above example in PHP 8.2: ``` Deprecated: Creation of dynamic property DefaultBehaviour::$nonExistingProp is deprecated in file on line 10 ``` See Also -------- [Attributes overview](https://www.php.net/manual/en/language.attributes.php) php SplFileObject::fputcsv SplFileObject::fputcsv ====================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SplFileObject::fputcsv — Write a field array as a CSV line ### Description ``` public SplFileObject::fputcsv( array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n" ): int|false ``` Writes the `fields` array to the file as a CSV line. ### Parameters `fields` An array of values. `separator` The optional `separator` parameter sets the field delimiter (one single-byte character only). `enclosure` The optional `enclosure` parameter sets the field enclosure (one single-byte character only). `escape` The optional `escape` parameter sets the escape character (at most one single-byte character). An empty string (`""`) disables the proprietary escape mechanism. `eol` The optional `eol` parameter sets a custom End of Line sequence. > > **Note**: > > > If an `enclosure` character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an `escape`. > > ### Return Values Returns the length of the written string or **`false`** on failure. Returns **`false`**, and does not write the CSV line to the file, if the `separator` or `enclosure` parameter is not a single character. ### Errors/Exceptions An **`E_WARNING`** level error is issued if the `separator` or `enclosure` parameter is not a single character. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The optional `eol` parameter has been added. | | 7.4.0 | The `escape` parameter now also accepts an empty string to disable the proprietary escape mechanism. | ### Examples **Example #1 **SplFileObject::fputcsv()** example** ``` <?php $list = array (     array('aaa', 'bbb', 'ccc', 'dddd'),     array('123', '456', '789'),     array('"aaa"', '"bbb"') ); $file = new SplFileObject('file.csv', 'w'); foreach ($list as $fields) {     $file->fputcsv($fields); } ?> ``` The above example will write the following to `file.csv`: ``` aaa,bbb,ccc,dddd 123,456,789 """aaa""","""bbb""" ``` ### See Also * [fputcsv()](function.fputcsv) - Format line as CSV and write to file pointer * [SplFileObject::fgetcsv()](splfileobject.fgetcsv) - Gets line from file and parse as CSV fields php ReflectionParameter::isVariadic ReflectionParameter::isVariadic =============================== (PHP 5 >= 5.6.0, PHP 7, PHP 8) ReflectionParameter::isVariadic — Checks if the parameter is variadic ### Description ``` public ReflectionParameter::isVariadic(): bool ``` Checks if the parameter was declared as a [variadic parameter](functions.arguments#functions.variable-arg-list). ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the parameter is variadic, otherwise **`false`**. php IntlCalendar::getTime IntlCalendar::getTime ===================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getTime — Get time currently represented by the object ### Description Object-oriented style ``` public IntlCalendar::getTime(): float|false ``` Procedural style ``` intlcal_get_time(IntlCalendar $calendar): float|false ``` Returns the time associated with this object, expressed as the number of milliseconds since the epoch. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. ### Return Values A float representing the number of milliseconds elapsed since the reference time (1 Jan 1970 00:00:00 UTC), or **`false`** on failure ### Examples **Example #1 **IntlCalendar::getTime()**** ``` <?php ini_set('date.timezone', 'Europe/Lisbon'); ini_set('intl.default_locale', 'en_US'); $cal = new IntlGregorianCalendar(2013, 4 /* May */, 1, 0, 0, 0); $time = $cal->getTime(); var_dump($time, $time / 1000 == strtotime('2013-05-01 00:00:00')); //true ``` The above example will output: ``` float(1367362800000) bool(true) ``` ### See Also * [IntlCalendar::getNow()](intlcalendar.getnow) - Get number representing the current time php SplObjectStorage::offsetUnset SplObjectStorage::offsetUnset ============================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplObjectStorage::offsetUnset — Removes an object from the storage ### Description ``` public SplObjectStorage::offsetUnset(object $object): void ``` Removes an object from the storage. > > **Note**: > > > **SplObjectStorage::offsetUnset()** is an alias of [SplObjectStorage::detach()](splobjectstorage.detach). > > ### Parameters `object` The object to remove. ### Return Values No value is returned. ### Examples **Example #1 **SplObjectStorage::offsetUnset()** example** ``` <?php $o = new StdClass; $s = new SplObjectStorage(); $s->attach($o); var_dump(count($s)); $s->offsetUnset($o); // Similar to unset($s[$o]) var_dump(count($s)); ?> ``` The above example will output something similar to: ``` int(1) int(0) ``` ### See Also * [SplObjectStorage::offsetGet()](splobjectstorage.offsetget) - Returns the data associated with an object * [SplObjectStorage::offsetSet()](splobjectstorage.offsetset) - Associates data to an object in the storage * [SplObjectStorage::offsetExists()](splobjectstorage.offsetexists) - Checks whether an object exists in the storage php gmp_testbit gmp\_testbit ============ (PHP 5 >= 5.3.0, PHP 7, PHP 8) gmp\_testbit — Tests if a bit is set ### Description ``` gmp_testbit(GMP|int|string $num, int $index): bool ``` Tests if the specified bit is set. ### Parameters `num` A [GMP](class.gmp) object, an int or a numeric string. `index` The bit to test ### Return Values Returns **`true`** if the bit is set in `num`, otherwise **`false`**. ### Errors/Exceptions An **`E_WARNING`** level error is issued when `index` is less than zero, and **`false`** is returned. ### Examples **Example #1 **gmp\_testbit()** example** ``` <?php $n = gmp_init("1000000"); var_dump(gmp_testbit($n, 1)); gmp_setbit($n, 1); var_dump(gmp_testbit($n, 1)); ?> ``` The above example will output: ``` bool(false) bool(true) ``` ### See Also * [gmp\_setbit()](function.gmp-setbit) - Set bit * [gmp\_clrbit()](function.gmp-clrbit) - Clear bit php ldap_first_reference ldap\_first\_reference ====================== (PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8) ldap\_first\_reference — Return first reference ### Description ``` ldap_first_reference(LDAP\Connection $ldap, LDAP\Result $result): LDAP\ResultEntry|false ``` **Warning**This function is currently not documented; only its argument list is available. php svn_fs_abort_txn svn\_fs\_abort\_txn =================== (PECL svn >= 0.2.0) svn\_fs\_abort\_txn — Aborts a transaction ### Description ``` svn_fs_abort_txn(resource $txn): bool ``` **Warning**This function is currently not documented; only its argument list is available. Aborts a transaction. ### Parameters `txn` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php SplHeap::top SplHeap::top ============ (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplHeap::top — Peeks at the node from the top of the heap ### Description ``` public SplHeap::top(): mixed ``` ### Parameters This function has no parameters. ### Return Values The value of the node on the top. ### Errors/Exceptions Throws [RuntimeException](class.runtimeexception) when the data-structure is empty. php stats_cdf_t stats\_cdf\_t ============= (PECL stats >= 1.0.0) stats\_cdf\_t — Calculates any one parameter of the t-distribution given values for the others ### Description ``` stats_cdf_t(float $par1, float $par2, int $which): float ``` Returns the cumulative distribution function, its inverse, or one of its parameters, of the t-distribution. The kind of the return value and parameters (`par1` and `par2`) are determined by `which`. The following table lists the return value and parameters by `which`. CDF, x, and nu denotes cumulative distribution function, the value of the random variable, and the degrees of freedom of the t-distribution, respectively. **Return value and parameters**| `which` | Return value | `par1` | `par2` | | --- | --- | --- | --- | | 1 | CDF | x | nu | | 2 | x | CDF | nu | | 3 | nu | x | CDF | ### Parameters `par1` The first parameter `par2` The second parameter `which` The flag to determine what to be calculated ### Return Values Returns CDF, x, or nu, determined by `which`. php php_uname php\_uname ========== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) php\_uname — Returns information about the operating system PHP is running on ### Description ``` php_uname(string $mode = "a"): string ``` **php\_uname()** returns a description of the operating system PHP is running on. This is the same string you see at the very top of the [phpinfo()](function.phpinfo) output. For the name of just the operating system, consider using the **`PHP_OS`** constant, but keep in mind this constant will contain the operating system PHP was *built* on. On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work. ### Parameters `mode` `mode` is a single character that defines what information is returned: * `'a'`: This is the default. Contains all modes in the sequence `"s n r v m"`. * `'s'`: Operating system name. eg. `FreeBSD`. * `'n'`: Host name. eg. `localhost.example.com`. * `'r'`: Release name. eg. `5.1.2-RELEASE`. * `'v'`: Version information. Varies a lot between operating systems. * `'m'`: Machine type. eg. `i386`. ### Return Values Returns the description, as a string. ### Examples **Example #1 Some **php\_uname()** examples** ``` <?php echo php_uname(); echo PHP_OS; /* Some possible outputs: Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686 Linux FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001 FreeBSD Windows NT XN1 5.1 build 2600 WINNT */ if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {     echo 'This is a server using Windows!'; } else {     echo 'This is a server not using Windows!'; } ?> ``` There are also some related [Predefined PHP constants](language.constants.predefined) that may come in handy, for example: **Example #2 A few OS related constant examples** ``` <?php // *nix echo DIRECTORY_SEPARATOR; // / echo PHP_SHLIB_SUFFIX;    // so echo PATH_SEPARATOR;      // : // Win* echo DIRECTORY_SEPARATOR; // \ echo PHP_SHLIB_SUFFIX;    // dll echo PATH_SEPARATOR;      // ; ?> ``` ### See Also * [phpversion()](function.phpversion) - Gets the current PHP version * [php\_sapi\_name()](function.php-sapi-name) - Returns the type of interface between web server and PHP * [phpinfo()](function.phpinfo) - Outputs information about PHP's configuration php Ds\Deque::remove Ds\Deque::remove ================ (PECL ds >= 1.0.0) Ds\Deque::remove — Removes and returns a value by index ### Description ``` public Ds\Deque::remove(int $index): mixed ``` Removes and returns a value by index. ### Parameters `index` The index of the value to remove. ### Return Values The value that was removed. ### Errors/Exceptions [OutOfRangeException](class.outofrangeexception) if the index is not valid. ### Examples **Example #1 **Ds\Deque::remove()** example** ``` <?php $deque = new \Ds\Deque(["a", "b", "c"]); var_dump($deque->remove(1)); var_dump($deque->remove(0)); var_dump($deque->remove(0)); ?> ``` The above example will output something similar to: ``` string(1) "b" string(1) "a" string(1) "c" ``` php zend_thread_id zend\_thread\_id ================ (PHP 5, PHP 7, PHP 8) zend\_thread\_id — Returns a unique identifier for the current thread ### Description ``` zend_thread_id(): int ``` This function returns a unique identifier for the current thread. ### Parameters This function has no parameters. ### Return Values Returns the thread id as an integer. ### Examples **Example #1 **zend\_thread\_id()** example** ``` <?php $thread_id = zend_thread_id(); echo 'Current thread id is: ' . $thread_id; ?> ``` The above example will output something similar to: ``` Current thread id is: 7864 ``` ### Notes > > **Note**: > > > This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (`--enable-debug`). > > php RecursiveIteratorIterator::endIteration RecursiveIteratorIterator::endIteration ======================================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) RecursiveIteratorIterator::endIteration — End Iteration ### Description ``` public RecursiveIteratorIterator::endIteration(): void ``` Called when the iteration ends (when [RecursiveIteratorIterator::valid()](recursiveiteratoriterator.valid) first returns **`false`**. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php Yaf_Session::count Yaf\_Session::count =================== (Yaf >=1.0.0) Yaf\_Session::count — The count purpose ### Description ``` public Yaf_Session::count(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php ReflectionType::allowsNull ReflectionType::allowsNull ========================== (PHP 7, PHP 8) ReflectionType::allowsNull — Checks if null is allowed ### Description ``` public ReflectionType::allowsNull(): bool ``` Checks whether the parameter allows **`null`**. ### Parameters This function has no parameters. ### Return Values **`true`** if **`null`** is allowed, otherwise **`false`** ### Examples **Example #1 **ReflectionType::allowsNull()** example** ``` <?php function someFunction(string $param, StdClass $param2 = null) {} $reflectionFunc = new ReflectionFunction('someFunction'); $reflectionParams = $reflectionFunc->getParameters(); var_dump($reflectionParams[0]->getType()->allowsNull()); var_dump($reflectionParams[1]->getType()->allowsNull()); ``` The above example will output: ``` bool(false) bool(true) ``` ### See Also * [ReflectionNamedType::isBuiltin()](reflectionnamedtype.isbuiltin) - Checks if it is a built-in type * [ReflectionType::\_\_toString()](reflectiontype.tostring) - To string * [ReflectionParameter::getType()](reflectionparameter.gettype) - Gets a parameter's type php EventBuffer::drain EventBuffer::drain ================== (PECL event >= 1.2.6-beta) EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere ### Description ``` public EventBuffer::drain( int $len ): bool ``` Behaves as [EventBuffer::read()](eventbuffer.read) , except that it does not copy the data: it just removes it from the front of the buffer. ### Parameters `len` The number of bytes to remove from the buffer. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventBuffer::read()](eventbuffer.read) - Read data from an evbuffer and drain the bytes read * [EventBuffer::appendFrom()](eventbuffer.appendfrom) - Moves the specified number of bytes from a source buffer to the end of the current buffer php ZipArchive::addFromString ZipArchive::addFromString ========================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0) ZipArchive::addFromString — Add a file to a ZIP archive using its contents ### Description ``` public ZipArchive::addFromString(string $name, string $content, int $flags = ZipArchive::FL_OVERWRITE): bool ``` Add a file to a ZIP archive using its contents. > **Note**: For maximum portability, it is recommended to always use forward slashes (`/`) as directory separator in ZIP filenames. > > ### Parameters `name` The name of the entry to create. `content` The contents to use to create the entry. It is used in a binary safe mode. `flags` Bitmask consisting of **`ZipArchive::FL_OVERWRITE`**, **`ZipArchive::FL_ENC_GUESS`**, **`ZipArchive::FL_ENC_UTF_8`**, **`ZipArchive::FL_ENC_CP437`**. The behaviour of these constants is described on the [ZIP constants](https://www.php.net/manual/en/zip.constants.php) page. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 / 1.18.0 | `flags` was added. | ### Examples **Example #1 Add an entry to a new archive** ``` <?php $zip = new ZipArchive; $res = $zip->open('test.zip', ZipArchive::CREATE); if ($res === TRUE) {     $zip->addFromString('test.txt', 'file content goes here');     $zip->close();     echo 'ok'; } else {     echo 'failed'; } ?> ``` **Example #2 Add file to a directory inside an archive** ``` <?php $zip = new ZipArchive; if ($zip->open('test.zip') === TRUE) {     $zip->addFromString('dir/test.txt', 'file content goes here');     $zip->close();     echo 'ok'; } else {     echo 'failed'; } ?> ```
programming_docs
php stream_socket_pair stream\_socket\_pair ==================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) stream\_socket\_pair — Creates a pair of connected, indistinguishable socket streams ### Description ``` stream_socket_pair(int $domain, int $type, int $protocol): array|false ``` **stream\_socket\_pair()** creates a pair of connected, indistinguishable socket streams. This function is commonly used in IPC (Inter-Process Communication). ### Parameters `domain` The protocol family to be used: **`STREAM_PF_INET`**, **`STREAM_PF_INET6`** or **`STREAM_PF_UNIX`** `type` The type of communication to be used: **`STREAM_SOCK_DGRAM`**, **`STREAM_SOCK_RAW`**, **`STREAM_SOCK_RDM`**, **`STREAM_SOCK_SEQPACKET`** or **`STREAM_SOCK_STREAM`** `protocol` The protocol to be used: **`STREAM_IPPROTO_ICMP`**, **`STREAM_IPPROTO_IP`**, **`STREAM_IPPROTO_RAW`**, **`STREAM_IPPROTO_TCP`** or **`STREAM_IPPROTO_UDP`** > **Note**: Please consult the [Streams constant list](https://www.php.net/manual/en/stream.constants.php) for further details on each constant. > > ### Return Values Returns an array with the two socket resources on success, or **`false`** on failure. ### Examples **Example #1 A **stream\_socket\_pair()** example** This example shows the basic usage of **stream\_socket\_pair()** in Inter-Process Communication. ``` <?php $sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); $pid     = pcntl_fork(); if ($pid == -1) {      die('could not fork'); } else if ($pid) {      /* parent */     fclose($sockets[0]);     fwrite($sockets[1], "child PID: $pid\n");     echo fgets($sockets[1]);     fclose($sockets[1]); } else {     /* child */     fclose($sockets[1]);     fwrite($sockets[0], "message from child\n");     echo fgets($sockets[0]);     fclose($sockets[0]); } ?> ``` The above example will output something similar to: ``` child PID: 1378 message from child ``` php None Unicode character properties ---------------------------- Since 5.1.0, three additional escape sequences to match generic character types are available when *UTF-8 mode* is selected. They are: *\p{xx}* a character with the xx property *\P{xx}* a character without the xx property *\X* an extended Unicode sequence The property names represented by `xx` above are limited to the Unicode general category properties. Each character has exactly one such property, specified by a two-letter abbreviation. For compatibility with Perl, negation can be specified by including a circumflex between the opening brace and the property name. For example, `\p{^Lu}` is the same as `\P{Lu}`. If only one letter is specified with `\p` or `\P`, it includes all the properties that start with that letter. In this case, in the absence of negation, the curly brackets in the escape sequence are optional; these two examples have the same effect: ``` \p{L} \pL ``` **Supported property codes**| Property | Matches | Notes | | --- | --- | --- | | `C` | Other | | | `Cc` | Control | | | `Cf` | Format | | | `Cn` | Unassigned | | | `Co` | Private use | | | `Cs` | Surrogate | | | `L` | Letter | Includes the following properties: `Ll`, `Lm`, `Lo`, `Lt` and `Lu`. | | `Ll` | Lower case letter | | | `Lm` | Modifier letter | | | `Lo` | Other letter | | | `Lt` | Title case letter | | | `Lu` | Upper case letter | | | `M` | Mark | | | `Mc` | Spacing mark | | | `Me` | Enclosing mark | | | `Mn` | Non-spacing mark | | | `N` | Number | | | `Nd` | Decimal number | | | `Nl` | Letter number | | | `No` | Other number | | | `P` | Punctuation | | | `Pc` | Connector punctuation | | | `Pd` | Dash punctuation | | | `Pe` | Close punctuation | | | `Pf` | Final punctuation | | | `Pi` | Initial punctuation | | | `Po` | Other punctuation | | | `Ps` | Open punctuation | | | `S` | Symbol | | | `Sc` | Currency symbol | | | `Sk` | Modifier symbol | | | `Sm` | Mathematical symbol | | | `So` | Other symbol | | | `Z` | Separator | | | `Zl` | Line separator | | | `Zp` | Paragraph separator | | | `Zs` | Space separator | | Extended properties such as `InMusicalSymbols` are not supported by PCRE. Specifying case-insensitive (caseless) matching does not affect these escape sequences. For example, `\p{Lu}` always matches only upper case letters. Sets of Unicode characters are defined as belonging to certain scripts. A character from one of these sets can be matched using a script name. For example: * `\p{Greek}` * `\P{Han}` Those that are not part of an identified script are lumped together as `Common`. The current list of scripts is: **Supported scripts**| `Arabic` | `Armenian` | `Avestan` | `Balinese` | `Bamum` | | `Batak` | `Bengali` | `Bopomofo` | `Brahmi` | `Braille` | | `Buginese` | `Buhid` | `Canadian_Aboriginal` | `Carian` | `Chakma` | | `Cham` | `Cherokee` | `Common` | `Coptic` | `Cuneiform` | | `Cypriot` | `Cyrillic` | `Deseret` | `Devanagari` | `Egyptian_Hieroglyphs` | | `Ethiopic` | `Georgian` | `Glagolitic` | `Gothic` | `Greek` | | `Gujarati` | `Gurmukhi` | `Han` | `Hangul` | `Hanunoo` | | `Hebrew` | `Hiragana` | `Imperial_Aramaic` | `Inherited` | `Inscriptional_Pahlavi` | | `Inscriptional_Parthian` | `Javanese` | `Kaithi` | `Kannada` | `Katakana` | | `Kayah_Li` | `Kharoshthi` | `Khmer` | `Lao` | `Latin` | | `Lepcha` | `Limbu` | `Linear_B` | `Lisu` | `Lycian` | | `Lydian` | `Malayalam` | `Mandaic` | `Meetei_Mayek` | `Meroitic_Cursive` | | `Meroitic_Hieroglyphs` | `Miao` | `Mongolian` | `Myanmar` | `New_Tai_Lue` | | `Nko` | `Ogham` | `Old_Italic` | `Old_Persian` | `Old_South_Arabian` | | `Old_Turkic` | `Ol_Chiki` | `Oriya` | `Osmanya` | `Phags_Pa` | | `Phoenician` | `Rejang` | `Runic` | `Samaritan` | `Saurashtra` | | `Sharada` | `Shavian` | `Sinhala` | `Sora_Sompeng` | `Sundanese` | | `Syloti_Nagri` | `Syriac` | `Tagalog` | `Tagbanwa` | `Tai_Le` | | `Tai_Tham` | `Tai_Viet` | `Takri` | `Tamil` | `Telugu` | | `Thaana` | `Thai` | `Tibetan` | `Tifinagh` | `Ugaritic` | | `Vai` | `Yi` | | | | | The `\X` escape matches a Unicode extended grapheme cluster. An extended grapheme cluster is one or more Unicode characters that combine to form a single glyph. In effect, this can be thought of as the Unicode equivalent of `.` as it will match one composed character, regardless of how many individual characters are actually used to render it. In versions of PCRE older than 8.32 (which corresponds to PHP versions before 5.4.14 when using the bundled PCRE library), `\X` is equivalent to `(?>\PM\pM*)`. That is, it matches a character without the "mark" property, followed by zero or more characters with the "mark" property, and treats the sequence as an atomic group (see below). Characters with the "mark" property are typically accents that affect the preceding character. Matching characters by Unicode property is not fast, because PCRE has to search a structure that contains data for over fifteen thousand characters. That is why the traditional escape sequences such as `\d` and `\w` do not use Unicode properties in PCRE. php RecursiveTreeIterator::endIteration RecursiveTreeIterator::endIteration =================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::endIteration — End iteration ### Description ``` public RecursiveTreeIterator::endIteration(): void ``` Called when the iteration ends (when [RecursiveTreeIterator::valid()](recursivetreeiterator.valid) first returns **`false`**) **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php unregister_tick_function unregister\_tick\_function ========================== (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) unregister\_tick\_function — De-register a function for execution on each tick ### Description ``` unregister_tick_function(callable $callback): void ``` De-registers the function `function` so it is no longer executed when a [tick](control-structures.declare) is called. ### Parameters `callback` The function to de-register. ### Return Values No value is returned. ### See Also * [register\_tick\_function()](function.register-tick-function) - Register a function for execution on each tick php xdiff_file_bpatch xdiff\_file\_bpatch =================== (PECL xdiff >= 1.5.0) xdiff\_file\_bpatch — Patch a file with a binary diff ### Description ``` xdiff_file_bpatch(string $file, string $patch, string $dest): bool ``` Patches a `file` with a binary `patch` and stores the result in a file `dest`. This function accepts patches created both via [xdiff\_file\_bdiff()](function.xdiff-file-bdiff) and [xdiff\_file\_rabdiff()](function.xdiff-file-rabdiff) functions or their string counterparts. ### Parameters `file` The original file. `patch` The binary patch file. `dest` Path of the resulting file. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **xdiff\_file\_bpatch()** example** The following code applies binary diff to a file. ``` <?php $old_version = 'archive-1.0.tgz'; $patch = 'archive.bpatch'; $result = xdiff_file_bpatch($old_version, $patch, 'archive-1.1.tgz'); if ($result) {    echo "File patched"; } else {    echo "File couldn't be patched"; } ?> ``` ### Notes > > **Note**: > > > Both files (`file` and `patch`) will be loaded into memory so ensure that your memory\_limit is set high enough. > > ### See Also * [xdiff\_file\_bdiff()](function.xdiff-file-bdiff) - Make binary diff of two files * [xdiff\_file\_rabdiff()](function.xdiff-file-rabdiff) - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm php pg_lo_read pg\_lo\_read ============ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_lo\_read — Read a large object ### Description ``` pg_lo_read(PgSql\Lob $lob, int $length = 8192): string|false ``` **pg\_lo\_read()** reads at most `length` bytes from a large object and returns it as a string. To use the large object interface, it is necessary to enclose it within a transaction block. > > **Note**: > > > This function used to be called **pg\_loread()**. > > ### Parameters `lob` An [PgSql\Lob](class.pgsql-lob) instance, returned by [pg\_lo\_open()](function.pg-lo-open). `length` An optional maximum number of bytes to return. ### Return Values A string containing `length` bytes from the large object, or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `lob` parameter expects an [PgSql\Lob](class.pgsql-lob) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_lo\_read()** example** ``` <?php    $doc_oid = 189762345;    $database = pg_connect("dbname=jacarta");    pg_query($database, "begin");    $handle = pg_lo_open($database, $doc_oid, "r");    $data = pg_lo_read($handle, 50000);    pg_query($database, "commit");    echo $data; ?> ``` ### See Also * [pg\_lo\_read\_all()](function.pg-lo-read-all) - Reads an entire large object and send straight to browser php eio_stat eio\_stat ========= (PECL eio >= 0.0.1dev) eio\_stat — Get file status ### Description ``` eio_stat( string $path, int $pri, callable $callback, mixed $data = NULL ): resource ``` **eio\_stat()** returns file status information in `result` argument of `callback` ### Parameters `path` The file path `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_stat()** returns request resource on success or **`false`** on error. On success assigns `result` argument of `callback` to an array. ### Examples **Example #1 **eio\_stat()** example** ``` <?php $tmp_filename = "eio-file.tmp"; touch($tmp_filename); function my_res_cb($data, $result) {     var_dump($data);     var_dump($result); } function my_open_cb($data, $result) {     eio_close($result);     eio_event_loop();     @unlink($data); } eio_stat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_stat"); eio_open($tmp_filename, EIO_O_RDONLY, NULL,  EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename); eio_event_loop(); ?> ``` The above example will output something similar to: ``` string(8) "eio_stat" array(12) { ["st_dev"]=> int(2050) ["st_ino"]=> int(2489173) ["st_mode"]=> int(33188) ["st_nlink"]=> int(1) ["st_uid"]=> int(1000) ["st_gid"]=> int(100) ["st_rdev"]=> int(0) ["st_blksize"]=> int(4096) ["st_blocks"]=> int(0) ["st_atime"]=> int(1318250380) ["st_mtime"]=> int(1318250380) ["st_ctime"]=> int(1318250380) } ``` ### See Also * [eio\_lstat()](function.eio-lstat) - Get file status * [eio\_fstat()](function.eio-fstat) - Get file status php ftp_set_option ftp\_set\_option ================ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) ftp\_set\_option — Set miscellaneous runtime FTP options ### Description ``` ftp_set_option(FTP\Connection $ftp, int $option, int|bool $value): bool ``` This function controls various runtime options for the specified FTP connection. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `option` Currently, the following options are supported: **Supported runtime FTP options**| **`FTP_TIMEOUT_SEC`** | Changes the timeout in seconds used for all network related functions. `value` must be an integer that is greater than 0. The default timeout is 90 seconds. | | **`FTP_AUTOSEEK`** | When enabled, GET or PUT requests with a `resumepos` or `startpos` parameter will first seek to the requested position within the file. This is enabled by default. | | **`FTP_USEPASVADDRESS`** | When disabled, PHP will ignore the IP address returned by the FTP server in response to the PASV command and instead use the IP address that was supplied in the ftp\_connect(). `value` must be a boolean. | `value` This parameter depends on which `option` is chosen to be altered. ### Return Values Returns **`true`** if the option could be set; **`false`** if not. A warning message will be thrown if the `option` is not supported or the passed `value` doesn't match the expected value for the given `option`. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_set\_option()** example** ``` <?php // Set the network timeout to 10 seconds ftp_set_option($ftp, FTP_TIMEOUT_SEC, 10); ?> ``` ### See Also * [ftp\_get\_option()](function.ftp-get-option) - Retrieves various runtime behaviours of the current FTP connection php ReflectionProperty::hasType ReflectionProperty::hasType =========================== (PHP 7 >= 7.4.0, PHP 8) ReflectionProperty::hasType — Checks if property has a type ### Description ``` public ReflectionProperty::hasType(): bool ``` Checks if the property has a type associated with it. ### Parameters This function has no parameters. ### Return Values **`true`** if a type is specified, **`false`** otherwise. ### Examples **Example #1 **ReflectionProperty::hasType()** example** ``` <?php class User {     public string $name; } $rp = new ReflectionProperty('User', 'name'); var_dump($rp->hasType()); ?> ``` The above example will output: ``` bool(true) ``` ### See Also * [ReflectionProperty::getType()](reflectionproperty.gettype) - Gets a property's type * [ReflectionProperty::isInitialized()](reflectionproperty.isinitialized) - Checks whether a property is initialized php pspell_new pspell\_new =========== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) pspell\_new — Load a new dictionary ### Description ``` pspell_new( string $language, string $spelling = "", string $jargon = "", string $encoding = "", int $mode = 0 ): PSpell\Dictionary|false ``` **pspell\_new()** opens up a new dictionary and returns an [PSpell\Dictionary](class.pspell-dictionary) instance for use in other pspell functions. For more information and examples, check out inline manual pspell website:[» http://aspell.net/](http://aspell.net/). ### Parameters `language` The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore. `spelling` The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'. `jargon` The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters. `encoding` The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-\*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using. `mode` The mode parameter is the mode in which spellchecker will work. There are several modes available: * **`PSPELL_FAST`** - Fast mode (least number of suggestions) * **`PSPELL_NORMAL`** - Normal mode (more suggestions) * **`PSPELL_BAD_SPELLERS`** - Slow mode (a lot of suggestions) * **`PSPELL_RUN_TOGETHER`** - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by [pspell\_check()](function.pspell-check); [pspell\_suggest()](function.pspell-suggest) will still return suggestions. Mode is a bitmask constructed from different constants listed above. However, **`PSPELL_FAST`**, **`PSPELL_NORMAL`** and **`PSPELL_BAD_SPELLERS`** are mutually exclusive, so you should select only one of them. ### Return Values Returns an [PSpell\Dictionary](class.pspell-dictionary) instance on success, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Returns an [PSpell\Dictionary](class.pspell-dictionary) instance now; previously, a [resource](language.types.resource) was returned. | ### Examples **Example #1 **pspell\_new()**** ``` <?php $pspell = pspell_new("en", "", "", "",                      (PSPELL_FAST|PSPELL_RUN_TOGETHER)); ?> ``` php Imagick::appendImages Imagick::appendImages ===================== (PECL imagick 2, PECL imagick 3) Imagick::appendImages — Append a set of images ### Description ``` public Imagick::appendImages(bool $stack): Imagick ``` Append a set of images into one larger image. ### Parameters `stack` Whether to stack the images vertically. By default (or if **`false`** is specified) images are stacked left-to-right. If `stack` is **`true`**, images are stacked top-to-bottom. ### Return Values Returns Imagick instance on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::appendImages()** example** ``` <?php /* Create new imagick object */ $im = new Imagick(); /* create red, green and blue images */ $im->newImage(100, 50, "red"); $im->newImage(100, 50, "green"); $im->newImage(100, 50, "blue"); /* Append the images into one */ $im->resetIterator(); $combined = $im->appendImages(true); /* Output the image */ $combined->setImageFormat("png"); header("Content-Type: image/png"); echo $combined; ?> ``` The above example will output something similar to:
programming_docs
php EvEmbed::createStopped EvEmbed::createStopped ====================== (PECL ev >= 0.2.0) EvEmbed::createStopped — Create stopped EvEmbed watcher object ### Description ``` final public static EvEmbed::createStopped( object $other , callable $callback = ?, mixed $data = ?, int $priority = ? ): void ``` The same as [EvEmbed::\_\_construct()](evembed.construct) , but doesn't start the watcher automatically. ### Parameters `other` The same as for [EvEmbed::\_\_construct()](evembed.construct) `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### Return Values Returns stopped EvEmbed object on success. ### See Also * [EvEmbed::\_\_construct()](evembed.construct) - Constructs the EvEmbed object * [Ev::embeddableBackends()](ev.embeddablebackends) - Returns the set of backends that are embeddable in other event loops php SQLite3Result::columnType SQLite3Result::columnType ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3Result::columnType — Returns the type of the nth column ### Description ``` public SQLite3Result::columnType(int $column): int|false ``` Returns the type of the column identified by `column`. ### Parameters `column` The numeric zero-based index of the column. ### Return Values Returns the data type index of the column identified by `column` (one of **`SQLITE3_INTEGER`**, **`SQLITE3_FLOAT`**, **`SQLITE3_TEXT`**, **`SQLITE3_BLOB`**, or **`SQLITE3_NULL`**), or **`false`** if the column does not exist. php Iterator::next Iterator::next ============== (PHP 5, PHP 7, PHP 8) Iterator::next — Move forward to next element ### Description ``` public Iterator::next(): void ``` Moves the current position to the next element. > > **Note**: > > > This method is called *after* each [foreach](control-structures.foreach) loop. > > ### Parameters This function has no parameters. ### Return Values Any returned value is ignored. php posix_getppid posix\_getppid ============== (PHP 4, PHP 5, PHP 7, PHP 8) posix\_getppid — Return the parent process identifier ### Description ``` posix_getppid(): int ``` Return the process identifier of the parent process of the current process. ### Parameters This function has no parameters. ### Return Values Returns the identifier, as an int. ### Examples **Example #1 Example use of **posix\_getppid()**** ``` <?php echo posix_getppid(); //8259 ?> ``` php Stringable::__toString Stringable::\_\_toString ======================== (PHP 8) Stringable::\_\_toString — Gets a string representation of the object ### Description ``` public Stringable::__toString(): string ``` ### Parameters This function has no parameters. ### Return Values Returns the string representation of the object. ### See Also * [\_\_toString()](language.oop5.magic#object.tostring) php next next ==== (PHP 4, PHP 5, PHP 7, PHP 8) next — Advance the internal pointer of an array ### Description ``` next(array|object &$array): mixed ``` **next()** behaves like [current()](function.current), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one. ### Parameters `array` The array being affected. ### Return Values Returns the array value in the next place that's pointed to by the internal array pointer, or **`false`** if there are no more elements. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Calling this function on objects is deprecated. Either use [get\_mangled\_object\_vars()](function.get-mangled-object-vars) on the object first, or use [ArrayIterator](class.arrayiterator). | ### Examples **Example #1 Example use of **next()** and friends** ``` <?php $transport = array('foot', 'bike', 'car', 'plane'); $mode = current($transport); // $mode = 'foot'; $mode = next($transport);    // $mode = 'bike'; $mode = next($transport);    // $mode = 'car'; $mode = prev($transport);    // $mode = 'bike'; $mode = end($transport);     // $mode = 'plane'; ?> ``` ### Notes > **Note**: The end of an array is indistinguishable from a bool **`false`** element. To properly traverse an array which may contain **`false`** elements, see the [`foreach`](control-structures.foreach) function. To still use **next()** and properly check if the end of the array has been reached, verify that the [key()](function.key) is **`null`**. > > ### See Also * [current()](function.current) - Return the current element in an array * [end()](function.end) - Set the internal pointer of an array to its last element * [prev()](function.prev) - Rewind the internal array pointer * [reset()](function.reset) - Set the internal pointer of an array to its first element * [each()](function.each) - Return the current key and value pair from an array and advance the array cursor php IntlDateFormatter::setLenient IntlDateFormatter::setLenient ============================= datefmt\_set\_lenient ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) IntlDateFormatter::setLenient -- datefmt\_set\_lenient — Set the leniency of the parser ### Description Object-oriented style ``` public IntlDateFormatter::setLenient(bool $lenient): void ``` Procedural style ``` datefmt_set_lenient(IntlDateFormatter $formatter, bool $lenient): void ``` Define if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly. Enabling lenient parsing allows the parser to accept otherwise flawed date or time patterns, parsing as much as possible to obtain a value. Extra space, unrecognized tokens, or invalid values ("February 30th") are not accepted. ### Parameters `formatter` The formatter resource `lenient` Sets whether the parser is lenient or not, default is **`true`** (lenient). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **datefmt\_set\_lenient()** example** ``` <?php $fmt = datefmt_create(     'en_US',      IntlDateFormatter::FULL,      IntlDateFormatter::FULL,      'America/Los_Angeles',      IntlDateFormatter::GREGORIAN,      'dd/MM/yyyy' ); echo 'lenient of the formatter is : '; if ($fmt->isLenient()) {     echo 'TRUE'; } else {     echo 'FALSE'; } datefmt_parse($fmt, '35/13/1971'); echo "\n Trying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971'); if (intl_get_error_code() != 0) {     echo "\nError_msg is : " . intl_get_error_message();     echo "\nError_code is : " . intl_get_error_code(); } datefmt_set_lenient($fmt, false); echo "\nNow lenient of the formatter is : "; if ($fmt->isLenient()) {     echo 'TRUE'; } else {     echo 'FALSE'; } datefmt_parse($fmt, '35/13/1971'); echo "\nTrying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971'); if (intl_get_error_code() != 0) {     echo "\nError_msg is : ".intl_get_error_message();     echo "\nError_code is : ".intl_get_error_code(); } ?> ``` **Example #2 OO example** ``` <?php $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN,     'dd/MM/yyyy' ); echo 'lenient of the formatter is : '; if ($fmt->isLenient()) {     echo 'TRUE'; } else {     echo 'FALSE'; } $fmt->parse('35/13/1971'); echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971'); if (intl_get_error_code() != 0) {     echo "\nError_msg is : " . intl_get_error_message();     echo "\nError_code is : " . intl_get_error_code(); } $fmt->setLenient(FALSE); echo "\nNow lenient of the formatter is : "; if ($fmt->isLenient()) {     echo 'TRUE'; } else {     echo 'FALSE'; } $fmt->parse('35/13/1971'); echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971'); if (intl_get_error_code() != 0) {     echo "\nError_msg is : " . intl_get_error_message();     echo "\nError_code is : " . intl_get_error_code(); } ?> ``` The above example will output: ``` lenient of the formatter is : TRUE Trying to do parse('35/13/1971'). Result is : 66038400 Now lenient of the formatter is : FALSE Trying to do parse('35/13/1971'). Result is : Error_msg is : Date parsing failed: U_PARSE_ERROR Error_code is : 9 ``` ### See Also * [datefmt\_is\_lenient()](intldateformatter.islenient) - Get the lenient used for the IntlDateFormatter * [datefmt\_create()](intldateformatter.create) - Create a date formatter php curl_close curl\_close =========== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) curl\_close — Close a cURL session ### Description ``` curl_close(CurlHandle $handle): void ``` > > **Note**: > > > This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource. > > Closes a cURL session and frees all resources. The cURL handle, `handle`, is also deleted. ### Parameters `handle` A cURL handle returned by [curl\_init()](function.curl-init). ### Return Values No value is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `handle` expects a [CurlHandle](class.curlhandle) instance now; previously, a resource was expected. | ### Examples **Example #1 Initializing a new cURL session and fetching a web page** ``` <?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); ?> ``` ### See Also * [curl\_init()](function.curl-init) - Initialize a cURL session * [curl\_multi\_close()](function.curl-multi-close) - Close a set of cURL handles php Ds\Map::isEmpty Ds\Map::isEmpty =============== (PECL ds >= 1.0.0) Ds\Map::isEmpty — Returns whether the map is empty ### Description ``` public Ds\Map::isEmpty(): bool ``` Returns whether the map is empty. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the map is empty, **`false`** otherwise. ### Examples **Example #1 **Ds\Map::isEmpty()** example** ``` <?php $a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); $b = new \Ds\Map(); var_dump($a->isEmpty()); var_dump($b->isEmpty()); ?> ``` The above example will output something similar to: ``` bool(false) bool(true) ``` php SolrQuery::getHighlightSimplePost SolrQuery::getHighlightSimplePost ================================= (PECL solr >= 0.9.2) SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term ### Description ``` public SolrQuery::getHighlightSimplePost(string $field_override = ?): string ``` Returns the text which appears after a highlighted term. Accepts an optional field override ### Parameters `field_override` The name of the field ### Return Values Returns a string on success and **`null`** if not set. php SplDoublyLinkedList::serialize SplDoublyLinkedList::serialize ============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SplDoublyLinkedList::serialize — Serializes the storage ### Description ``` public SplDoublyLinkedList::serialize(): string ``` Serializes the storage. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The serialized string. ### See Also * [SplDoublyLinkedList::unserialize()](spldoublylinkedlist.unserialize) - Unserializes the storage php SplDoublyLinkedList::unserialize SplDoublyLinkedList::unserialize ================================ (PHP 5 >= 5.4.0, PHP 7, PHP 8) SplDoublyLinkedList::unserialize — Unserializes the storage ### Description ``` public SplDoublyLinkedList::unserialize(string $data): void ``` Unserializes the storage, from [SplDoublyLinkedList::serialize()](spldoublylinkedlist.serialize). **Warning**This function is currently not documented; only its argument list is available. ### Parameters `data` The serialized string. ### Return Values No value is returned. ### See Also * [SplDoublyLinkedList::serialize()](spldoublylinkedlist.serialize) - Serializes the storage php XMLWriter::endDocument XMLWriter::endDocument ====================== xmlwriter\_end\_document ======================== (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::endDocument -- xmlwriter\_end\_document — End current document ### Description Object-oriented style ``` public XMLWriter::endDocument(): bool ``` Procedural style ``` xmlwriter_end_document(XMLWriter $writer): bool ``` Ends the current document. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::startDocument()](xmlwriter.startdocument) - Create document tag php intl_is_failure intl\_is\_failure ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) intl\_is\_failure — Check whether the given error code indicates failure ### Description ``` intl_is_failure(int $errorCode): bool ``` ### Parameters `errorCode` is a value that returned by functions: [intl\_get\_error\_code()](function.intl-get-error-code), [collator\_get\_error\_code()](collator.geterrorcode) . ### Return Values **`true`** if it the code indicates some failure, and **`false`** in case of success or a warning. ### Examples **Example #1 **intl\_is\_failure()** example** ``` <?php function check( $err_code ) {     var_export( intl_is_failure( $err_code ) );     echo "\n"; } check( U_ZERO_ERROR ); check( U_USING_FALLBACK_WARNING ); check( U_ILLEGAL_ARGUMENT_ERROR ); ?> ``` The above example will output something similar to: ``` false false true ``` ### See Also * [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code * [collator\_get\_error\_code()](collator.geterrorcode) - Get collator's last error code * [Collator-getErrorCode()](collator.geterrorcode) - Get collator's last error code php odbc_close odbc\_close =========== (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_close — Close an ODBC connection ### Description ``` odbc_close(resource $odbc): void ``` Closes down the connection to the database server. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. ### Return Values No value is returned. ### Notes > > **Note**: > > > This function will fail if there are open transactions on this connection. The connection will remain open in this case. > > php ImagickDraw::pathLineToAbsolute ImagickDraw::pathLineToAbsolute =============================== (PECL imagick 2) ImagickDraw::pathLineToAbsolute — Draws a line path ### Description ``` public ImagickDraw::pathLineToAbsolute(float $x, float $y): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a line path from the current point to the given coordinate using absolute coordinates. The coordinate then becomes the new current point. ### Parameters `x` starting x coordinate `y` ending x coordinate ### Return Values No value is returned. php streamWrapper::stream_metadata streamWrapper::stream\_metadata =============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) streamWrapper::stream\_metadata — Change stream metadata ### Description ``` public streamWrapper::stream_metadata(string $path, int $option, mixed $value): bool ``` This method is called to set metadata on the stream. It is called when one of the following functions is called on a stream URL: * [touch()](function.touch) * [chmod()](function.chmod) * [chown()](function.chown) * [chgrp()](function.chgrp) Please note that some of these operations may not be available on your system. ### Parameters `path` The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported. `option` One of: * **`STREAM_META_TOUCH`** (The method was called in response to [touch()](function.touch)) * **`STREAM_META_OWNER_NAME`** (The method was called in response to [chown()](function.chown) with string parameter) * **`STREAM_META_OWNER`** (The method was called in response to [chown()](function.chown)) * **`STREAM_META_GROUP_NAME`** (The method was called in response to [chgrp()](function.chgrp)) * **`STREAM_META_GROUP`** (The method was called in response to [chgrp()](function.chgrp)) * **`STREAM_META_ACCESS`** (The method was called in response to [chmod()](function.chmod)) `value` If `option` is * **`STREAM_META_TOUCH`**: Array consisting of two arguments of the [touch()](function.touch) function. * **`STREAM_META_OWNER_NAME`** or **`STREAM_META_GROUP_NAME`**: The name of the owner user/group as string. * **`STREAM_META_OWNER`** or **`STREAM_META_GROUP`**: The value owner user/group argument as int. * **`STREAM_META_ACCESS`**: The argument of the [chmod()](function.chmod) as int. ### Return Values Returns **`true`** on success or **`false`** on failure. If `option` is not implemented, **`false`** should be returned. ### See Also * [touch()](function.touch) - Sets access and modification time of file * [chmod()](function.chmod) - Changes file mode * [chown()](function.chown) - Changes file owner * [chgrp()](function.chgrp) - Changes file group php Yaf_Response_Abstract::clearHeaders Yaf\_Response\_Abstract::clearHeaders ===================================== (Yaf >=1.0.0) Yaf\_Response\_Abstract::clearHeaders — Discard all set headers ### Description ``` public Yaf_Response_Abstract::clearHeaders(): void ``` ### Parameters This function has no parameters. ### Return Values ### See Also * [Yaf\_Response\_Abstract::getHeader()](yaf-response-abstract.getheader) - The getHeader purpose * [Yaf\_Response\_Abstract::setHeader()](yaf-response-abstract.setheader) - Set reponse header php Ds\Map::count Ds\Map::count ============= (PECL ds >= 1.0.0) Ds\Map::count — Returns the number of values in the map See [Countable::count()](countable.count) php imagefontwidth imagefontwidth ============== (PHP 4, PHP 5, PHP 7, PHP 8) imagefontwidth — Get font width ### Description ``` imagefontwidth(GdFont|int $font): int ``` Returns the pixel width of a character in font. ### Parameters `font` Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or [GdFont](class.gdfont) instance, returned by [imageloadfont()](function.imageloadfont). ### Return Values Returns the pixel width of the font. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `font` parameter now accepts both an [GdFont](class.gdfont) instance and an int; previously only int was accepted. | ### Examples **Example #1 Using **imagefontwidth()** on built-in fonts** ``` <?php echo 'Font width: ' . imagefontwidth(4); ?> ``` The above example will output something similar to: ``` Font width: 8 ``` **Example #2 Using **imagefontwidth()** together with [imageloadfont()](function.imageloadfont)** ``` <?php // Load a .gdf font $font = imageloadfont('anonymous.gdf'); echo 'Font width: ' . imagefontwidth($font); ?> ``` The above example will output something similar to: ``` Font width: 23 ``` ### See Also * [imagefontheight()](function.imagefontheight) - Get font height * [imageloadfont()](function.imageloadfont) - Load a new font
programming_docs
php svn_repos_create svn\_repos\_create ================== (PECL svn >= 0.1.0) svn\_repos\_create — Create a new subversion repository at path ### Description ``` svn_repos_create(string $path, array $config = ?, array $fsconfig = ?): resource ``` **Warning**This function is currently not documented; only its argument list is available. Create a new subversion repository at path ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php EventBuffer::appendFrom EventBuffer::appendFrom ======================= (PECL event >= 1.6.0) EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer ### Description ``` public EventBuffer::appendFrom( EventBuffer $buf , int $len ): int ``` Moves the specified number of bytes from a source buffer to the end of the current buffer. If there are fewer number of bytes, it moves all the bytes available from the source buffer. ### Parameters `buf` Source buffer. `len` ### Return Values Returns the number of bytes read. ### Changelog | Version | Description | | --- | --- | | PECL event 1.6.0 | Renamed **EventBuffer::appendFrom()**(the old method name) to **EventBuffer::appendFrom()**. | ### See Also * [EventBuffer::copyout()](eventbuffer.copyout) - Copies out specified number of bytes from the front of the buffer * [EventBuffer::drain()](eventbuffer.drain) - Removes specified number of bytes from the front of the buffer without copying it anywhere * [EventBuffer::pullup()](eventbuffer.pullup) - Linearizes data within buffer and returns it's contents as a string * [EventBuffer::readLine()](eventbuffer.readline) - Extracts a line from the front of the buffer * [EventBuffer::read()](eventbuffer.read) - Read data from an evbuffer and drain the bytes read php fread fread ===== (PHP 4, PHP 5, PHP 7, PHP 8) fread — Binary-safe file read ### Description ``` fread(resource $stream, int $length): string|false ``` **fread()** reads up to `length` bytes from the file pointer referenced by `stream`. Reading stops as soon as one of the following conditions is met: * `length` bytes have been read * EOF (end of file) is reached * a packet becomes available or the [socket timeout](function.socket-set-timeout) occurs (for network streams) * if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size. ### Parameters `stream` A file system pointer resource that is typically created using [fopen()](function.fopen). `length` Up to `length` number of bytes read. ### Return Values Returns the read string or **`false`** on failure. ### Examples **Example #1 A simple **fread()** example** ``` <?php // get contents of a file into a string $filename = "/usr/local/something.txt"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); ?> ``` **Example #2 Binary **fread()** example** **Warning** On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in [fopen()](function.fopen) mode parameter. ``` <?php $filename = "c:\\files\\somepic.gif"; $handle = fopen($filename, "rb"); $contents = fread($handle, filesize($filename)); fclose($handle); ?> ``` **Example #3 Remote **fread()** examples** **Warning** When reading from anything that is not a regular local file, such as streams returned when reading [remote files](https://www.php.net/manual/en/features.remote-files.php) or from [popen()](function.popen) and [fsockopen()](function.fsockopen), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below. ``` <?php $handle = fopen("http://www.example.com/", "rb"); $contents = stream_get_contents($handle); fclose($handle); ?> ``` ``` <?php $handle = fopen("http://www.example.com/", "rb"); if (FALSE === $handle) {     exit("Failed to open stream to URL"); } $contents = ''; while (!feof($handle)) {     $contents .= fread($handle, 8192); } fclose($handle); ?> ``` ### Notes > > **Note**: > > > If you just want to get the contents of a file into a string, use [file\_get\_contents()](function.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()](function.ftell) to find the current position of the pointer and [rewind()](function.rewind) to rewind the pointer position. > > ### See Also * [fwrite()](function.fwrite) - Binary-safe file write * [fopen()](function.fopen) - Opens file or URL * [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection * [popen()](function.popen) - Opens process file pointer * [fgets()](function.fgets) - Gets line from file pointer * [fgetss()](function.fgetss) - Gets line from file pointer and strip HTML tags * [fscanf()](function.fscanf) - Parses input from a file according to a format * [file()](function.file) - Reads entire file into an array * [fpassthru()](function.fpassthru) - Output all remaining data on a file pointer * [fseek()](function.fseek) - Seeks on a file pointer * [ftell()](function.ftell) - Returns the current position of the file read/write pointer * [rewind()](function.rewind) - Rewind the position of a file pointer * [unpack()](function.unpack) - Unpack data from binary string php openssl_get_cipher_methods openssl\_get\_cipher\_methods ============================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) openssl\_get\_cipher\_methods — Gets available cipher methods ### Description ``` openssl_get_cipher_methods(bool $aliases = false): array ``` Gets a list of available cipher methods. ### Parameters `aliases` Set to **`true`** if cipher aliases should be included within the returned array. ### Return Values An array of available cipher methods. Note that prior to OpenSSL 1.1.1, the cipher methods have been returned in upper case and lower case spelling; as of OpenSSL 1.1.1 only the lower case variants are returned. ### Examples **Example #1 **openssl\_get\_cipher\_methods()** example** Shows how the available ciphers might look, and also which aliases might be available. ``` <?php $ciphers             = openssl_get_cipher_methods(); $ciphers_and_aliases = openssl_get_cipher_methods(true); $cipher_aliases      = array_diff($ciphers_and_aliases, $ciphers); //ECB mode should be avoided $ciphers = array_filter( $ciphers, function($n) { return stripos($n,"ecb")===FALSE; } ); //At least as early as Aug 2016, Openssl declared the following weak: RC2, RC4, DES, 3DES, MD5 based $ciphers = array_filter( $ciphers, function($c) { return stripos($c,"des")===FALSE; } ); $ciphers = array_filter( $ciphers, function($c) { return stripos($c,"rc2")===FALSE; } ); $ciphers = array_filter( $ciphers, function($c) { return stripos($c,"rc4")===FALSE; } ); $ciphers = array_filter( $ciphers, function($c) { return stripos($c,"md5")===FALSE; } ); $cipher_aliases = array_filter($cipher_aliases,function($c) { return stripos($c,"des")===FALSE; } ); $cipher_aliases = array_filter($cipher_aliases,function($c) { return stripos($c,"rc2")===FALSE; } ); print_r($ciphers); print_r($cipher_aliases); ?> ``` The above example will output something similar to: ``` Array ( [0] => aes-128-cbc [1] => aes-128-cbc-hmac-sha1 [2] => aes-128-cbc-hmac-sha256 [3] => aes-128-ccm [4] => aes-128-cfb [5] => aes-128-cfb1 [6] => aes-128-cfb8 [7] => aes-128-ctr [9] => aes-128-gcm [10] => aes-128-ocb [11] => aes-128-ofb [12] => aes-128-xts [13] => aes-192-cbc [14] => aes-192-ccm [15] => aes-192-cfb [16] => aes-192-cfb1 [17] => aes-192-cfb8 [18] => aes-192-ctr [20] => aes-192-gcm [21] => aes-192-ocb [22] => aes-192-ofb [23] => aes-256-cbc [24] => aes-256-cbc-hmac-sha1 [25] => aes-256-cbc-hmac-sha256 [26] => aes-256-ccm [27] => aes-256-cfb [28] => aes-256-cfb1 [29] => aes-256-cfb8 [30] => aes-256-ctr [32] => aes-256-gcm [33] => aes-256-ocb [34] => aes-256-ofb [35] => aes-256-xts [36] => aria-128-cbc [37] => aria-128-ccm [38] => aria-128-cfb [39] => aria-128-cfb1 [40] => aria-128-cfb8 [41] => aria-128-ctr [43] => aria-128-gcm [44] => aria-128-ofb [45] => aria-192-cbc [46] => aria-192-ccm [47] => aria-192-cfb [48] => aria-192-cfb1 [49] => aria-192-cfb8 [50] => aria-192-ctr [52] => aria-192-gcm [53] => aria-192-ofb [54] => aria-256-cbc [55] => aria-256-ccm [56] => aria-256-cfb [57] => aria-256-cfb1 [58] => aria-256-cfb8 [59] => aria-256-ctr [61] => aria-256-gcm [62] => aria-256-ofb [63] => bf-cbc [64] => bf-cfb [66] => bf-ofb [67] => camellia-128-cbc [68] => camellia-128-cfb [69] => camellia-128-cfb1 [70] => camellia-128-cfb8 [71] => camellia-128-ctr [73] => camellia-128-ofb [74] => camellia-192-cbc [75] => camellia-192-cfb [76] => camellia-192-cfb1 [77] => camellia-192-cfb8 [78] => camellia-192-ctr [80] => camellia-192-ofb [81] => camellia-256-cbc [82] => camellia-256-cfb [83] => camellia-256-cfb1 [84] => camellia-256-cfb8 [85] => camellia-256-ctr [87] => camellia-256-ofb [88] => cast5-cbc [89] => cast5-cfb [91] => cast5-ofb [92] => chacha20 [93] => chacha20-poly1305 [111] => id-aes128-CCM [112] => id-aes128-GCM [113] => id-aes128-wrap [114] => id-aes128-wrap-pad [115] => id-aes192-CCM [116] => id-aes192-GCM [117] => id-aes192-wrap [118] => id-aes192-wrap-pad [119] => id-aes256-CCM [120] => id-aes256-GCM [121] => id-aes256-wrap [122] => id-aes256-wrap-pad [124] => idea-cbc [125] => idea-cfb [127] => idea-ofb [137] => seed-cbc [138] => seed-cfb [140] => seed-ofb [141] => sm4-cbc [142] => sm4-cfb [143] => sm4-ctr [145] => sm4-ofb ) Array ( [36] => aes128 [37] => aes128-wrap [38] => aes192 [39] => aes192-wrap [40] => aes256 [41] => aes256-wrap [69] => aria128 [70] => aria192 [71] => aria256 [72] => bf [77] => blowfish [99] => camellia128 [100] => camellia192 [101] => camellia256 [102] => cast [103] => cast-cbc [146] => idea [164] => seed [169] => sm4 ) ``` ### See Also * [openssl\_get\_md\_methods()](function.openssl-get-md-methods) - Gets available digest methods php Ds\Sequence::map Ds\Sequence::map ================ (PECL ds >= 1.0.0) Ds\Sequence::map — Returns the result of applying a callback to each value ### Description ``` abstract public Ds\Sequence::map(callable $callback): Ds\Sequence ``` Returns the result of applying a `callback` function to each value in the sequence. ### Parameters `callback` ``` callback(mixed $value): mixed ``` A [callable](language.types.callable) to apply to each value in the sequence. The callable should return what the new value will be in the new sequence. ### Return Values The result of applying a `callback` to each value in the sequence. > > **Note**: > > > The values of the current instance won't be affected. > > ### Examples **Example #1 **Ds\Sequence::map()** example** ``` <?php $sequence = new \Ds\Vector([1, 2, 3]); print_r($sequence->map(function($value) { return $value * 2; })); print_r($sequence); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 2 [1] => 4 [2] => 6 ) Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 ) ``` php uopz_get_exit_status uopz\_get\_exit\_status ======================= (PECL uopz 5, PECL uopz , PECL uopz 7) uopz\_get\_exit\_status — Retrieve the last set exit status ### Description ``` uopz_get_exit_status(): mixed ``` Retrieves the last set exit status, i.e. the value passed to [exit()](function.exit). ### Parameters This function has no parameters. ### Return Values This function returns the last exit status, or **`null`** if [exit()](function.exit) has not been called. ### Examples **Example #1 **uopz\_get\_exit\_status()** example** ``` <?php exit(123);  echo uopz_get_exit_status();?> ``` The above example will output: ``` 123 ``` ### Notes **Caution** [OPcache](https://www.php.net/manual/en/book.opcache.php) optimizes away dead code after unconditional exit. ### See Also * [uopz\_allow\_exit()](function.uopz-allow-exit) - Allows control over disabled exit opcode php Imagick::remapImage Imagick::remapImage =================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::remapImage — Remaps image colors ### Description ``` public Imagick::remapImage(Imagick $replacement, int $DITHER): bool ``` Replaces colors an image with those defined by `replacement`. The colors are replaced with the closest possible color. This method is available if Imagick has been compiled against ImageMagick version 6.4.5 or newer. ### Parameters `replacement` An Imagick object containing the replacement colors `DITHER` Refer to this list of [dither method constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.dithermethod) ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php libxml_get_external_entity_loader libxml\_get\_external\_entity\_loader ===================================== (PHP 8 >= 8.2.0) libxml\_get\_external\_entity\_loader — Get the current external entity loader ### Description ``` libxml_get_external_entity_loader(): ?callable ``` Get external entity loader previously installed by [libxml\_set\_external\_entity\_loader()](function.libxml-set-external-entity-loader). ### Parameters This function has no parameters. ### Return Values The external entity loader previously installed by [libxml\_set\_external\_entity\_loader()](function.libxml-set-external-entity-loader). If that function was never called, or if it was called with **`null`**, **`null`** will be returned. ### See Also * [libxml\_set\_external\_entity\_loader()](function.libxml-set-external-entity-loader) - Changes the default external entity loader php CachingIterator::getInnerIterator CachingIterator::getInnerIterator ================================= (PHP 5, PHP 7, PHP 8) CachingIterator::getInnerIterator — Returns the inner iterator ### Description ``` public CachingIterator::getInnerIterator(): Iterator ``` **Warning**This function is currently not documented; only its argument list is available. Returns the iterator sent to the constructor. ### Parameters This function has no parameters. ### Return Values Returns an object implementing the Iterator interface. php QuickHashIntSet::__construct QuickHashIntSet::\_\_construct ============================== (PECL quickhash >= Unknown) QuickHashIntSet::\_\_construct — Creates a new QuickHashIntSet object ### Description ``` public QuickHashIntSet::__construct(int $size, int $options = ?) ``` This constructor creates a new [QuickHashIntSet](class.quickhashintset). The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported. ### Parameters `size` The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from `4` to `4194304`. `options` The options that you can pass in are: **`QuickHashIntSet::CHECK_FOR_DUPES`**, which makes sure no duplicate entries are added to the set; **`QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC`** to not use PHP's internal memory manager as well as one of **`QuickHashIntSet::HASHER_NO_HASH`**, **`QuickHashIntSet::HASHER_JENKINS1`** or **`QuickHashIntSet::HASHER_JENKINS2`**. These last three configure which hashing algorithm to use. All options can be combined using bitmasks. ### Return Values Returns a new [QuickHashIntSet](class.quickhashintset) object. ### Examples **Example #1 **QuickHashIntSet::\_\_construct()** example** ``` <?php var_dump( new QuickHashIntSet( 1024 ) ); var_dump( new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES ) ); var_dump(     new QuickHashIntSet(         1024,         QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC | QuickHashIntSet::HASHER_JENKINS2     ) ); ?> ``` php Yaf_Response_Abstract::__construct Yaf\_Response\_Abstract::\_\_construct ====================================== (Yaf >=1.0.0) Yaf\_Response\_Abstract::\_\_construct — The \_\_construct purpose ### Description public **Yaf\_Response\_Abstract::\_\_construct**() **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php SQLite3Stmt::paramCount SQLite3Stmt::paramCount ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement ### Description ``` public SQLite3Stmt::paramCount(): int ``` Returns the number of parameters within the prepared statement. ### Parameters This function has no parameters. ### Return Values Returns the number of parameters within the prepared statement. ### See Also * [SQLite3::prepare()](sqlite3.prepare) - Prepares an SQL statement for execution php stats_dens_chisquare stats\_dens\_chisquare ====================== (PECL stats >= 1.0.0) stats\_dens\_chisquare — Probability density function of the chi-square distribution ### Description ``` stats_dens_chisquare(float $x, float $dfr): float ``` Returns the probability density at `x`, where the random variable follows the chi-square distribution of which the degree of freedom is `dfr`. ### Parameters `x` The value at which the probability density is calculated `dfr` The degree of freedom of the distribution ### Return Values The probability density at `x` or **`false`** for failure. php is_int is\_int ======= (PHP 4, PHP 5, PHP 7, PHP 8) is\_int — Find whether the type of a variable is integer ### Description ``` is_int(mixed $value): bool ``` Finds whether the type of the given variable is integer. > > **Note**: > > > To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use [is\_numeric()](function.is-numeric). > > ### Parameters `value` The variable being evaluated. ### Return Values Returns **`true`** if `value` is an int, **`false`** otherwise. ### Examples **Example #1 **is\_int()** example** ``` <?php $values = array(23, "23", 23.5, "23.5", null, true, false); foreach ($values as $value) {     echo "is_int(";     var_export($value);     echo ") = ";     var_dump(is_int($value)); } ?> ``` The above example will output: ``` is_int(23) = bool(true) is_int('23') = bool(false) is_int(23.5) = bool(false) is_int('23.5') = bool(false) is_int(NULL) = bool(false) is_int(true) = bool(false) is_int(false) = bool(false) ``` ### See Also * [is\_bool()](function.is-bool) - Finds out whether a variable is a boolean * [is\_float()](function.is-float) - Finds whether the type of a variable is float * [is\_numeric()](function.is-numeric) - Finds whether a variable is a number or a numeric string * [is\_string()](function.is-string) - Find whether the type of a variable is string * [is\_array()](function.is-array) - Finds whether a variable is an array * [is\_object()](function.is-object) - Finds whether a variable is an object
programming_docs
php Memcached::addByKey Memcached::addByKey =================== (PECL memcached >= 0.1.0) Memcached::addByKey — Add an item under a new key on a specific server ### Description ``` public Memcached::addByKey( string $server_key, string $key, mixed $value, int $expiration = ? ): bool ``` **Memcached::addByKey()** is functionally equivalent to [Memcached::add()](memcached.add), except that the free-form `server_key` can be used to map the `key` to a specific server. This is useful if you need to keep a bunch of related keys on a certain server. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `key` The key under which to store the value. `value` The value to store. `expiration` The expiration time, defaults to 0. See [Expiration Times](https://www.php.net/manual/en/memcached.expiration.php) for more info. ### Return Values Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTSTORED`** if the key already exists. ### See Also * [Memcached::add()](memcached.add) - Add an item under a new key * [Memcached::set()](memcached.set) - Store an item * [Memcached::replace()](memcached.replace) - Replace the item under an existing key php SolrQuery::getHighlightFragmenter SolrQuery::getHighlightFragmenter ================================= (PECL solr >= 0.9.2) SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text ### Description ``` public SolrQuery::getHighlightFragmenter(string $field_override = ?): string ``` Returns the text snippet generator for highlighted text. Accepts an optional field override. ### Parameters `field_override` The name of the field ### Return Values Returns a string on success and **`null`** if not set. php SolrParams::getPreparedParams SolrParams::getPreparedParams ============================= (PECL solr >= 0.9.2) SolrParams::getPreparedParams — Returns an array of URL-encoded parameters ### Description ``` final public SolrParams::getPreparedParams(): array ``` Returns an array on URL-encoded parameters ### Parameters This function has no parameters. ### Return Values Returns an array on URL-encoded parameters php defined defined ======= (PHP 4, PHP 5, PHP 7, PHP 8) defined — Checks whether a given named constant exists ### Description ``` defined(string $constant_name): bool ``` Checks whether the given constant exists and is defined. > > **Note**: > > > If you want to see if a variable exists, use [isset()](function.isset) as **defined()** only applies to [constants](language.constants). If you want to see if a function exists, use [function\_exists()](function.function-exists). > > ### Parameters `constant_name` The constant name. ### Return Values Returns **`true`** if the named constant given by `constant_name` has been defined, **`false`** otherwise. ### Examples **Example #1 Checking Constants** ``` <?php /* Note the use of quotes, this is important.  This example is checking  * if the string 'TEST' is the name of a constant named TEST */ if (defined('TEST')) {     echo TEST; } ?> ``` ### See Also * [define()](function.define) - Defines a named constant * [constant()](function.constant) - Returns the value of a constant * [get\_defined\_constants()](function.get-defined-constants) - Returns an associative array with the names of all the constants and their values * [function\_exists()](function.function-exists) - Return true if the given function has been defined * The section on [Constants](language.constants) php ResourceBundle::get ResourceBundle::get =================== resourcebundle\_get =================== (PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0) ResourceBundle::get -- resourcebundle\_get — Get data from the bundle ### Description Object-oriented style ``` public ResourceBundle::get(string|int $index, bool $fallback = true): mixed ``` Procedural style ``` resourcebundle_get(ResourceBundle $bundle, string|int $index, bool $fallback = true): mixed ``` Get the data from the bundle by index or string key. ### Parameters `bundle` [ResourceBundle](class.resourcebundle) object. `index` Data index, must be string or integer. `fallback` Whether locale should match exactly or fallback to parent locale is allowed. ### Return Values Returns the data located at the index or **`null`** on error. Strings, integers and binary data strings are returned as corresponding PHP types, integer array is returned as PHP array. Complex types are returned as [ResourceBundle](class.resourcebundle) object. ### Examples **Example #1 **resourcebundle\_get()** example** ``` <?php $r = resourcebundle_create( 'es', "/usr/share/data/myapp"); echo resourcebundle_get($r, 'somestring'); ?> ``` **Example #2 OO example** ``` <?php $r = new ResourceBundle( 'es', "/usr/share/data/myapp"); echo $r->get('somestring'); ?> ``` The above example will output: ``` ?Hola, mundo! ``` ### See Also * [resourcebundle\_count()](resourcebundle.count) - Get number of elements in the bundle php EventHttpConnection::setLocalAddress EventHttpConnection::setLocalAddress ==================================== (PECL event >= 1.2.6-beta) EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made ### Description ``` public EventHttpConnection::setLocalAddress( string $address ): void ``` Sets the IP address from which http connections are made. ### Parameters `address` The IP address from which HTTP connections are made. ### Return Values No value is returned. ### See Also * [EventHttpConnection::setLocalPort()](eventhttpconnection.setlocalport) - Sets the local port from which connections are made php ibase_blob_import ibase\_blob\_import =================== (PHP 5, PHP 7 < 7.4.0) ibase\_blob\_import — Create blob, copy file in it, and close it ### Description ``` ibase_blob_import(resource $link_identifier, resource $file_handle): string ``` ``` ibase_blob_import(resource $file_handle): string ``` This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id. ### Parameters `link_identifier` An InterBase link identifier. If omitted, the last opened link is assumed. `file_handle` The file handle is a handle returned by [fopen()](function.fopen). ### Return Values Returns the BLOB id on success, or **`false`** on error. ### Examples **Example #1 **ibase\_blob\_import()** example** ``` <?php $dbh = ibase_connect($host, $username, $password); $filename = '/tmp/bar'; $fd = fopen($filename, 'r'); if ($fd) {     $blob = ibase_blob_import($dbh, $fd);     fclose($fd);     if (!is_string($blob)) {         // import failed     } else {         $query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";         $prepared = ibase_prepare($dbh, $query);         if (!ibase_execute($prepared, $blob)) {             // record insertion failed         }     } } else {     // unable to open the data file } ?> ``` ### See Also * [ibase\_blob\_add()](function.ibase-blob-add) - Add data into a newly created blob * [ibase\_blob\_cancel()](function.ibase-blob-cancel) - Cancel creating blob * [ibase\_blob\_close()](function.ibase-blob-close) - Close blob * [ibase\_blob\_create()](function.ibase-blob-create) - Create a new blob for adding data php Event::signal Event::signal ============= (PECL event >= 1.2.6-beta) Event::signal — Constructs signal event object ### Description ``` public static Event::signal( EventBase $base , int $signum , callable $cb , mixed $arg = ? ): Event ``` Constructs signal event object. This is a straightforward method to create a signal event. Note, the generic [Event::\_\_construct()](event.construct) method can contruct signal event objects too. ### Parameters `base` The associated event base object. `signum` The signal number. `cb` The signal event callback. See [Event callbacks](https://www.php.net/manual/en/event.callbacks.php) . `arg` Custom data. If specified, it will be passed to the callback when event triggers. ### Return Values Returns Event object on success. Otherwise **`false`**. ### See Also * [Constructing signal events](https://www.php.net/manual/en/event.constructing.signal.events.php) php IntlDateFormatter::getTimeType IntlDateFormatter::getTimeType ============================== datefmt\_get\_timetype ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) IntlDateFormatter::getTimeType -- datefmt\_get\_timetype — Get the timetype used for the IntlDateFormatter ### Description Object-oriented style ``` public IntlDateFormatter::getTimeType(): int|false ``` Procedural style ``` datefmt_get_timetype(IntlDateFormatter $formatter): int|false ``` Return time type used by the formatter. ### Parameters `formatter` The formatter resource. ### Return Values The current [date type](class.intldateformatter#intl.intldateformatter-constants) value of the formatter, or **`false`** on failure. ### Examples **Example #1 **datefmt\_get\_timetype()** example** ``` <?php $fmt = datefmt_create(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'timetype of the formatter is : ' . datefmt_get_timetype($fmt); echo 'First Formatted output with timetype is ' . datefmt_format($fmt, 0); $fmt = datefmt_create(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::SHORT,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'Now timetype of the formatter is : ' . datefmt_get_timetype($fmt); echo 'Second Formatted output with timetype is ' . datefmt_format($fmt, 0); ?> ``` **Example #2 OO example** ``` <?php $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'timetype of the formatter is : ' . $fmt->getTimeType(); echo 'First Formatted output is ' . $fmt->format(0); $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::SHORT,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'Now timetype of the formatter is : ' . $fmt->getTimeType(); echo 'Second Formatted output is ' . $fmt->format(0); ?> ``` The above example will output: ``` timetype of the formatter is : 0 First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT Now timetype of the formatter is : 3 Second Formatted output is Wednesday, December 31, 1969 4:00 PM ``` ### See Also * [datefmt\_get\_datetype()](intldateformatter.getdatetype) - Get the datetype used for the IntlDateFormatter * [datefmt\_create()](intldateformatter.create) - Create a date formatter php empty empty ===== (PHP 4, PHP 5, PHP 7, PHP 8) empty — Determine whether a variable is empty ### Description ``` empty(mixed $var): bool ``` Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals **`false`**. **empty()** does not generate a warning if the variable does not exist. ### Parameters `var` Variable to be checked No warning is generated if the variable does not exist. That means **empty()** is essentially the concise equivalent to **!isset($var) || $var == false**. ### Return Values Returns **`true`** if `var` does not exist or has a value that is empty or equal to zero, aka falsey, see [conversion to boolean](language.types.boolean#language.types.boolean.casting). Otherwise returns **`false`**. ### Examples **Example #1 A simple **empty()** / [isset()](function.isset) comparison.** ``` <?php $var = 0; // Evaluates to true because $var is empty if (empty($var)) {     echo '$var is either 0, empty, or not set at all'; } // Evaluates as true because $var is set if (isset($var)) {     echo '$var is set even though it is empty'; } ?> ``` **Example #2 **empty()** on String Offsets** ``` <?php $expected_array_got_string = 'somestring'; var_dump(empty($expected_array_got_string['some_key'])); var_dump(empty($expected_array_got_string[0])); var_dump(empty($expected_array_got_string['0'])); var_dump(empty($expected_array_got_string[0.5])); var_dump(empty($expected_array_got_string['0.5'])); var_dump(empty($expected_array_got_string['0 Mostel'])); ?> ``` The above example will output: ``` bool(true) bool(false) bool(false) bool(false) bool(true) bool(true) ``` ### Notes > **Note**: Because this is a language construct and not a function, it cannot be called using [variable functions](functions.variable-functions), or [named arguments](functions.arguments#functions.named-arguments). > > > > **Note**: > > > When using **empty()** on inaccessible object properties, the [\_\_isset()](language.oop5.overloading#object.isset) overloading method will be called, if declared. > > ### See Also * [isset()](function.isset) - Determine if a variable is declared and is different than null * [\_\_isset()](language.oop5.overloading#object.isset) * [unset()](function.unset) - Unset a given variable * [array\_key\_exists()](function.array-key-exists) - Checks if the given key or index exists in the array * [count()](function.count) - Counts all elements in an array or in a Countable object * [strlen()](function.strlen) - Get string length * [The type comparison tables](https://www.php.net/manual/en/types.comparisons.php) php DateTimeInterface::getTimestamp DateTimeInterface::getTimestamp =============================== DateTimeImmutable::getTimestamp =============================== DateTime::getTimestamp ====================== date\_timestamp\_get ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) DateTimeInterface::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTime::getTimestamp -- date\_timestamp\_get — Gets the Unix timestamp ### Description Object-oriented style ``` public DateTimeInterface::getTimestamp(): int ``` ``` public DateTimeImmutable::getTimestamp(): int ``` ``` public DateTime::getTimestamp(): int ``` Procedural style ``` date_timestamp_get(DateTimeInterface $object): int ``` Gets the Unix timestamp. ### Parameters This function has no parameters. ### Return Values Returns the Unix timestamp representing the date. ### Errors/Exceptions If the timestamp cannot be represented as int, a [ValueError](class.valueerror) is thrown. Prior to PHP 8.0.0, **`false`** was returned in this case. Still, the timestamp can be retrieved as string by using [DateTimeInterface::format()](datetime.format) with the `U` format. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | These functions no longer return **`false`** on failure. | ### Examples **Example #1 **DateTime::getTimestamp()** example** Object-oriented style ``` <?php $date = new DateTimeImmutable(); echo $date->getTimestamp(); ?> ``` Procedural style ``` <?php $date = date_create(); echo date_timestamp_get($date); ?> ``` The above examples will output something similar to: ``` 1272509157 ``` ### See Also * [DateTime::setTimestamp()](datetime.settimestamp) - Sets the date and time based on an Unix timestamp * [DateTime::format()](datetime.format) - Returns date formatted according to given format php atanh atanh ===== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) atanh — Inverse hyperbolic tangent ### Description ``` atanh(float $num): float ``` Returns the inverse hyperbolic tangent of `num`, i.e. the value whose hyperbolic tangent is `num`. ### Parameters `num` The argument to process ### Return Values Inverse hyperbolic tangent of `num` ### See Also * [tanh()](function.tanh) - Hyperbolic tangent * [atan()](function.atan) - Arc tangent * [asinh()](function.asinh) - Inverse hyperbolic sine * [acosh()](function.acosh) - Inverse hyperbolic cosine php SolrQuery::setOmitHeader SolrQuery::setOmitHeader ======================== (PECL solr >= 0.9.2) SolrQuery::setOmitHeader — Exclude the header from the returned results ### Description ``` public SolrQuery::setOmitHeader(bool $flag): SolrQuery ``` Exclude the header from the returned results. ### Parameters `flag` **`true`** excludes the header from the result. ### Return Values Returns the current SolrQuery object, if the return value is used. php mysqli_stmt::fetch mysqli\_stmt::fetch =================== mysqli\_stmt\_fetch =================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::fetch -- mysqli\_stmt\_fetch — Fetch results from a prepared statement into the bound variables ### Description Object-oriented style ``` public mysqli_stmt::fetch(): ?bool ``` Procedural style ``` mysqli_stmt_fetch(mysqli_stmt $statement): ?bool ``` Fetch the result from a prepared statement into the variables bound by [mysqli\_stmt\_bind\_result()](mysqli-stmt.bind-result). > > **Note**: > > > Note that all columns must be bound by the application before calling **mysqli\_stmt\_fetch()**. > > > > **Note**: > > > Data are transferred unbuffered without calling [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result) which can decrease performance (but reduces memory cost). > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values **Return Values**| Value | Description | | --- | --- | | **`true`** | Success. Data has been fetched | | **`false`** | Error occurred | | **`null`** | No more rows/data exists or data truncation occurred | ### Examples **Example #1 Object-oriented style** ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5"; if ($stmt = $mysqli->prepare($query)) {     /* execute statement */     $stmt->execute();     /* bind result variables */     $stmt->bind_result($name, $code);     /* fetch values */     while ($stmt->fetch()) {         printf ("%s (%s)\n", $name, $code);     }     /* close statement */     $stmt->close(); } /* close connection */ $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5"; if ($stmt = mysqli_prepare($link, $query)) {     /* execute statement */     mysqli_stmt_execute($stmt);     /* bind result variables */     mysqli_stmt_bind_result($stmt, $name, $code);     /* fetch values */     while (mysqli_stmt_fetch($stmt)) {         printf ("%s (%s)\n", $name, $code);     }     /* close statement */     mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Rockford (USA) Tallahassee (USA) Salinas (USA) Santa Clarita (USA) Springfield (USA) ``` ### See Also * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_stmt\_errno()](mysqli-stmt.errno) - Returns the error code for the most recent statement call * [mysqli\_stmt\_error()](mysqli-stmt.error) - Returns a string description for last statement error * [mysqli\_stmt\_bind\_result()](mysqli-stmt.bind-result) - Binds variables to a prepared statement for result storage
programming_docs
php file file ==== (PHP 4, PHP 5, PHP 7, PHP 8) file — Reads entire file into an array ### Description ``` file(string $filename, int $flags = 0, ?resource $context = null): array|false ``` Reads an entire file into an array. > > **Note**: > > > You can use [file\_get\_contents()](function.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](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) 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](https://www.php.net/manual/en/ini.core.php#ini.include-path). **`FILE_IGNORE_NEW_LINES`** Omit newline at the end of each array element **`FILE_SKIP_EMPTY_LINES`** Skip empty lines `context` A [context stream](https://www.php.net/manual/en/stream.contexts.php) resource. ### Return Values Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, **file()** returns **`false`**. > > **Note**: > > > Each line in the resulting array will include the line ending, unless **`FILE_IGNORE_NEW_LINES`** is used. > > > **Note**: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the [auto\_detect\_line\_endings](https://www.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings) run-time configuration option may help resolve the problem. > > ### Errors/Exceptions Emits an **`E_WARNING`** level error if the file does not exist. ### Examples **Example #1 **file()** example** ``` <?php // Get a file into an array.  In this example we'll go through HTTP to get // the HTML source of a URL. $lines = file('http://www.example.com/'); // Loop through our array, show HTML source as HTML source; and line numbers too. foreach ($lines as $line_num => $line) {     echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n"; } // Using the optional flags parameter $trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); ?> ``` ### Notes **Warning**When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a `close_notify` indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of [error\_reporting](https://www.php.net/manual/en/errorfunc.configuration.php#ini.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()](function.fsockopen) to create an `ssl://` socket, the developer is responsible for detecting and suppressing this warning. ### See Also * [file\_get\_contents()](function.file-get-contents) - Reads entire file into a string * [readfile()](function.readfile) - Outputs a file * [fopen()](function.fopen) - Opens file or URL * [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection * [popen()](function.popen) - Opens process file pointer * [include](function.include) - include * [stream\_context\_create()](function.stream-context-create) - Creates a stream context php The SolrClientException class The SolrClientException class ============================= Introduction ------------ (PECL solr >= 0.9.2) An exception thrown when there is an error while making a request to the server from the client. Class synopsis -------------- class **SolrClientException** extends [SolrException](class.solrexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; protected int [$sourceline](class.solrexception#solrexception.props.sourceline); protected string [$sourcefile](class.solrexception#solrexception.props.sourcefile); protected string [$zif\_name](class.solrexception#solrexception.props.zif-name); /\* Methods \*/ ``` public getInternalInfo(): array ``` /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` ``` public SolrException::getInternalInfo(): array ``` } Table of Contents ----------------- * [SolrClientException::getInternalInfo](solrclientexception.getinternalinfo) — Returns internal information where the Exception was thrown php QuickHashStringIntHash::exists QuickHashStringIntHash::exists ============================== (No version information available, might only be in Git) QuickHashStringIntHash::exists — This method checks whether a key is part of the hash ### Description ``` public QuickHashStringIntHash::exists(string $key): bool ``` This method checks whether an entry with the provided key exists in the hash. ### Parameters `key` The key of the entry to check for whether it exists in the hash. ### Return Values Returns **`true`** when the entry was found, or **`false`** when the entry is not found. php apache_get_version apache\_get\_version ==================== (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) apache\_get\_version — Fetch Apache version ### Description ``` apache_get_version(): string|false ``` Fetch the Apache version. ### Parameters This function has no parameters. ### Return Values Returns the Apache version on success or **`false`** on failure. ### Examples **Example #1 **apache\_get\_version()** example** ``` <?php $version = apache_get_version(); echo "$version\n"; ?> ``` The above example will output something similar to: ``` Apache/1.3.29 (Unix) PHP/4.3.4 ``` ### See Also * [phpinfo()](function.phpinfo) - Outputs information about PHP's configuration php RarEntry::getVersion RarEntry::getVersion ==================== (PECL rar >= 0.1) RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry ### Description ``` public RarEntry::getVersion(): int ``` Returns minimum version of RAR program (e.g. WinRAR) required to unpack the entry. It is encoded as 10 \* major version + minor version. ### Parameters This function has no parameters. ### Return Values Returns the version or **`false`** on error. ### Examples **Example #1 **RarEntry::getVersion()** example** ``` <?php $rar_file = rar_open('example.rar') or die("Failed to open Rar archive"); $entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry"); echo "Rar version required for unpacking: " . $entry->getVersion(); ?> ``` php Componere\Definition::getClosures Componere\Definition::getClosures ================================= (Componere 2 >= 2.1.0) Componere\Definition::getClosures — Get Closures ### Description ``` public Componere\Definition::getClosures(): array ``` Shall return an array of Closures ### Return Values Shall return all methods as an array of Closure objects bound to the correct scope ### Exceptions **Warning** Shall throw [RuntimeException](class.runtimeexception) if Definition was registered php imagecharup imagecharup =========== (PHP 4, PHP 5, PHP 7, PHP 8) imagecharup — Draw a character vertically ### Description ``` imagecharup( GdImage $image, GdFont|int $font, int $x, int $y, string $char, int $color ): bool ``` Draws the character `char` vertically at the specified coordinate on the given `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `font` Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or [GdFont](class.gdfont) instance, returned by [imageloadfont()](function.imageloadfont). `x` x-coordinate of the start. `y` y-coordinate of the start. `char` The character to draw. `color` A color identifier created with [imagecolorallocate()](function.imagecolorallocate). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `font` parameter now accepts both an [GdFont](class.gdfont) instance and an int; previously only int was accepted. | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagecharup()** example** ``` <?php $im = imagecreate(100, 100); $string = 'Note that the first letter is a N'; $bg = imagecolorallocate($im, 255, 255, 255); $black = imagecolorallocate($im, 0, 0, 0); // prints a black "Z" on a white background imagecharup($im, 3, 10, 10, $string, $black); header('Content-type: image/png'); imagepng($im); ?> ``` The above example will output something similar to: ### See Also * [imagechar()](function.imagechar) - Draw a character horizontally * [imageloadfont()](function.imageloadfont) - Load a new font php Imagick::transformImage Imagick::transformImage ======================= (PECL imagick 2, PECL imagick 3) Imagick::transformImage — Convenience method for setting crop size and the image geometry **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::transformImage(string $crop, string $geometry): Imagick ``` A convenience method for setting crop size and the image geometry from strings. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `crop` A crop geometry string. This geometry defines a subregion of the image to crop. `geometry` An image geometry string. This geometry defines the final size of the image. ### Return Values Returns an Imagick object containing the transformed image. ### Examples **Example #1 Using **Imagick::transformImage()**:** The example creates a 100x100 black image. ``` <?php $image = new Imagick(); $image->newImage(300, 200, "black"); $new_image = $image->transformImage("100x100", "100x100"); $new_image->writeImage('test_out.jpg'); ?> ``` ### See Also * [Imagick::cropImage()](imagick.cropimage) - Extracts a region of the image * [Imagick::resizeImage()](imagick.resizeimage) - Scales an image * [Imagick::thumbnailImage()](imagick.thumbnailimage) - Changes the size of an image php None Value listing ------------- Both Pure Enums and Backed Enums implement an internal interface named [UnitEnum](class.unitenum). `UnitEnum` includes a static method `cases()`. `cases()` returns a packed array of all defined Cases in the order of declaration. ``` <?php Suit::cases(); // Produces: [Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades] ?> ``` Manually defining a `cases()` method on an Enum will result in a fatal error. php fdf_get_flags fdf\_get\_flags =============== (PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_get\_flags — Gets the flags of a field ### Description ``` fdf_get_flags(resource $fdf_document, string $fieldname, int $whichflags): int ``` **Warning**This function is currently not documented; only its argument list is available. php ReflectionFunction::export ReflectionFunction::export ========================== (PHP 5, PHP 7) ReflectionFunction::export — Exports function **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public static ReflectionFunction::export(string $name, string $return = ?): string ``` Exports a Reflected function. ### Parameters `name` The reflection to export. `return` Setting to **`true`** will return the export, as opposed to emitting it. Setting to **`false`** (the default) will do the opposite. ### Return Values If the `return` parameter is set to **`true`**, then the export is returned as a string, otherwise **`null`** is returned. ### See Also * [ReflectionFunction::invoke()](reflectionfunction.invoke) - Invokes function * [ReflectionFunction::\_\_toString()](reflectionfunction.tostring) - To string php The MultipleIterator class The MultipleIterator class ========================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) An Iterator that sequentially iterates over all attached iterators Class synopsis -------------- class **MultipleIterator** implements [Iterator](class.iterator) { /\* Constants \*/ public const int [MIT\_NEED\_ANY](class.multipleiterator#multipleiterator.constants.mit-need-any); public const int [MIT\_NEED\_ALL](class.multipleiterator#multipleiterator.constants.mit-need-all); public const int [MIT\_KEYS\_NUMERIC](class.multipleiterator#multipleiterator.constants.mit-keys-numeric); public const int [MIT\_KEYS\_ASSOC](class.multipleiterator#multipleiterator.constants.mit-keys-assoc); /\* Methods \*/ public [\_\_construct](multipleiterator.construct)(int `$flags` = MultipleIterator::MIT\_NEED\_ALL | MultipleIterator::MIT\_KEYS\_NUMERIC) ``` public attachIterator(Iterator $iterator, string|int|null $info = null): void ``` ``` public containsIterator(Iterator $iterator): bool ``` ``` public countIterators(): int ``` ``` public current(): array ``` ``` public detachIterator(Iterator $iterator): void ``` ``` public getFlags(): int ``` ``` public key(): array ``` ``` public next(): void ``` ``` public rewind(): void ``` ``` public setFlags(int $flags): void ``` ``` public valid(): bool ``` } Predefined Constants -------------------- **`MultipleIterator::MIT_NEED_ANY`** Do not require all sub iterators to be valid in iteration. **`MultipleIterator::MIT_NEED_ALL`** Require all sub iterators to be valid in iteration. **`MultipleIterator::MIT_KEYS_NUMERIC`** Keys are created from the sub iterators position. **`MultipleIterator::MIT_KEYS_ASSOC`** Keys are created from sub iterators associated information. Table of Contents ----------------- * [MultipleIterator::attachIterator](multipleiterator.attachiterator) — Attaches iterator information * [MultipleIterator::\_\_construct](multipleiterator.construct) — Constructs a new MultipleIterator * [MultipleIterator::containsIterator](multipleiterator.containsiterator) — Checks if an iterator is attached * [MultipleIterator::countIterators](multipleiterator.countiterators) — Gets the number of attached iterator instances * [MultipleIterator::current](multipleiterator.current) — Gets the registered iterator instances * [MultipleIterator::detachIterator](multipleiterator.detachiterator) — Detaches an iterator * [MultipleIterator::getFlags](multipleiterator.getflags) — Gets the flag information * [MultipleIterator::key](multipleiterator.key) — Gets the registered iterator instances * [MultipleIterator::next](multipleiterator.next) — Moves all attached iterator instances forward * [MultipleIterator::rewind](multipleiterator.rewind) — Rewinds all attached iterator instances * [MultipleIterator::setFlags](multipleiterator.setflags) — Sets flags * [MultipleIterator::valid](multipleiterator.valid) — Checks the validity of sub iterators php sodium_crypto_pwhash_scryptsalsa208sha256 sodium\_crypto\_pwhash\_scryptsalsa208sha256 ============================================ (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_pwhash\_scryptsalsa208sha256 — Derives a key from a password, using scrypt ### Description ``` sodium_crypto_pwhash_scryptsalsa208sha256( int $length, string $password, string $salt, int $opslimit, int $memlimit ): string ``` This is the scrypt counterpart to [sodium\_crypto\_pwhash()](function.sodium-crypto-pwhash). A common reason to use this particular function is to derive the seeds for cryptographic keys from a password and salt, and then use these seeds to generate the actual keys needed for some purpose (e.g. [sodium\_crypto\_sign\_detached()](function.sodium-crypto-sign-detached)). ### Parameters `length` The length of the password hash to generate, in bytes. `password` The password to generate a hash for. `salt` A salt to add to the password before hashing. The salt should be unpredictable, ideally generated from a good random number source such as [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php), and have a length of at least **`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES`** bytes. `opslimit` Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are some constants available to set the operations limit to appropriate values depending on intended use, in order of strength: **`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE`** and **`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE`**. `memlimit` The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: **`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE`** and **`SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE`**. Typically these should be paired with the matching `opslimit` values. ### Return Values A string of bytes of the desired length. php EvLoop::periodic EvLoop::periodic ================ (PECL ev >= 0.2.0) EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance ### Description ``` final public EvLoop::periodic( float $offset , float $interval , callable $callback , mixed $data = null , int $priority = 0 ): EvPeriodic ``` Creates EvPeriodic watcher object associated with the current event loop instance ### Parameters All parameters have the same maening as for [EvPeriodic::\_\_construct()](evperiodic.construct) ### Return Values Returns EvPeriodic object on success. ### See Also * [EvPeriodic::\_\_construct()](evperiodic.construct) - Constructs EvPeriodic watcher object php SolrDocument::current SolrDocument::current ===================== (PECL solr >= 0.9.2) SolrDocument::current — Retrieves the current field ### Description ``` public SolrDocument::current(): SolrDocumentField ``` Retrieves the current field ### Parameters This function has no parameters. ### Return Values Returns the field
programming_docs
php Gmagick::getimagetype Gmagick::getimagetype ===================== (PECL gmagick >= Unknown) Gmagick::getimagetype — Gets the potential image type ### Description ``` public Gmagick::getimagetype(): int ``` Gets the potential image type. ### Parameters This function has no parameters. ### Return Values Returns the potential image type. ### Errors/Exceptions Throws an **GmagickException** on error. php sodium_crypto_sign_detached sodium\_crypto\_sign\_detached ============================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_sign\_detached — Sign the message ### Description ``` sodium_crypto_sign_detached(string $message, string $secret_key): string ``` Sign a message with a secret key, that can be verified by the corresponding public key. This function returns a detached signature. ### Parameters `message` Message to sign. `secret_key` Secret key. See [sodium\_crypto\_sign\_secretkey()](function.sodium-crypto-sign-secretkey) ### Return Values Cryptographic signature. php imap_close imap\_close =========== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_close — Close an IMAP stream ### Description ``` imap_close(IMAP\Connection $imap, int $flags = 0): bool ``` Closes the imap stream. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `flags` If set to **`CL_EXPUNGE`**, the function will silently expunge the mailbox before closing, removing all messages marked for deletion. You can achieve the same thing by using [imap\_expunge()](function.imap-expunge) ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_open()](function.imap-open) - Open an IMAP stream to a mailbox php rar_wrapper_cache_stats rar\_wrapper\_cache\_stats ========================== (PECL rar >= 3.0.0) rar\_wrapper\_cache\_stats — Cache hits and misses for the URL wrapper ### Description ``` rar_wrapper_cache_stats(): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Ds\Sequence::shift Ds\Sequence::shift ================== (PECL ds >= 1.0.0) Ds\Sequence::shift — Removes and returns the first value ### Description ``` abstract public Ds\Sequence::shift(): mixed ``` Removes and returns the first value. ### Parameters This function has no parameters. ### Return Values The first value, which was removed. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Sequence::shift()** example** ``` <?php $sequence = new \Ds\Vector(["a", "b", "c"]); var_dump($sequence->shift()); var_dump($sequence->shift()); var_dump($sequence->shift()); ?> ``` The above example will output something similar to: ``` string(1) "a" string(1) "b" string(1) "c" ``` php json_last_error json\_last\_error ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) json\_last\_error — Returns the last error occurred ### Description ``` json_last_error(): int ``` Returns the last error (if any) occurred during the last JSON encoding/decoding, which did not specify **`JSON_THROW_ON_ERROR`**. ### Parameters This function has no parameters. ### Return Values Returns an integer, the value can be one of the following constants: **JSON error codes**| Constant | Meaning | Availability | | --- | --- | --- | | **`JSON_ERROR_NONE`** | No error has occurred | | | **`JSON_ERROR_DEPTH`** | The maximum stack depth has been exceeded | | | **`JSON_ERROR_STATE_MISMATCH`** | Invalid or malformed JSON | | | **`JSON_ERROR_CTRL_CHAR`** | Control character error, possibly incorrectly encoded | | | **`JSON_ERROR_SYNTAX`** | Syntax error | | | **`JSON_ERROR_UTF8`** | Malformed UTF-8 characters, possibly incorrectly encoded | | | **`JSON_ERROR_RECURSION`** | One or more recursive references in the value to be encoded | | | **`JSON_ERROR_INF_OR_NAN`** | One or more [**`NAN`**](language.types.float#language.types.float.nan) or [**`INF`**](function.is-infinite) values in the value to be encoded | | | **`JSON_ERROR_UNSUPPORTED_TYPE`** | A value of a type that cannot be encoded was given | | | **`JSON_ERROR_INVALID_PROPERTY_NAME`** | A property name that cannot be encoded was given | | | **`JSON_ERROR_UTF16`** | Malformed UTF-16 characters, possibly incorrectly encoded | | ### Examples **Example #1 **json\_last\_error()** example** ``` <?php // A valid json string $json[] = '{"Organization": "PHP Documentation Team"}'; // An invalid json string which will cause an syntax  // error, in this case we used ' instead of " for quotation $json[] = "{'Organization': 'PHP Documentation Team'}"; foreach ($json as $string) {     echo 'Decoding: ' . $string;     json_decode($string);     switch (json_last_error()) {         case JSON_ERROR_NONE:             echo ' - No errors';         break;         case JSON_ERROR_DEPTH:             echo ' - Maximum stack depth exceeded';         break;         case JSON_ERROR_STATE_MISMATCH:             echo ' - Underflow or the modes mismatch';         break;         case JSON_ERROR_CTRL_CHAR:             echo ' - Unexpected control character found';         break;         case JSON_ERROR_SYNTAX:             echo ' - Syntax error, malformed JSON';         break;         case JSON_ERROR_UTF8:             echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';         break;         default:             echo ' - Unknown error';         break;     }     echo PHP_EOL; } ?> ``` The above example will output: ``` Decoding: {"Organization": "PHP Documentation Team"} - No errors Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON ``` **Example #2 **json\_last\_error()** with [json\_encode()](function.json-encode)** ``` <?php // An invalid UTF8 sequence $text = "\xB1\x31"; $json  = json_encode($text); $error = json_last_error(); var_dump($json, $error === JSON_ERROR_UTF8); ?> ``` The above example will output: ``` string(4) "null" bool(true) ``` **Example #3 **json\_last\_error()** and **`JSON_THROW_ON_ERROR`**** ``` <?php // An invalid UTF8 sequence which causes JSON_ERROR_UTF8 json_encode("\xB1\x31"); // The following does not cause a JSON error json_encode('okay', JSON_THROW_ON_ERROR); // The global error state has not been changed by the former json_encode() var_dump(json_last_error() === JSON_ERROR_UTF8); ?> ``` The above example will output: ``` bool(true) ``` ### See Also * [json\_last\_error\_msg()](function.json-last-error-msg) - Returns the error string of the last json\_encode() or json\_decode() call * [json\_decode()](function.json-decode) - Decodes a JSON string * [json\_encode()](function.json-encode) - Returns the JSON representation of a value php Pool::submitTo Pool::submitTo ============== (PECL pthreads >= 2.0.0) Pool::submitTo — Submits a task to a specific worker for execution ### Description ``` public Pool::submitTo(int $worker, Threaded $task): int ``` Submit a task to the specified worker in the pool. The workers are indexed from 0, and will only exist if the pool has needed to create them (since threads are lazily spawned). ### Parameters `worker` The worker to stack the task onto, indexed from `0`. `task` The task for execution. ### Return Values The identifier of the worker that accepted the task. ### Examples **Example #1 Submitting tasks to a specific worker** ``` <?php class Task extends Threaded {     public function run() {         var_dump(Thread::getCurrentThreadID());     } } $pool = new Pool(2); $pool->submit(new Task()); for ($i = 0; $i < 5; ++$i) {     $pool->submitTo(0, new Task()); // stack all tasks onto the first worker } $pool->submitTo(1, new Task()); // cannot stack the task onto the second worker due to it not existing yet $pool->shutdown(); ``` The above example will output: ``` int(4475011072) int(4475011072) int(4475011072) int(4475011072) int(4475011072) int(4475011072) Fatal error: Uncaught Exception: The selected worker (1) does not exist in %s:%d ``` php runkit7_method_copy runkit7\_method\_copy ===================== (PECL runkit7 >= Unknown) runkit7\_method\_copy — Copies a method from class to another ### Description ``` runkit7_method_copy( string $destination_class, string $destination_method_name, string $source_class, string $source_method_name = ? ): bool ``` ### Parameters `destination_class` Destination class for copied method `destination_method_name` Destination method name `source_class` Source class of the method to copy `source_method_name` Name of the method to copy from the source class. If this parameter is omitted, the value of `destination_method_name` is assumed. ### Return Values ### Examples **Example #1 **runkit7\_method\_copy()** example** ``` <?php class Foo {     function example() {         return "foo!\n";     } } class Bar {     // initially, no methods } // copy the example() method from the Foo class to the Bar class, as baz() runkit7_method_copy('Bar', 'baz', 'Foo', 'example'); // output copied function echo Bar::baz(); ?> ``` The above example will output: ``` foo! ``` ### See Also * [runkit7\_method\_add()](function.runkit7-method-add) - Dynamically adds a new method to a given class * [runkit7\_method\_redefine()](function.runkit7-method-redefine) - Dynamically changes the code of the given method * [runkit7\_method\_remove()](function.runkit7-method-remove) - Dynamically removes the given method * [runkit7\_method\_rename()](function.runkit7-method-rename) - Dynamically changes the name of the given method * [runkit7\_function\_copy()](function.runkit7-function-copy) - Copy a function to a new function name php imap_append imap\_append ============ (PHP 4, PHP 5, PHP 7, PHP 8) imap\_append — Append a string message to a specified mailbox ### Description ``` imap_append( IMAP\Connection $imap, string $folder, string $message, ?string $options = null, ?string $internal_date = null ): bool ``` Appends a string `message` to the specified `folder`. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `folder` The mailbox name, see [imap\_open()](function.imap-open) for more information **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. `message` The message to be append, as a string When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail `options` If provided, the `options` will also be written to the `folder` `internal_date` If this parameter is set, it will set the INTERNALDATE on the appended message. The parameter should be a date string that conforms to the rfc2060 specifications for a date\_time value. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `options` and `internal_date` are now nullable. | ### Examples **Example #1 **imap\_append()** example** ``` <?php $imap = imap_open("{imap.example.org}INBOX.Drafts", "username", "password"); $check = imap_check($imap); echo "Msg Count before append: ". $check->Nmsgs . "\n"; imap_append($imap, "{imap.example.org}INBOX.Drafts"                    , "From: [email protected]\r\n"                    . "To: [email protected]\r\n"                    . "Subject: test\r\n"                    . "\r\n"                    . "this is a test message, please ignore\r\n"                    ); $check = imap_check($imap); echo "Msg Count after append : ". $check->Nmsgs . "\n"; imap_close($imap); ?> ``` php pg_untrace pg\_untrace =========== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) pg\_untrace — Disable tracing of a PostgreSQL connection ### Description ``` pg_untrace(?PgSql\Connection $connection = null): bool ``` Stop tracing started by [pg\_trace()](function.pg-trace). ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is **`null`**, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. ### Return Values Always returns **`true`**. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `connection` is now nullable. | ### Examples **Example #1 **pg\_untrace()** example** ``` <?php $pgsql_conn = pg_connect("dbname=mark host=localhost"); if ($pgsql_conn) {    pg_trace('/tmp/trace.log', 'w', $pgsql_conn);    pg_query("SELECT 1");    pg_untrace($pgsql_conn);    // Now tracing of backend communication is disabled } else {    print pg_last_error($pgsql_conn);    exit; } ?> ``` ### See Also * [pg\_trace()](function.pg-trace) - Enable tracing a PostgreSQL connection php session_commit session\_commit =============== (PHP 4 >= 4.4.0, PHP 5, PHP 7, PHP 8) session\_commit — Alias of [session\_write\_close()](function.session-write-close) ### Description This function is an alias of: [session\_write\_close()](function.session-write-close). php IntlTimeZone::getDSTSavings IntlTimeZone::getDSTSavings =========================== intltz\_get\_dst\_savings ========================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::getDSTSavings -- intltz\_get\_dst\_savings — Get the amount of time to be added to local standard time to get local wall clock time ### Description Object-oriented style (method): ``` public IntlTimeZone::getDSTSavings(): int ``` Procedural style: ``` intltz_get_dst_savings(IntlTimeZone $timezone): int ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Imagick::getImageFormat Imagick::getImageFormat ======================= (PECL imagick 2, PECL imagick 3) Imagick::getImageFormat — Returns the format of a particular image in a sequence ### Description ``` public Imagick::getImageFormat(): string ``` Returns the format of a particular image in a sequence. ### Parameters This function has no parameters. ### Return Values Returns a string containing the image format on success. ### Errors/Exceptions Throws ImagickException on error. php parse_url parse\_url ========== (PHP 4, PHP 5, PHP 7, PHP 8) parse\_url — Parse a URL and return its components ### Description ``` parse_url(string $url, int $component = -1): int|string|array|null|false ``` This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are *not* URL decoded. This function is *not* meant to validate the given URL, it only breaks it up into the parts listed below. Partial and invalid URLs are also accepted, **parse\_url()** tries its best to parse them correctly. ### Parameters `url` The URL to parse. `component` Specify one of **`PHP_URL_SCHEME`**, **`PHP_URL_HOST`**, **`PHP_URL_PORT`**, **`PHP_URL_USER`**, **`PHP_URL_PASS`**, **`PHP_URL_PATH`**, **`PHP_URL_QUERY`** or **`PHP_URL_FRAGMENT`** to retrieve just a specific URL component as a string (except when **`PHP_URL_PORT`** is given, in which case the return value will be an int). ### Return Values On seriously malformed URLs, **parse\_url()** may return **`false`**. If the `component` parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are: * scheme - e.g. http * host * port * user * pass * path * query - after the question mark `?` * fragment - after the hashmark `#` If the `component` parameter is specified, **parse\_url()** returns a string (or an int, in the case of **`PHP_URL_PORT`**) instead of an array. If the requested component doesn't exist within the given URL, **`null`** will be returned. As of PHP 8.0.0, **parse\_url()** distinguishes absent and empty queries and fragments: ``` http://example.com/foo → query = null, fragment = null http://example.com/foo? → query = "", fragment = null http://example.com/foo# → query = null, fragment = "" http://example.com/foo?# → query = "", fragment = "" ``` Previously all cases resulted in query and fragment being **`null`**. Note that control characters (cf. [ctype\_cntrl()](function.ctype-cntrl)) in the components are replaced with underscores (`_`). ### Changelog | Version | Description | | --- | --- | | 8.0.0 | **parse\_url()** will now distinguish absent and empty queries and fragments. | ### Examples **Example #1 A **parse\_url()** example** ``` <?php $url = 'http://username:password@hostname:9090/path?arg=value#anchor'; var_dump(parse_url($url)); var_dump(parse_url($url, PHP_URL_SCHEME)); var_dump(parse_url($url, PHP_URL_USER)); var_dump(parse_url($url, PHP_URL_PASS)); var_dump(parse_url($url, PHP_URL_HOST)); var_dump(parse_url($url, PHP_URL_PORT)); var_dump(parse_url($url, PHP_URL_PATH)); var_dump(parse_url($url, PHP_URL_QUERY)); var_dump(parse_url($url, PHP_URL_FRAGMENT)); ?> ``` The above example will output: ``` array(8) { ["scheme"]=> string(4) "http" ["host"]=> string(8) "hostname" ["port"]=> int(9090) ["user"]=> string(8) "username" ["pass"]=> string(8) "password" ["path"]=> string(5) "/path" ["query"]=> string(9) "arg=value" ["fragment"]=> string(6) "anchor" } string(4) "http" string(8) "username" string(8) "password" string(8) "hostname" int(9090) string(5) "/path" string(9) "arg=value" string(6) "anchor" ``` **Example #2 A **parse\_url()** example with missing scheme** ``` <?php $url = '//www.example.com/path?googleguy=googley'; // Prior to 5.4.7 this would show the path as "//www.example.com/path" var_dump(parse_url($url)); ?> ``` The above example will output: ``` array(3) { ["host"]=> string(15) "www.example.com" ["path"]=> string(5) "/path" ["query"]=> string(17) "googleguy=googley" } ``` ### Notes **Caution** This function may not give correct results for relative or invalid URLs, and the results may not even match common behavior of HTTP clients. If URLs from untrusted input need to be parsed, extra validation is required, e.g. by using [filter\_var()](function.filter-var) with the **`FILTER_VALIDATE_URL`** filter. > > **Note**: > > > This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP's backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///...) are allowed. For any other scheme this is invalid. > > ### See Also * [pathinfo()](function.pathinfo) - Returns information about a file path * [parse\_str()](function.parse-str) - Parses the string into variables * [http\_build\_query()](function.http-build-query) - Generate URL-encoded query string * [dirname()](function.dirname) - Returns a parent directory's path * [basename()](function.basename) - Returns trailing name component of path * [» RFC 3986](http://www.faqs.org/rfcs/rfc3986)
programming_docs
php Imagick::equalizeImage Imagick::equalizeImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::equalizeImage — Equalizes the image histogram ### Description ``` public Imagick::equalizeImage(): bool ``` Equalizes the image histogram. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::equalizeImage()**** ``` <?php function equalizeImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->equalizeImage();     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php sodium_crypto_auth_keygen sodium\_crypto\_auth\_keygen ============================ (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_auth\_keygen — Generate a random key for sodium\_crypto\_auth ### Description ``` sodium_crypto_auth_keygen(): string ``` Generate a key for use with [sodium\_crypto\_auth()](function.sodium-crypto-auth) and [sodium\_crypto\_auth\_verify()](function.sodium-crypto-auth-verify). ### Parameters This function has no parameters. ### Return Values Returns a 256-bit random key. php Imagick::setImageResolution Imagick::setImageResolution =========================== (PECL imagick 2, PECL imagick 3) Imagick::setImageResolution — Sets the image resolution ### Description ``` public Imagick::setImageResolution(float $x_resolution, float $y_resolution): bool ``` Sets the image resolution. ### Parameters `x_resolution` `y_resolution` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::setImageResolution()**** ``` <?php function setImageResolution($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->setImageResolution(50, 50);          header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php SolrCollapseFunction::getMax SolrCollapseFunction::getMax ============================ (PECL solr >= 2.2.0) SolrCollapseFunction::getMax — Returns max parameter ### Description ``` public SolrCollapseFunction::getMax(): string ``` Returns max parameter ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrCollapseFunction::setMax()](solrcollapsefunction.setmax) - Selects the group heads by the max value of a numeric field or function query php The Yaf_Route_Simple class The Yaf\_Route\_Simple class ============================ Introduction ------------ (Yaf >=1.0.0) **Yaf\_Route\_Simple** will match the query string, and find the route info. all you need to do is tell **Yaf\_Route\_Simple** what key in the $\_GET is module, what key is controller, and what key is action. [Yaf\_Route\_Simple::route()](yaf-route-simple.route) will always return **`true`**, so it is important put **Yaf\_Route\_Simple** in the front of the Route stack, otherwise all the other routes will not be called. Class synopsis -------------- class **Yaf\_Route\_Simple** implements [Yaf\_Route\_Interface](class.yaf-route-interface) { /\* Properties \*/ protected [$controller](class.yaf-route-simple#yaf-route-simple.props.controller); protected [$module](class.yaf-route-simple#yaf-route-simple.props.module); protected [$action](class.yaf-route-simple#yaf-route-simple.props.action); /\* Methods \*/ public [\_\_construct](yaf-route-simple.construct)(string `$module_name`, string `$controller_name`, string `$action_name`) ``` public assemble(array $info, array $query = ?): string ``` ``` public route(Yaf_Request_Abstract $request): bool ``` } Properties ---------- controller module action Table of Contents ----------------- * [Yaf\_Route\_Simple::assemble](yaf-route-simple.assemble) — Assemble a url * [Yaf\_Route\_Simple::\_\_construct](yaf-route-simple.construct) — Yaf\_Route\_Simple constructor * [Yaf\_Route\_Simple::route](yaf-route-simple.route) — Route a request php sqlsrv_fetch_object sqlsrv\_fetch\_object ===================== (No version information available, might only be in Git) sqlsrv\_fetch\_object — Retrieves the next row of data in a result set as an object ### Description ``` sqlsrv_fetch_object( resource $stmt, string $className = ?, array $ctorParams = ?, int $row = ?, int $offset = ? ): mixed ``` Retrieves the next row of data in a result set as an instance of the specified class with properties that match the row field names and values that correspond to the row field values. ### Parameters `stmt` A statement resource created by [sqlsrv\_query()](function.sqlsrv-query) or [sqlsrv\_execute()](function.sqlsrv-execute). `className` The name of the class to instantiate. If no class name is specified, stdClass is instantiated. `ctorParams` Values passed to the constructor of the specified class. If the constructor of the specified class takes parameters, the ctorParams array must be supplied. `row` The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values: * SQLSRV\_SCROLL\_NEXT * SQLSRV\_SCROLL\_PRIOR * SQLSRV\_SCROLL\_FIRST * SQLSRV\_SCROLL\_LAST * SQLSRV\_SCROLL\_ABSOLUTE * SQLSRV\_SCROLL\_RELATIVE `offset` Specifies the row to be accessed if the row parameter is set to **`SQLSRV_SCROLL_ABSOLUTE`** or **`SQLSRV_SCROLL_RELATIVE`**. Note that the first row in a result set has index 0. ### Return Values Returns an object on success, **`null`** if there are no more rows to return, and **`false`** if an error occurs or if the specified class does not exist. ### Examples **Example #1 **sqlsrv\_fetch\_object()** example** The following example demonstrates how to retrieve a row as a stdClass object. ``` <?php $serverName = "serverName\sqlexpress"; $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false ) {      die( print_r( sqlsrv_errors(), true)); } $sql = "SELECT fName, lName FROM Table_1"; $stmt = sqlsrv_query( $conn, $sql); if( $stmt === false ) {      die( print_r( sqlsrv_errors(), true)); } // Retrieve each row as an object. // Because no class is specified, each row will be retrieved as a stdClass object. // Property names correspond to field names. while( $obj = sqlsrv_fetch_object( $stmt)) {       echo $obj->fName.", ".$obj->lName."<br />"; } ?> ``` ### Notes If a class name is specified with the optional $className parameter and the class has properties whose names match the result set field names, the corresponding result set values are applied to the properties. If a result set field name does not match a class property, a property with the result set field name is added to the object and the result set value is applied to the property. The following rules apply when using the $className parameter: * Field-property name matching is case-sensitive. * Field-property matching occurs regardless of access modifiers. * Class property data types are ignored when applying a field value to a property. * If the class does not exist, the function returns **`false`** and adds an error to the error collection. Regardless of whether the $className parameter is supplied, if a field with no name is returned, the field value will be ignored and a warning will be added to the error collection. When consuming a result set that has multiple columns with the same name, it may be better to use [sqlsrv\_fetch\_array()](function.sqlsrv-fetch-array) or the combination of [sqlsrv\_fetch()](function.sqlsrv-fetch) and [sqlsrv\_get\_field()](function.sqlsrv-get-field). ### See Also * [sqlsrv\_fetch()](function.sqlsrv-fetch) - Makes the next row in a result set available for reading * [sqlsrv\_fetch\_array()](function.sqlsrv-fetch-array) - Returns a row as an array php streamWrapper::stream_lock streamWrapper::stream\_lock =========================== (PHP 5, PHP 7, PHP 8) streamWrapper::stream\_lock — Advisory file locking ### Description ``` public streamWrapper::stream_lock(int $operation): bool ``` This method is called in response to [flock()](function.flock), when [file\_put\_contents()](function.file-put-contents) (when `flags` contains **`LOCK_EX`**), [stream\_set\_blocking()](function.stream-set-blocking) and when closing the stream (**`LOCK_UN`**). ### Parameters `operation` `operation` is one of the following: * **`LOCK_SH`** to acquire a shared lock (reader). * **`LOCK_EX`** to acquire an exclusive lock (writer). * **`LOCK_UN`** to release a lock (shared or exclusive). * **`LOCK_NB`** if you don't want [flock()](function.flock) to block while locking. (not supported on Windows) ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Emits **`E_WARNING`** if call to this method fails (i.e. not implemented). ### See Also * [stream\_set\_blocking()](function.stream-set-blocking) - Set blocking/non-blocking mode on a stream * [flock()](function.flock) - Portable advisory file locking php fbird_server_info fbird\_server\_info =================== (PHP 5, PHP 7 < 7.4.0) fbird\_server\_info — Alias of [ibase\_server\_info()](function.ibase-server-info) ### Description This function is an alias of: [ibase\_server\_info()](function.ibase-server-info). php IntlChar::isdigit IntlChar::isdigit ================= (PHP 7, PHP 8) IntlChar::isdigit — Check if code point is a digit character ### Description ``` public static IntlChar::isdigit(int|string $codepoint): ?bool ``` Determines whether the specified code point is a digit character. **`true`** for characters with general category "Nd" (decimal digit numbers). Beginning with Unicode 4, this is the same as testing for the Numeric\_Type of Decimal. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` is a digit character, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isdigit("A")); var_dump(IntlChar::isdigit("1")); var_dump(IntlChar::isdigit("\t")); ?> ``` The above example will output: ``` bool(false) bool(true) bool(false) ``` ### See Also * [IntlChar::isalpha()](intlchar.isalpha) - Check if code point is a letter character * [IntlChar::isalnum()](intlchar.isalnum) - Check if code point is an alphanumeric character * [IntlChar::isxdigit()](intlchar.isxdigit) - Check if code point is a hexadecimal digit php eio_fsync eio\_fsync ========== (PECL eio >= 0.0.1dev) eio\_fsync — Synchronize a file's in-core state with storage device ### Description ``` eio_fsync( mixed $fd, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` Synchronize a file's in-core state with storage device ### Parameters `fd` Stream, Socket resource, or numeric file descriptor. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_fsync()** returns request resource on success, or **`false`** on failure. ### See Also * [eio\_sync()](function.eio-sync) - Commit buffer cache to disk php sqlsrv_errors sqlsrv\_errors ============== (No version information available, might only be in Git) sqlsrv\_errors — Returns error and warning information about the last SQLSRV operation performed ### Description ``` sqlsrv_errors(int $errorsOrWarnings = ?): mixed ``` Returns error and warning information about the last SQLSRV operation performed. ### Parameters `errorsOrWarnings` Determines whether error information, warning information, or both are returned. If this parameter is not supplied, both error information and warning information are returned. The following are the supported values for this parameter: SQLSRV\_ERR\_ALL, SQLSRV\_ERR\_ERRORS, SQLSRV\_ERR\_WARNINGS. ### Return Values If errors and/or warnings occurred on the last sqlsrv operation, an array of arrays containing error information is returned. If no errors and/or warnings occurred on the last sqlsrv operation, **`null`** is returned. The following table describes the structure of the returned arrays: **Array returned by sqlsrv\_errors**| Key | Description | | --- | --- | | SQLSTATE | For errors that originate from the ODBC driver, the SQLSTATE returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of 01SSP. | | code | For errors that originate from SQL Server, the native SQL Server error code. For errors that originate from the ODBC driver, the error code returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers for PHP for SQL Server error code. | | message | A description of the error. | ### Examples **Example #1 **functionname()** example** ``` <?php $serverName = "serverName/sqlexpress"; $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false ) {      die( print_r( sqlsrv_errors(), true)); } /* Set up a query to select an invalid column name. */ $sql = "SELECT BadColumnName FROM Table_1"; /* Execution of the query will fail because of the bad column name. */ $stmt = sqlsrv_query( $conn, $sql ); if( $stmt === false ) {     if( ($errors = sqlsrv_errors() ) != null) {         foreach( $errors as $error ) {             echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";             echo "code: ".$error[ 'code']."<br />";             echo "message: ".$error[ 'message']."<br />";         }     } } ?> ``` ### Notes By default, warnings generated on a call to any SQLSRV function are treated as errors. This means that if a warning occurs on a call to a SQLSRV function, the function returns **`false`**. However, warnings that correspond to SQLSTATE values 01000, 01001, 01003, and 01S02 are never treated as errors. For information about changing this behavior, see [sqlsrv\_configure()](function.sqlsrv-configure) and the WarningsReturnAsErrors setting. ### See Also * [sqlsrv\_configure()](function.sqlsrv-configure) - Changes the driver error handling and logging configurations php Event::set Event::set ========== (PECL event >= 1.2.6-beta) Event::set — Re-configures event ### Description ``` public Event::set( EventBase $base , mixed $fd , int $what = ?, callable $cb = ?, mixed $arg = ? ): bool ``` Re-configures event. Note, this function doesn't invoke obsolete libevent's event\_set. It calls event\_assign instead. ### Parameters `base` The event base to associate the event with. `fd` Stream resource, socket resource, or numeric file descriptor. For timer events pass **`-1`** . For signal events pass the signal number, e.g. **`SIGHUP`** . `what` See [Event flags](https://www.php.net/manual/en/event.flags.php) . `cb` The event callback. See [Event callbacks](https://www.php.net/manual/en/event.callbacks.php) . `arg` Custom data associated with the event. It will be passed to the callback when the event becomes active. ### Return Values Returns **`true`** on success or **`false`** on failure. php msg_stat_queue msg\_stat\_queue ================ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) msg\_stat\_queue — Returns information from the message queue data structure ### Description ``` msg_stat_queue(SysvMessageQueue $queue): array|false ``` **msg\_stat\_queue()** returns the message queue meta data for the message queue specified by the `queue`. This is useful, for example, to determine which process sent the message that was just received. ### Parameters `queue` The message queue. ### Return Values On success, the return value is an array whose keys and values have the following meanings: **Array structure for msg\_stat\_queue**| `msg_perm.uid` | The uid of the owner of the queue. | | `msg_perm.gid` | The gid of the owner of the queue. | | `msg_perm.mode` | The file access mode of the queue. | | `msg_stime` | The time that the last message was sent to the queue. | | `msg_rtime` | The time that the last message was received from the queue. | | `msg_ctime` | The time that the queue was last changed. | | `msg_qnum` | The number of messages waiting to be read from the queue. | | `msg_qbytes` | The maximum number of bytes allowed in one message queue. On Linux, this value may be read and modified via /proc/sys/kernel/msgmnb. | | `msg_lspid` | The pid of the process that sent the last message to the queue. | | `msg_lrpid` | The pid of the process that received the last message from the queue. | Returns **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `queue` expects a [SysvMessageQueue](class.sysvmessagequeue) instance now; previously, a resource was expected. | ### See Also * [msg\_remove\_queue()](function.msg-remove-queue) - Destroy a message queue * [msg\_receive()](function.msg-receive) - Receive a message from a message queue * [msg\_get\_queue()](function.msg-get-queue) - Create or attach to a message queue * [msg\_set\_queue()](function.msg-set-queue) - Set information in the message queue data structure php openssl_x509_verify openssl\_x509\_verify ===================== (PHP 7 >= 7.4.0, PHP 8) openssl\_x509\_verify — Verifies digital signature of x509 certificate against a public key ### Description ``` openssl_x509_verify(OpenSSLCertificate|string $certificate, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key): int ``` **openssl\_x509\_verify()** verifies that the `certificate` certificate was signed by the private key corresponding to public key `public_key`. ### Parameters `x509` See [Key/Certificate parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values. `public_key` [OpenSSLAsymmetricKey](class.opensslasymmetrickey) - a key, returned by [openssl\_get\_publickey()](function.openssl-get-publickey) string - a PEM formatted key, example, "-----BEGIN PUBLIC KEY----- MIIBCgK..." ### Return Values Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was accepted. | | 8.0.0 | `public_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) or [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` or `OpenSSL X.509` was accepted. | ### Examples **Example #1 **openssl\_x509\_verify()** example** ``` <?php $hostname = "news.php.net"; $ssloptions = array(     "capture_peer_cert" => true,      "capture_peer_cert_chain" => true,      "allow_self_signed"=> false,      "CN_match" => $hostname,     "verify_peer" => true,     "SNI_enabled" => true,     "SNI_server_name" => $hostname, );   $ctx = stream_context_create( array("ssl" => $ssloptions) ); $result = stream_socket_client("ssl://$hostname:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx); $cont = stream_context_get_params($result); $x509 = $cont["options"]["ssl"]["peer_certificate"]; $certparsed = openssl_x509_parse($x509); foreach($cont["options"]["ssl"]["peer_certificate_chain"] as $chaincert) {     $chainparsed = openssl_x509_parse($chaincert);     $chain_public_key = openssl_get_publickey($chaincert);     $r = openssl_x509_verify($x509, $chain_public_key);        if ($r==1)     {         echo $certparsed['subject']['CN'];         echo " was digitally signed by ";         echo $chainparsed['subject']['CN']."\n";     } } ?> ``` ### See Also * [openssl\_verify()](function.openssl-verify) - Verify signature * [openssl\_get\_publickey()](function.openssl-get-publickey) - Alias of openssl\_pkey\_get\_public
programming_docs
php Imagick::getImageWhitePoint Imagick::getImageWhitePoint =========================== (PECL imagick 2, PECL imagick 3) Imagick::getImageWhitePoint — Returns the chromaticity white point ### Description ``` public Imagick::getImageWhitePoint(): array ``` Returns the chromaticity white point as an associative array with the keys "x" and "y". ### Parameters This function has no parameters. ### Return Values Returns the chromaticity white point as an associative array with the keys "x" and "y". ### Errors/Exceptions Throws ImagickException on error. php DateTimeZone::listAbbreviations DateTimeZone::listAbbreviations =============================== timezone\_abbreviations\_list ============================= (PHP 5 >= 5.2.0, PHP 7, PHP 8) DateTimeZone::listAbbreviations -- timezone\_abbreviations\_list — Returns associative array containing dst, offset and the timezone name ### Description Object-oriented style ``` public static DateTimeZone::listAbbreviations(): array ``` Procedural style ``` timezone_abbreviations_list(): array ``` The returned list of abbreviations includes all historical use of abbreviations, which can lead to correct, but confusing entries. There are also conflicts, as `PST` is used both in the US and in the Philippines. The list that this function returns is therefore not suitable for building an array with options to present a choice of timezone to users. > > **Note**: > > > The data for this function are precompiled for performance reasons, and are not updated when using a newer [» timezonedb](https://pecl.php.net/package/timezonedb). > > ### Parameters This function has no parameters. ### Return Values Returns the array of timezone abbreviations. ### Examples **Example #1 A [timezone\_abbreviations\_list()](function.timezone-abbreviations-list) example** ``` <?php $timezone_abbreviations = DateTimeZone::listAbbreviations(); print_r($timezone_abbreviations["acst"]); ?> ``` The above example will output something similar to: ``` Array ( [0] => Array ( [dst] => 1 [offset] => -14400 [timezone_id] => America/Porto_Acre ) [1] => Array ( [dst] => 1 [offset] => -14400 [timezone_id] => America/Eirunepe ) [2] => Array ( [dst] => 1 [offset] => -14400 [timezone_id] => America/Rio_Branco ) [3] => Array ( [dst] => 1 [offset] => -14400 [timezone_id] => Brazil/Acre ) ) ``` ### See Also * [timezone\_identifiers\_list()](function.timezone-identifiers-list) - Alias of DateTimeZone::listIdentifiers php SolrCollapseFunction::setHint SolrCollapseFunction::setHint ============================= (PECL solr >= 2.2.0) SolrCollapseFunction::setHint — Sets collapse hint ### Description ``` public SolrCollapseFunction::setHint(string $hint): SolrCollapseFunction ``` Sets collapse hint ### Parameters `hint` Currently there is only one hint available "top\_fc", which stands for top level FieldCache ### Return Values [SolrCollapseFunction](class.solrcollapsefunction) ### Examples **Example #1 **SolrCollapseFunction::setHint()** example** ``` <?php /* ... */ ?> ``` The above example will output something similar to: ``` ... ``` php The Stringable interface The Stringable interface ======================== Introduction ------------ (PHP 8) The **Stringable** interface denotes a class as having a [\_\_toString()](language.oop5.magic#object.tostring) method. Unlike most interfaces, **Stringable** is implicitly present on any class that has the magic [\_\_toString()](language.oop5.magic#object.tostring) method defined, although it can and should be declared explicitly. Its primary value is to allow functions to type check against the union type `string|Stringable` to accept either a string primitive or an object that can be cast to a string. Interface synopsis ------------------ interface **Stringable** { /\* Methods \*/ ``` public __toString(): string ``` } Stringable Examples ------------------- **Example #1 Basic Stringable Usage** ``` <?php class IPv4Address implements Stringable {     private string $oct1;     private string $oct2;     private string $oct3;     private string $oct4;     public function __construct(string $oct1, string $oct2, string $oct3, string $oct4) {         $this->oct1 = $oct1;         $this->oct2 = $oct2;         $this->oct3 = $oct3;         $this->oct4 = $oct4;     }     public function __toString(): string {         return "$this->oct1.$this->oct2.$this->oct3.$this->oct4";     } } function showStuff(string|Stringable $value) {     // A Stringable will get converted to a string here by calling     // __toString.     print $value; } $ip = new IPv4Address('123', '234', '42', '9'); showStuff($ip); ?> ``` The above example will output something similar to: ``` 123.234.42.9 ``` Table of Contents ----------------- * [Stringable::\_\_toString](stringable.tostring) — Gets a string representation of the object php QuickHashIntStringHash::get QuickHashIntStringHash::get =========================== (PECL quickhash >= Unknown) QuickHashIntStringHash::get — This method retrieves a value from the hash by its key ### Description ``` public QuickHashIntStringHash::get(int $key): mixed ``` This method retrieves a value from the hash by its key. ### Parameters `key` The key of the entry to retrieve. ### Return Values The value if the key exists, or **`null`** if the key wasn't part of the hash. ### Examples **Example #1 **QuickHashIntStringHash::get()** example** ``` <?php $hash = new QuickHashIntStringHash( 8 ); var_dump( $hash->get( 1 ) ); var_dump( $hash->add( 2, "two" ) ); var_dump( $hash->get( 2 ) ); var_dump( $hash->add( 3, 5 ) ); var_dump( $hash->get( 3 ) ); ?> ``` The above example will output something similar to: ``` bool(false) bool(true) string(3) "two" bool(true) string(1) "5" ``` php EventBufferEvent::getEnabled EventBufferEvent::getEnabled ============================ (PECL event >= 1.2.6-beta) EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event ### Description ``` public EventBufferEvent::getEnabled(): int ``` Returns bitmask of events currently enabled on the buffer event ### Parameters This function has no parameters. ### Return Values Returns integer representing a bitmask of events currently enabled on the buffer event ### See Also * [EventBufferEvent::enable()](eventbufferevent.enable) - Enable events read, write, or both on a buffer event * [EventBufferEvent::disable()](eventbufferevent.disable) - Disable events read, write, or both on a buffer event php touch touch ===== (PHP 4, PHP 5, PHP 7, PHP 8) touch — Sets access and modification time of file ### Description ``` touch(string $filename, ?int $mtime = null, ?int $atime = null): bool ``` Attempts to set the access and modification times of the file named in the `filename` parameter to the value given in `mtime`. Note that the access time is always modified, regardless of the number of parameters. If the file does not exist, it will be created. ### Parameters `filename` The name of the file being touched. `mtime` The touch time. If `mtime` is **`null`**, the current system [time()](function.time) is used. `atime` If not **`null`**, the access time of the given filename is set to the value of `atime`. Otherwise, it is set to the value passed to the `mtime` parameter. If both are **`null`**, the current system time is used. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `mtime` and `atime` are now nullable. | ### Examples **Example #1 **touch()** example** ``` <?php if (touch($filename)) {     echo $filename . ' modification time has been changed to present time'; } else {     echo 'Sorry, could not change modification time of ' . $filename; } ?> ``` **Example #2 **touch()** using the `mtime` parameter** ``` <?php // This is the touch time, we'll set it to one hour in the past. $time = time() - 3600; // Touch the file if (!touch('some_file.txt', $time)) {     echo 'Whoops, something went wrong...'; } else {     echo 'Touched file with success'; } ?> ``` ### Notes > > **Note**: > > > Note that time resolution may differ from one file system to another. > > > php ImagickDraw::destroy ImagickDraw::destroy ==================== (PECL imagick 2, PECL imagick 3) ImagickDraw::destroy — Frees all associated resources ### Description ``` public ImagickDraw::destroy(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Frees all resources associated with the [ImagickDraw](class.imagickdraw) object. ### Return Values No value is returned. php radius_put_vendor_int radius\_put\_vendor\_int ======================== (PECL radius >= 1.1.0) radius\_put\_vendor\_int — Attaches a vendor specific integer attribute ### Description ``` radius_put_vendor_int( resource $radius_handle, int $vendor, int $type, int $value, int $options = 0, int $tag = ? ): bool ``` Attaches a vendor specific integer attribute to the current RADIUS request. > > **Note**: > > > A request must be created via [radius\_create\_request()](function.radius-create-request) before this function can be called. > > > ### Parameters `radius_handle` The RADIUS resource. `vendor` The vendor ID. `type` The attribute type. `value` The attribute value. `options` A bitmask of the attribute options. The available options include [**`RADIUS_OPTION_TAGGED`**](https://www.php.net/manual/en/radius.constants.options.php#constant.radius-option-tagged) and [**`RADIUS_OPTION_SALT`**](https://www.php.net/manual/en/radius.constants.options.php#constant.radius-option-salt). `tag` The attribute tag. This parameter is ignored unless the [**`RADIUS_OPTION_TAGGED`**](https://www.php.net/manual/en/radius.constants.options.php#constant.radius-option-tagged) option is set. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | PECL radius 1.3.0 | The `options` and `tag` parameters were added. | ### See Also * [radius\_put\_vendor\_string()](function.radius-put-vendor-string) - Attaches a vendor specific string attribute php bzerrno bzerrno ======= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) bzerrno — Returns a bzip2 error number ### Description ``` bzerrno(resource $bz): int ``` Returns the error number of any bzip2 error returned by the given file pointer. ### Parameters `bz` The file pointer. It must be valid and must point to a file successfully opened by [bzopen()](function.bzopen). ### Return Values Returns the error number as an integer. ### See Also * [bzerror()](function.bzerror) - Returns the bzip2 error number and error string in an array * [bzerrstr()](function.bzerrstr) - Returns a bzip2 error string php ibase_drop_db ibase\_drop\_db =============== (PHP 5, PHP 7 < 7.4.0) ibase\_drop\_db — Drops a database ### Description ``` ibase_drop_db(resource $connection = null): bool ``` This functions drops a database that was opened by either [ibase\_connect()](function.ibase-connect) or [ibase\_pconnect()](function.ibase-pconnect). The database is closed and deleted from the server. ### Parameters `connection` An InterBase link identifier. If omitted, the last opened link is assumed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [ibase\_connect()](function.ibase-connect) - Open a connection to a database * [ibase\_pconnect()](function.ibase-pconnect) - Open a persistent connection to an InterBase database php GmagickDraw::point GmagickDraw::point ================== (PECL gmagick >= Unknown) GmagickDraw::point — Draws a point ### Description ``` public GmagickDraw::point(float $x, float $y): GmagickDraw ``` Draws a point using the current stroke color and stroke thickness at the specified coordinates. ### Parameters `x` target x coordinate `y` target y coordinate ### Return Values The [GmagickDraw](class.gmagickdraw) object. php SolrDisMaxQuery::setQueryAlt SolrDisMaxQuery::setQueryAlt ============================ (No version information available, might only be in Git) SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter) ### Description ``` public SolrDisMaxQuery::setQueryAlt(string $q): SolrDisMaxQuery ``` Set Query Alternate (q.alt parameter) When the main *q* parameter is not specified or is blank. The *q.alt* parameter is used ### Parameters `q` Query String ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::setQueryAlt()** example** ``` <?php $dismaxQuery = new DisMaxQuery(); $dismaxQuery->setQueryAlt('*:*'); ?> ``` The above example will output something similar to: ``` defType=edismax&q.alt=*:*&q= ``` php IntlCalendar::getFirstDayOfWeek IntlCalendar::getFirstDayOfWeek =============================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendarʼs locale ### Description Object-oriented style ``` public IntlCalendar::getFirstDayOfWeek(): int|false ``` Procedural style ``` intlcal_get_first_day_of_week(IntlCalendar $calendar): int|false ``` The week day deemed to start a week, either the default value for this locale or the value set with [IntlCalendar::setFirstDayOfWeek()](intlcalendar.setfirstdayofweek). ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. ### Return Values One of the constants **`IntlCalendar::DOW_SUNDAY`**, **`IntlCalendar::DOW_MONDAY`**, …, **`IntlCalendar::DOW_SATURDAY`** or **`false`** on failure. ### Examples **Example #1 **IntlCalendar::getFirstDayOfWeek()**** ``` <?php ini_set('date.timezone', 'UTC'); $cal1 = IntlCalendar::createInstance(NULL, 'es_ES'); var_dump($cal1->getFirstDayOfWeek()); // Monday $cal1->set(2013, 1 /* February */, 3); // a Sunday var_dump($cal1->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 5 $cal2 = IntlCalendar::createInstance(NULL, 'en_US'); var_dump($cal2->getFirstDayOfWeek()); // Sunday $cal2->set(2013, 1 /* February */, 3); // a Sunday var_dump($cal2->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 6 ``` The above example will output: ``` int(2) int(5) int(1) int(6) ``` ### See Also * [IntlCalendar::setFirstDayOfWeek()](intlcalendar.setfirstdayofweek) - Set the day on which the week is deemed to start php mb_stripos mb\_stripos =========== (PHP 5 >= 5.2.0, PHP 7, PHP 8) mb\_stripos — Finds position of first occurrence of a string within another, case insensitive ### Description ``` mb_stripos( string $haystack, string $needle, int $offset = 0, ?string $encoding = null ): int|false ``` **mb\_stripos()** returns the numeric position of the first occurrence of `needle` in the `haystack` string. Unlike [mb\_strpos()](function.mb-strpos), **mb\_stripos()** is case-insensitive. If `needle` is not found, it returns **`false`**. ### Parameters `haystack` The string from which to get the position of the first occurrence of `needle` `needle` The string to find in `haystack` `offset` The position in `haystack` to start searching. A negative offset counts from the end of the string. `encoding` Character encoding name to use. If it is omitted, internal character encoding is used. ### Return Values Return the numeric position of the first occurrence of `needle` in the `haystack` string, or **`false`** if `needle` is not found. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `needle` now accepts an empty string. | | 8.0.0 | `encoding` is nullable now. | | 7.1.0 | Support for negative `offset`s has been added. | ### See Also * [stripos()](function.stripos) - Find the position of the first occurrence of a case-insensitive substring in a string * [strpos()](function.strpos) - Find the position of the first occurrence of a substring in a string * [mb\_strpos()](function.mb-strpos) - Find position of first occurrence of string in a string php stats_rand_gen_chisquare stats\_rand\_gen\_chisquare =========================== (PECL stats >= 1.0.0) stats\_rand\_gen\_chisquare — Generates a random deviate from the chi-square distribution ### Description ``` stats_rand_gen_chisquare(float $df): float ``` Returns a random deviate from the chi-square distribution where the degrees of freedom is `df`. ### Parameters `df` The degrees of freedom ### Return Values A random deviate php posix_getsid posix\_getsid ============= (PHP 4, PHP 5, PHP 7, PHP 8) posix\_getsid — Get the current sid of the process ### Description ``` posix_getsid(int $process_id): int|false ``` Return the session id of the process `process_id`. The session id of a process is the process group id of the session leader. ### Parameters `process_id` The process identifier. If set to 0, the current process is assumed. If an invalid `process_id` is specified, then **`false`** is returned and an error is set which can be checked with [posix\_get\_last\_error()](function.posix-get-last-error). ### Return Values Returns the identifier, as an int, or **`false`** on failure. ### Examples **Example #1 Example use of **posix\_getsid()**** ``` <?php $pid = posix_getpid(); echo posix_getsid($pid); //8805 ?> ``` ### See Also * [posix\_getpgid()](function.posix-getpgid) - Get process group id for job control * [posix\_setsid()](function.posix-setsid) - Make the current process a session leader * POSIX man page GETSID(2) php scandir scandir ======= (PHP 5, PHP 7, PHP 8) scandir — List files and directories inside the specified path ### Description ``` scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, ?resource $context = null): array|false ``` Returns an array of files and directories from the `directory`. ### Parameters `directory` The directory that will be scanned. `sorting_order` By default, the sorted order is alphabetical in ascending order. If the optional `sorting_order` is set to **`SCANDIR_SORT_DESCENDING`**, then the sort order is alphabetical in descending order. If it is set to **`SCANDIR_SORT_NONE`** then the result is unsorted. `context` For a description of the `context` parameter, refer to [the streams section](https://www.php.net/manual/en/ref.stream.php) of the manual. ### Return Values Returns an array of filenames on success, or **`false`** on failure. If `directory` is not a directory, then boolean **`false`** is returned, and an error of level **`E_WARNING`** is generated. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `context` is now nullable. | ### Examples **Example #1 A simple **scandir()** example** ``` <?php $dir    = '/tmp'; $files1 = scandir($dir); $files2 = scandir($dir, SCANDIR_SORT_DESCENDING); print_r($files1); print_r($files2); ?> ``` The above example will output something similar to: ``` Array ( [0] => . [1] => .. [2] => bar.php [3] => foo.txt [4] => somedir ) Array ( [0] => somedir [1] => foo.txt [2] => bar.php [3] => .. [4] => . ) ``` ### Notes **Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. ### See Also * [opendir()](function.opendir) - Open directory handle * [readdir()](function.readdir) - Read entry from directory handle * [glob()](function.glob) - Find pathnames matching a pattern * [is\_dir()](function.is-dir) - Tells whether the filename is a directory * [sort()](function.sort) - Sort an array in ascending order
programming_docs
php The Yaf_Route_Map class The Yaf\_Route\_Map class ========================= Introduction ------------ (Yaf >=1.0.0) **Yaf\_Route\_Map** is a built-in route, it simply convert a URI endpoint (that part of the URI which comes after the base URI: see [Yaf\_Request\_Abstract::setBaseUri()](yaf-request-abstract.setbaseuri)) to a controller name or action name(depends on the parameter passed to [Yaf\_Route\_Map::\_\_construct()](yaf-route-map.construct)) in following rule: A => controller A. A/B/C => controller A\_B\_C. A/B/C/D/E => controller A\_B\_C\_D\_E. If the second parameter of [Yaf\_Route\_Map::\_\_construct()](yaf-route-map.construct) is specified, then only the part before delimiter of URI will used to routing, the part after it is used to routing request parameters (see the example section of [Yaf\_Route\_Map::\_\_construct()](yaf-route-map.construct)). Class synopsis -------------- class **Yaf\_Route\_Map** implements [Yaf\_Route\_Interface](class.yaf-route-interface) { /\* Properties \*/ protected [$\_ctl\_router](class.yaf-route-map#yaf-route-map.props.ctl-router); protected [$\_delimiter](class.yaf-route-map#yaf-route-map.props.delimiter); /\* Methods \*/ public [\_\_construct](yaf-route-map.construct)(string `$controller_prefer` = **`false`**, string `$delimiter` = "") ``` public assemble(array $info, array $query = ?): string ``` ``` public route(Yaf_Request_Abstract $request): bool ``` } Properties ---------- \_ctl\_router \_delimiter Table of Contents ----------------- * [Yaf\_Route\_Map::assemble](yaf-route-map.assemble) — Assemble a url * [Yaf\_Route\_Map::\_\_construct](yaf-route-map.construct) — The \_\_construct purpose * [Yaf\_Route\_Map::route](yaf-route-map.route) — The route purpose php SolrQuery::setHighlightMaxAnalyzedChars SolrQuery::setHighlightMaxAnalyzedChars ======================================= (PECL solr >= 0.9.2) SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets ### Description ``` public SolrQuery::setHighlightMaxAnalyzedChars(int $value): SolrQuery ``` Specifies the number of characters into a document to look for suitable snippets ### Parameters `value` The number of characters into a document to look for suitable snippets ### Return Values Returns the current SolrQuery object, if the return value is used. php Imagick::annotateImage Imagick::annotateImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::annotateImage — Annotates an image with text ### Description ``` public Imagick::annotateImage( ImagickDraw $draw_settings, float $x, float $y, float $angle, string $text ): bool ``` Annotates an image with text. ### Parameters `draw_settings` The ImagickDraw object that contains settings for drawing the text `x` Horizontal offset in pixels to the left of text `y` Vertical offset in pixels to the baseline of text `angle` The angle at which to write the text `text` The string to draw ### Return Values Returns **`true`** on success. ### Examples **Example #1 Using **Imagick::annotateImage()**:** Annotate text on an empty image ``` <?php /* Create some objects */ $image = new Imagick(); $draw = new ImagickDraw(); $pixel = new ImagickPixel( 'gray' ); /* New image */ $image->newImage(800, 75, $pixel); /* Black text */ $draw->setFillColor('black'); /* Font properties */ $draw->setFont('Bookman-DemiItalic'); $draw->setFontSize( 30 ); /* Create text */ $image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog'); /* Give image a format */ $image->setImageFormat('png'); /* Output the image with headers */ header('Content-type: image/png'); echo $image; ?> ``` ### See Also * [ImagickDraw::annotation()](imagickdraw.annotation) - Draws text on the image * [ImagickDraw::setFont()](imagickdraw.setfont) - Sets the fully-specified font to use when annotating with text php ReflectionExtension::getName ReflectionExtension::getName ============================ (PHP 5, PHP 7, PHP 8) ReflectionExtension::getName — Gets extension name ### Description ``` public ReflectionExtension::getName(): string ``` Gets the extensions name. ### Parameters This function has no parameters. ### Return Values The extensions name. ### Examples **Example #1 **ReflectionExtension::getName()** example** ``` <?php $ext = new ReflectionExtension('mysqli'); var_dump($ext->getName()); ?> ``` The above example will output something similar to: ``` string(6) "mysqli" ``` ### See Also * [ReflectionExtension::getClassNames()](reflectionextension.getclassnames) - Gets class names php APCUIterator::next APCUIterator::next ================== (PECL apcu >= 5.0.0) APCUIterator::next — Move pointer to next item ### Description ``` public APCUIterator::next(): bool ``` Moves the iterator pointer to the next element. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [APCUIterator::current()](apcuiterator.current) - Get current item * [APCUIterator::rewind()](apcuiterator.rewind) - Rewinds iterator * [Iterator::next()](iterator.next) - Move forward to next element php SplFileObject::fread SplFileObject::fread ==================== (PHP 5 >= 5.5.11, PHP 7, PHP 8) SplFileObject::fread — Read from file ### Description ``` public SplFileObject::fread(int $length): string|false ``` Reads the given number of bytes from the file. ### Parameters `length` The number of bytes to read. ### Return Values Returns the string read from the file or **`false`** on failure. ### Examples **Example #1 **SplFileObject::fread()** example** ``` <?php // Get contents of a file into a string $filename = "/usr/local/something.txt"; $file = new SplFileObject($filename, "r"); $contents = $file->fread($file->getSize()); ?> ``` ### Notes > > **Note**: > > > Note that **SplFileObject::fread()** reads from the current position of the file pointer. Use [SplFileObject::ftell()](splfileobject.ftell) to find the current position of the pointer and [SplFileObject::rewind()](splfileobject.rewind) (or [SplFileObject::fseek()](splfileobject.fseek)) to rewind the pointer position. > > ### See Also * [fread()](function.fread) - Binary-safe file read php SplDoublyLinkedList::offsetExists SplDoublyLinkedList::offsetExists ================================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists ### Description ``` public SplDoublyLinkedList::offsetExists(int $index): bool ``` ### Parameters `index` The index being checked. ### Return Values **`true`** if the requested `index` exists, otherwise **`false`** php The Normalizer class The Normalizer class ==================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Normalization is a process that involves transforming characters and sequences of characters into a formally-defined underlying representation. This process is most important when text needs to be compared for sorting and searching, but it is also used when storing text to ensure that the text is stored in a consistent representation. The Unicode Consortium has defined a number of normalization forms reflecting the various needs of applications: * Normalization Form D (NFD) - Canonical Decomposition * Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition * Normalization Form KD (NFKD) - Compatibility Decomposition * Normalization Form KC (NFKC) - Compatibility Decomposition followed by Canonical Composition The different forms are defined in terms of a set of transformations on the text, transformations that are expressed by both an algorithm and a set of data files. Class synopsis -------------- class **Normalizer** { /\* Methods \*/ ``` public static getRawDecomposition(string $string, int $form = Normalizer::FORM_C): ?string ``` ``` public static isNormalized(string $string, int $form = Normalizer::FORM_C): bool ``` ``` public static normalize(string $string, int $form = Normalizer::FORM_C): string|false ``` } Predefined Constants -------------------- The following constants define the normalization form used by the normalizer: **`Normalizer::FORM_C`** (int) Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition **`Normalizer::FORM_D`** (int) Normalization Form D (NFD) - Canonical Decomposition **`Normalizer::FORM_KC`** (int) Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition **`Normalizer::FORM_KD`** (int) Normalization Form KD (NFKD) - Compatibility Decomposition **`Normalizer::NONE`** (int) No decomposition/composition **`Normalizer::OPTION_DEFAULT`** (int) Default normalization options See Also -------- * [» Unicode Normalization](http://unicode.org/reports/tr15/) * [» Unicode Normalization FAQ](http://unicode.org/faq/normalization.html) * [» ICU User Guide - Normalization](https://unicode-org.github.io/icu/userguide/transforms/normalization/) * [» ICU API Reference - Normalization](http://www.icu-project.org/apiref/icu4c/unorm_8h.html) Table of Contents ----------------- * [Normalizer::getRawDecomposition](normalizer.getrawdecomposition) — Gets the Decomposition\_Mapping property for the given UTF-8 encoded code point * [Normalizer::isNormalized](normalizer.isnormalized) — Checks if the provided string is already in the specified normalization form * [Normalizer::normalize](normalizer.normalize) — Normalizes the input provided and returns the normalized string php ZipArchive::addEmptyDir ZipArchive::addEmptyDir ======================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.8.0) ZipArchive::addEmptyDir — Add a new directory ### Description ``` public ZipArchive::addEmptyDir(string $dirname, int $flags = 0): bool ``` Adds an empty directory in the archive. ### Parameters `dirname` The directory to add. `flags` Bitmask consisting of **`ZipArchive::FL_ENC_GUESS`**, **`ZipArchive::FL_ENC_UTF_8`**, **`ZipArchive::FL_ENC_CP437`**. The behaviour of these constants is described on the [ZIP constants](https://www.php.net/manual/en/zip.constants.php) page. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 / 1.18.0 | `flags` was added. | ### Examples **Example #1 Create a new directory in an archive** ``` <?php $zip = new ZipArchive; if ($zip->open('test.zip') === TRUE) {     if($zip->addEmptyDir('newDirectory')) {         echo 'Created a new root directory';     } else {         echo 'Could not create the directory';     }     $zip->close(); } else {     echo 'failed'; } ?> ``` php nl_langinfo nl\_langinfo ============ (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) nl\_langinfo — Query language and locale information ### Description ``` nl_langinfo(int $item): string|false ``` **nl\_langinfo()** is used to access individual elements of the locale categories. Unlike [localeconv()](function.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()](function.strftime) to represent time and date. | | **`D_FMT`** | String that can be used as the format string for [strftime()](function.strftime) to represent date. | | **`T_FMT`** | String that can be used as the format string for [strftime()](function.strftime) to represent time. | | **`T_FMT_AMPM`** | String that can be used as the format string for [strftime()](function.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()](function.strftime)). | | **`ERA_D_FMT`** | Date in alternate era format (string can be used in [strftime()](function.strftime)). | | **`ERA_T_FMT`** | Time in alternate era format (string can be used in [strftime()](function.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. ### Examples **Example #1 **nl\_langinfo()** example** ``` <?php var_dump(nl_langinfo(CODESET)); var_dump(nl_langinfo(YESEXPR)); ?> ``` The above example will output something similar to: ``` string(14) "ANSI_X3.4-1968" string(5) "^[yY]" ``` ### Notes > **Note**: This function is not implemented on Windows platforms. > > ### See Also * [setlocale()](function.setlocale) - Set locale information * [localeconv()](function.localeconv) - Get numeric formatting information php None Passing by Reference -------------------- You can pass a variable by reference to a function so the function can modify the variable. The syntax is as follows: ``` <?php function foo(&$var) {     $var++; } $a=5; foo($a); // $a is 6 here ?> ``` > **Note**: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. > > The following things can be passed by reference: * Variables, i.e. `foo($a)` * References returned from functions, i.e.: ``` <?php function foo(&$var) {     $var++; } function &bar() {     $a = 5;     return $a; } foo(bar()); ?> ``` See more about [returning by reference](language.references.return). No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid: ``` <?php function foo(&$var) {     $var++; } function bar() // Note the missing & {     $a = 5;     return $a; } foo(bar()); // Produces a notice foo($a = 5); // Expression, not variable foo(5); // Produces fatal error class Foobar { } foo(new Foobar()) // Produces a notice as of PHP 7.0.7                   // Notice: Only variables should be passed by reference ?> ``` php SolrQuery::getHighlightMergeContiguous SolrQuery::getHighlightMergeContiguous ====================================== (PECL solr >= 0.9.2) SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment ### Description ``` public SolrQuery::getHighlightMergeContiguous(string $field_override = ?): bool ``` Returns whether or not the collapse contiguous fragments into a single fragment. Accepts an optional field override. ### Parameters `field_override` The name of the field ### Return Values Returns a boolean on success and **`null`** if not set. php ReflectionClass::getFileName ReflectionClass::getFileName ============================ (PHP 5, PHP 7, PHP 8) ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined ### Description ``` public ReflectionClass::getFileName(): string|false ``` Gets the filename of the file in which the class has been defined. ### Parameters This function has no parameters. ### Return Values Returns the filename of the file in which the class has been defined. If the class is defined in the PHP core or in a PHP extension, **`false`** is returned. ### See Also * [ReflectionClass::getExtensionName()](reflectionclass.getextensionname) - Gets the name of the extension which defined the class php PharFileInfo::isCRCChecked PharFileInfo::isCRCChecked ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified ### Description ``` public PharFileInfo::isCRCChecked(): bool ``` This returns whether a file within a Phar archive has had its CRC verified. ### Parameters This function has no parameters. ### Return Values **`true`** if the file has had its CRC verified, **`false`** if not. ### Examples **Example #1 A **PharFileInfo::isCRCChecked()** example** ``` <?php try {     $p = new Phar('/path/to/my.phar', 0, 'my.phar');     $p['myfile.txt'] = 'hi';     $file = $p['myfile.txt'];     var_dump($file->isCRCChecked()); } catch (Exception $e) {     echo 'Create/modify operations failed on my.phar: ', $e; } ?> ``` The above example will output: ``` bool(true) ``` php Memcached::getByKey Memcached::getByKey =================== (PECL memcached >= 0.1.0) Memcached::getByKey — Retrieve an item from a specific server ### Description ``` public Memcached::getByKey( string $server_key, string $key, callable $cache_cb = ?, int $flags = ? ): mixed ``` **Memcached::getByKey()** is functionally equivalent to [Memcached::get()](memcached.get), except that the free-form `server_key` can be used to map the `key` to a specific server. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `key` The key of the item to fetch. `cache_cb` Read-through caching callback or **`null`** `flags` Flags to control the returned result. When value of **`Memcached::GET_EXTENDED`** is given will return the CAS token. ### Return Values Returns the value stored in the cache or **`false`** otherwise. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTFOUND`** if the key does not exist. ### Changelog | Version | Description | | --- | --- | | PECL memcached 3.0.0 | The `&cas_token` parameter was removed. Instead `flags` was added and when it is given the value of **`Memcached::GET_EXTENDED`** it will ensure the CAS token to be fetched. | ### See Also * [Memcached::get()](memcached.get) - Retrieve an item * [Memcached::getMulti()](memcached.getmulti) - Retrieve multiple items * [Memcached::getDelayed()](memcached.getdelayed) - Request multiple items
programming_docs
php ImagickDraw::pathCurveToSmoothAbsolute ImagickDraw::pathCurveToSmoothAbsolute ====================================== (PECL imagick 2, PECL imagick 3) ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve ### Description ``` public ImagickDraw::pathCurveToSmoothAbsolute( float $x2, float $y2, float $x, float $y ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a cubic Bezier curve from the current point to (x,y) using absolute coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier. ### Parameters `x2` x coordinate of the second control point `y2` y coordinate of the second control point `x` x coordinate of the ending point `y` y coordinate of the ending point ### Return Values No value is returned. php mailparse_uudecode_all mailparse\_uudecode\_all ======================== (PECL mailparse >= 0.9.0) mailparse\_uudecode\_all — Scans the data from fp and extract each embedded uuencoded file ### Description ``` mailparse_uudecode_all(resource $fp): array ``` Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file. ### Parameters `fp` A valid file pointer. ### Return Values Returns an array of associative arrays listing filename information. | | | | --- | --- | | `filename` | Path to the temporary file name created | | `origfilename` | The original filename, for uuencoded parts only | The first filename entry is the message body. The next entries are the decoded uuencoded files. ### Examples **Example #1 **mailparse\_uudecode\_all()** example** ``` <?php $text = <<<EOD To: [email protected] hello, this is some text hello. blah blah blah. begin 644 test.txt /=&AI<R!I<R!A('1E<W0* ` end EOD; $fp = tmpfile(); fwrite($fp, $text); $data = mailparse_uudecode_all($fp); echo "BODY\n"; readfile($data[0]["filename"]); echo "UUE ({$data[1]['origfilename']})\n"; readfile($data[1]["filename"]); // Clean up unlink($data[0]["filename"]); unlink($data[1]["filename"]); ?> ``` The above example will output: ``` BODY To: [email protected] hello, this is some text hello. blah blah blah. UUE (test.txt) this is a test ``` php SplFileInfo::isDir SplFileInfo::isDir ================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::isDir — Tells if the file is a directory ### Description ``` public SplFileInfo::isDir(): bool ``` This method can be used to determine if the file is a directory. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if a directory, **`false`** otherwise. ### Examples **Example #1 **SplFileInfo::isDir()** example** ``` <?php $d = new SplFileInfo(dirname(__FILE__)); var_dump($d->isDir()); $d = new SplFileInfo(__FILE__); var_dump($d->isDir()); ?> ``` The above example will output something similar to: ``` bool(true) bool(false) ``` php SplFileObject::__construct SplFileObject::\_\_construct ============================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::\_\_construct — Construct a new file object ### Description public **SplFileObject::\_\_construct**( string `$filename`, string `$mode` = "r", bool `$useIncludePath` = **`false`**, ?resource `$context` = **`null`** ) Construct a new file object. ### Parameters `filename` The file to read. **Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. `mode` The mode in which to open the file. See [fopen()](function.fopen) for a list of allowed modes. `useIncludePath` Whether to search in the [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path) for `filename`. `context` A valid context resource created with [stream\_context\_create()](function.stream-context-create). ### Errors/Exceptions Throws a [RuntimeException](class.runtimeexception) if the `filename` cannot be opened. Throws a [LogicException](class.logicexception) if the `filename` is a directory. ### Examples **Example #1 **SplFileObject::\_\_construct()** example** This example opens the current file and iterates over its contents line by line. ``` <?php $file = new SplFileObject(__FILE__); foreach ($file as $line_num => $line) {     echo "Line $line_num is $line"; } ?> ``` The above example will output something similar to: ``` Line 0 is <?php Line 1 is $file = new SplFileObject(__FILE__); Line 2 is foreach ($file as $line_num => $line) { Line 3 is echo "Line $line_num is $line"; Line 4 is } Line 5 is ?> ``` ### See Also * [SplFileInfo::openFile()](splfileinfo.openfile) - Gets an SplFileObject object for the file * [fopen()](function.fopen) - Opens file or URL php ftp_mdtm ftp\_mdtm ========= (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_mdtm — Returns the last modified time of the given file ### Description ``` ftp_mdtm(FTP\Connection $ftp, string $filename): int ``` **ftp\_mdtm()** gets the last modified time for a remote file. > > **Note**: > > > Not all servers support this feature! > > > > **Note**: > > > **ftp\_mdtm()** does not work with directories. > > ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `filename` The file from which to extract the last modification time. ### Return Values Returns the last modified time as a *local* Unix timestamp on success, or -1 on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_mdtm()** example** ``` <?php $file = 'somefile.txt'; // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); //  get the last modified time $buff = ftp_mdtm($ftp, $file); if ($buff != -1) {     // somefile.txt was last modified on: March 26 2003 14:16:41.     echo "$file was last modified on : " . date("F d Y H:i:s.", $buff); } else {     echo "Couldn't get mdtime"; } // close the connection ftp_close($ftp); ?> ``` php ArrayObject::offsetGet ArrayObject::offsetGet ====================== (PHP 5, PHP 7, PHP 8) ArrayObject::offsetGet — Returns the value at the specified index ### Description ``` public ArrayObject::offsetGet(mixed $key): mixed ``` ### Parameters `key` The index with the value. ### Return Values The value at the specified index or **`null`**. ### Errors/Exceptions Produces an **`E_NOTICE`** error message when the specified index does not exist. ### Examples **Example #1 **ArrayObject::offsetGet()** example** ``` <?php $arrayobj = new ArrayObject(array('zero', 7, 'example'=>'e.g.')); var_dump($arrayobj->offsetGet(1)); var_dump($arrayobj->offsetGet('example')); var_dump($arrayobj->offsetExists('notfound')); ?> ``` The above example will output: ``` int(7) string(4) "e.g." bool(false) ``` php sodium_crypto_sign_open sodium\_crypto\_sign\_open ========================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_sign\_open — Check that the signed message has a valid signature ### Description ``` sodium_crypto_sign_open(string $signed_message, string $public_key): string|false ``` Verify the signature attached to a message and return the message ### Parameters `signed_message` A message signed with [sodium\_crypto\_sign()](function.sodium-crypto-sign) `public_key` An Ed25519 public key ### Return Values Returns the original signed message on success, or **`false`** on failure. php ReflectionEnum::hasCase ReflectionEnum::hasCase ======================= (PHP 8 >= 8.1.0) ReflectionEnum::hasCase — Checks for a case on an Enum ### Description ``` public ReflectionEnum::hasCase(string $name): bool ``` Determines if a given case is defined on an Enum. ### Parameters `name` The case to check for. ### Return Values **`true`** if the case is defined, **`false`** if not. ### Examples **Example #1 **ReflectionEnum::hasCase()** example** ``` <?php enum Suit {     case Hearts;     case Diamonds;     case Clubs;     case Spades; } $rEnum = new ReflectionEnum(Suit::class); var_dump($rEnum->hasCase('Hearts')); var_dump($rEnum->hasCase('Horseshoes')); ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### See Also * [Enumerations](https://www.php.net/manual/en/language.enumerations.php) * [ReflectionEnum::getCase()](reflectionenum.getcase) - Returns a specific case of an Enum * [ReflectionEnum::getCases()](reflectionenum.getcases) - Returns a list of all cases on an Enum php IntlChar::isMirrored IntlChar::isMirrored ==================== (PHP 7, PHP 8) IntlChar::isMirrored — Check if code point has the Bidi\_Mirrored property ### Description ``` public static IntlChar::isMirrored(int|string $codepoint): ?bool ``` Determines whether the code point has the Bidi\_Mirrored property. This property is set for characters that are commonly used in Right-To-Left contexts and need to be displayed with a "mirrored" glyph. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` has the Bidi\_Mirrored property, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isMirrored("A")); var_dump(IntlChar::isMirrored("<")); var_dump(IntlChar::isMirrored("(")); ?> ``` The above example will output: ``` bool(false) bool(true) bool(true) ``` ### See Also * [IntlChar::charMirror()](intlchar.charmirror) - Get the "mirror-image" character for a code point * **`IntlChar::PROPERTY_BIDI_MIRRORED`** php Stomp::hasFrame Stomp::hasFrame =============== stomp\_has\_frame ================= (PECL stomp >= 0.1.0) Stomp::hasFrame -- stomp\_has\_frame — Indicates whether or not there is a frame ready to read ### Description Object-oriented style (method): ``` public Stomp::hasFrame(): bool ``` Procedural style: ``` stomp_has_frame(resource $link): bool ``` Indicates whether or not there is a frame ready to read. ### Parameters `link` Procedural style only: The stomp link identifier returned by [stomp\_connect()](stomp.construct). ### Return Values Returns **`true`** if a frame is ready to read, or **`false`** otherwise. php sodium_crypto_core_ristretto255_scalar_negate sodium\_crypto\_core\_ristretto255\_scalar\_negate ================================================== (PHP 8 >= 8.1.0) sodium\_crypto\_core\_ristretto255\_scalar\_negate — Negates a scalar value ### Description ``` sodium_crypto_core_ristretto255_scalar_negate(string $s): string ``` Negates a scalar value. Available as of libsodium 1.0.18. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `s` Scalar value. ### Return Values Returns a 32-byte random string. ### Examples **Example #1 **sodium\_crypto\_core\_ristretto255\_scalar\_negate()** example** ``` <?php $foo = sodium_crypto_core_ristretto255_scalar_random(); $negate = sodium_crypto_core_ristretto255_scalar_negate($foo); $reNegate = sodium_crypto_core_ristretto255_scalar_negate($negate); var_dump(hash_equals($foo, $reNegate)); ?> ``` The above example will output: ``` bool(true) ``` ### See Also * [sodium\_crypto\_core\_ristretto255\_scalar\_random()](function.sodium-crypto-core-ristretto255-scalar-random) - Generates a random key php Ds\Set::xor Ds\Set::xor =========== (PECL ds >= 1.0.0) Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both ### Description ``` public Ds\Set::xor(Ds\Set $set): Ds\Set ``` Creates a new set containing values in the current instance as well as another `set`, but not in both. `A ⊖ B = {x : x ∈ (A \ B) ∪ (B \ A)}` ### Parameters `set` The other set. ### Return Values A new set containing values in the current instance as well as another `set`, but not in both. ### See Also * [» Symmetric Difference](https://en.wikipedia.org/wiki/Symmetric_difference) on Wikipedia ### Examples **Example #1 **Ds\Set::xor()** example** ``` <?php $a = new \Ds\Set([1, 2, 3]); $b = new \Ds\Set([3, 4, 5]); var_dump($a->xor($b)); ?> ``` The above example will output something similar to: ``` object(Ds\Set)#3 (4) { [0]=> int(1) [1]=> int(2) [2]=> int(4) [3]=> int(5) } ``` php The XMLReader class The XMLReader class =================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way. Class synopsis -------------- class **XMLReader** { /\* Constants \*/ public const int [NONE](class.xmlreader#xmlreader.constants.none); public const int [ELEMENT](class.xmlreader#xmlreader.constants.element); public const int [ATTRIBUTE](class.xmlreader#xmlreader.constants.attribute); public const int [TEXT](class.xmlreader#xmlreader.constants.text); public const int [CDATA](class.xmlreader#xmlreader.constants.cdata); public const int [ENTITY\_REF](class.xmlreader#xmlreader.constants.entity-ref); public const int [ENTITY](class.xmlreader#xmlreader.constants.entity); public const int [PI](class.xmlreader#xmlreader.constants.pi); public const int [COMMENT](class.xmlreader#xmlreader.constants.comment); public const int [DOC](class.xmlreader#xmlreader.constants.doc); public const int [DOC\_TYPE](class.xmlreader#xmlreader.constants.doc-type); public const int [DOC\_FRAGMENT](class.xmlreader#xmlreader.constants.doc-fragment); public const int [NOTATION](class.xmlreader#xmlreader.constants.notation); public const int [WHITESPACE](class.xmlreader#xmlreader.constants.whitespace); public const int [SIGNIFICANT\_WHITESPACE](class.xmlreader#xmlreader.constants.significant-whitespace); public const int [END\_ELEMENT](class.xmlreader#xmlreader.constants.end-element); public const int [END\_ENTITY](class.xmlreader#xmlreader.constants.end-entity); public const int [XML\_DECLARATION](class.xmlreader#xmlreader.constants.xml-declaration); public const int [LOADDTD](class.xmlreader#xmlreader.constants.loaddtd); public const int [DEFAULTATTRS](class.xmlreader#xmlreader.constants.defaultattrs); public const int [VALIDATE](class.xmlreader#xmlreader.constants.validate); public const int [SUBST\_ENTITIES](class.xmlreader#xmlreader.constants.subst-entities); /\* Properties \*/ public int [$attributeCount](class.xmlreader#xmlreader.props.attributecount); public string [$baseURI](class.xmlreader#xmlreader.props.baseuri); public int [$depth](class.xmlreader#xmlreader.props.depth); public bool [$hasAttributes](class.xmlreader#xmlreader.props.hasattributes); public bool [$hasValue](class.xmlreader#xmlreader.props.hasvalue); public bool [$isDefault](class.xmlreader#xmlreader.props.isdefault); public bool [$isEmptyElement](class.xmlreader#xmlreader.props.isemptyelement); public string [$localName](class.xmlreader#xmlreader.props.localname); public string [$name](class.xmlreader#xmlreader.props.name); public string [$namespaceURI](class.xmlreader#xmlreader.props.namespaceuri); public int [$nodeType](class.xmlreader#xmlreader.props.nodetype); public string [$prefix](class.xmlreader#xmlreader.props.prefix); public string [$value](class.xmlreader#xmlreader.props.value); public string [$xmlLang](class.xmlreader#xmlreader.props.xmllang); /\* Methods \*/ public [\_\_construct](xmlreader.construct)() ``` public close(): bool ``` ``` public expand(?DOMNode $baseNode = null): DOMNode|false ``` ``` public getAttribute(string $name): ?string ``` ``` public getAttributeNo(int $index): ?string ``` ``` public getAttributeNs(string $name, string $namespace): ?string ``` ``` public getParserProperty(int $property): bool ``` ``` public isValid(): bool ``` ``` public lookupNamespace(string $prefix): ?string ``` ``` public moveToAttribute(string $name): bool ``` ``` public moveToAttributeNo(int $index): bool ``` ``` public moveToAttributeNs(string $name, string $namespace): bool ``` ``` public moveToElement(): bool ``` ``` public moveToFirstAttribute(): bool ``` ``` public moveToNextAttribute(): bool ``` ``` public next(?string $name = null): bool ``` ``` public static open(string $uri, ?string $encoding = null, int $flags = 0): bool|XMLReader ``` ``` public read(): bool ``` ``` public readInnerXml(): string ``` ``` public readOuterXml(): string ``` ``` public readString(): string ``` ``` public setParserProperty(int $property, bool $value): bool ``` ``` public setRelaxNGSchema(?string $filename): bool ``` ``` public setRelaxNGSchemaSource(?string $source): bool ``` ``` public setSchema(?string $filename): bool ``` ``` public static XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader ``` } Properties ---------- attributeCount The number of attributes on the node baseURI The base URI of the node depth Depth of the node in the tree, starting at 0 hasAttributes Indicates if node has attributes hasValue Indicates if node has a text value isDefault Indicates if attribute is defaulted from DTD isEmptyElement Indicates if node is an empty element tag localName The local name of the node name The qualified name of the node namespaceURI The URI of the namespace associated with the node nodeType The node type for the node prefix The prefix of the namespace associated with the node value The text value of the node xmlLang The xml:lang scope which the node resides Predefined Constants -------------------- XMLReader Node Types -------------------- **`XMLReader::NONE`** No node type **`XMLReader::ELEMENT`** Start element **`XMLReader::ATTRIBUTE`** Attribute node **`XMLReader::TEXT`** Text node **`XMLReader::CDATA`** CDATA node **`XMLReader::ENTITY_REF`** Entity Reference node **`XMLReader::ENTITY`** Entity Declaration node **`XMLReader::PI`** Processing Instruction node **`XMLReader::COMMENT`** Comment node **`XMLReader::DOC`** Document node **`XMLReader::DOC_TYPE`** Document Type node **`XMLReader::DOC_FRAGMENT`** Document Fragment node **`XMLReader::NOTATION`** Notation node **`XMLReader::WHITESPACE`** Whitespace node **`XMLReader::SIGNIFICANT_WHITESPACE`** Significant Whitespace node **`XMLReader::END_ELEMENT`** End Element **`XMLReader::END_ENTITY`** End Entity **`XMLReader::XML_DECLARATION`** XML Declaration node XMLReader Parser Options ------------------------ **`XMLReader::LOADDTD`** Load DTD but do not validate **`XMLReader::DEFAULTATTRS`** Load DTD and default attributes but do not validate **`XMLReader::VALIDATE`** Load DTD and validate while parsing **`XMLReader::SUBST_ENTITIES`** Substitute entities and expand references Table of Contents ----------------- * [XMLReader::close](xmlreader.close) — Close the XMLReader input * [XMLReader::\_\_construct](xmlreader.construct) — Construct a new XMLReader instance * [XMLReader::expand](xmlreader.expand) — Returns a copy of the current node as a DOM object * [XMLReader::getAttribute](xmlreader.getattribute) — Get the value of a named attribute * [XMLReader::getAttributeNo](xmlreader.getattributeno) — Get the value of an attribute by index * [XMLReader::getAttributeNs](xmlreader.getattributens) — Get the value of an attribute by localname and URI * [XMLReader::getParserProperty](xmlreader.getparserproperty) — Indicates if specified property has been set * [XMLReader::isValid](xmlreader.isvalid) — Indicates if the parsed document is valid * [XMLReader::lookupNamespace](xmlreader.lookupnamespace) — Lookup namespace for a prefix * [XMLReader::moveToAttribute](xmlreader.movetoattribute) — Move cursor to a named attribute * [XMLReader::moveToAttributeNo](xmlreader.movetoattributeno) — Move cursor to an attribute by index * [XMLReader::moveToAttributeNs](xmlreader.movetoattributens) — Move cursor to a named attribute * [XMLReader::moveToElement](xmlreader.movetoelement) — Position cursor on the parent Element of current Attribute * [XMLReader::moveToFirstAttribute](xmlreader.movetofirstattribute) — Position cursor on the first Attribute * [XMLReader::moveToNextAttribute](xmlreader.movetonextattribute) — Position cursor on the next Attribute * [XMLReader::next](xmlreader.next) — Move cursor to next node skipping all subtrees * [XMLReader::open](xmlreader.open) — Set the URI containing the XML to parse * [XMLReader::read](xmlreader.read) — Move to next node in document * [XMLReader::readInnerXml](xmlreader.readinnerxml) — Retrieve XML from current node * [XMLReader::readOuterXml](xmlreader.readouterxml) — Retrieve XML from current node, including itself * [XMLReader::readString](xmlreader.readstring) — Reads the contents of the current node as a string * [XMLReader::setParserProperty](xmlreader.setparserproperty) — Set parser options * [XMLReader::setRelaxNGSchema](xmlreader.setrelaxngschema) — Set the filename or URI for a RelaxNG Schema * [XMLReader::setRelaxNGSchemaSource](xmlreader.setrelaxngschemasource) — Set the data containing a RelaxNG Schema * [XMLReader::setSchema](xmlreader.setschema) — Validate document against XSD * [XMLReader::XML](xmlreader.xml) — Set the data containing the XML to parse
programming_docs
php Imagick::getImageAlphaChannel Imagick::getImageAlphaChannel ============================= (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::getImageAlphaChannel — Checks if the image has an alpha channel ### Description ``` public Imagick::getImageAlphaChannel(): bool ``` Returns whether the image has an alpha channel. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the image has an alpha channel value and **`false`** if not, i.e. the image is RGB rather than RGBA or CMYK rather than CMYKA. ### Errors/Exceptions Throws ImagickException on error. ### Changelog | Version | Description | | --- | --- | | imagick 3.6.0 | Returns a bool now; previously, an int was returned. | php ArrayIterator::offsetExists ArrayIterator::offsetExists =========================== (PHP 5, PHP 7, PHP 8) ArrayIterator::offsetExists — Check if offset exists ### Description ``` public ArrayIterator::offsetExists(mixed $key): bool ``` Checks if the offset exists. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `key` The offset being checked. ### Return Values **`true`** if the offset exists, otherwise **`false`** ### See Also * [ArrayIterator::valid()](arrayiterator.valid) - Check whether array contains more entries php ReflectionFunction::isAnonymous ReflectionFunction::isAnonymous =============================== (PHP 8 >= 8.2.0) ReflectionFunction::isAnonymous — Checks if a function is anonymous ### Description ``` public ReflectionFunction::isAnonymous(): bool ``` Checks if a function is [anonymous](functions.anonymous). ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the function is anonymous, otherwise **`false`**. ### Examples **Example #1 **ReflectionFunction::isAnonymous()** example** ``` <?php $rf = new ReflectionFunction(function() {}); var_dump($rf->isAnonymous()); $rf = new ReflectionFunction('strlen'); var_dump($rf->isAnonymous()); ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### See Also * [Anonymous functions](functions.anonymous) php crc32 crc32 ===== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) crc32 — Calculates the crc32 polynomial of a string ### Description ``` crc32(string $string): int ``` Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the `string`. 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()](function.sprintf) or [printf()](function.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()](function.sprintf) or [printf()](function.printf) or the [dechex()](function.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()](function.md5) does) might have been a better plan to begin with. For a more portable solution you may also consider the generic [hash()](function.hash). `hash("crc32b", $str)` will return the same string as `str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT)`. ### Parameters `string` The data. ### Return Values Returns the crc32 checksum of `string` as an integer. ### Examples **Example #1 Displaying a crc32 checksum** This example shows how to print a converted checksum with the [printf()](function.printf) function: ``` <?php $checksum = crc32("The quick brown fox jumped over the lazy dog."); printf("%u\n", $checksum); ?> ``` ### See Also * [hash()](function.hash) - Generate a hash value (message digest) * [md5()](function.md5) - Calculate the md5 hash of a string * [sha1()](function.sha1) - Calculate the sha1 hash of a string php Parle\RParser::build Parle\RParser::build ==================== (PECL parle >= 0.7.0) Parle\RParser::build — Finalize the grammar rules ### Description ``` public Parle\RParser::build(): void ``` Any tokens and grammar rules previously added are finalized. The rule set becomes readonly and the parser is ready to start. ### Parameters This function has no parameters. ### Return Values No value is returned. php QuickHashIntHash::delete QuickHashIntHash::delete ======================== (PECL quickhash >= Unknown) QuickHashIntHash::delete — This method deletes an entry from the hash ### Description ``` public QuickHashIntHash::delete(int $key): bool ``` This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed. Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return **`false`** like would happen with any other deletion failure. ### Parameters `key` The key of the entry to delete. ### Return Values **`true`** when the entry was deleted, and **`false`** if the entry was not deleted. ### Examples **Example #1 **QuickHashIntHash::delete()** example** ``` <?php $hash = new QuickHashIntHash( 1024 ); var_dump( $hash->exists( 4 ) ); var_dump( $hash->add( 4, 5 ) ); var_dump( $hash->delete( 4 ) ); var_dump( $hash->exists( 4 ) ); var_dump( $hash->delete( 4 ) ); ?> ``` The above example will output something similar to: ``` bool(false) bool(true) bool(true) bool(false) bool(false) ``` php ImagickDraw::setResolution ImagickDraw::setResolution ========================== (PECL imagick 3 >= 3.1.0) ImagickDraw::setResolution — Description ### Description ``` public ImagickDraw::setResolution(float $x_resolution, float $y_resolution): bool ``` Sets the resolution. ### Parameters `x_resolution` `y_resolution` ### Return Values Returns **`true`** on success. php ldap_delete_ext ldap\_delete\_ext ================= (PHP 7 >= 7.3.0, PHP 8) ldap\_delete\_ext — Delete an entry from a directory ### Description ``` ldap_delete_ext(LDAP\Connection $ldap, string $dn, ?array $controls = null): LDAP\Result|false ``` Does the same thing as [ldap\_delete()](function.ldap-delete) but returns an [LDAP\Result](class.ldap-result) instance to be parsed with [ldap\_parse\_result()](function.ldap-parse-result). ### Parameters See [ldap\_delete()](function.ldap-delete) ### Return Values Returns an [LDAP\Result](class.ldap-result) instance, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | Returns an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was returned. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | ### See Also * [ldap\_delete()](function.ldap-delete) - Delete an entry from a directory * [ldap\_parse\_result()](function.ldap-parse-result) - Extract information from result php proc_nice proc\_nice ========== (PHP 5, PHP 7, PHP 8) proc\_nice — Change the priority of the current process ### Description ``` proc_nice(int $priority): bool ``` **proc\_nice()** changes the priority of the current process by the amount specified in `priority`. A positive `priority` will lower the priority of the current process, whereas a negative `priority` will raise the priority. **proc\_nice()** is not related to [proc\_open()](function.proc-open) and its associated functions in any way. ### Parameters `priority` The new priority value, the value of this may differ on platforms. On Unix, a low value, such as `-20` means high priority whereas positive values have a lower priority. For Windows the `priority` parameter has the following meaning: | Priority class | Possible values | | --- | --- | | High priority | `priority` `< -9` | | Above normal priority | `priority` `< -4` | | Normal priority | `priority` `< 5` & `priority` `> -5` | | Below normal priority | `priority` `> 5` | | Idle priority | `priority` `> 9` | ### Return Values Returns **`true`** on success or **`false`** on failure. If an error occurs, like the user lacks permission to change the priority, an error of level **`E_WARNING`** is also generated. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | This function is now available on Windows. | ### Examples **Example #1 Using **proc\_nice()** to set the process priority to high** ``` <?php // Highest priority proc_nice(-20); ?> ``` ### Notes > > **Note**: **Availability** > > > > **proc\_nice()** will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3. > > > > **Note**: **Windows only** > > > > **proc\_nice()** will change the current *process* priority, even if PHP was compiled using thread safety. > > ### See Also * [pcntl\_setpriority()](function.pcntl-setpriority) - Change the priority of any process php NumberFormatter::setSymbol NumberFormatter::setSymbol ========================== numfmt\_set\_symbol =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::setSymbol -- numfmt\_set\_symbol — Set a symbol value ### Description Object-oriented style ``` public NumberFormatter::setSymbol(int $symbol, string $value): bool ``` Procedural style ``` numfmt_set_symbol(NumberFormatter $formatter, int $symbol, string $value): bool ``` Set a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. `symbol` Symbol specifier, one of the [format symbol](class.numberformatter#intl.numberformatter-constants.unumberformatsymbol) constants. `value` Text for the symbol. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **numfmt\_set\_symbol()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL ); echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n"; echo numfmt_format($fmt, 1234567.891234567890000)."\n"; numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*"); echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n"; echo numfmt_format($fmt, 1234567.891234567890000)."\n"; ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL ); echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n"; echo $fmt->format(1234567.891234567890000)."\n"; $fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*"); echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n"; echo $fmt->format(1234567.891234567890000)."\n"; ?> ``` The above example will output: ``` Sep: . 1.234.567,891 Sep: * 1*234*567,891 ``` ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [numfmt\_get\_symbol()](numberformatter.getsymbol) - Get a symbol value php IntlChar::isIDPart IntlChar::isIDPart ================== (PHP 7, PHP 8) IntlChar::isIDPart — Check if code point is permissible in an identifier ### Description ``` public static IntlChar::isIDPart(int|string $codepoint): ?bool ``` Determines if the specified character is permissible in an identifier. **`true`** for characters with general categories "L" (letters), "Nl" (letter numbers), "Nd" (decimal digits), "Mc" and "Mn" (combining marks), "Pc" (connecting punctuation), and u\_isIDIgnorable(c). > > **Note**: > > > This is almost the same as Unicode's ID\_Continue (**`IntlChar::PROPERTY_ID_CONTINUE`**) except that Unicode recommends to ignore Cf which is less than [IntlChar::isIDIgnorable()](intlchar.isidignorable). > > ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` is the code point may occur in an identifier, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isIDPart("A")); var_dump(IntlChar::isIDPart("$")); var_dump(IntlChar::isIDPart("\n")); var_dump(IntlChar::isIDPart("\u{2603}")); ?> ``` The above example will output: ``` bool(true) bool(false) bool(false) bool(false) ``` ### See Also * [IntlChar::isIDIgnorable()](intlchar.isidignorable) - Check if code point is an ignorable character * [IntlChar::isIDStart()](intlchar.isidstart) - Check if code point is permissible as the first character in an identifier * **`IntlChar::PROPERTY_ID_CONTINUE`** php sodium_crypto_core_ristretto255_scalar_complement sodium\_crypto\_core\_ristretto255\_scalar\_complement ====================================================== (PHP 8 >= 8.1.0) sodium\_crypto\_core\_ristretto255\_scalar\_complement — The sodium\_crypto\_core\_ristretto255\_scalar\_complement purpose ### Description ``` sodium_crypto_core_ristretto255_scalar_complement(string $s): string ``` Available as of libsodium 1.0.18. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `s` Scalar value. ### Return Values Returns a 32-byte random string. ### See Also * [sodium\_crypto\_core\_ristretto255\_scalar\_random()](function.sodium-crypto-core-ristretto255-scalar-random) - Generates a random key php CURLFile::getMimeType CURLFile::getMimeType ===================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) CURLFile::getMimeType — Get MIME type ### Description ``` public CURLFile::getMimeType(): string ``` ### Parameters This function has no parameters. ### Return Values Returns MIME type. php Yaf_Route_Static::route Yaf\_Route\_Static::route ========================= (Yaf >=1.0.0) Yaf\_Route\_Static::route — Route a request ### Description ``` public Yaf_Route_Static::route(Yaf_Request_Abstract $request): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `request` ### Return Values always be **`true`** ### Examples **Example #1 **Yaf\_Route\_Static::route()**example** ``` // assuming there is only one module defined:Index Request: http://yourdomain.com/a/b => module = index, controller=a, action=b //assuming ap.action_prefer = On Request: http://yourdomain.com/b => module = default(index), controller = default(index), action = b //assuming ap.action_prefer = Off Request: http://yourdomain.com/b => module = default(index), controller = b, action = default(index) Request: http://yourdomain.com/a/b/foo/bar/test/a/id/4 => module = default(index), controller = a, action = b, request parameters: foo = bar, test = a, id = 4 ``` ### See Also * [Yaf\_Route\_Supervar::route()](yaf-route-supervar.route) - The route purpose * [Yaf\_Route\_Simple::route()](yaf-route-simple.route) - Route a request * [Yaf\_Route\_Regex::route()](yaf-route-regex.route) - The route purpose * [Yaf\_Route\_Rewrite::route()](yaf-route-rewrite.route) - The route purpose * [Yaf\_Route\_Map::route()](yaf-route-map.route) - The route purpose php $http_response_header $http\_response\_header ======================= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) $http\_response\_header — HTTP response headers ### Description The $http\_response\_header array is similar to the [get\_headers()](function.get-headers) function. When using the [HTTP wrapper](https://www.php.net/manual/en/wrappers.http.php), $http\_response\_header will be populated with the HTTP response headers. $http\_response\_header will be created in the [local scope](language.variables.scope). ### Examples **Example #1 $http\_response\_header example** ``` <?php function get_contents() {   file_get_contents("http://example.com");   var_dump($http_response_header); } get_contents(); var_dump($http_response_header); ?> ``` The above example will output something similar to: ``` array(9) { [0]=> string(15) "HTTP/1.1 200 OK" [1]=> string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT" [2]=> string(29) "Server: Apache/2.2.3 (CentOS)" [3]=> string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT" [4]=> string(27) "ETag: "280100-1b6-80bfd280"" [5]=> string(20) "Accept-Ranges: bytes" [6]=> string(19) "Content-Length: 438" [7]=> string(17) "Connection: close" [8]=> string(38) "Content-Type: text/html; charset=UTF-8" } NULL ``` php ReflectionMethod::invoke ReflectionMethod::invoke ======================== (PHP 5, PHP 7, PHP 8) ReflectionMethod::invoke — Invoke ### Description ``` public ReflectionMethod::invoke(?object $object, mixed ...$args): mixed ``` Invokes a reflected method. ### Parameters `object` The object to invoke the method on. For static methods, pass null to this parameter. `args` Zero or more parameters to be passed to the method. It accepts a variable number of parameters which are passed to the method. ### Return Values Returns the method result. ### Errors/Exceptions A [ReflectionException](class.reflectionexception) if the `object` parameter does not contain an instance of the class that this method was declared in. A [ReflectionException](class.reflectionexception) if the method invocation failed. ### Examples **Example #1 **ReflectionMethod::invoke()** example** ``` <?php class HelloWorld {     public function sayHelloTo($name) {         return 'Hello ' . $name;     } } $reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo'); echo $reflectionMethod->invoke(new HelloWorld(), 'Mike'); ?> ``` The above example will output: ``` Hello Mike ``` ### Notes > > **Note**: > > > **ReflectionMethod::invoke()** cannot be used when reference parameters are expected. [ReflectionMethod::invokeArgs()](reflectionmethod.invokeargs) has to be used instead (passing references in the argument list). > > ### See Also * [ReflectionMethod::invokeArgs()](reflectionmethod.invokeargs) - Invoke args * [\_\_invoke()](language.oop5.magic#object.invoke) * [call\_user\_func()](function.call-user-func) - Call the callback given by the first parameter php stats_rand_gen_iuniform stats\_rand\_gen\_iuniform ========================== (PECL stats >= 1.0.0) stats\_rand\_gen\_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive) ### Description ``` stats_rand_gen_iuniform(int $low, int $high): int ``` Returns a random integer from the discrete uniform distribution between `low` (inclusive) and `high` (inclusive). ### Parameters `low` The lower bound `high` The upper bound ### Return Values A random integer
programming_docs
php GearmanWorker::echo GearmanWorker::echo =================== (PECL gearman >= 0.6.0) GearmanWorker::echo — Test job server response ### Description ``` public GearmanWorker::echo(string $workload): bool ``` Sends data to all job servers to see if they echo it back. This is a test function to see if job servers are responding properly. ### Parameters `workload` Arbitrary serialized data ### Return Values Standard Gearman return value. ### See Also * [GearmanClient::echo()](gearmanclient.echo) - Send data to all job servers to see if they echo it back [deprecated] php DatePeriod::getStartDate DatePeriod::getStartDate ======================== (PHP 5 >= 5.6.5, PHP 7, PHP 8) DatePeriod::getStartDate — Gets the start date ### Description Object-oriented style ``` public DatePeriod::getStartDate(): DateTimeInterface ``` Gets the start date of the period. ### Parameters This function has no parameters. ### Return Values Returns a [DateTimeImmutable](class.datetimeimmutable) object when the [DatePeriod](class.dateperiod) is initialized with a [DateTimeImmutable](class.datetimeimmutable) object as the `start` parameter. Returns a [DateTime](class.datetime) object otherwise. ### Examples **Example #1 **DatePeriod::getStartDate()** example** ``` <?php $period = new DatePeriod('R7/2016-05-16T00:00:00Z/P1D'); $start = $period->getStartDate(); echo $start->format(DateTime::ISO8601); ?> ``` The above example will output: ``` 2016-05-16T00:00:00+0000 ``` ### See Also * [DatePeriod::getEndDate()](dateperiod.getenddate) - Gets the end date * [DatePeriod::getDateInterval()](dateperiod.getdateinterval) - Gets the interval php Phar::decompress Phar::decompress ================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::decompress — Decompresses the entire Phar archive ### Description ``` public Phar::decompress(?string $extension = null): ?Phar ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > For tar-based and phar-based phar archives, this method decompresses the entire archive. For Zip-based phar archives, this method fails with an exception. The [zlib](https://www.php.net/manual/en/ref.zlib.php) extension must be enabled to decompress an archive compressed with gzip compression, and the [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extension must be enabled in order to decompress an archive compressed with bzip2 compression. As with all functionality that modifies the contents of a phar, the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable must be off in order to succeed. In addition, this method automatically changes the file extension of the archive, `.phar` by default for phar archives, or `.phar.tar` for tar-based phar archives. Alternatively, a file extension may be specified with the second parameter. ### Parameters `extension` For decompressing, the default file extensions are `.phar` and `.phar.tar`. Use this parameter to specify another file extension. Be aware that all executable phar archives must contain `.phar` in their filename. ### Return Values A [Phar](class.phar) object is returned on success, and **`null`** on failure. ### Errors/Exceptions Throws [BadMethodCallException](class.badmethodcallexception) if the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable is on, the [zlib](https://www.php.net/manual/en/ref.zlib.php) extension is not available, or the [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extension is not enabled. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `extension` is now nullable. | ### Examples **Example #1 A **Phar::decompress()** example** ``` <?php $p = new Phar('/path/to/my.phar', 0, 'my.phar.gz'); $p['myfile.txt'] = 'hi'; $p['myfile2.txt'] = 'hi'; $p3 = $p2->decompress(); // creates /path/to/my.phar ?> ``` ### See Also * [PharFileInfo::getCompressedSize()](pharfileinfo.getcompressedsize) - Returns the actual size of the file (with compression) inside the Phar archive * [PharFileInfo::isCompressed()](pharfileinfo.iscompressed) - Returns whether the entry is compressed * [PharFileInfo::compress()](pharfileinfo.compress) - Compresses the current Phar entry with either zlib or bzip2 compression * [PharFileInfo::decompress()](pharfileinfo.decompress) - Decompresses the current Phar entry within the phar * [PharData::compress()](phardata.compress) - Compresses the entire tar/zip archive using Gzip or Bzip2 compression * [Phar::canCompress()](phar.cancompress) - Returns whether phar extension supports compression using either zlib or bzip2 * [Phar::isCompressed()](phar.iscompressed) - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on) * [Phar::compress()](phar.compress) - Compresses the entire Phar archive using Gzip or Bzip2 compression * [Phar::getSupportedCompression()](phar.getsupportedcompression) - Return array of supported compression algorithms * [Phar::compressFiles()](phar.compressfiles) - Compresses all files in the current Phar archive * [Phar::decompressFiles()](phar.decompressfiles) - Decompresses all files in the current Phar archive php ssh2_sftp_realpath ssh2\_sftp\_realpath ==================== (PECL ssh2 >= 0.9.0) ssh2\_sftp\_realpath — Resolve the realpath of a provided path string ### Description ``` ssh2_sftp_realpath(resource $sftp, string $filename): string ``` Translates `filename` into the effective real path on the remote filesystem. ### Parameters `sftp` An SSH2 SFTP resource opened by [ssh2\_sftp()](function.ssh2-sftp). `filename` ### Return Values Returns the real path as a string. ### Examples **Example #1 Resolving a pathname** ``` <?php $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $sftp = ssh2_sftp($connection); $realpath = ssh2_sftp_realpath($sftp, '/home/username/../../../..//./usr/../etc/passwd'); /* $realpath is now: '/etc/passwd' */ ?> ``` ### See Also * [realpath()](function.realpath) - Returns canonicalized absolute pathname * [ssh2\_sftp\_symlink()](function.ssh2-sftp-symlink) - Create a symlink * [ssh2\_sftp\_readlink()](function.ssh2-sftp-readlink) - Return the target of a symbolic link php Imagick::setImageBluePrimary Imagick::setImageBluePrimary ============================ (PECL imagick 2, PECL imagick 3) Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point ### Description ``` public Imagick::setImageBluePrimary(float $x, float $y): bool ``` Sets the image chromaticity blue primary point. ### Parameters `x` `y` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php sodium_crypto_aead_chacha20poly1305_keygen sodium\_crypto\_aead\_chacha20poly1305\_keygen ============================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_aead\_chacha20poly1305\_keygen — Generate a random ChaCha20-Poly1305 key. ### Description ``` sodium_crypto_aead_chacha20poly1305_keygen(): string ``` Generate a random key for use with [sodium\_crypto\_aead\_chacha20poly1305\_encrypt()](function.sodium-crypto-aead-chacha20poly1305-encrypt) and [sodium\_crypto\_aead\_chacha20poly1305\_decrypt()](function.sodium-crypto-aead-chacha20poly1305-decrypt). ### Parameters This function has no parameters. ### Return Values Returns a 256-bit random key. php The CURLStringFile class The CURLStringFile class ======================== Introduction ------------ (PHP 8 >= 8.1.0) **CURLStringFile** makes it possible to upload a file directly from a variable. This is similar to [CURLFile](class.curlfile), but works with the contents of the file, not filename. This class or [CURLFile](class.curlfile) should be used to upload the contents of the file with **`CURLOPT_POSTFIELDS`**. Class synopsis -------------- class **CURLStringFile** { /\* Properties \*/ public string [$data](class.curlstringfile#curlstringfile.props.data); public string [$postname](class.curlstringfile#curlstringfile.props.postname); public string [$mime](class.curlstringfile#curlstringfile.props.mime); /\* Methods \*/ public [\_\_construct](curlstringfile.construct)(string `$data`, string `$postname`, string `$mime` = "application/octet-stream") } Properties ---------- data The contents to be uploaded. postname The name of the file to be used in the upload data. mime MIME type of the file (default is `application/octet-stream`). See Also -------- * [curl\_setopt()](function.curl-setopt) * [CURLFile](class.curlfile) Table of Contents ----------------- * [CURLStringFile::\_\_construct](curlstringfile.construct) — Create a CURLStringFile object php gmp_export gmp\_export =========== (PHP 5 >= 5.6.1, PHP 7, PHP 8) gmp\_export — Export to a binary string ### Description ``` gmp_export(GMP|int|string $num, int $word_size = 1, int $flags = GMP_MSW_FIRST | GMP_NATIVE_ENDIAN): string ``` Export a GMP number to a binary string ### Parameters `num` The GMP number being exported `word_size` Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter. `flags` Default value is **`GMP_MSW_FIRST`** | **`GMP_NATIVE_ENDIAN`**. ### Return Values Returns a string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function no longer returns **`false`** on failure. | ### Examples **Example #1 **gmp\_export()** example** ``` <?php $number = gmp_init(16705); echo gmp_export($number) . "\n"; ?> ``` The above example will output: ``` AA ``` ### See Also * [gmp\_import()](function.gmp-import) - Import from a binary string php Phar::isWritable Phar::isWritable ================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::isWritable — Returns true if the phar archive can be modified ### Description ``` public Phar::isWritable(): bool ``` This method returns **`true`** if `phar.readonly` is `0`, and the actual phar archive on disk is not read-only. ### Parameters No parameters. ### Return Values Returns **`true`** if the phar archive can be modified ### See Also * [Phar::canWrite()](phar.canwrite) - Returns whether phar extension supports writing and creating phars * [PharData::isWritable()](phardata.iswritable) - Returns true if the tar/zip archive can be modified php None FAQ: things you need to know about namespaces --------------------------------------------- (PHP 5 >= 5.3.0, PHP 7, PHP 8) This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully. First, the common questions. 1. [If I don't use namespaces, should I care about any of this?](language.namespaces.faq#language.namespaces.faq.shouldicare) 2. [How do I use internal or global classes in a namespace?](language.namespaces.faq#language.namespaces.faq.globalclass) 3. [How do I use namespaces classes functions, or constants in their own namespace?](language.namespaces.faq#language.namespaces.faq.innamespace) 4. [How does a name like `\my\name` or `\name` resolve?](language.namespaces.faq#language.namespaces.faq.full) 5. [How does a name like `my\name` resolve?](language.namespaces.faq#language.namespaces.faq.qualified) 6. [How does an unqualified class name like `name` resolve?](language.namespaces.faq#language.namespaces.faq.shortname1) 7. [How does an unqualified function name or unqualified constant name like `name` resolve?](language.namespaces.faq#language.namespaces.faq.shortname2) There are a few implementation details of the namespace implementations that are helpful to understand. 1. [Import names must not conflict with classes defined in the same file.](language.namespaces.faq#language.namespaces.faq.conflict) 2. [Nested namespaces are not allowed.](language.namespaces.faq#language.namespaces.faq.nested) 3. [Dynamic namespace names (quoted identifiers) should escape backslash.](language.namespaces.faq#language.namespaces.faq.quote) 4. [Undefined Constants referenced using any backslash die with fatal error](language.namespaces.faq#language.namespaces.faq.constants) 5. [Cannot override special constants NULL, TRUE, FALSE, ZEND\_THREAD\_SAFE or ZEND\_DEBUG\_BUILD](language.namespaces.faq#language.namespaces.faq.builtinconst) ### If I don't use namespaces, should I care about any of this? No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish: **Example #1 Accessing global classes outside a namespace** ``` <?php $a = new \stdClass; ?> ``` This is functionally equivalent to: **Example #2 Accessing global classes outside a namespace** ``` <?php $a = new stdClass; ?> ``` ### How do I use internal or global classes in a namespace? **Example #3 Accessing internal classes in namespaces** ``` <?php namespace foo; $a = new \stdClass; function test(\ArrayObject $parameter_type_example = null) {} $a = \DirectoryIterator::CURRENT_AS_FILEINFO; // extending an internal or global class class MyException extends \Exception {} ?> ``` ### How do I use namespaces classes, functions, or constants in their own namespace? **Example #4 Accessing internal classes, functions or constants in namespaces** ``` <?php namespace foo; class MyClass {} // using a class from the current namespace as a parameter type function test(MyClass $parameter_type_example = null) {} // another way to use a class from the current namespace as a parameter type function test(\foo\MyClass $parameter_type_example = null) {} // extending a class from the current namespace class Extended extends MyClass {} // accessing a global function $a = \globalfunc(); // accessing a global constant $b = \INI_ALL; ?> ``` ### How does a name like `\my\name` or `\name` resolve? Names that begin with a `\` always resolve to what they look like, so `\my\name` is in fact `my\name`, and `\Exception` is `Exception`. **Example #5 Fully Qualified names** ``` <?php namespace foo; $a = new \my\name(); // instantiates "my\name" class echo \strlen('hi'); // calls function "strlen" $a = \INI_ALL; // $a is set to the value of constant "INI_ALL" ?> ``` ### How does a name like `my\name` resolve? Names that contain a backslash but do not begin with a backslash like `my\name` can be resolved in 2 different ways. If there is an import statement that aliases another name to `my`, then the import alias is applied to the `my` in `my\name`. Otherwise, the current namespace name is prepended to `my\name`. **Example #6 Qualified names** ``` <?php namespace foo; use blah\blah as foo; $a = new my\name(); // instantiates "foo\my\name" class foo\bar::name(); // calls static method "name" in class "blah\blah\bar" my\bar(); // calls function "foo\my\bar" $a = my\BAR; // sets $a to the value of constant "foo\my\BAR" ?> ``` ### How does an unqualified class name like `name` resolve? Class names that do not contain a backslash like `name` can be resolved in 2 different ways. If there is an import statement that aliases another name to `name`, then the import alias is applied. Otherwise, the current namespace name is prepended to `name`. **Example #7 Unqualified class names** ``` <?php namespace foo; use blah\blah as foo; $a = new name(); // instantiates "foo\name" class foo::name(); // calls static method "name" in class "blah\blah" ?> ``` ### How does an unqualified function name or unqualified constant name like `name` resolve? Function or constant names that do not contain a backslash like `name` can be resolved in 2 different ways. First, the current namespace name is prepended to `name`. Finally, if the constant or function `name` does not exist in the current namespace, a global constant or function `name` is used if it exists. **Example #8 Unqualified function or constant names** ``` <?php namespace foo; use blah\blah as foo; const FOO = 1; function my() {} function foo() {} function sort(&$a) {     \sort($a); // calls the global function "sort"     $a = array_flip($a);     return $a; } my(); // calls "foo\my" $a = strlen('hi'); // calls global function "strlen" because "foo\strlen" does not exist $arr = array(1,3,2); $b = sort($arr); // calls function "foo\sort" $c = foo(); // calls function "foo\foo" - import is not applied $a = FOO; // sets $a to value of constant "foo\FOO" - import is not applied $b = INI_ALL; // sets $b to value of global constant "INI_ALL" ?> ``` ### Import names must not conflict with classes defined in the same file. The following script combinations are legal: file1.php ``` <?php namespace my\stuff; class MyClass {} ?> ``` another.php ``` <?php namespace another; class thing {} ?> ``` file2.php ``` <?php namespace my\stuff; include 'file1.php'; include 'another.php'; use another\thing as MyClass; $a = new MyClass; // instantiates class "thing" from namespace another ?> ``` There is no name conflict, even though the class `MyClass` exists within the `my\stuff` namespace, because the MyClass definition is in a separate file. However, the next example causes a fatal error on name conflict because MyClass is defined in the same file as the use statement. ``` <?php namespace my\stuff; use another\thing as MyClass; class MyClass {} // fatal error: MyClass conflicts with import statement $a = new MyClass; ?> ``` ### Nested namespaces are not allowed. PHP does not allow nesting namespaces ``` <?php namespace my\stuff {     namespace nested {         class foo {}     } } ?> ``` However, it is easy to simulate nested namespaces like so: ``` <?php namespace my\stuff\nested {     class foo {} } ?> ``` ### Dynamic namespace names (quoted identifiers) should escape backslash It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences: **Example #9 Dangers of using namespaced names inside a double-quoted string** ``` <?php $a = "dangerous\name"; // \n is a newline inside double quoted strings! $obj = new $a; $a = 'not\at\all\dangerous'; // no problems here. $obj = new $a; ?> ``` Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice. ### Undefined Constants referenced using any backslash die with fatal error Any undefined constant that is unqualified like `FOO` will produce a notice explaining that PHP assumed `FOO` was the value of the constant. Any constant, qualified or fully qualified, that contains a backslash will produce a fatal error if not found. **Example #10 Undefined constants** ``` <?php namespace bar; $a = FOO; // produces notice - undefined constants "FOO" assumed "FOO"; $a = \FOO; // fatal error, undefined namespace constant FOO $a = Bar\FOO; // fatal error, undefined namespace constant bar\Bar\FOO $a = \Bar\FOO; // fatal error, undefined namespace constant Bar\FOO ?> ``` ### Cannot override special constants NULL, TRUE, FALSE, ZEND\_THREAD\_SAFE or ZEND\_DEBUG\_BUILD Any attempt to define a namespaced constant that is a special, built-in constant results in a fatal error **Example #11 Undefined constants** ``` <?php namespace bar; const NULL = 0; // fatal error; const true = 'stupid'; // also fatal error; // etc. ?> ```
programming_docs
php openssl_x509_export openssl\_x509\_export ===================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) openssl\_x509\_export — Exports a certificate as a string ### Description ``` openssl_x509_export(OpenSSLCertificate|string $certificate, string &$output, bool $no_text = true): bool ``` **openssl\_x509\_export()** stores `certificate` into a string named by `output` in a PEM encoded format. ### Parameters `x509` See [Key/Certificate parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values. `output` On success, this will hold the PEM. `no_text` The optional parameter `notext` affects the verbosity of the output; if it is **`false`**, then additional human-readable information is included in the output. The default value of `notext` is **`true`**. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was accepted. | php mysqli_stmt::data_seek mysqli\_stmt::data\_seek ======================== mysqli\_stmt\_data\_seek ======================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::data\_seek -- mysqli\_stmt\_data\_seek — Seeks to an arbitrary row in statement result set ### Description Object-oriented style ``` public mysqli_stmt::data_seek(int $offset): void ``` Procedural style ``` mysqli_stmt_data_seek(mysqli_stmt $statement, int $offset): void ``` Seeks to an arbitrary result pointer in the statement result set. [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result) must be called prior to **mysqli\_stmt\_data\_seek()**. ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). `offset` Must be between zero and the total number of rows minus one (0.. [mysqli\_stmt\_num\_rows()](mysqli-stmt.num-rows) - 1). ### Return Values No value is returned. ### Examples **Example #1 Object-oriented style** ``` <?php /* Open a connection */ $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, CountryCode FROM City ORDER BY Name"; if ($stmt = $mysqli->prepare($query)) {     /* execute query */     $stmt->execute();     /* bind result variables */     $stmt->bind_result($name, $code);     /* store result */     $stmt->store_result();     /* seek to row no. 400 */     $stmt->data_seek(399);     /* fetch values */     $stmt->fetch();     printf ("City: %s  Countrycode: %s\n", $name, $code);     /* close statement */     $stmt->close(); } /* close connection */ $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php /* Open a connection */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, CountryCode FROM City ORDER BY Name"; if ($stmt = mysqli_prepare($link, $query)) {     /* execute query */     mysqli_stmt_execute($stmt);     /* bind result variables */     mysqli_stmt_bind_result($stmt, $name, $code);     /* store result */     mysqli_stmt_store_result($stmt);     /* seek to row no. 400 */     mysqli_stmt_data_seek($stmt, 399);     /* fetch values */     mysqli_stmt_fetch($stmt);     printf ("City: %s  Countrycode: %s\n", $name, $code);     /* close statement */     mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` City: Benin City Countrycode: NGA ``` ### See Also * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution php UConverter::getSourceType UConverter::getSourceType ========================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) UConverter::getSourceType — Get the source converter type ### Description ``` public UConverter::getSourceType(): int|false|null ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php pg_socket pg\_socket ========== (PHP 5 >= 5.6.0, PHP 7, PHP 8) pg\_socket — Get a read only handle to the socket underlying a PostgreSQL connection ### Description ``` pg_socket(PgSql\Connection $connection): resource|false ``` **pg\_socket()** returns a read only resource corresponding to the socket underlying the given PostgreSQL connection. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. ### Return Values A socket resource on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | php curl_setopt curl\_setopt ============ (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) curl\_setopt — Set an option for a cURL transfer ### Description ``` curl_setopt(CurlHandle $handle, int $option, mixed $value): bool ``` Sets an option on the given cURL session handle. ### Parameters `handle` A cURL handle returned by [curl\_init()](function.curl-init). `option` The `CURLOPT_XXX` option to set. `value` The value to be set on `option`. `value` should be a bool for the following values of the `option` parameter: | Option | Set `value` to | Notes | | --- | --- | --- | | **`CURLOPT_AUTOREFERER`** | **`true`** to automatically set the `Referer:` field in requests where it follows a `Location:` redirect. | | | **`CURLOPT_COOKIESESSION`** | **`true`** to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies or not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. | | | **`CURLOPT_CERTINFO`** | **`true`** to output SSL certification information to `STDERR` on secure transfers. | Added in cURL 7.19.1. Requires **`CURLOPT_VERBOSE`** to be on to have an effect. | | **`CURLOPT_CONNECT_ONLY`** | **`true`** tells the library to perform all the required proxy authentication and connection setup, but no data transfer. This option is implemented for HTTP, SMTP and POP3. | Added in 7.15.2. | | **`CURLOPT_CRLF`** | **`true`** to convert Unix newlines to CRLF newlines on transfers. | | | **`CURLOPT_DISALLOW_USERNAME_IN_URL`** | **`true`** to not allow URLs that include a username. Usernames are allowed by default (0). | Added in cURL 7.61.0. Available since PHP 7.3.0. | | **`CURLOPT_DNS_SHUFFLE_ADDRESSES`** | **`true`** to shuffle the order of all returned addresses so that they will be used in a random order, when a name is resolved and more than one IP address is returned. This may cause IPv4 to be used before IPv6 or vice versa. | Added in cURL 7.60.0. Available since PHP 7.3.0. | | **`CURLOPT_HAPROXYPROTOCOL`** | **`true`** to send an HAProxy PROXY protocol v1 header at the start of the connection. The default action is not to send this header. | Added in cURL 7.60.0. Available since PHP 7.3.0. | | **`CURLOPT_SSH_COMPRESSION`** | **`true`** to enable built-in SSH compression. This is a request, not an order; the server may or may not do it. | Added in cURL 7.56.0. Available since PHP 7.3.0. | | **`CURLOPT_DNS_USE_GLOBAL_CACHE`** | **`true`** to use a global DNS cache. This option is not thread-safe. It is conditionally enabled by default if PHP is built for non-threaded use (CLI, FCGI, Apache2-Prefork, etc.). | | | **`CURLOPT_FAILONERROR`** | **`true`** to fail verbosely if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code. | | | **`CURLOPT_SSL_FALSESTART`** | **`true`** to enable TLS false start. | Added in cURL 7.42.0. Available since PHP 7.0.7. | | **`CURLOPT_FILETIME`** | **`true`** to attempt to retrieve the modification date of the remote document. This value can be retrieved using the **`CURLINFO_FILETIME`** option with [curl\_getinfo()](function.curl-getinfo). | | | **`CURLOPT_FOLLOWLOCATION`** | **`true`** to follow any `"Location: "` header that the server sends as part of the HTTP header. See also **`CURLOPT_MAXREDIRS`**. | | | **`CURLOPT_FORBID_REUSE`** | **`true`** to force the connection to explicitly close when it has finished processing, and not be pooled for reuse. | | | **`CURLOPT_FRESH_CONNECT`** | **`true`** to force the use of a new connection instead of a cached one. | | | **`CURLOPT_FTP_USE_EPRT`** | **`true`** to use EPRT (and LPRT) when doing active FTP downloads. Use **`false`** to disable EPRT and LPRT and use PORT only. | | | **`CURLOPT_FTP_USE_EPSV`** | **`true`** to first try an EPSV command for FTP transfers before reverting back to PASV. Set to **`false`** to disable EPSV. | | | **`CURLOPT_FTP_CREATE_MISSING_DIRS`** | **`true`** to create missing directories when an FTP operation encounters a path that currently doesn't exist. | | | **`CURLOPT_FTPAPPEND`** | **`true`** to append to the remote file instead of overwriting it. | | | **`CURLOPT_TCP_NODELAY`** | **`true`** to disable TCP's Nagle algorithm, which tries to minimize the number of small packets on the network. | Available for versions compiled with libcurl 7.11.2 or greater. | | **`CURLOPT_FTPASCII`** | An alias of **`CURLOPT_TRANSFERTEXT`**. Use that instead. | | | **`CURLOPT_FTPLISTONLY`** | **`true`** to only list the names of an FTP directory. | | | **`CURLOPT_HEADER`** | **`true`** to include the header in the output. | | | **`CURLINFO_HEADER_OUT`** | **`true`** to track the handle's request string. | The **`CURLINFO_`** prefix is intentional. | | **`CURLOPT_HTTP09_ALLOWED`** | Whether to allow HTTP/0.9 responses. Defaults to **`false`** as of libcurl 7.66.0; formerly it defaulted to **`true`**. | Available since PHP 7.3.15 and 7.4.3, respectively, if built against libcurl >= 7.64.0 | | **`CURLOPT_HTTPGET`** | **`true`** to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed. | | | **`CURLOPT_HTTPPROXYTUNNEL`** | **`true`** to tunnel through a given HTTP proxy. | | | **`CURLOPT_HTTP_CONTENT_DECODING`** | **`false`** to get the raw HTTP response body. | Available if built against libcurl >= 7.16.2. | | **`CURLOPT_KEEP_SENDING_ON_ERROR`** | **`true`** to keep sending the request body if the HTTP code returned is equal to or larger than 300. The default action would be to stop sending and close the stream or connection. Suitable for manual NTLM authentication. Most applications do not need this option. | Available as of PHP 7.3.0 if built against libcurl >= 7.51.0. | | **`CURLOPT_MUTE`** | **`true`** to be completely silent with regards to the cURL functions. | Removed in cURL 7.15.5 (You can use CURLOPT\_RETURNTRANSFER instead) | | **`CURLOPT_NETRC`** | **`true`** to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with. | | | **`CURLOPT_NOBODY`** | **`true`** to exclude the body from the output. Request method is then set to HEAD. Changing this to **`false`** does not change it to GET. | | | **`CURLOPT_NOPROGRESS`** | **`true`** to disable the progress meter for cURL transfers. **Note**: PHP automatically sets this option to **`true`**, this should only be changed for debugging purposes. | | | **`CURLOPT_NOSIGNAL`** | **`true`** to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used. | Added in cURL 7.10. | | **`CURLOPT_PATH_AS_IS`** | **`true`** to not handle dot dot sequences. | Added in cURL 7.42.0. Available since PHP 7.0.7. | | **`CURLOPT_PIPEWAIT`** | **`true`** to wait for pipelining/multiplexing. | Added in cURL 7.43.0. Available since PHP 7.0.7. | | **`CURLOPT_POST`** | **`true`** to do a regular HTTP POST. This POST is the normal `application/x-www-form-urlencoded` kind, most commonly used by HTML forms. | | | **`CURLOPT_PUT`** | **`true`** to HTTP PUT a file. The file to PUT must be set with **`CURLOPT_INFILE`** and **`CURLOPT_INFILESIZE`**. | | | **`CURLOPT_RETURNTRANSFER`** | **`true`** to return the transfer as a string of the return value of [curl\_exec()](function.curl-exec) instead of outputting it directly. | | | **`CURLOPT_SASL_IR`** | **`true`** to enable sending the initial response in the first packet. | Added in cURL 7.31.10. Available since PHP 7.0.7. | | **`CURLOPT_SSL_ENABLE_ALPN`** | **`false`** to disable ALPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2. | Added in cURL 7.36.0. Available since PHP 7.0.7. | | **`CURLOPT_SSL_ENABLE_NPN`** | **`false`** to disable NPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2. | Added in cURL 7.36.0. Available since PHP 7.0.7. | | **`CURLOPT_SSL_VERIFYPEER`** | **`false`** to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the **`CURLOPT_CAINFO`** option or a certificate directory can be specified with the **`CURLOPT_CAPATH`** option. | **`true`** by default as of cURL 7.10. Default bundle installed as of cURL 7.10. | | **`CURLOPT_SSL_VERIFYSTATUS`** | **`true`** to verify the certificate's status. | Added in cURL 7.41.0. Available since PHP 7.0.7. | | **`CURLOPT_PROXY_SSL_VERIFYPEER`** | **`false`** to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the **`CURLOPT_CAINFO`** option or a certificate directory can be specified with the **`CURLOPT_CAPATH`** option. When set to false, the peer certificate verification succeeds regardless. | **`true`** by default. Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_SAFE_UPLOAD`** | Always **`true`**, what disables support for the `@` prefix for uploading files in **`CURLOPT_POSTFIELDS`**, which means that values starting with `@` can be safely passed as fields. [CURLFile](class.curlfile) may be used for uploads instead. | | | **`CURLOPT_SUPPRESS_CONNECT_HEADERS`** | **`true`** to suppress proxy CONNECT response headers from the user callback functions **`CURLOPT_HEADERFUNCTION`** and **`CURLOPT_WRITEFUNCTION`**, when **`CURLOPT_HTTPPROXYTUNNEL`** is used and a CONNECT request is made. | Added in cURL 7.54.0. Available since PHP 7.3.0. | | **`CURLOPT_TCP_FASTOPEN`** | **`true`** to enable TCP Fast Open. | Added in cURL 7.49.0. Available since PHP 7.0.7. | | **`CURLOPT_TFTP_NO_OPTIONS`** | **`true`** to not send TFTP options requests. | Added in cURL 7.48.0. Available since PHP 7.0.7. | | **`CURLOPT_TRANSFERTEXT`** | **`true`** to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set `STDOUT` to binary mode. | | | **`CURLOPT_UNRESTRICTED_AUTH`** | **`true`** to keep sending the username and password when following locations (using **`CURLOPT_FOLLOWLOCATION`**), even when the hostname has changed. | | | **`CURLOPT_UPLOAD`** | **`true`** to prepare for an upload. | | | **`CURLOPT_VERBOSE`** | **`true`** to output verbose information. Writes output to `STDERR`, or the file specified using **`CURLOPT_STDERR`**. | | `value` should be an int for the following values of the `option` parameter: | Option | Set `value` to | Notes | | --- | --- | --- | | **`CURLOPT_BUFFERSIZE`** | The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. | Added in cURL 7.10. | | **`CURLOPT_CONNECTTIMEOUT`** | The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. | | | **`CURLOPT_CONNECTTIMEOUT_MS`** | The number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. | | **`CURLOPT_DNS_CACHE_TIMEOUT`** | The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default. | | | **`CURLOPT_EXPECT_100_TIMEOUT_MS`** | The timeout for Expect: 100-continue responses in milliseconds. Defaults to 1000 milliseconds. | Added in cURL 7.36.0. Available since PHP 7.0.7. | | **`CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS`** | Head start for ipv6 for the happy eyeballs algorithm. Happy eyeballs attempts to connect to both IPv4 and IPv6 addresses for dual-stack hosts, preferring IPv6 first for timeout milliseconds. Defaults to CURL\_HET\_DEFAULT, which is currently 200 milliseconds. | Added in cURL 7.59.0. Available since PHP 7.3.0. | | **`CURLOPT_FTPSSLAUTH`** | The FTP authentication method (when is activated): `CURLFTPAUTH_SSL` (try SSL first), `CURLFTPAUTH_TLS` (try TLS first), or `CURLFTPAUTH_DEFAULT` (let cURL decide). | Added in cURL 7.12.2. | | **`CURLOPT_HEADEROPT`** | How to deal with headers. One of the following constants: **`CURLHEADER_UNIFIED`**: the headers specified in **`CURLOPT_HTTPHEADER`** will be used in requests both to servers and proxies. With this option enabled, **`CURLOPT_PROXYHEADER`** will not have any effect. **`CURLHEADER_SEPARATE`**: makes **`CURLOPT_HTTPHEADER`** headers only get sent to a server and not to a proxy. Proxy headers must be set with **`CURLOPT_PROXYHEADER`** to get used. Note that if a non-CONNECT request is sent to a proxy, libcurl will send both server headers and proxy headers. When doing CONNECT, libcurl will send **`CURLOPT_PROXYHEADER`** headers only to the proxy and then **`CURLOPT_HTTPHEADER`** headers only to the server. Defaults to **`CURLHEADER_SEPARATE`** as of cURL 7.42.1, and **`CURLHEADER_UNIFIED`** before. | Added in cURL 7.37.0. Available since PHP 7.0.7. | | **`CURLOPT_HTTP_VERSION`** | **`CURL_HTTP_VERSION_NONE`** (default, lets CURL decide which version to use), **`CURL_HTTP_VERSION_1_0`** (forces HTTP/1.0), **`CURL_HTTP_VERSION_1_1`** (forces HTTP/1.1), **`CURL_HTTP_VERSION_2_0`** (attempts HTTP 2), **`CURL_HTTP_VERSION_2`** (alias of **`CURL_HTTP_VERSION_2_0`**), **`CURL_HTTP_VERSION_2TLS`** (attempts HTTP 2 over TLS (HTTPS) only) or **`CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE`** (issues non-TLS HTTP requests using HTTP/2 without HTTP/1.1 Upgrade). | | | **`CURLOPT_HTTPAUTH`** | The HTTP authentication method(s) to use. The options are: **`CURLAUTH_BASIC`**, **`CURLAUTH_DIGEST`**, **`CURLAUTH_GSSNEGOTIATE`**, **`CURLAUTH_NTLM`**, **`CURLAUTH_ANY`**, and **`CURLAUTH_ANYSAFE`**. The bitwise `|` (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one. **`CURLAUTH_ANY`** is an alias for `CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM`. **`CURLAUTH_ANYSAFE`** is an alias for `CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM`. | | | **`CURLOPT_INFILESIZE`** | The expected size, in bytes, of the file when uploading a file to a remote site. Note that using this option will not stop libcurl from sending more data, as exactly what is sent depends on **`CURLOPT_READFUNCTION`**. | | | **`CURLOPT_LOW_SPEED_LIMIT`** | The transfer speed, in bytes per second, that the transfer should be below during the count of **`CURLOPT_LOW_SPEED_TIME`** seconds before PHP considers the transfer too slow and aborts. | | | **`CURLOPT_LOW_SPEED_TIME`** | The number of seconds the transfer speed should be below **`CURLOPT_LOW_SPEED_LIMIT`** before PHP considers the transfer too slow and aborts. | | | **`CURLOPT_MAXCONNECTS`** | The maximum amount of persistent connections that are allowed. When the limit is reached, the oldest one in the cache is closed to prevent increasing the number of open connections. | | | **`CURLOPT_MAXREDIRS`** | The maximum amount of HTTP redirections to follow. Use this option alongside **`CURLOPT_FOLLOWLOCATION`**. Default value of `20` is set to prevent infinite redirects. Setting to `-1` allows inifinite redirects, and `0` refuses all redirects. | | | **`CURLOPT_PORT`** | An alternative port number to connect to. | | | **`CURLOPT_POSTREDIR`** | A bitmask of 1 (301 Moved Permanently), 2 (302 Found) and 4 (303 See Other) if the HTTP POST method should be maintained when **`CURLOPT_FOLLOWLOCATION`** is set and a specific type of redirect occurs. | Added in cURL 7.19.1. | | **`CURLOPT_PROTOCOLS`** | Bitmask of **`CURLPROTO_*`** values. If used, this bitmask limits what protocols libcurl may use in the transfer. This allows you to have a libcurl built to support a wide range of protocols but still limit specific transfers to only be allowed to use a subset of them. By default libcurl will accept all protocols it supports. See also **`CURLOPT_REDIR_PROTOCOLS`**. Valid protocol options are: **`CURLPROTO_HTTP`**, **`CURLPROTO_HTTPS`**, **`CURLPROTO_FTP`**, **`CURLPROTO_FTPS`**, **`CURLPROTO_SCP`**, **`CURLPROTO_SFTP`**, **`CURLPROTO_TELNET`**, **`CURLPROTO_LDAP`**, **`CURLPROTO_LDAPS`**, **`CURLPROTO_DICT`**, **`CURLPROTO_FILE`**, **`CURLPROTO_TFTP`**, **`CURLPROTO_ALL`** | Added in cURL 7.19.4. | | **`CURLOPT_PROXYAUTH`** | The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in **`CURLOPT_HTTPAUTH`**. For proxy authentication, only **`CURLAUTH_BASIC`** and **`CURLAUTH_NTLM`** are currently supported. | Added in cURL 7.10.7. | | **`CURLOPT_PROXYPORT`** | The port number of the proxy to connect to. This port number can also be set in **`CURLOPT_PROXY`**. | | | **`CURLOPT_PROXYTYPE`** | Either **`CURLPROXY_HTTP`** (default), **`CURLPROXY_SOCKS4`**, **`CURLPROXY_SOCKS5`**, **`CURLPROXY_SOCKS4A`** or **`CURLPROXY_SOCKS5_HOSTNAME`**. | Added in cURL 7.10. | | **`CURLOPT_REDIR_PROTOCOLS`** | Bitmask of **`CURLPROTO_*`** values. If used, this bitmask limits what protocols libcurl may use in a transfer that it follows to in a redirect when **`CURLOPT_FOLLOWLOCATION`** is enabled. This allows you to limit specific transfers to only be allowed to use a subset of protocols in redirections. By default libcurl will allow all protocols except for FILE and SCP. This is a difference compared to pre-7.19.4 versions which unconditionally would follow to all protocols supported. See also **`CURLOPT_PROTOCOLS`** for protocol constant values. | Added in cURL 7.19.4. | | **`CURLOPT_RESUME_FROM`** | The offset, in bytes, to resume a transfer from. | | | **`CURLOPT_SOCKS5_AUTH`** | The SOCKS5 authentication method(s) to use. The options are: **`CURLAUTH_BASIC`**, **`CURLAUTH_GSSAPI`**, **`CURLAUTH_NONE`**. The bitwise `|` (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one. **`CURLAUTH_BASIC`** allows username/password authentication. **`CURLAUTH_GSSAPI`** allows GSS-API authentication. **`CURLAUTH_NONE`** allows no authentication. Defaults to `CURLAUTH_BASIC|CURLAUTH_GSSAPI`. Set the actual username and password with the **`CURLOPT_PROXYUSERPWD`** option. | Available as of 7.3.0 and curl >= 7.55.0. | | **`CURLOPT_SSL_OPTIONS`** | Set SSL behavior options, which is a bitmask of any of the following constants: **`CURLSSLOPT_ALLOW_BEAST`**: do not attempt to use any workarounds for a security flaw in the SSL3 and TLS1.0 protocols. **`CURLSSLOPT_NO_REVOKE`**: disable certificate revocation checks for those SSL backends where such behavior is present. | Added in cURL 7.25.0. Available since PHP 7.0.7. | | **`CURLOPT_SSL_VERIFYHOST`** | `2` to verify that a Common Name field or a Subject Alternate Name field in the SSL peer certificate matches the provided hostname. `0` to not check the names. `1` should not be used. In production environments the value of this option should be kept at `2` (default value). | Support for value `1` removed in cURL 7.28.1. | | **`CURLOPT_SSLVERSION`** | One of **`CURL_SSLVERSION_DEFAULT`** (0), **`CURL_SSLVERSION_TLSv1`** (1), **`CURL_SSLVERSION_SSLv2`** (2), **`CURL_SSLVERSION_SSLv3`** (3), **`CURL_SSLVERSION_TLSv1_0`** (4), **`CURL_SSLVERSION_TLSv1_1`** (5) or **`CURL_SSLVERSION_TLSv1_2`** (6). The maximum TLS version can be set by using one of the **`CURL_SSLVERSION_MAX_*`** constants. It is also possible to OR one of the **`CURL_SSLVERSION_*`** constants with one of the **`CURL_SSLVERSION_MAX_*`** constants. **`CURL_SSLVERSION_MAX_DEFAULT`** (the maximum version supported by the library), **`CURL_SSLVERSION_MAX_TLSv1_0`**, **`CURL_SSLVERSION_MAX_TLSv1_1`**, **`CURL_SSLVERSION_MAX_TLSv1_2`**, or **`CURL_SSLVERSION_MAX_TLSv1_3`**. **Note**: Your best bet is to not set this and let it use the default. Setting it to 2 or 3 is very dangerous given the known vulnerabilities in SSLv2 and SSLv3. | | | **`CURLOPT_PROXY_SSL_OPTIONS`** | Set proxy SSL behavior options, which is a bitmask of any of the following constants: **`CURLSSLOPT_ALLOW_BEAST`**: do not attempt to use any workarounds for a security flaw in the SSL3 and TLS1.0 protocols. **`CURLSSLOPT_NO_REVOKE`**: disable certificate revocation checks for those SSL backends where such behavior is present. (curl >= 7.44.0) **`CURLSSLOPT_NO_PARTIALCHAIN`**: do not accept "partial" certificate chains, which it otherwise does by default. (curl >= 7.68.0) | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_SSL_VERIFYHOST`** | Set to `2` to verify in the HTTPS proxy's certificate name fields against the proxy name. When set to `0` the connection succeeds regardless of the names used in the certificate. Use that ability with caution! `1` treated as a debug option in curl 7.28.0 and earlier. From curl 7.28.1 to 7.65.3 **`CURLE_BAD_FUNCTION_ARGUMENT`** is returned. From curl 7.66.0 onwards `1` and `2` is treated as the same value. In production environments the value of this option should be kept at `2` (default value). | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_SSLVERSION`** | One of **`CURL_SSLVERSION_DEFAULT`**, **`CURL_SSLVERSION_TLSv1`**, **`CURL_SSLVERSION_TLSv1_0`**, **`CURL_SSLVERSION_TLSv1_1`**, **`CURL_SSLVERSION_TLSv1_2`**, **`CURL_SSLVERSION_TLSv1_3`**, **`CURL_SSLVERSION_MAX_DEFAULT`**, **`CURL_SSLVERSION_MAX_TLSv1_0`**, **`CURL_SSLVERSION_MAX_TLSv1_1`**, **`CURL_SSLVERSION_MAX_TLSv1_2`**, **`CURL_SSLVERSION_MAX_TLSv1_3`** or **`CURL_SSLVERSION_SSLv3`**. **Note**: Your best bet is to not set this and let it use the default **`CURL_SSLVERSION_DEFAULT`** which will attempt to figure out the remote SSL protocol version. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_STREAM_WEIGHT`** | Set the numerical stream weight (a number between 1 and 256). | Added in cURL 7.46.0. Available since PHP 7.0.7. | | **`CURLOPT_TCP_KEEPALIVE`** | If set to `1`, TCP keepalive probes will be sent. The delay and frequency of these probes can be controlled by the **`CURLOPT_TCP_KEEPIDLE`** and **`CURLOPT_TCP_KEEPINTVL`** options, provided the operating system supports them. If set to `0` (default) keepalive probes are disabled. | Added in cURL 7.25.0. | | **`CURLOPT_TCP_KEEPIDLE`** | Sets the delay, in seconds, that the operating system will wait while the connection is idle before sending keepalive probes, if **`CURLOPT_TCP_KEEPALIVE`** is enabled. Not all operating systems support this option. The default is `60`. | Added in cURL 7.25.0. | | **`CURLOPT_TCP_KEEPINTVL`** | Sets the interval, in seconds, that the operating system will wait between sending keepalive probes, if **`CURLOPT_TCP_KEEPALIVE`** is enabled. Not all operating systems support this option. The default is `60`. | Added in cURL 7.25.0. | | **`CURLOPT_TIMECONDITION`** | How **`CURLOPT_TIMEVALUE`** is treated. Use **`CURL_TIMECOND_IFMODSINCE`** to return the page only if it has been modified since the time specified in **`CURLOPT_TIMEVALUE`**. If it hasn't been modified, a `"304 Not Modified"` header will be returned assuming **`CURLOPT_HEADER`** is **`true`**. Use **`CURL_TIMECOND_IFUNMODSINCE`** for the reverse effect. Use **`CURL_TIMECOND_NONE`** to ignore **`CURLOPT_TIMEVALUE`** and always return the page. **`CURL_TIMECOND_NONE`** is the default. | Before cURL 7.46.0 the default was **`CURL_TIMECOND_IFMODSINCE`**. | | **`CURLOPT_TIMEOUT`** | The maximum number of seconds to allow cURL functions to execute. | | | **`CURLOPT_TIMEOUT_MS`** | The maximum number of milliseconds to allow cURL functions to execute. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. | | **`CURLOPT_TIMEVALUE`** | The time in seconds since January 1st, 1970. The time will be used by **`CURLOPT_TIMECONDITION`**. | | | **`CURLOPT_TIMEVALUE_LARGE`** | The time in seconds since January 1st, 1970. The time will be used by **`CURLOPT_TIMECONDITION`**. Defaults to zero. The difference between this option and **`CURLOPT_TIMEVALUE`** is the type of the argument. On systems where 'long' is only 32 bit wide, this option has to be used to set dates beyond the year 2038. | Added in cURL 7.59.0. Available since PHP 7.3.0. | | **`CURLOPT_MAX_RECV_SPEED_LARGE`** | If a download exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. | | **`CURLOPT_MAX_SEND_SPEED_LARGE`** | If an upload exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. | | **`CURLOPT_SSH_AUTH_TYPES`** | A bitmask consisting of one or more of **`CURLSSH_AUTH_PUBLICKEY`**, **`CURLSSH_AUTH_PASSWORD`**, **`CURLSSH_AUTH_HOST`**, **`CURLSSH_AUTH_KEYBOARD`**. Set to **`CURLSSH_AUTH_ANY`** to let libcurl pick one. | Added in cURL 7.16.1. | | **`CURLOPT_IPRESOLVE`** | Allows an application to select what kind of IP addresses to use when resolving host names. This is only interesting when using host names that resolve addresses using more than one version of IP, possible values are **`CURL_IPRESOLVE_WHATEVER`**, **`CURL_IPRESOLVE_V4`**, **`CURL_IPRESOLVE_V6`**, by default **`CURL_IPRESOLVE_WHATEVER`**. | Added in cURL 7.10.8. | | **`CURLOPT_FTP_FILEMETHOD`** | Tell curl which method to use to reach a file on a FTP(S) server. Possible values are **`CURLFTPMETHOD_MULTICWD`**, **`CURLFTPMETHOD_NOCWD`** and **`CURLFTPMETHOD_SINGLECWD`**. | Added in cURL 7.15.1. | `value` should be a string for the following values of the `option` parameter: | Option | Set `value` to | Notes | | --- | --- | --- | | **`CURLOPT_ABSTRACT_UNIX_SOCKET`** | Enables the use of an abstract Unix domain socket instead of establishing a TCP connection to a host and sets the path to the given string. This option shares the same semantics as **`CURLOPT_UNIX_SOCKET_PATH`**. These two options share the same storage and therefore only one of them can be set per handle. | Available since PHP 7.3.0 and cURL 7.53.0 | | **`CURLOPT_CAINFO`** | The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with **`CURLOPT_SSL_VERIFYPEER`**. | Might require an absolute path. | | **`CURLOPT_CAPATH`** | A directory that holds multiple CA certificates. Use this option alongside **`CURLOPT_SSL_VERIFYPEER`**. | | | **`CURLOPT_COOKIE`** | The contents of the `"Cookie: "` header to be used in the HTTP request. Note that multiple cookies are separated with a semicolon followed by a space (e.g., "`fruit=apple; colour=red`") | | | **`CURLOPT_COOKIEFILE`** | The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled. | | | **`CURLOPT_COOKIEJAR`** | The name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curl\_close. | | | **`CURLOPT_COOKIELIST`** | A cookie string (i.e. a single line in Netscape/Mozilla format, or a regular HTTP-style Set-Cookie header) adds that single cookie to the internal cookie store. `"ALL"` erases all cookies held in memory. `"SESS"` erases all session cookies held in memory. `"FLUSH"` writes all known cookies to the file specified by **`CURLOPT_COOKIEJAR`**. `"RELOAD"` loads all cookies from the files specified by **`CURLOPT_COOKIEFILE`**. | Available since cURL 7.14.1. | | **`CURLOPT_CUSTOMREQUEST`** | A custom request method to use instead of `"GET"` or `"HEAD"` when doing a HTTP request. This is useful for doing `"DELETE"` or other, more obscure HTTP requests. Valid values are things like `"GET"`, `"POST"`, `"CONNECT"` and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering `"GET /index.html HTTP/1.0\r\n\r\n"` would be incorrect. **Note**: Don't do this without making sure the server supports the custom request method first. | | | **`CURLOPT_DEFAULT_PROTOCOL`** | The default protocol to use if the URL is missing a scheme name. | Added in cURL 7.45.0. Available since PHP 7.0.7. | | **`CURLOPT_DNS_INTERFACE`** | Set the name of the network interface that the DNS resolver should bind to. This must be an interface name (not an address). | Added in cURL 7.33.0. Available since PHP 7.0.7. | | **`CURLOPT_DNS_LOCAL_IP4`** | Set the local IPv4 address that the resolver should bind to. The argument should contain a single numerical IPv4 address as a string. | Added in cURL 7.33.0. Available since PHP 7.0.7. | | **`CURLOPT_DNS_LOCAL_IP6`** | Set the local IPv6 address that the resolver should bind to. The argument should contain a single numerical IPv6 address as a string. | Added in cURL 7.33.0. Available since PHP 7.0.7. | | **`CURLOPT_EGDSOCKET`** | Like **`CURLOPT_RANDOM_FILE`**, except a filename to an Entropy Gathering Daemon socket. | | | **`CURLOPT_ENCODING`** | The contents of the `"Accept-Encoding: "` header. This enables decoding of the response. Supported encodings are `"identity"`, `"deflate"`, and `"gzip"`. If an empty string, `""`, is set, a header containing all supported encoding types is sent. | Added in cURL 7.10. | | **`CURLOPT_FTPPORT`** | The value which will be used to get the IP address to use for the FTP "PORT" instruction. The "PORT" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address. | | | **`CURLOPT_INTERFACE`** | The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name. | | | **`CURLOPT_KEYPASSWD`** | The password required to use the **`CURLOPT_SSLKEY`** or **`CURLOPT_SSH_PRIVATE_KEYFILE`** private key. | Added in cURL 7.16.1. | | **`CURLOPT_KRB4LEVEL`** | The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: `"clear"`, `"safe"`, `"confidential"`, `"private".`. If the string does not match one of these, `"private"` is used. Setting this option to **`null`** will disable KRB4 security. Currently KRB4 security only works with FTP transactions. | | | **`CURLOPT_LOGIN_OPTIONS`** | Can be used to set protocol specific login options, such as the preferred authentication mechanism via "AUTH=NTLM" or "AUTH=\*", and should be used in conjunction with the **`CURLOPT_USERNAME`** option. | Added in cURL 7.34.0. Available since PHP 7.0.7. | | **`CURLOPT_PINNEDPUBLICKEY`** | Set the pinned public key. The string can be the file name of your pinned public key. The file format expected is "PEM" or "DER". The string can also be any number of base64 encoded sha256 hashes preceded by "sha256//" and separated by ";". | Added in cURL 7.39.0. Available since PHP 7.0.7. | | **`CURLOPT_POSTFIELDS`** | The full data to post in a HTTP "POST" operation. This parameter can either be passed as a urlencoded string like '`para1=val1&para2=val2&...`' or as an array with the field name as key and field data as value. If `value` is an array, the `Content-Type` header will be set to `multipart/form-data`. Files can be sent using [CURLFile](class.curlfile) or [CURLStringFile](class.curlstringfile), in which case `value` must be an array. | | | **`CURLOPT_PRIVATE`** | Any data that should be associated with this cURL handle. This data can subsequently be retrieved with the **`CURLINFO_PRIVATE`** option of [curl\_getinfo()](function.curl-getinfo). cURL does nothing with this data. When using a cURL multi handle, this private data is typically a unique key to identify a standard cURL handle. | Added in cURL 7.10.3. | | **`CURLOPT_PRE_PROXY`** | Set a string holding the host name or dotted numerical IP address to be used as the preproxy that curl connects to before it connects to the HTTP(S) proxy specified in the **`CURLOPT_PROXY`** option for the upcoming request. The preproxy can only be a SOCKS proxy and it should be prefixed with `[scheme]://` to specify which kind of socks is used. A numerical IPv6 address must be written within [brackets]. Setting the preproxy to an empty string explicitly disables the use of a preproxy. To specify port number in this string, append `:[port]` to the end of the host name. The proxy's port number may optionally be specified with the separate option **`CURLOPT_PROXYPORT`**. Defaults to using port 1080 for proxies if a port is not specified. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY`** | The HTTP proxy to tunnel requests through. | | | **`CURLOPT_PROXY_SERVICE_NAME`** | The proxy authentication service name. | Added in cURL 7.43.0 for HTTP proxies, and in cURL 7.49.0 for SOCKS5 proxies. Available since PHP 7.0.7. | | **`CURLOPT_PROXY_CAINFO`** | The path to proxy Certificate Authority (CA) bundle. Set the path as a string naming a file holding one or more certificates to verify the HTTPS proxy with. This option is for connecting to an HTTPS proxy, not an HTTPS server. Defaults set to the system path where libcurl's cacert bundle is assumed to be stored. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_CAPATH`** | The directory holding multiple CA certificates to verify the HTTPS proxy with. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_CRLFILE`** | Set the file name with the concatenation of CRL (Certificate Revocation List) in PEM format to use in the certificate validation that occurs during the SSL exchange. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_KEYPASSWD`** | Set the string be used as the password required to use the **`CURLOPT_PROXY_SSLKEY`** private key. You never needed a passphrase to load a certificate but you need one to load your private key. This option is for connecting to an HTTPS proxy, not an HTTPS server. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_PINNEDPUBLICKEY`** | Set the pinned public key for HTTPS proxy. The string can be the file name of your pinned public key. The file format expected is "PEM" or "DER". The string can also be any number of base64 encoded sha256 hashes preceded by "sha256//" and separated by ";" | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_SSLCERT`** | The file name of your client certificate used to connect to the HTTPS proxy. The default format is "P12" on Secure Transport and "PEM" on other engines, and can be changed with **`CURLOPT_PROXY_SSLCERTTYPE`**. With NSS or Secure Transport, this can also be the nickname of the certificate you wish to authenticate with as it is named in the security database. If you want to use a file from the current directory, please precede it with "./" prefix, in order to avoid confusion with a nickname. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_SSLCERTTYPE`** | The format of your client certificate used when connecting to an HTTPS proxy. Supported formats are "PEM" and "DER", except with Secure Transport. OpenSSL (versions 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7 or later) also support "P12" for PKCS#12-encoded files. Defaults to "PEM". | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_SSL_CIPHER_LIST`** | The list of ciphers to use for the connection to the HTTPS proxy. The list must be syntactically correct, it consists of one or more cipher strings separated by colons. Commas or spaces are also acceptable separators but colons are normally used, !, - and + can be used as operators. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_TLS13_CIPHERS`** | The list of cipher suites to use for the TLS 1.3 connection to a proxy. The list must be syntactically correct, it consists of one or more cipher suite strings separated by colons. This option is currently used only when curl is built to use OpenSSL 1.1.1 or later. If you are using a different SSL backend you can try setting TLS 1.3 cipher suites by using the **`CURLOPT_PROXY_SSL_CIPHER_LIST`** option. | Available since PHP 7.3.0 and libcurl >= cURL 7.61.0. Available when built with OpenSSL >= 1.1.1. | | **`CURLOPT_PROXY_SSLKEY`** | The file name of your private key used for connecting to the HTTPS proxy. The default format is "PEM" and can be changed with **`CURLOPT_PROXY_SSLKEYTYPE`**. (iOS and Mac OS X only) This option is ignored if curl was built against Secure Transport. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. Available if built TLS enabled. | | **`CURLOPT_PROXY_SSLKEYTYPE`** | The format of your private key. Supported formats are "PEM", "DER" and "ENG". | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_TLSAUTH_PASSWORD`** | The password to use for the TLS authentication method specified with the **`CURLOPT_PROXY_TLSAUTH_TYPE`** option. Requires that the **`CURLOPT_PROXY_TLSAUTH_USERNAME`** option to also be set. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_TLSAUTH_TYPE`** | The method of the TLS authentication used for the HTTPS connection. Supported method is "SRP". **Note**: Secure Remote Password (SRP) authentication for TLS provides mutual authentication if both sides have a shared secret. To use TLS-SRP, you must also set the **`CURLOPT_PROXY_TLSAUTH_USERNAME`** and **`CURLOPT_PROXY_TLSAUTH_PASSWORD`** options. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXY_TLSAUTH_USERNAME`** | The username to use for the HTTPS proxy TLS authentication method specified with the **`CURLOPT_PROXY_TLSAUTH_TYPE`** option. Requires that the **`CURLOPT_PROXY_TLSAUTH_PASSWORD`** option to also be set. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. | | **`CURLOPT_PROXYUSERPWD`** | A username and password formatted as `"[username]:[password]"` to use for the connection to the proxy. | | | **`CURLOPT_RANDOM_FILE`** | A filename to be used to seed the random number generator for SSL. | | | **`CURLOPT_RANGE`** | Range(s) of data to retrieve in the format `"X-Y"` where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format `"X-Y,N-M"`. | | | **`CURLOPT_REFERER`** | The contents of the `"Referer: "` header to be used in a HTTP request. | | | **`CURLOPT_SERVICE_NAME`** | The authentication service name. | Added in cURL 7.43.0. Available since PHP 7.0.7. | | **`CURLOPT_SSH_HOST_PUBLIC_KEY_MD5`** | A string containing 32 hexadecimal digits. The string should be the MD5 checksum of the remote host's public key, and libcurl will reject the connection to the host unless the md5sums match. This option is only for SCP and SFTP transfers. | Added in cURL 7.17.1. | | **`CURLOPT_SSH_PUBLIC_KEYFILE`** | The file name for your public key. If not used, libcurl defaults to $HOME/.ssh/id\_dsa.pub if the HOME environment variable is set, and just "id\_dsa.pub" in the current directory if HOME is not set. | Added in cURL 7.16.1. | | **`CURLOPT_SSH_PRIVATE_KEYFILE`** | The file name for your private key. If not used, libcurl defaults to $HOME/.ssh/id\_dsa if the HOME environment variable is set, and just "id\_dsa" in the current directory if HOME is not set. If the file is password-protected, set the password with **`CURLOPT_KEYPASSWD`**. | Added in cURL 7.16.1. | | **`CURLOPT_SSL_CIPHER_LIST`** | A list of ciphers to use for SSL. For example, `RC4-SHA` and `TLSv1` are valid cipher lists. | | | **`CURLOPT_SSLCERT`** | The name of a file containing a PEM formatted certificate. | | | **`CURLOPT_SSLCERTPASSWD`** | The password required to use the **`CURLOPT_SSLCERT`** certificate. | | | **`CURLOPT_SSLCERTTYPE`** | The format of the certificate. Supported formats are `"PEM"` (default), `"DER"`, and `"ENG"`. As of OpenSSL 0.9.3, `"P12"` (for PKCS#12-encoded files) is also supported. | Added in cURL 7.9.3. | | **`CURLOPT_SSLENGINE`** | The identifier for the crypto engine of the private SSL key specified in **`CURLOPT_SSLKEY`**. | | | **`CURLOPT_SSLENGINE_DEFAULT`** | The identifier for the crypto engine used for asymmetric crypto operations. | | | **`CURLOPT_SSLKEY`** | The name of a file containing a private SSL key. | | | **`CURLOPT_SSLKEYPASSWD`** | The secret password needed to use the private SSL key specified in **`CURLOPT_SSLKEY`**. **Note**: Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe. | | | **`CURLOPT_SSLKEYTYPE`** | The key type of the private SSL key specified in **`CURLOPT_SSLKEY`**. Supported key types are `"PEM"` (default), `"DER"`, and `"ENG"`. | | | **`CURLOPT_TLS13_CIPHERS`** | The list of cipher suites to use for the TLS 1.3 connection. The list must be syntactically correct, it consists of one or more cipher suite strings separated by colons. This option is currently used only when curl is built to use OpenSSL 1.1.1 or later. If you are using a different SSL backend you can try setting TLS 1.3 cipher suites by using the **`CURLOPT_SSL_CIPHER_LIST`** option. | Available since PHP 7.3.0 and libcurl >= cURL 7.61.0. Available when built with OpenSSL >= 1.1.1. | | **`CURLOPT_UNIX_SOCKET_PATH`** | Enables the use of Unix domain sockets as connection endpoint and sets the path to the given string. | Added in cURL 7.40.0. Available since PHP 7.0.7. | | **`CURLOPT_URL`** | The URL to fetch. This can also be set when initializing a session with [curl\_init()](function.curl-init). | | | **`CURLOPT_USERAGENT`** | The contents of the `"User-Agent: "` header to be used in a HTTP request. | | | **`CURLOPT_USERNAME`** | The user name to use in authentication. | Added in cURL 7.19.1. | | **`CURLOPT_PASSWORD`** | The password to use in authentication. | Added in cURL 7.19.1. | | **`CURLOPT_USERPWD`** | A username and password formatted as `"[username]:[password]"` to use for the connection. | | | **`CURLOPT_XOAUTH2_BEARER`** | Specifies the OAuth 2.0 access token. | Added in cURL 7.33.0. Available since PHP 7.0.7. | `value` should be an array for the following values of the `option` parameter: | Option | Set `value` to | Notes | | --- | --- | --- | | **`CURLOPT_CONNECT_TO`** | Connect to a specific host and port instead of the URL's host and port. Accepts an array of strings with the format `HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT`. | Added in cURL 7.49.0. Available since PHP 7.0.7. | | **`CURLOPT_HTTP200ALIASES`** | An array of HTTP 200 responses that will be treated as valid responses and not as errors. | Added in cURL 7.10.3. | | **`CURLOPT_HTTPHEADER`** | An array of HTTP header fields to set, in the format `array('Content-type: text/plain', 'Content-length: 100')` | | | **`CURLOPT_POSTQUOTE`** | An array of FTP commands to execute on the server after the FTP request has been performed. | | | **`CURLOPT_PROXYHEADER`** | An array of custom HTTP headers to pass to proxies. | Added in cURL 7.37.0. Available since PHP 7.0.7. | | **`CURLOPT_QUOTE`** | An array of FTP commands to execute on the server prior to the FTP request. | | | **`CURLOPT_RESOLVE`** | Provide a custom address for a specific host and port pair. An array of hostname, port, and IP address strings, each element separated by a colon. In the format: `array("example.com:80:127.0.0.1")` | Added in cURL 7.21.3. | `value` should be a stream resource (using [fopen()](function.fopen), for example) for the following values of the `option` parameter: | Option | Set `value` to | | --- | --- | | **`CURLOPT_FILE`** | The file that the transfer should be written to. The default is `STDOUT` (the browser window). | | **`CURLOPT_INFILE`** | The file that the transfer should be read from when uploading. | | **`CURLOPT_STDERR`** | An alternative location to output errors to instead of `STDERR`. | | **`CURLOPT_WRITEHEADER`** | The file that the header part of the transfer is written to. | `value` should be the name of a valid function or a Closure for the following values of the `option` parameter: | Option | Set `value` to | Notes | | --- | --- | --- | | **`CURLOPT_HEADERFUNCTION`** | A callback accepting two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written by this callback. Return the number of bytes written. | | | **`CURLOPT_PASSWDFUNCTION`** | A callback accepting three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password. | Removed as of PHP 7.3.0. | | **`CURLOPT_PROGRESSFUNCTION`** | A callback accepting five parameters. The first is the cURL resource, the second is the total number of bytes expected to be downloaded in this transfer, the third is the number of bytes downloaded so far, the fourth is the total number of bytes expected to be uploaded in this transfer, and the fifth is the number of bytes uploaded so far. **Note**: The callback is only called when the **`CURLOPT_NOPROGRESS`** option is set to **`false`**. Return a non-zero value to abort the transfer. In which case, the transfer will set a **`CURLE_ABORTED_BY_CALLBACK`** error. | | | **`CURLOPT_READFUNCTION`** | A callback accepting three parameters. The first is the cURL resource, the second is a stream resource provided to cURL through the option **`CURLOPT_INFILE`**, and the third is the maximum amount of data to be read. The callback must return a string with a length equal or smaller than the amount of data requested, typically by reading it from the passed stream resource. It should return an empty string to signal `EOF`. | | | **`CURLOPT_WRITEFUNCTION`** | A callback accepting two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be saved by this callback. It must return the exact number of bytes written or the transfer will be aborted with an error. | | | **`CURLOPT_XFERINFOFUNCTION`** | A callback accepting two parameters. Has a similar purpose as **`CURLOPT_PROGRESSFUNCTION`** but is more modern and the preferred option from cURL. | Added in 7.32.0. Available as of PHP 8.2.0. | Other values: | Option | Set `value` to | | --- | --- | | **`CURLOPT_SHARE`** | A result of [curl\_share\_init()](function.curl-share-init). Makes the cURL handle to use the data from the shared handle. | ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `handle` expects a [CurlHandle](class.curlhandle) instance now; previously, a resource was expected. | | 7.3.15, 7.4.3 | Introduced **`CURLOPT_HTTP09_ALLOWED`** . | | 7.3.0 | Introduced **`CURLOPT_ABSTRACT_UNIX_SOCKET`**, **`CURLOPT_KEEP_SENDING_ON_ERROR`**, **`CURLOPT_PRE_PROXY`**, **`CURLOPT_PROXY_CAINFO`**, **`CURLOPT_PROXY_CAPATH`**, **`CURLOPT_PROXY_CRLFILE`**, **`CURLOPT_PROXY_KEYPASSWD`**, **`CURLOPT_PROXY_PINNEDPUBLICKEY`**, **`CURLOPT_PROXY_SSLCERT`**, **`CURLOPT_PROXY_SSLCERTTYPE`**, **`CURLOPT_PROXY_SSL_CIPHER_LIST`**, **`CURLOPT_PROXY_SSLKEY`**, **`CURLOPT_PROXY_SSLKEYTYPE`**, **`CURLOPT_PROXY_SSL_OPTIONS`**, **`CURLOPT_PROXY_SSL_VERIFYHOST`**, **`CURLOPT_PROXY_SSL_VERIFYPEER`**, **`CURLOPT_PROXY_SSLVERSION`**, **`CURLOPT_PROXY_TLSAUTH_PASSWORD`**, **`CURLOPT_PROXY_TLSAUTH_TYPE`**, **`CURLOPT_PROXY_TLSAUTH_USERNAME`**, **`CURLOPT_SOCKS5_AUTH`**, **`CURLOPT_SUPPRESS_CONNECT_HEADERS`**, **`CURLOPT_DISALLOW_USERNAME_IN_URL`**, **`CURLOPT_DNS_SHUFFLE_ADDRESSES`**, **`CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS`**, **`CURLOPT_HAPROXYPROTOCOL`**, **`CURLOPT_PROXY_TLS13_CIPHERS`**, **`CURLOPT_SSH_COMPRESSION`**, **`CURLOPT_TIMEVALUE_LARGE`** and **`CURLOPT_TLS13_CIPHERS`**. | | 7.0.7 | Introduced **`CURL_HTTP_VERSION_2`**, **`CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE`**, **`CURL_HTTP_VERSION_2TLS`**, **`CURL_REDIR_POST_301`**, **`CURL_REDIR_POST_302`**, **`CURL_REDIR_POST_303`**, **`CURL_REDIR_POST_ALL`**, **`CURL_VERSION_KERBEROS5`**, **`CURL_VERSION_PSL`**, **`CURL_VERSION_UNIX_SOCKETS`**, **`CURLAUTH_NEGOTIATE`**, **`CURLAUTH_NTLM_WB`**, **`CURLFTP_CREATE_DIR`**, **`CURLFTP_CREATE_DIR_NONE`**, **`CURLFTP_CREATE_DIR_RETRY`**, **`CURLHEADER_SEPARATE`**, **`CURLHEADER_UNIFIED`**, **`CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE`**, **`CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE`**, **`CURLMOPT_MAX_HOST_CONNECTIONS`**, **`CURLMOPT_MAX_PIPELINE_LENGTH`**, **`CURLMOPT_MAX_TOTAL_CONNECTIONS`**, **`CURLOPT_CONNECT_TO`**, **`CURLOPT_DEFAULT_PROTOCOL`**, **`CURLOPT_DNS_INTERFACE`**, **`CURLOPT_DNS_LOCAL_IP4`**, **`CURLOPT_DNS_LOCAL_IP6`**, **`CURLOPT_EXPECT_100_TIMEOUT_MS`**, **`CURLOPT_HEADEROPT`**, **`CURLOPT_LOGIN_OPTIONS`**, **`CURLOPT_PATH_AS_IS`**, **`CURLOPT_PINNEDPUBLICKEY`**, **`CURLOPT_PIPEWAIT`**, **`CURLOPT_PROXY_SERVICE_NAME`**, **`CURLOPT_PROXYHEADER`**, **`CURLOPT_SASL_IR`**, **`CURLOPT_SERVICE_NAME`**, **`CURLOPT_SSL_ENABLE_ALPN`**, **`CURLOPT_SSL_ENABLE_NPN`**, **`CURLOPT_SSL_FALSESTART`**, **`CURLOPT_SSL_VERIFYSTATUS`**, **`CURLOPT_STREAM_WEIGHT`**, **`CURLOPT_TCP_FASTOPEN`**, **`CURLOPT_TFTP_NO_OPTIONS`**, **`CURLOPT_UNIX_SOCKET_PATH`**, **`CURLOPT_XOAUTH2_BEARER`**, **`CURLPROTO_SMB`**, **`CURLPROTO_SMBS`**, **`CURLPROXY_HTTP_1_0`**, **`CURLSSH_AUTH_AGENT`** and **`CURLSSLOPT_NO_REVOKE`**. | ### Examples **Example #1 Initializing a new cURL session and fetching a web page** ``` <?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, false); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); ?> ``` ### Notes > > **Note**: > > > Passing an array to **`CURLOPT_POSTFIELDS`** will encode the data as *multipart/form-data*, while passing a URL-encoded string will encode the data as *application/x-www-form-urlencoded*. > > ### See Also * [curl\_setopt\_array()](function.curl-setopt-array) - Set multiple options for a cURL transfer * [CURLFile](class.curlfile) * [CURLStringFile](class.curlstringfile)
programming_docs
php SolrQuery::getTermsPrefix SolrQuery::getTermsPrefix ========================= (PECL solr >= 0.9.2) SolrQuery::getTermsPrefix — Returns the term prefix ### Description ``` public SolrQuery::getTermsPrefix(): string ``` Returns the prefix to which matching terms must be restricted. This will restrict matches to only terms that start with the prefix ### Parameters This function has no parameters. ### Return Values Returns a string on success and **`null`** if not set. php SolrDisMaxQuery::setPhraseFields SolrDisMaxQuery::setPhraseFields ================================ (No version information available, might only be in Git) SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter ### Description ``` public SolrDisMaxQuery::setPhraseFields(string $fields): SolrDisMaxQuery ``` Sets Phrase Fields (pf) and their boosts (and slops) ### Parameters `fields` Fields, boosts [, slops] ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::setPhraseFields()** example** ``` <?php $dismaxQuery = new SolrDisMaxQuery("lucene"); $dismaxQuery->setPhraseFields("cat~5.1^2 feature^4.5"); echo $dismaxQuery.PHP_EOL; ?> ``` The above example will output something similar to: ``` q=lucene&defType=edismax&pf=cat~5.1^2 feature^4.5 ``` ### See Also * **SolrDisMaxQuery::addPhraseFields()** * [SolrDisMaxQuery::removePhraseField()](solrdismaxquery.removephrasefield) - Removes a Phrase Field (pf parameter) php SessionHandlerInterface::close SessionHandlerInterface::close ============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SessionHandlerInterface::close — Close the session ### Description ``` public SessionHandlerInterface::close(): bool ``` Closes the current session. This function is automatically executed when closing the session, or explicitly via [session\_write\_close()](function.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. php Ds\Set::join Ds\Set::join ============ (PECL ds >= 1.0.0) Ds\Set::join — Joins all values together as a string ### Description ``` public Ds\Set::join(string $glue = ?): string ``` Joins all values together as a string using an optional separator between each value. ### Parameters `glue` An optional string to separate each value. ### Return Values All values of the set joined together as a string. ### Examples **Example #1 **Ds\Set::join()** example using a separator string** ``` <?php $set = new \Ds\Set(["a", "b", "c", 1, 2, 3]); var_dump($set->join("|")); ?> ``` The above example will output something similar to: ``` string(11) "a|b|c|1|2|3" ``` **Example #2 **Ds\Set::join()** example without a separator string** ``` <?php $set = new \Ds\Set(["a", "b", "c", 1, 2, 3]); var_dump($set->join()); ?> ``` The above example will output something similar to: ``` string(11) "abc123" ``` php array_pop array\_pop ========== (PHP 4, PHP 5, PHP 7, PHP 8) array\_pop — Pop the element off the end of array ### Description ``` array_pop(array &$array): mixed ``` **array\_pop()** pops and returns the value of the last element of `array`, shortening the `array` by one element. > **Note**: This function will [reset()](function.reset) the array pointer of the input array after use. > > ### Parameters `array` The array to get the value from. ### Return Values Returns the value of the last element of `array`. If `array` is empty, **`null`** will be returned. ### Examples **Example #1 **array\_pop()** example** ``` <?php $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); print_r($stack); ?> ``` After this, $stack will have only 3 elements: ``` Array ( [0] => orange [1] => banana [2] => apple ) ``` and `raspberry` will be assigned to $fruit. ### See Also * [array\_push()](function.array-push) - Push one or more elements onto the end of array * [array\_shift()](function.array-shift) - Shift an element off the beginning of array * [array\_unshift()](function.array-unshift) - Prepend one or more elements to the beginning of an array php None Escaping from HTML ------------------ Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content. This allows PHP to be embedded in HTML documents, for example to create templates. ``` <p>This is going to be ignored by PHP and displayed by the browser.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored by PHP and displayed by the browser.</p> ``` This works as expected, because when the PHP interpreter hits the ?> closing tags, it simply starts outputting whatever it finds (except for the immediately following newline - see [instruction separation](language.basic-syntax.instruction-separation)) until it hits another opening tag unless in the middle of a conditional statement in which case the interpreter will determine the outcome of the conditional before making a decision of what to skip over. See the next example. Using structures with conditions **Example #1 Advanced escaping using conditions** ``` <?php if ($expression == true): ?>   This will show if the expression is true. <?php else: ?>   Otherwise this will show. <?php endif; ?> ``` In this example PHP will skip the blocks where the condition is not met, even though they are outside of the PHP open/close tags; PHP skips them according to the condition since the PHP interpreter will jump over blocks contained within a condition that is not met. For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through [echo](function.echo) or [print](function.print). > > **Note**: > > > If PHP is embeded within XML or XHTML the normal PHP `<?php ?>` must be used to remain compliant with the standards. > > php openssl_x509_free openssl\_x509\_free =================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) openssl\_x509\_free — Free certificate resource **Warning**This function has been *DEPRECATED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` openssl_x509_free(OpenSSLCertificate $certificate): void ``` > > **Note**: > > > This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource. > > **openssl\_x509\_free()** frees the certificate associated with the specified `certificate` resource from memory. ### Parameters `certificate` ### Return Values No value is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function is now deprecated as it doesn't have an effect anymore. | | 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was accepted. | php SolrQuery::getFacetFields SolrQuery::getFacetFields ========================= (PECL solr >= 0.9.2) SolrQuery::getFacetFields — Returns all the facet fields ### Description ``` public SolrQuery::getFacetFields(): array ``` Returns all the facet fields ### Parameters This function has no parameters. ### Return Values Returns an array of all the fields and **`null`** if none was set php openssl_csr_get_subject openssl\_csr\_get\_subject ========================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) openssl\_csr\_get\_subject — Returns the subject of a CSR ### Description ``` openssl_csr_get_subject(OpenSSLCertificateSigningRequest|string $csr, bool $short_names = true): array|false ``` **openssl\_csr\_get\_subject()** returns subject distinguished name information encoded in the `csr` including fields commonName (CN), organizationName (O), countryName (C) etc. ### Parameters `csr` See [CSR parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values. `short_names` `shortnames` controls how the data is indexed in the array - if `shortnames` is **`true`** (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName. ### Return Values Returns an associative array with subject description, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `csr` accepts an [OpenSSLCertificateSigningRequest](class.opensslcertificatesigningrequest) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509 CSR` was accepted. | ### Examples **Example #1 openssl\_csr\_get\_subject() example** ``` <?php $subject = array(     "countryName" => "CA",     "stateOrProvinceName" => "Alberta",     "localityName" => "Calgary",     "organizationName" => "XYZ Widgets Inc",     "organizationalUnitName" => "PHP Documentation Team",     "commonName" => "Wez Furlong",     "emailAddress" => "[email protected]", ); $private_key = openssl_pkey_new(array(     "private_key_bits" => 2048,     "private_key_type" => OPENSSL_KEYTYPE_RSA, )); $configargs = array(     'digest_alg' => 'sha512WithRSAEncryption' ); $csr = openssl_csr_new($subject, $privkey, $configargs); print_r(openssl_csr_get_subject($csr)); ?> ``` The above example will output something similar to: ``` Array ( [C] => CA [ST] => Alberta [L] => Calgary [O] => XYZ Widgets Inc [OU] => PHP Documentation Team [CN] => Wez Furlong [emailAddress] => [email protected] ) ``` ### See Also * [openssl\_csr\_new()](function.openssl-csr-new) - Generates a CSR * [openssl\_csr\_get\_public\_key()](function.openssl-csr-get-public-key) - Returns the public key of a CSR * [openssl\_x509\_parse()](function.openssl-x509-parse) - Parse an X509 certificate and return the information as an array php Ds\Vector::reverse Ds\Vector::reverse ================== (PECL ds >= 1.0.0) Ds\Vector::reverse — Reverses the vector in-place ### Description ``` public Ds\Vector::reverse(): void ``` Reverses the vector in-place. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Vector::reverse()** example** ``` <?php $vector = new \Ds\Vector(["a", "b", "c"]); $vector->reverse(); print_r($vector); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => c [1] => b [2] => a ) ``` php EventUtil::getLastSocketErrno EventUtil::getLastSocketErrno ============================= (PECL event >= 1.2.6-beta) EventUtil::getLastSocketErrno — Returns the most recent socket error number ### Description ``` public static EventUtil::getLastSocketErrno( mixed $socket = null ): int ``` Returns the most recent socket error number( `errno` ). ### Parameters `socket` Socket resource, stream or a file descriptor of a socket. ### Return Values Returns the most recent socket error number( `errno` ). ### See Also * [EventUtil::getLastSocketError()](eventutil.getlastsocketerror) - Returns the most recent socket error php ParseError ParseError ========== Introduction ------------ (PHP 7, PHP 8) **ParseError** is thrown when an error occurs while parsing PHP code, such as when [eval()](function.eval) is called. > **Note**: **ParseError** extends [CompileError](class.compileerror) as of PHP 7.3.0. Formerly, it extended [Error](class.error). > > Class synopsis -------------- class **ParseError** extends [CompileError](class.compileerror) { /\* Inherited properties \*/ protected string [$message](class.error#error.props.message) = ""; private string [$string](class.error#error.props.string) = ""; protected int [$code](class.error#error.props.code); protected string [$file](class.error#error.props.file) = ""; protected int [$line](class.error#error.props.line); private array [$trace](class.error#error.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.error#error.props.previous) = null; /\* Inherited methods \*/ ``` final public Error::getMessage(): string ``` ``` final public Error::getPrevious(): ?Throwable ``` ``` final public Error::getCode(): int ``` ``` final public Error::getFile(): string ``` ``` final public Error::getLine(): int ``` ``` final public Error::getTrace(): array ``` ``` final public Error::getTraceAsString(): string ``` ``` public Error::__toString(): string ``` ``` private Error::__clone(): void ``` } php wincache_ucache_meminfo wincache\_ucache\_meminfo ========================= (PECL wincache >= 1.1.0) wincache\_ucache\_meminfo — Retrieves information about user cache memory usage ### Description ``` wincache_ucache_meminfo(): array|false ``` Retrieves information about memory usage by user cache. ### Parameters This function has no parameters. ### Return Values Array of meta data about user cache memory usage or **`false`** on failure The array returned by this function contains the following elements: * `memory_total` - amount of memory in bytes allocated for the user cache * `memory_free` - amount of free memory in bytes available for the user cache * `num_used_blks` - number of memory blocks used by the user cache * `num_free_blks` - number of free memory blocks available for the user cache * `memory_overhead` - amount of memory in bytes used for the user cache internal structures ### Examples **Example #1 A **wincache\_ucache\_meminfo()** example** ``` <pre> <?php print_r(wincache_ucache_meminfo()); ?> </pre> ``` The above example will output: ``` Array ( [memory_total] => 5242880 [memory_free] => 5215056 [num_used_blks] => 6 [num_free_blks] => 3 [memory_overhead] => 176 ) ``` ### See Also * [wincache\_fcache\_fileinfo()](function.wincache-fcache-fileinfo) - Retrieves information about files cached in the file cache * [wincache\_fcache\_meminfo()](function.wincache-fcache-meminfo) - Retrieves information about file cache memory usage * [wincache\_ocache\_fileinfo()](function.wincache-ocache-fileinfo) - Retrieves information about files cached in the opcode cache * [wincache\_rplist\_fileinfo()](function.wincache-rplist-fileinfo) - Retrieves information about resolve file path cache * [wincache\_rplist\_meminfo()](function.wincache-rplist-meminfo) - Retrieves information about memory usage by the resolve file path cache * [wincache\_refresh\_if\_changed()](function.wincache-refresh-if-changed) - Refreshes the cache entries for the cached files * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache * [wincache\_scache\_info()](function.wincache-scache-info) - Retrieves information about files cached in the session cache * [wincache\_scache\_meminfo()](function.wincache-scache-meminfo) - Retrieves information about session cache memory usage php AppendIterator::getArrayIterator AppendIterator::getArrayIterator ================================ (PHP 5 >= 5.2.0, PHP 7, PHP 8) AppendIterator::getArrayIterator — Gets the ArrayIterator ### Description ``` public AppendIterator::getArrayIterator(): ArrayIterator ``` This method gets the [ArrayIterator](class.arrayiterator) that is used to store the iterators added with [AppendIterator::append()](appenditerator.append). ### Parameters This function has no parameters. ### Return Values Returns an [ArrayIterator](class.arrayiterator) containing the appended iterators. ### See Also * [AppendIterator::getInnerIterator()](appenditerator.getinneriterator) - Gets the inner iterator php pcntl_signal_get_handler pcntl\_signal\_get\_handler =========================== (PHP 7 >= 7.1.0, PHP 8) pcntl\_signal\_get\_handler — Get the current handler for specified signal ### Description ``` pcntl_signal_get_handler(int $signal): callable|int ``` The **pcntl\_signal\_get\_handler()** function will get the current handler for the specified `signal`. ### Parameters `signal` The signal number. ### Return Values This function may return an integer value that refers to **`SIG_DFL`** or **`SIG_IGN`**. If a custom handler has been set, that [callable](language.types.callable) is returned. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | **pcntl\_signal\_get\_handler()** has been added. | ### Examples **Example #1 **pcntl\_signal\_get\_handler()** example** ``` <?php var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0) function pcntl_test($signo) {} pcntl_signal(SIGUSR1, 'pcntl_test'); var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: string(10) "pcntl_test" pcntl_signal(SIGUSR1, SIG_DFL); var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0) pcntl_signal(SIGUSR1, SIG_IGN); var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(1) ?> ``` ### See Also * [pcntl\_signal()](function.pcntl-signal) - Installs a signal handler php ArrayObject::count ArrayObject::count ================== (PHP 5, PHP 7, PHP 8) ArrayObject::count — Get the number of public properties in the ArrayObject ### Description ``` public ArrayObject::count(): int ``` Get the number of public properties in the [ArrayObject](class.arrayobject). ### Parameters This function has no parameters. ### Return Values The number of public properties in the [ArrayObject](class.arrayobject). > > **Note**: > > > When the [ArrayObject](class.arrayobject) is constructed from an array all properties are public. > > ### Examples **Example #1 **ArrayObject::count()** example** ``` <?php class Example {     public $public = 'prop:public';     private $prv   = 'prop:private';     protected $prt = 'prop:protected'; } $arrayobj = new ArrayObject(new Example()); var_dump($arrayobj->count()); $arrayobj = new ArrayObject(array('first','second','third')); var_dump($arrayobj->count()); ?> ``` The above example will output: ``` int(1) int(3) ``` php ReflectionProperty::setValue ReflectionProperty::setValue ============================ (PHP 5, PHP 7, PHP 8) ReflectionProperty::setValue — Set property value ### Description ``` public ReflectionProperty::setValue(object $object, mixed $value): void ``` ``` public ReflectionProperty::setValue(mixed $value): void ``` Sets (changes) the property's value. ### Parameters `object` If the property is non-static an object must be provided to change the property on. If the property is static this parameter is left out and only `value` needs to be provided. `value` The new value. ### Return Values No value is returned. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Private and protected properties can be accessed by **ReflectionProperty::setValue()** right away. Previously, they needed to be made accessible by calling [ReflectionProperty::setAccessible()](reflectionproperty.setaccessible); otherwise a [ReflectionException](class.reflectionexception) was thrown. | ### Examples **Example #1 **ReflectionProperty::setValue()** example** ``` <?php class Foo {     public static $staticProperty;          public $property;     protected $privateProperty; } $reflectionClass = new ReflectionClass('Foo'); $reflectionClass->getProperty('staticProperty')->setValue('foo'); var_dump(Foo::$staticProperty); $foo = new Foo; $reflectionClass->getProperty('property')->setValue($foo, 'bar'); var_dump($foo->property); $reflectionProperty = $reflectionClass->getProperty('privateProperty'); $reflectionProperty->setAccessible(true); // only required prior to PHP 8.1.0 $reflectionProperty->setValue($foo, 'foobar'); var_dump($reflectionProperty->getValue($foo)); ?> ``` The above example will output: ``` string(3) "foo" string(3) "bar" string(6) "foobar" ``` ### See Also * [ReflectionProperty::getValue()](reflectionproperty.getvalue) - Gets value * [ReflectionProperty::setAccessible()](reflectionproperty.setaccessible) - Set property accessibility * [ReflectionClass::setStaticPropertyValue()](reflectionclass.setstaticpropertyvalue) - Sets static property value
programming_docs
php is_callable is\_callable ============ (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) is\_callable — Verify that a value can be called as a function from the current scope. ### Description ``` is_callable(mixed $value, bool $syntax_only = false, string &$callable_name = null): bool ``` Verify that a value is a [callable](language.types.callable). ### Parameters `value` The value to check `syntax_only` If set to **`true`** the function only verifies that `value` might be a function or method. It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback. The valid ones are supposed to have only 2 entries, the first of which is an object or a string, and the second a string. `callable_name` Receives the "callable name". In the example below it is "someClass::someMethod". Note, however, that despite the implication that someClass::SomeMethod() is a callable static method, this is not the case. ### Return Values Returns **`true`** if `value` is callable, **`false`** otherwise. ### Examples **Example #1 **is\_callable()** example** ``` <?php //  How to check a variable to see if it can be called //  as a function. // //  Simple variable containing a function // function someFunction()  { } $functionVariable = 'someFunction'; var_dump(is_callable($functionVariable, false, $callable_name));  // bool(true) echo $callable_name, "\n";  // someFunction // //  Array containing a method // class someClass {   function someMethod()    {   } } $anObject = new someClass(); $methodVariable = array($anObject, 'someMethod'); var_dump(is_callable($methodVariable, true, $callable_name));  //  bool(true) echo $callable_name, "\n";  //  someClass::someMethod ?> ``` **Example #2 **is\_callable()** and constructors** **is\_callable()** reports constructors as not being callable. ``` <?php class Foo {     public function __construct() {}     public function foo() {} } var_dump(     is_callable(array('Foo', '__construct')),     is_callable(array('Foo', 'foo')) ); ``` The above example will output: ``` bool(false) bool(false) ``` ### Notes * An object is always callable if it implements [\_\_invoke()](language.oop5.magic#object.invoke), and that method is visible in the current scope. * A class name is callable if it implements [\_\_callStatic()](language.oop5.overloading#object.callstatic). * If an object implements [\_\_call()](language.oop5.overloading#object.call), then this function will return **`true`** for any method on that object, even if the method is not defined. * This function may trigger autoloading if called with the name of a class. ### See Also * [function\_exists()](function.function-exists) - Return true if the given function has been defined * [method\_exists()](function.method-exists) - Checks if the class method exists php parse_str parse\_str ========== (PHP 4, PHP 5, PHP 7, PHP 8) parse\_str — Parses the string into variables ### Description ``` parse_str(string $string, array &$result): void ``` Parses `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 `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. As of PHP 8.0.0, the `result` parameter is *mandatory*. ### Return Values No value is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `result` is no longer optional. | | 7.2.0 | Usage of **parse\_str()** without a second parameter now emits an **`E_DEPRECATED`** notice. | ### Examples **Example #1 Using **parse\_str()**** ``` <?php $str = "first=value&arr[]=foo+bar&arr[]=baz"; // Recommended parse_str($str, $output); echo $output['first'];  // value echo $output['arr'][0]; // foo bar echo $output['arr'][1]; // baz // DISCOURAGED parse_str($str); echo $first;  // value echo $arr[0]; // foo bar echo $arr[1]; // baz ?> ``` Because variables in PHP can't have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with `result` parameter. **Example #2 **parse\_str()** name mangling** ``` <?php parse_str("My Value=Something"); echo $My_Value; // Something parse_str("My Value=Something", $output); echo $output['My_Value']; // Something ?> ``` ### Notes > > **Note**: > > > All variables created (or values returned into array if second parameter is set) are already [urldecode()](function.urldecode)d. > > > > **Note**: > > > To get the current `QUERY_STRING`, you may use the variable [$\_SERVER['QUERY\_STRING']](reserved.variables.server). Also, you may want to read the section on [variables from external sources](language.variables.external). > > ### See Also * [parse\_url()](function.parse-url) - Parse a URL and return its components * [pathinfo()](function.pathinfo) - Returns information about a file path * [http\_build\_query()](function.http-build-query) - Generate URL-encoded query string * [urldecode()](function.urldecode) - Decodes URL-encoded string php GearmanClient::getErrno GearmanClient::getErrno ======================= (PECL gearman >= 0.5.0) GearmanClient::getErrno — Get an errno value ### Description ``` public GearmanClient::getErrno(): int ``` Value of errno in the case of a GEARMAN\_ERRNO return value. ### Parameters This function has no parameters. ### Return Values A valid Gearman errno. ### See Also * [GearmanClient::error()](gearmanclient.error) - Returns an error string for the last error encountered php SolrQuery::getTermsLimit SolrQuery::getTermsLimit ======================== (PECL solr >= 0.9.2) SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return ### Description ``` public SolrQuery::getTermsLimit(): int ``` Returns the maximum number of terms Solr should return ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php Generator::throw Generator::throw ================ (PHP 5 >= 5.5.0, PHP 7, PHP 8) Generator::throw — Throw an exception into the generator ### Description ``` public Generator::throw(Throwable $exception): mixed ``` Throws an exception into the generator and resumes execution of the generator. The behavior will be the same as if the current [yield](language.generators.syntax#control-structures.yield) expression was replaced with a `throw $exception` statement. If the generator is already closed when this method is invoked, the exception will be thrown in the caller's context instead. ### Parameters `exception` Exception to throw into the generator. ### Return Values Returns the yielded value. ### Examples **Example #1 Throwing an exception into a generator** ``` <?php function gen() {     echo "Foo\n";     try {         yield;     } catch (Exception $e) {         echo "Exception: {$e->getMessage()}\n";     }     echo "Bar\n"; }   $gen = gen(); $gen->rewind(); $gen->throw(new Exception('Test')); ?> ``` The above example will output: ``` Foo Exception: Test Bar ``` php odbc_result odbc\_result ============ (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_result — Get result data ### Description ``` odbc_result(resource $statement, string|int $field): string|bool|null ``` Get result data ### Parameters `statement` The ODBC resource. `field` The field name being retrieved. It can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field. ### Return Values Returns the string contents of the field, **`false`** on error, **`null`** for NULL data, or **`true`** for binary data. ### Examples The first call to **odbc\_result()** returns the value of the third field in the current record of the query result. The second function call to **odbc\_result()** returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried. **Example #1 **odbc\_result()** examples** ``` <?php $item_3   = odbc_result($Query_ID, 3); $item_val = odbc_result($Query_ID, "val"); ?> ``` ### Notes Field indices start from 1. Regarding the way binary or long column data is returned refer to [odbc\_binmode()](function.odbc-binmode) and [odbc\_longreadlen()](function.odbc-longreadlen). php eio_readdir eio\_readdir ============ (PECL eio >= 0.0.1dev) eio\_readdir — Reads through a whole directory ### Description ``` eio_readdir( string $path, int $flags, int $pri, callable $callback, string $data = NULL ): resource ``` Reads through a whole directory(via the `opendir`, `readdir` and `closedir` system calls) and returns either the names or an array in `result` argument of `callback` function, depending on the `flags` argument. ### Parameters `path` Directory path. `flags` Combination of *EIO\_READDIR\_\** constants. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_readdir()** returns request resource on success, or **`false`** on failure. Sets `result` argument of `callback` function according to `flags`: **`EIO_READDIR_DENTS`** (int) **eio\_readdir()** flag. If specified, the result argument of the callback becomes an array with the following keys: `'names'` - array of directory names `'dents'` - array of `struct eio_dirent`-like arrays having the following keys each: `'name'` - the directory name; `'type'` - one of *EIO\_DT\_\** constants; `'inode'` - the inode number, if available, otherwise unspecified; **`EIO_READDIR_DIRS_FIRST`** (int) When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order. **`EIO_READDIR_STAT_ORDER`** (int) When this flag is specified, then the names will be returned in an order suitable for `stat`'ing each one. When planning to [stat()](function.stat) all files in the given directory, the returned order will likely be fastest. **`EIO_READDIR_FOUND_UNKNOWN`** (int) Node types: **`EIO_DT_UNKNOWN`** (int) Unknown node type(very common). Further [stat()](function.stat) needed. **`EIO_DT_FIFO`** (int) FIFO node type **`EIO_DT_CHR`** (int) Node type **`EIO_DT_MPC`** (int) Multiplexed char device (v7+coherent) node type **`EIO_DT_DIR`** (int) Directory node type **`EIO_DT_NAM`** (int) Xenix special named file node type **`EIO_DT_BLK`** (int) Node type **`EIO_DT_MPB`** (int) Multiplexed block device (v7+coherent) **`EIO_DT_REG`** (int) Node type **`EIO_DT_NWK`** (int) **`EIO_DT_CMP`** (int) HP-UX network special node type **`EIO_DT_LNK`** (int) Link node type **`EIO_DT_SOCK`** (int) Socket node type **`EIO_DT_DOOR`** (int) Solaris door node type **`EIO_DT_WHT`** (int) Node type **`EIO_DT_MAX`** (int) Highest node type value ### Examples **Example #1 **eio\_readdir()** example** ``` <?php /* Is called when eio_readdir() finishes */ function my_readdir_callback($data, $result) {     echo __FUNCTION__, " called\n";     echo "data: "; var_dump($data);     echo "result: "; var_dump($result);     echo "\n"; } eio_readdir("/var/spool/news", EIO_READDIR_STAT_ORDER | EIO_READDIR_DIRS_FIRST,   EIO_PRI_DEFAULT, "my_readdir_callback"); eio_event_loop(); ?> ``` The above example will output something similar to: ``` my_readdir_callback called data: NULL result: array(2) { ["names"]=> array(7) { [0]=> string(7) "archive" [1]=> string(8) "articles" [2]=> string(8) "incoming" [3]=> string(7) "innfeed" [4]=> string(8) "outgoing" [5]=> string(8) "overview" [6]=> string(3) "tmp" } ["dents"]=> array(7) { [0]=> array(3) { ["name"]=> string(7) "archive" ["type"]=> int(4) ["inode"]=> int(393265) } [1]=> array(3) { ["name"]=> string(8) "articles" ["type"]=> int(4) ["inode"]=> int(393266) } [2]=> array(3) { ["name"]=> string(8) "incoming" ["type"]=> int(4) ["inode"]=> int(393267) } [3]=> array(3) { ["name"]=> string(7) "innfeed" ["type"]=> int(4) ["inode"]=> int(393269) } [4]=> array(3) { ["name"]=> string(8) "outgoing" ["type"]=> int(4) ["inode"]=> int(393270) } [5]=> array(3) { ["name"]=> string(8) "overview" ["type"]=> int(4) ["inode"]=> int(393271) } [6]=> array(3) { ["name"]=> string(3) "tmp" ["type"]=> int(4) ["inode"]=> int(393272) } } } ``` php Yaf_Session::start Yaf\_Session::start =================== (Yaf >=1.0.0) Yaf\_Session::start — The start purpose ### Description ``` public Yaf_Session::start(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php iconv_strpos iconv\_strpos ============= (PHP 5, PHP 7, PHP 8) iconv\_strpos — Finds position of first occurrence of a needle within a haystack ### Description ``` iconv_strpos( string $haystack, string $needle, int $offset = 0, ?string $encoding = null ): int|false ``` Finds position of first occurrence of a `needle` within a `haystack`. In contrast to [strpos()](function.strpos), the return value of **iconv\_strpos()** is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set `encoding`. ### Parameters `haystack` The entire string. `needle` The searched substring. `offset` The optional `offset` parameter specifies the position from which the search should be performed. If the offset is negative, it is counted from the end of the string. `encoding` If `encoding` parameter is omitted or **`null`**, `string` are assumed to be encoded in [iconv.internal\_encoding](https://www.php.net/manual/en/iconv.configuration.php). If `haystack` or `needle` is not a string, it is converted to a string and applied as the ordinal value of a character. ### Return Values Returns the numeric position of the first occurrence of `needle` in `haystack`. If `needle` is not found, **iconv\_strpos()** will return **`false`**. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | | 7.1.0 | Support for negative `offset`s has been added. | ### See Also * [strpos()](function.strpos) - Find the position of the first occurrence of a substring in a string * [iconv\_strrpos()](function.iconv-strrpos) - Finds the last occurrence of a needle within a haystack * [mb\_strpos()](function.mb-strpos) - Find position of first occurrence of string in a string php Imagick::removeImageProfile Imagick::removeImageProfile =========================== (PECL imagick 2, PECL imagick 3) Imagick::removeImageProfile — Removes the named image profile and returns it ### Description ``` public Imagick::removeImageProfile(string $name): string ``` Removes the named image profile and returns it. ### Parameters `name` ### Return Values Returns a string containing the profile of the image. ### Errors/Exceptions Throws ImagickException on error. php SplHeap::valid SplHeap::valid ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplHeap::valid — Check whether the heap contains more nodes ### Description ``` public SplHeap::valid(): bool ``` Checks if the heap contains any more nodes. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the heap contains any more nodes, **`false`** otherwise. php ldap_error ldap\_error =========== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_error — Return the LDAP error message of the last LDAP command ### Description ``` ldap_error(LDAP\Connection $ldap): string ``` Returns the string error message explaining the error generated by the last LDAP command for the given `ldap`. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check. Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with `@` (at) characters to suppress warning output, the errors generated will also show up in your HTML output. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). ### Return Values Returns string error message. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [ldap\_err2str()](function.ldap-err2str) - Convert LDAP error number into string error message * [ldap\_errno()](function.ldap-errno) - Return the LDAP error number of the last LDAP command php None continue -------- (PHP 4, PHP 5, PHP 7, PHP 8) `continue` is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. > **Note**: In PHP the [switch](control-structures.switch) statement is considered a looping structure for the purposes of `continue`. `continue` behaves like `break` (when no arguments are passed) but will raise a warning as this is likely to be a mistake. If a `switch` is inside a loop, `continue 2` will continue with the next iteration of the outer loop. > > `continue` accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is `1`, thus skipping to the end of the current loop. ``` <?php foreach ($arr as $key => $value) {     if (!($key % 2)) { // skip even members         continue;     }     do_something_odd($value); } $i = 0; while ($i++ < 5) {     echo "Outer<br />\n";     while (1) {         echo "Middle<br />\n";         while (1) {             echo "Inner<br />\n";             continue 3;         }         echo "This never gets output.<br />\n";     }     echo "Neither does this.<br />\n"; } ?> ``` Omitting the semicolon after `continue` can lead to confusion. Here's an example of what you shouldn't do. ``` <?php for ($i = 0; $i < 5; ++$i) {     if ($i == 2)         continue     print "$i\n"; } ?> ``` One can expect the result to be: ``` 0 1 3 4 ``` **Changelog for `continue`**| Version | Description | | --- | --- | | 7.3.0 | `continue` within a `switch` that is attempting to act like a `break` statement for the `switch` will trigger an **`E_WARNING`**. |
programming_docs
php DOMElement::getAttributeNodeNS DOMElement::getAttributeNodeNS ============================== (PHP 5, PHP 7, PHP 8) DOMElement::getAttributeNodeNS — Returns attribute node ### Description ``` public DOMElement::getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null ``` Returns the attribute node in namespace `namespace` with local name `localName` for the current node. ### Parameters `namespace` The namespace URI. `localName` The local name. ### Return Values The attribute node. Note that for XML namespace declarations (`xmlns` and `xmlns:*` attributes) an instance of **DOMNameSpaceNode** is returned instead of a [DOMAttr](class.domattr) object. ### See Also * [DOMElement::hasAttributeNS()](domelement.hasattributens) - Checks to see if attribute exists * [DOMElement::setAttributeNodeNS()](domelement.setattributenodens) - Adds new attribute node to element * [DOMElement::removeAttributeNode()](domelement.removeattributenode) - Removes attribute php php_user_filter::filter php\_user\_filter::filter ========================= (PHP 5, PHP 7, PHP 8) php\_user\_filter::filter — Called when applying the filter ### Description ``` public php_user_filter::filter( resource $in, resource $out, int &$consumed, bool $closing ): int ``` This method is called whenever data is read from or written to the attached stream (such as with [fread()](function.fread) or [fwrite()](function.fwrite)). ### Parameters `in` `in` is a resource pointing to a `bucket brigade` which contains one or more `bucket` objects containing data to be filtered. `out` `out` is a resource pointing to a second `bucket brigade` into which your modified buckets should be placed. `consumed` `consumed`, which must *always* be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment `consumed` by `$bucket->datalen` for each `$bucket`. `closing` If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the `closing` parameter will be set to **`true`**. ### Return Values The **filter()** method must return one of three values upon completion. | Return Value | Meaning | | --- | --- | | **`PSFS_PASS_ON`** | Filter processed successfully with data available in the `out` `bucket brigade`. | | **`PSFS_FEED_ME`** | Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter. | | **`PSFS_ERR_FATAL`** (default) | The filter experienced an unrecoverable error and cannot continue. | php mysqli::query mysqli::query ============= mysqli\_query ============= (PHP 5, PHP 7, PHP 8) mysqli::query -- mysqli\_query — Performs a query on the database ### Description Object-oriented style ``` public mysqli::query(string $query, int $result_mode = MYSQLI_STORE_RESULT): mysqli_result|bool ``` Procedural style ``` mysqli_query(mysqli $mysql, string $query, int $result_mode = MYSQLI_STORE_RESULT): mysqli_result|bool ``` Performs a `query` against the database. For non-DML queries (not INSERT, UPDATE or DELETE), this function is similar to calling [mysqli\_real\_query()](mysqli.real-query) followed by either [mysqli\_use\_result()](mysqli.use-result) or [mysqli\_store\_result()](mysqli.store-result). > > **Note**: > > > In the case where a statement is passed to **mysqli\_query()** that is longer than `max_allowed_packet` of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (`mysqlnd`) or MySQL Client Library (`libmysqlclient`). The behavior is as follows: > > * `mysqlnd` on Linux returns an error code of 1153. The error message means got a packet bigger than `max_allowed_packet` bytes. > * `mysqlnd` on Windows returns an error code 2006. This error message means server has gone away. > * `libmysqlclient` on all platforms returns an error code 2006. This error message means server has gone away. > > ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `query` The query string. **Warning** Security warning: SQL injection =============================== If the query contains any variable input then [parameterized prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the [mysqli\_real\_escape\_string()](mysqli.real-escape-string) function. `result_mode` The result mode can be one of 3 constants indicating how the result will be returned from the MySQL server. **`MYSQLI_STORE_RESULT`** (default) - returns a [mysqli\_result](class.mysqli-result) object with buffered result set. **`MYSQLI_USE_RESULT`** - returns a [mysqli\_result](class.mysqli-result) object with unbuffered result set. As long as there are pending records waiting to be fetched, the connection line will be busy and all subsequent calls will return error `Commands out of sync`. To avoid the error all records must be fetched from the server or the result set must be discarded by calling [mysqli\_free\_result()](mysqli-result.free). **`MYSQLI_ASYNC`** (available with mysqlnd) - the query is performed asynchronously and no result set is immediately returned. [mysqli\_poll()](mysqli.poll) is then used to get results from such queries. Used in combination with either **`MYSQLI_STORE_RESULT`** or **`MYSQLI_USE_RESULT`** constant. ### Return Values Returns **`false`** on failure. For successful queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, **mysqli\_query()** will return a [mysqli\_result](class.mysqli-result) object. For other successful queries, **mysqli\_query()** will return **`true`**. ### Examples **Example #1 **mysqli::query()** example** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* Create table doesn't return a resultset */ $mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City"); printf("Table myCity successfully created.\n"); /* Select queries return a resultset */ $result = $mysqli->query("SELECT Name FROM City LIMIT 10"); printf("Select returned %d rows.\n", $result->num_rows); /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ $result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT); /* Note, that we can't execute any functions which interact with the     server until all records have been fully retrieved or the result     set was closed. All calls will return an 'out of sync' error */ $mysqli->query("SET @a:='this will not work'"); ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* Create table doesn't return a resultset */ mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City"); printf("Table myCity successfully created.\n"); /* Select queries return a resultset */ $result = mysqli_query($link, "SELECT Name FROM City LIMIT 10"); printf("Select returned %d rows.\n", mysqli_num_rows($result)); /* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */ $result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT); /* Note, that we can't execute any functions which interact with the     server until all records have been fully retrieved or the result     set was closed. All calls will return an 'out of sync' error */ mysqli_query($link, "SET @a:='this will not work'"); ``` The above examples will output something similar to: ``` Table myCity successfully created. Select returned 10 rows. Fatal error: Uncaught mysqli_sql_exception: Commands out of sync; you can't run this command now in... ``` ### See Also * [mysqli\_real\_query()](mysqli.real-query) - Execute an SQL query * [mysqli\_multi\_query()](mysqli.multi-query) - Performs one or more queries on the database * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_free\_result()](mysqli-result.free) - Frees the memory associated with a result php SolrDisMaxQuery::addPhraseField SolrDisMaxQuery::addPhraseField =============================== (No version information available, might only be in Git) SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter) ### Description ``` public SolrDisMaxQuery::addPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery ``` Adds a Phrase Field (pf parameter) ### Parameters `field` field name `boost` `slop` ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::addPhraseField()** example** ``` <?php $dismaxQuery = new SolrDisMaxQuery("lucene"); $dismaxQuery     ->addPhraseField('cat', 3, 1)     ->addPhraseField('third', 4, 2)     ->addPhraseField('source', 55) ; echo $dismaxQuery; ?> ``` The above example will output something similar to: ``` q=lucene&defType=edismax&pf=cat~1^3 third~2^4 source^55 ``` ### See Also * [SolrDisMaxQuery::removePhraseField()](solrdismaxquery.removephrasefield) - Removes a Phrase Field (pf parameter) * [SolrDisMaxQuery::setPhraseFields()](solrdismaxquery.setphrasefields) - Sets Phrase Fields and their boosts (and slops) using pf2 parameter php ReflectionProperty::getName ReflectionProperty::getName =========================== (PHP 5, PHP 7, PHP 8) ReflectionProperty::getName — Gets property name ### Description ``` public ReflectionProperty::getName(): string ``` Gets the properties name. ### Parameters This function has no parameters. ### Return Values The name of the reflected property. ### See Also * [ReflectionProperty::getValue()](reflectionproperty.getvalue) - Gets value php None First class callable syntax --------------------------- The first class callable syntax is introduced as of PHP 8.1.0, as a way of creating [anonymous functions](functions.anonymous) from [callable](language.types.callable). It supersedes existing callable syntax using strings and arrays. The advantage of this syntax is that it is accessible to static analysis, and uses the scope at the point where the callable is acquired. `CallableExpr(...)` syntax is used to create a [Closure](class.closure) object from callable. `CallableExpr` accepts any expression that can be directly called in the PHP grammar: **Example #1 Simple first class callable syntax** ``` <?php class Foo {    public function method() {}    public static function staticmethod() {}    public function __invoke() {} } $obj = new Foo(); $classStr = 'Foo'; $methodStr = 'method'; $staticmethodStr = 'staticmethod'; $f1 = strlen(...); $f2 = $obj(...);  // invokable object $f3 = $obj->method(...); $f4 = $obj->$methodStr(...); $f5 = Foo::staticmethod(...); $f6 = $classStr::$staticmethodStr(...); // traditional callable using string, array $f7 = 'strlen'(...); $f8 = [$obj, 'method'](...); $f9 = [Foo::class, 'staticmethod'](...); ?> ``` > > **Note**: > > > The `...` is part of the syntax, and not an omission. > > `CallableExpr(...)` has the same semantics as [Closure::fromCallable()](closure.fromcallable). That is, unlike callable using strings and arrays, `CallableExpr(...)` respects the scope at the point where it is created: **Example #2 Scope comparison of `CallableExpr(...)` and traditional callable** ``` <?php class Foo {     public function getPrivateMethod() {         return [$this, 'privateMethod'];     }     private function privateMethod() {         echo __METHOD__, "\n";     } } $foo = new Foo; $privateMethod = $foo->getPrivateMethod(); $privateMethod(); // Fatal error: Call to private method Foo::privateMethod() from global scope // This is because call is performed outside from Foo and visibility will be checked from this point. class Foo1 {     public function getPrivateMethod() {         // Uses the scope where the callable is acquired.         return $this->privateMethod(...); // identical to Closure::fromCallable([$this, 'privateMethod']);     }     private function privateMethod() {         echo __METHOD__, "\n";     } } $foo1 = new Foo1; $privateMethod = $foo1->getPrivateMethod(); $privateMethod();  // Foo1::privateMethod ?> ``` > > **Note**: > > > Object creation by this syntax (e.g `new Foo(...)`) is not supported, because `new Foo()` syntax is not considered a call. > > > > **Note**: > > > The first-class callable syntax cannot be combined with the [nullsafe operator](language.oop5.basic#language.oop5.basic.nullsafe). Both of the following result in a compile-time error: > > > > ``` > <?php > $obj?->method(...); > $obj?->prop->method(...); > ?> > ``` > php Gmagick::getimagehistogram Gmagick::getimagehistogram ========================== (PECL gmagick >= Unknown) Gmagick::getimagehistogram — Gets the image histogram ### Description ``` public Gmagick::getimagehistogram(): array ``` Returns the image histogram as an array of [GmagickPixel](class.gmagickpixel) objects. Throw an **GmagickException** on error. ### Parameters This function has no parameters. ### Return Values Returns the image histogram as an array of [GmagickPixel](class.gmagickpixel) objects. ### Errors/Exceptions Throws an **GmagickException** on error. php readlink readlink ======== (PHP 4, PHP 5, PHP 7, PHP 8) readlink — Returns the target of a symbolic link ### Description ``` readlink(string $path): string|false ``` **readlink()** does the same as the readlink C function. ### Parameters `path` The symbolic link path. ### Return Values Returns the contents of the symbolic link path or **`false`** on error. > **Note**: The function fails if `path` is not a symlink, except on Windows, where the normalized path will be returned. > > ### Examples **Example #1 **readlink()** example** ``` <?php // output e.g. /boot/vmlinux-2.4.20-xfs echo readlink('/vmlinuz'); ?> ``` ### See Also * [is\_link()](function.is-link) - Tells whether the filename is a symbolic link * [symlink()](function.symlink) - Creates a symbolic link * [linkinfo()](function.linkinfo) - Gets information about a link php Parle\Lexer::dump Parle\Lexer::dump ================= (PECL parle >= 0.5.1) Parle\Lexer::dump — Dump the state machine ### Description ``` public Parle\Lexer::dump(): void ``` Dump the current state machine to stdout. ### Parameters This function has no parameters. ### Return Values No value is returned. php EventDnsBase::__construct EventDnsBase::\_\_construct =========================== (PECL event >= 1.2.6-beta) EventDnsBase::\_\_construct — Constructs EventDnsBase object ### Description ``` public EventDnsBase::__construct( EventBase $base , bool $initialize ) ``` Constructs EventDnsBase object. ### Parameters `base` Event base. `initialize` If the `initialize` argument is **`true`**, it tries to configure the DNS base sensibly given your operating system’s default. Otherwise, it leaves the event DNS base empty, with no nameservers or options configured. In the latter case DNS base should be configured manually, e.g. with [EventDnsBase::parseResolvConf()](eventdnsbase.parseresolvconf) . ### Return Values Returns EventDnsBase object. php ImagickDraw::setFontStretch ImagickDraw::setFontStretch =========================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text ### Description ``` public ImagickDraw::setFontStretch(int $fontStretch): bool ``` **Warning**This function is currently not documented; only its argument list is available. Sets the font stretch to use when annotating with text. The AnyStretch enumeration acts as a wild-card "don't care" option. ### Parameters `fontStretch` One of the [STRETCH](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.stretch) constant (`imagick::STRETCH_*`). ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setFontStretch()** example** ``` <?php function setFontStretch($fillColor, $strokeColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(2);     $draw->setFontSize(36);     $fontStretchTypes = [         \Imagick::STRETCH_ULTRACONDENSED,          \Imagick::STRETCH_CONDENSED,          \Imagick::STRETCH_SEMICONDENSED,          \Imagick::STRETCH_SEMIEXPANDED,          \Imagick::STRETCH_EXPANDED,          \Imagick::STRETCH_EXTRAEXPANDED,          \Imagick::STRETCH_ULTRAEXPANDED,          \Imagick::STRETCH_ANY     ];     $offset = 0;     foreach ($fontStretchTypes as $fontStretch) {         $draw->setFontStretch($fontStretch);         $draw->annotation(50, 75 + $offset, "Lorem Ipsum!");         $offset += 50;     }     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php ReflectionIntersectionType::getTypes ReflectionIntersectionType::getTypes ==================================== (PHP 8 >= 8.1.0) ReflectionIntersectionType::getTypes — Returns the types included in the intersection type ### Description ``` public ReflectionIntersectionType::getTypes(): array ``` Returns the reflections of types included in the intersection type. ### Parameters This function has no parameters. ### Return Values An array of [ReflectionType](class.reflectiontype) objects. ### Examples **Example #1 **ReflectionIntersectionType::getTypes()** example** ``` <?php function someFunction(Iterator&Countable $value) {} $reflectionFunc = new ReflectionFunction('someFunction'); $reflectionParam = $reflectionFunc->getParameters()[0]; var_dump($reflectionParam->getType()->getTypes()); ?> ``` The above example will output something similar to: ``` array(2) { [0] => class ReflectionNamedType#4(0) { } [1] => class ReflectionNamedType#5(0) { } } ``` ### See Also * [ReflectionType::allowsNull()](reflectiontype.allowsnull) - Checks if null is allowed * [ReflectionParameter::getType()](reflectionparameter.gettype) - Gets a parameter's type php stream_filter_remove stream\_filter\_remove ====================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) stream\_filter\_remove — Remove a filter from a stream ### Description ``` stream_filter_remove(resource $stream_filter): bool ``` Removes a stream filter previously added to a stream with [stream\_filter\_prepend()](function.stream-filter-prepend) or [stream\_filter\_append()](function.stream-filter-append). Any data remaining in the filter's internal buffer will be flushed through to the next filter before removing it. ### Parameters `stream_filter` The stream filter to be removed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Dynamically refiltering a stream** ``` <?php /* Open a test file for reading and writing */ $fp = fopen("test.txt", "rw"); $rot13_filter = stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE); fwrite($fp, "This is "); stream_filter_remove($rot13_filter); fwrite($fp, "a test\n"); rewind($fp); fpassthru($fp); fclose($fp); ?> ``` The above example will output: ``` Guvf vf a test ``` ### See Also * [stream\_filter\_register()](function.stream-filter-register) - Register a user defined stream filter * [stream\_filter\_append()](function.stream-filter-append) - Attach a filter to a stream * [stream\_filter\_prepend()](function.stream-filter-prepend) - Attach a filter to a stream
programming_docs
php None Attributes overview ------------------- (PHP 8) Attributes offer the ability to add structured, machine-readable metadata information on declarations in code: Classes, methods, functions, parameters, properties and class constants can be the target of an attribute. The metadata defined by attributes can then be inspected at runtime using the [Reflection APIs](https://www.php.net/manual/en/book.reflection.php). Attributes could therefore be thought of as a configuration language embedded directly into code. With attributes the generic implementation of a feature and its concrete use in an application can be decoupled. In a way it is comparable to interfaces and their implementations. But where interfaces and implementations are about code, attributes are about annotating extra information and configuration. Interfaces can be implemented by classes, yet attributes can also be declared on methods, functions, parameters, properties and class constants. As such they are more flexible than interfaces. A simple example of attribute usage is to convert an interface that has optional methods to use attributes. Lets assume an `ActionHandler` interface representing an operation in an application, where some implementations of an action handler require setup and others do not. Instead of requiring all classes that implement `ActionHandler` to implement a method `setUp()`, an attribute can be used. One benefit of this approach is that we can use the attribute several times. **Example #1 Implementing optional methods of an interface with Attributes** ``` <?php interface ActionHandler {     public function execute(); } #[Attribute] class SetUp {} class CopyFile implements ActionHandler {     public string $fileName;     public string $targetDirectory;     #[SetUp]     public function fileExists()     {         if (!file_exists($this->fileName)) {             throw new RuntimeException("File does not exist");         }     }     #[SetUp]     public function targetDirectoryExists()     {         if (!file_exists($this->targetDirectory)) {             mkdir($this->targetDirectory);         } elseif (!is_dir($this->targetDirectory)) {             throw new RuntimeException("Target directory $this->targetDirectory is not a directory");         }     }     public function execute()     {         copy($this->fileName, $this->targetDirectory . '/' . basename($this->fileName));     } } function executeAction(ActionHandler $actionHandler) {     $reflection = new ReflectionObject($actionHandler);     foreach ($reflection->getMethods() as $method) {         $attributes = $method->getAttributes(SetUp::class);         if (count($attributes) > 0) {             $methodName = $method->getName();             $actionHandler->$methodName();         }     }     $actionHandler->execute(); } $copyAction = new CopyFile(); $copyAction->fileName = "/tmp/foo.jpg"; $copyAction->targetDirectory = "/home/user"; executeAction($copyAction); ``` php ArrayIterator::count ArrayIterator::count ==================== (PHP 5, PHP 7, PHP 8) ArrayIterator::count — Count elements ### Description ``` public ArrayIterator::count(): int ``` Gets the number of elements in the array, or the number of public properties in the object. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The number of elements or public properties in the associated array or object, respectively. ### See Also * [ArrayIterator::getFlags()](arrayiterator.getflags) - Get behavior flags php Locale::getDisplayName Locale::getDisplayName ====================== locale\_get\_display\_name ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Locale::getDisplayName -- locale\_get\_display\_name — Returns an appropriately localized display name for the input locale ### Description Object-oriented style ``` public static Locale::getDisplayName(string $locale, ?string $displayLocale = null): string|false ``` Procedural style ``` locale_get_display_name(string $locale, ?string $displayLocale = null): string|false ``` Returns an appropriately localized display name for the input locale. If `locale` is **`null`** then the default locale is used. ### Parameters `locale` The locale to return a display name for. `displayLocale` optional format locale ### Return Values Display name of the locale in the format appropriate for `displayLocale`, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `displayLocale` is nullable now. | ### Examples **Example #1 **locale\_get\_display\_name()** example** ``` <?php echo locale_get_display_name('sl-Latn-IT-nedis', 'en'); echo ";\n"; echo locale_get_display_name('sl-Latn-IT-nedis', 'fr'); echo ";\n"; echo locale_get_display_name('sl-Latn-IT-nedis', 'de'); ?> ``` **Example #2 OO example** ``` <?php echo Locale::getDisplayName('sl-Latn-IT-nedis', 'en'); echo ";\n"; echo Locale::getDisplayName('sl-Latn-IT-nedis', 'fr'); echo ";\n"; echo Locale::getDisplayName('sl-Latn-IT-nedis', 'de'); ?> ``` The above example will output: ``` Slovenian (Latin, Italy, Natisone dialect); slov\xc3\xa8ne (latin, Italie, dialecte de Natisone; Slowenisch (Lateinisch, Italien, NEDIS) ``` ### See Also * [locale\_get\_display\_language()](locale.getdisplaylanguage) - Returns an appropriately localized display name for language of the inputlocale * [locale\_get\_display\_script()](locale.getdisplayscript) - Returns an appropriately localized display name for script of the input locale * [locale\_get\_display\_region()](locale.getdisplayregion) - Returns an appropriately localized display name for region of the input locale * [locale\_get\_display\_variant()](locale.getdisplayvariant) - Returns an appropriately localized display name for variants of the input locale php ReflectionProperty::hasDefaultValue ReflectionProperty::hasDefaultValue =================================== (PHP 8) ReflectionProperty::hasDefaultValue — Checks if property has a default value declared ### Description ``` public ReflectionProperty::hasDefaultValue(): bool ``` Checks whether the property was declared with a default value, including an implicit **`null`** default value. Only returns **`false`** for typed properties without default value (or dynamic properties). ### Parameters This function has no parameters. ### Return Values If the property has any default value (including **`null`**) **`true`** is returned; if the property is typed without a default value declared or is a dynamic property, **`false`** is returned. ### Examples **Example #1 **ReflectionProperty::hasDefaultValue()** example** ``` <?php class Foo {     public $bar;     public ?int $baz;     public ?int $foo = null;     public int $boing;          public function __construct()     {         $this->ping = '';     } } $ro = new ReflectionObject(new Foo()); var_dump($ro->getProperty('bar')->hasDefaultValue()); var_dump($ro->getProperty('baz')->hasDefaultValue()); var_dump($ro->getProperty('foo')->hasDefaultValue()); var_dump($ro->getProperty('boing')->hasDefaultValue()); var_dump($ro->getProperty('ping')->hasDefaultValue()); // Dynamic property var_dump($ro->getProperty('pong')->hasDefaultValue()); // Not defined property ?> ``` The above example will output: ``` bool(true) bool(false) bool(true) bool(false) bool(false) Fatal error: Uncaught ReflectionException: Property Foo::$pong does not exist in example.php ``` ### See Also * [ReflectionProperty::getDefaultValue()](reflectionproperty.getdefaultvalue) - Returns the default value declared for a property php SolrQuery::setStart SolrQuery::setStart =================== (PECL solr >= 0.9.2) SolrQuery::setStart — Specifies the number of rows to skip ### Description ``` public SolrQuery::setStart(int $start): SolrQuery ``` Specifies the number of rows to skip. Useful in pagination of results. ### Parameters `start` The number of rows to skip. ### Return Values Returns the current SolrQuery object. php SolrQuery::setExpandQuery SolrQuery::setExpandQuery ========================= (PECL solr >= 2.2.0) SolrQuery::setExpandQuery — Sets the expand.q parameter ### Description ``` public SolrQuery::setExpandQuery(string $q): SolrQuery ``` Sets the expand.q parameter. Overrides the main q parameter, determines which documents to include in the main group. ### Parameters `q` ### Return Values [SolrQuery](class.solrquery) ### See Also * [SolrQuery::setExpand()](solrquery.setexpand) - Enables/Disables the Expand Component * [SolrQuery::addExpandSortField()](solrquery.addexpandsortfield) - Orders the documents within the expanded groups (expand.sort parameter) * [SolrQuery::removeExpandSortField()](solrquery.removeexpandsortfield) - Removes an expand sort field from the expand.sort parameter * [SolrQuery::setExpandRows()](solrquery.setexpandrows) - Sets the number of rows to display in each group (expand.rows). Server Default 5 * [SolrQuery::addExpandFilterQuery()](solrquery.addexpandfilterquery) - Overrides main filter query, determines which documents to include in the main group * [SolrQuery::removeExpandFilterQuery()](solrquery.removeexpandfilterquery) - Removes an expand filter query php mcrypt_enc_get_modes_name mcrypt\_enc\_get\_modes\_name ============================= (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_enc\_get\_modes\_name — Returns the name of the opened mode **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_enc_get_modes_name(resource $td): string ``` This function returns the name of the mode. ### Parameters `td` The encryption descriptor. ### Return Values Returns the name as a string. ### Examples **Example #1 **mcrypt\_enc\_get\_modes\_name()** example** ``` <?php $td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, ''); echo mcrypt_enc_get_modes_name($td). "\n"; $td = mcrypt_module_open ('cast-256', '', 'ecb', ''); echo mcrypt_enc_get_modes_name($td). "\n"; ?> ``` The above example will output: ``` CFB ECB ``` php SplSubject::attach SplSubject::attach ================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplSubject::attach — Attach an SplObserver ### Description ``` public SplSubject::attach(SplObserver $observer): void ``` Attaches an [SplObserver](class.splobserver) so that it can be notified of updates. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `observer` The [SplObserver](class.splobserver) to attach. ### Return Values No value is returned. php levenshtein levenshtein =========== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) levenshtein — Calculate Levenshtein distance between two strings ### Description ``` levenshtein( string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1 ): int ``` The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform `string1` into `string2`. The complexity of the algorithm is `O(m*n)`, where `n` and `m` are the length of `string1` and `string2` (rather good when compared to [similar\_text()](function.similar-text), which is `O(max(n,m)**3)`, but still expensive). If `insertion_cost`, `replacement_cost` and/or `deletion_cost` are unequal to `1`, the algorithm adapts to choose the cheapest transforms. E.g. if `$insertion_cost + $deletion_cost < $replacement_cost`, no replacements will be done, but rather inserts and deletions instead. ### Parameters `string1` One of the strings being evaluated for Levenshtein distance. `string2` One of the strings being evaluated for Levenshtein distance. `insertion_cost` Defines the cost of insertion. `replacement_cost` Defines the cost of replacement. `deletion_cost` Defines the cost of deletion. ### Return Values This function returns the Levenshtein-Distance between the two argument strings. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Prior to this version, **levenshtein()** had to be called with either two or five arguments. | | 8.0.0 | Prior to this version, **levenshtein()** would return `-1` if one of the argument strings is longer than 255 characters. | ### Examples **Example #1 **levenshtein()** example** ``` <?php // input misspelled word $input = 'carrrot'; // array of words to check against $words  = array('apple','pineapple','banana','orange',                 'radish','carrot','pea','bean','potato'); // no shortest distance found, yet $shortest = -1; // loop through words to find the closest foreach ($words as $word) {     // calculate the distance between the input word,     // and the current word     $lev = levenshtein($input, $word);     // check for an exact match     if ($lev == 0) {         // closest word is this one (exact match)         $closest = $word;         $shortest = 0;         // break out of the loop; we've found an exact match         break;     }     // if this distance is less than the next found shortest     // distance, OR if a next shortest word has not yet been found     if ($lev <= $shortest || $shortest < 0) {         // set the closest match, and shortest distance         $closest  = $word;         $shortest = $lev;     } } echo "Input word: $input\n"; if ($shortest == 0) {     echo "Exact match found: $closest\n"; } else {     echo "Did you mean: $closest?\n"; } ?> ``` The above example will output: ``` Input word: carrrot Did you mean: carrot? ``` ### See Also * [soundex()](function.soundex) - Calculate the soundex key of a string * [similar\_text()](function.similar-text) - Calculate the similarity between two strings * [metaphone()](function.metaphone) - Calculate the metaphone key of a string php Yaf_Plugin_Abstract::postDispatch Yaf\_Plugin\_Abstract::postDispatch =================================== (Yaf >=1.0.0) Yaf\_Plugin\_Abstract::postDispatch — The postDispatch purpose ### Description ``` public Yaf_Plugin_Abstract::postDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `request` `response` ### Return Values php ZipArchive::registerCancelCallback ZipArchive::registerCancelCallback ================================== (PHP >= 8.0.0, PECL zip >= 1.17.0) ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close. ### Description ``` public ZipArchive::registerCancelCallback(callable $callback): bool ``` Register a `callback` function to allow cancellation during archive close. ### Parameters `callback` If this function return 0 operation will continue, other value it will be cancelled. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples This example creates a ZIP file archive php.zip and cancel operation on some run condition. **Example #1 Archive a file** ``` <?php $zip = new ZipArchive(); if ($zip->open('php.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {     $zip->addFile(PHP_BINARY, 'php');     $zip->registerCancelCallback(function () {         return ($someruncondition ? -1 : 0);     });     $zip->close(); } ``` ### Notes > > **Note**: > > > This function is only available if built against libzip ≥ 1.6.0. > > ### See Also * [ZipArchive::registerProgressCallback()](ziparchive.registerprogresscallback) - Register a callback to provide updates during archive close. php ReflectionZendExtension::__toString ReflectionZendExtension::\_\_toString ===================================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionZendExtension::\_\_toString — To string handler ### Description ``` public ReflectionZendExtension::__toString(): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Stomp::unsubscribe Stomp::unsubscribe ================== stomp\_unsubscribe ================== (PECL stomp >= 0.1.0) Stomp::unsubscribe -- stomp\_unsubscribe — Removes an existing subscription ### Description Object-oriented style (method): ``` public Stomp::unsubscribe(string $destination, array $headers = ?): bool ``` Procedural style: ``` stomp_unsubscribe(resource $link, string $destination, array $headers = ?): bool ``` Removes an existing subscription. ### Parameters `link` Procedural style only: The stomp link identifier returned by [stomp\_connect()](stomp.construct). `destination` Subscription to remove. `headers` Associative array containing the additional headers (example: receipt). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples See [stomp\_ack()](stomp.ack). ### Notes **Tip**Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached. php ImagickPixel::isSimilar ImagickPixel::isSimilar ======================= (PECL imagick 2, PECL imagick 3) ImagickPixel::isSimilar — Check the distance between this color and another ### Description ``` public ImagickPixel::isSimilar(ImagickPixel $color, float $fuzz): bool ``` **Warning**This function is currently not documented; only its argument list is available. Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar. Deprecated in favour of [ImagickPixel::isPixelSimilar()](imagickpixel.ispixelsimilar). ### Parameters `color` The ImagickPixel object to compare this object against. `fuzz` The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732). ### Return Values Returns **`true`** on success. ### Examples **Example #1 **ImagickPixel::isSimilar()**** ``` <?php         // The tests below are written with the maximum distance expressed as 255         // so we need to scale them by the square root of 3 - the diagonal length         // of a unit cube.         $root3 = 1.732050807568877;         $tests = array(             ['rgb(245, 0, 0)',      'rgb(255, 0, 0)',   9 / $root3,         false,],             ['rgb(245, 0, 0)',      'rgb(255, 0, 0)',  10 / $root3,         true,],             ['rgb(0, 0, 0)',        'rgb(7, 7, 0)',     9 / $root3,         false,],             ['rgb(0, 0, 0)',        'rgb(7, 7, 0)',    10 / $root3,         true,],             ['rgba(0, 0, 0, 1)',    'rgba(7, 7, 0, 1)', 9 / $root3,         false,],             ['rgba(0, 0, 0, 1)',    'rgba(7, 7, 0, 1)',    10 / $root3,     true,],             ['rgb(128, 128, 128)',  'rgb(128, 128, 120)',   7 / $root3,     false,],             ['rgb(128, 128, 128)',  'rgb(128, 128, 120)',   8 / $root3,     true,],             ['rgb(0, 0, 0)',        'rgb(255, 255, 255)',   254.9,          false,],             ['rgb(0, 0, 0)',        'rgb(255, 255, 255)',   255,            true,],             ['rgb(255, 0, 0)',      'rgb(0, 255, 255)',     254.9,          false,],             ['rgb(255, 0, 0)',      'rgb(0, 255, 255)',     255,            true,],             ['black',               'rgba(0, 0, 0)',        0.0,            true],             ['black',               'rgba(10, 0, 0, 1.0)',  10.0 / $root3,  true],);         $output = "<table width='100%' class='infoTable'><thead>                 <tr>                 <th>                 Color 1                 </th>                 <th>                 Color 2                 </th>                 <th>                     Test distance * 255                 </th>                 <th>                     Is within distance                 </th>                 </tr>         </thead>";         $output .= "<tbody>";         foreach ($tests as $testInfo) {             $color1 = $testInfo[0];             $color2 = $testInfo[1];             $distance = $testInfo[2];             $expectation = $testInfo[3];             $testDistance = ($distance / 255.0);             $color1Pixel = new \ImagickPixel($color1);             $color2Pixel = new \ImagickPixel($color2);             $isSimilar = $color1Pixel->isPixelSimilar($color2Pixel, $testDistance);             if ($isSimilar !== $expectation) {                 echo "Test distance failed. Color [$color1] compared to color [$color2] is not within distance $testDistance FAILED.".NL;             }             $layout = "<tr>                 <td>%s</td>                 <td>%s</td>                 <td>%s</td>                 <td style='text-align: center;'>%s</td>             </tr>";                          $output .= sprintf(                 $layout,                 $color1,                 $color2,                 $distance,                 $isSimilar ? 'yes' : 'no'             );         }         $output .= "</tbody></table>";                  return $output; ?> ```
programming_docs
php mysqli::ssl_set mysqli::ssl\_set ================ mysqli\_ssl\_set ================ (PHP 5, PHP 7, PHP 8) mysqli::ssl\_set -- mysqli\_ssl\_set — Used for establishing secure connections using SSL ### Description Object-oriented style ``` public mysqli::ssl_set( ?string $key, ?string $certificate, ?string $ca_certificate, ?string $ca_path, ?string $cipher_algos ): bool ``` Procedural style ``` mysqli_ssl_set( mysqli $mysql, ?string $key, ?string $certificate, ?string $ca_certificate, ?string $ca_path, ?string $cipher_algos ): bool ``` Used for establishing secure connections using SSL. It must be called before [mysqli\_real\_connect()](mysqli.real-connect). This function does nothing unless OpenSSL support is enabled. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `key` The path name to the key file. `certificate` The path name to the certificate file. `ca_certificate` The path name to the certificate authority file. `ca_path` The pathname to a directory that contains trusted SSL CA certificates in PEM format. `cipher_algos` A list of allowable ciphers to use for SSL encryption. ### Return Values This function always returns **`true`** value. If SSL setup is incorrect [mysqli\_real\_connect()](mysqli.real-connect) will return an error when you attempt to connect. ### See Also * [mysqli\_options()](mysqli.options) - Set options * [mysqli\_real\_connect()](mysqli.real-connect) - Opens a connection to a mysql server php Yaf_Request_Abstract::isXmlHttpRequest Yaf\_Request\_Abstract::isXmlHttpRequest ======================================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::isXmlHttpRequest — Determine if request is AJAX request ### Description ``` public Yaf_Request_Abstract::isXmlHttpRequest(): bool ``` ### Parameters This function has no parameters. ### Return Values boolean ### See Also * [Yaf\_Request\_Abstract::isHead()](yaf-request-abstract.ishead) - Determine if request is HEAD request * [Yaf\_Request\_Abstract::isCli()](yaf-request-abstract.iscli) - Determine if request is CLI request * [Yaf\_Request\_Abstract::isPost()](yaf-request-abstract.ispost) - Determine if request is POST request * [Yaf\_Request\_Abstract::isPut()](yaf-request-abstract.isput) - Determine if request is PUT request * [Yaf\_Request\_Abstract::isOptions()](yaf-request-abstract.isoptions) - Determine if request is OPTIONS request * [Yaf\_Request\_Abstract::isGet()](yaf-request-abstract.isget) - Determine if request is GET request php Imagick::getImageHistogram Imagick::getImageHistogram ========================== (PECL imagick 2, PECL imagick 3) Imagick::getImageHistogram — Gets the image histogram ### Description ``` public Imagick::getImageHistogram(): array ``` Returns the image histogram as an array of ImagickPixel objects. ### Parameters This function has no parameters. ### Return Values Returns the image histogram as an array of ImagickPixel objects. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Generates **Imagick::getImageHistogram()**** ``` <?php function getColorStatistics($histogramElements, $colorChannel) {     $colorStatistics = [];     foreach ($histogramElements as $histogramElement) {         $color = $histogramElement->getColorValue($colorChannel);         $color = intval($color * 255);         $count = $histogramElement->getColorCount();         if (array_key_exists($color, $colorStatistics)) {             $colorStatistics[$color] += $count;         }         else {             $colorStatistics[$color] = $count;         }     }     ksort($colorStatistics);          return $colorStatistics; }      function getImageHistogram($imagePath) {     $backgroundColor = 'black';     $draw = new \ImagickDraw();     $draw->setStrokeWidth(0); //make the lines be as thin as possible     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     $histogramWidth = 256;     $histogramHeight = 100; // the height for each RGB segment     $imagick = new \Imagick(realpath($imagePath));     //Resize the image to be small, otherwise PHP tends to run out of memory     //This might lead to bad results for images that are pathologically 'pixelly'     $imagick->adaptiveResizeImage(200, 200, true);     $histogramElements = $imagick->getImageHistogram();     $histogram = new \Imagick();     $histogram->newpseudoimage($histogramWidth, $histogramHeight * 3, 'xc:black');     $histogram->setImageFormat('png');     $getMax = function ($carry, $item)  {         if ($item > $carry) {             return $item;         }         return $carry;     };     $colorValues = [         'red' => getColorStatistics($histogramElements, \Imagick::COLOR_RED),         'lime' => getColorStatistics($histogramElements, \Imagick::COLOR_GREEN),         'blue' => getColorStatistics($histogramElements, \Imagick::COLOR_BLUE),     ];     $max = array_reduce($colorValues['red'] , $getMax, 0);     $max = array_reduce($colorValues['lime'] , $getMax, $max);     $max = array_reduce($colorValues['blue'] , $getMax, $max);     $scale =  $histogramHeight / $max;     $count = 0;     foreach ($colorValues as $color => $values) {         $draw->setstrokecolor($color);         $offset = ($count + 1) * $histogramHeight;         foreach ($values as $index => $value) {             $draw->line($index, $offset, $index, $offset - ($value * $scale));         }         $count++;     }     $histogram->drawImage($draw);          header( "Content-Type: image/png" );     echo $histogram; } ?> ``` php Imagick::rotationalBlurImage Imagick::rotationalBlurImage ============================ (PECL imagick 3 >= 3.3.0) Imagick::rotationalBlurImage — Description ### Description ``` public Imagick::rotationalBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` Rotational blurs an image. ### Parameters `angle` The angle to apply the blur over. `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) using bitwise operators. Defaults to **`Imagick::CHANNEL_DEFAULT`**. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::rotationalBlurImage()**** ``` <?php function rotationalBlurImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->rotationalBlurImage(3);     $imagick->rotationalBlurImage(5);     $imagick->rotationalBlurImage(7);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php gzeof gzeof ===== (PHP 4, PHP 5, PHP 7, PHP 8) gzeof — Test for EOF on a gz-file pointer ### Description ``` gzeof(resource $stream): bool ``` Tests the given GZ file pointer for EOF. ### Parameters `stream` The gz-file pointer. It must be valid, and must point to a file successfully opened by [gzopen()](function.gzopen). ### Return Values Returns **`true`** if the gz-file pointer is at EOF or an error occurs; otherwise returns **`false`**. ### Examples **Example #1 **gzeof()** example** ``` <?php $gz = gzopen('somefile.gz', 'r'); while (!gzeof($gz)) {   echo gzgetc($gz); } gzclose($gz); ?> ``` php php_user_filter::__construct php\_user\_filter::\_\_construct ================================ (PHP 5, PHP 7, PHP 8) php\_user\_filter::\_\_construct — Construct a new php\_user\_filter instance ### Description public **php\_user\_filter::\_\_construct**() Constructs a new [php\_user\_filter](class.php-user-filter) instance. ### Parameters This function has no parameters. php ImagickDraw::comment ImagickDraw::comment ==================== (PECL imagick 2, PECL imagick 3) ImagickDraw::comment — Adds a comment ### Description ``` public ImagickDraw::comment(string $comment): bool ``` **Warning**This function is currently not documented; only its argument list is available. Adds a comment to a vector output stream. ### Parameters `comment` The comment string to add to vector output stream ### Return Values No value is returned. php openssl_pkey_new openssl\_pkey\_new ================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) openssl\_pkey\_new — Generates a new private key ### Description ``` openssl_pkey_new(?array $options = null): OpenSSLAsymmetricKey|false ``` **openssl\_pkey\_new()** generates a new private key. How to obtain the public component of the key is shown in an example below. > **Note**: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under [the installation section](https://www.php.net/manual/en/openssl.installation.php) for more information. > > ### Parameters `options` You can finetune the key generation (such as specifying the number of bits) using `options`. See [openssl\_csr\_new()](function.openssl-csr-new) for more information about `options`. ### Return Values Returns an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) instance for the pkey on success, or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` was returned. | | 7.1.0 | The `curve_name` option was added to make it possible to create EC keys. | ### Examples **Example #1 Obtain the public key from a private key** ``` <?php $private_key = openssl_pkey_new(); $public_key_pem = openssl_pkey_get_details($private_key)['key']; echo $public_key_pem; $public_key = openssl_pkey_get_public($public_key_pem); var_dump($public_key); ?> ``` The above example will output something similar to: ``` -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZFsmN2P6rx1Xt7YV95o gcdlal0k3ryiIhFNzjwtRNNTXfEfBr6lUuaIJYQ8/XqEBX0hpcfuuF6tTRlonA3t WLME0QFD93YVsAaXcy76YqjjqcRRodIBphAbYyyMI/lXkQAdn7kbAmr7neSOsMYJ El9Wo4Hl4oG6e52ZnYHyqW9dxh4hX93eupR2TmcCdVf+r9xoHewP0KJYSHt7vDUX AQlWYcQiWHIadFsmL0orr6mutlXFReoHbesgKY9/3YLOu0JfxflSjIZ2JeL1NTl1 MsmODsUwgAUrwnWKKx+eQUP5g3GnSB3dPkRh9zRVRiLNWbCugyjrf3e6DgQWrW7j pwIDAQAB -----END PUBLIC KEY----- resource(5) of type (OpenSSL key) ``` php Imagick::getImageColors Imagick::getImageColors ======================= (PECL imagick 2, PECL imagick 3) Imagick::getImageColors — Gets the number of unique colors in the image ### Description ``` public Imagick::getImageColors(): int ``` Gets the number of unique colors in the image. ### Parameters This function has no parameters. ### Return Values Returns an int, the number of unique colors in the image. php ReflectionFiber::getExecutingFile ReflectionFiber::getExecutingFile ================================= (PHP 8 >= 8.1.0) ReflectionFiber::getExecutingFile — Get the file name of the current execution point ### Description ``` public ReflectionFiber::getExecutingFile(): string ``` Returns the full path and file name of the current execution point in the reflected [Fiber](class.fiber). If the fiber has not been started or has terminated, an [Error](class.error) is thrown. ### Parameters This function has no parameters. ### Return Values The full path and file name of the reflected fiber. php svn_fs_copy svn\_fs\_copy ============= (PECL svn >= 0.2.0) svn\_fs\_copy — Copies a file or a directory ### Description ``` svn_fs_copy( resource $from_root, string $from_path, resource $to_root, string $to_path ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Copies a file or a directory. ### Parameters `from_root` `from_path` `to_root` `to_path` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php xmlrpc_server_register_introspection_callback xmlrpc\_server\_register\_introspection\_callback ================================================= (PHP 4 >= 4.1.0, PHP 5, PHP 7) xmlrpc\_server\_register\_introspection\_callback — Register a PHP function to generate documentation ### Description ``` xmlrpc_server_register_introspection_callback(resource $server, string $function): bool ``` **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. **Warning**This function is currently not documented; only its argument list is available. php Ds\Deque::contains Ds\Deque::contains ================== (PECL ds >= 1.0.0) Ds\Deque::contains — Determines if the deque contains given values ### Description ``` public Ds\Deque::contains(mixed ...$values): bool ``` Determines if the deque contains all values. ### Parameters `values` Values to check. ### Return Values **`false`** if any of the provided `values` are not in the deque, **`true`** otherwise. ### Examples **Example #1 **Ds\Deque::contains()** example** ``` <?php $deque = new \Ds\Deque(['a', 'b', 'c', 1, 2, 3]); var_dump($deque->contains('a'));                // true var_dump($deque->contains('a', 'b'));           // true var_dump($deque->contains('c', 'd'));           // false var_dump($deque->contains(...['c', 'b', 'a'])); // true // Always strict var_dump($deque->contains(1));                  // true var_dump($deque->contains('1'));                // false var_dump($sequece->contains(...[]));               // true ?> ``` The above example will output something similar to: ``` bool(true) bool(true) bool(false) bool(true) bool(true) bool(false) bool(true) ``` php IntlCalendar::createInstance IntlCalendar::createInstance ============================ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::createInstance — Create a new IntlCalendar ### Description Object-oriented style ``` public static IntlCalendar::createInstance(IntlTimeZone|DateTimeZone|string|null $timezone = null, ?string $locale = null): ?IntlCalendar ``` Procedural style ``` intlcal_create_instance(IntlTimeZone|DateTimeZone|string|null $timezone = null, ?string $locale = null): ?IntlCalendar ``` Given a timezone and locale, this method creates an [IntlCalendar](class.intlcalendar) object. This factory method may return a subclass of [IntlCalendar](class.intlcalendar). The calendar created will represent the time instance at which it was created, based on the system time. The fields can all be cleared by calling **IntCalendar::clear()** with no arguments. See also [IntlGregorianCalendar::\_\_construct()](intlgregoriancalendar.construct). ### Parameters `timezone` The timezone to use. * **`null`**, in which case the default timezone will be used, as specified in the ini setting [date.timezone](https://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone) or through the function [date\_default\_timezone\_set()](function.date-default-timezone-set) and as returned by [date\_default\_timezone\_get()](function.date-default-timezone-get). * An [IntlTimeZone](class.intltimezone), which will be used directly. * A [DateTimeZone](class.datetimezone). Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICUʼs database, not PHPʼs. * A string, which should be a valid ICU timezone identifier. See [IntlTimeZone::createTimeZoneIDEnumeration()](intltimezone.createtimezoneidenumeration). Raw offsets such as `"GMT+08:30"` are also accepted. `locale` A locale to use or **`null`** to use [the default locale](https://www.php.net/manual/en/intl.configuration.php#ini.intl.default-locale). ### Return Values The created [IntlCalendar](class.intlcalendar) instance or **`null`** on failure. ### Examples **Example #1 **IntlCalendar::createInstance()**** ``` <?php ini_set('intl.default_locale', 'es_ES'); ini_set('date.timezone', 'Europe/Madrid'); $cal = IntlCalendar::createInstance(); echo "No arguments\n"; var_dump(get_class($cal),         IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL)); echo "\n"; echo "Explicit timezone\n"; $cal = IntlCalendar::createInstance(IntlTimeZone::getGMT()); var_dump(get_class($cal),         IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL)); echo "\n"; echo "Explicit locale (with calendar)\n"; $cal = IntlCalendar::createInstance(NULL, 'es_ES@calendar=persian'); var_dump(get_class($cal),         IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL)); ``` The above example will output: ``` No arguments string(21) "IntlGregorianCalendar" string(68) "martes 18 de junio de 2013 14:11:02 Hora de verano de Europa Central" Explicit timezone string(21) "IntlGregorianCalendar" string(45) "martes 18 de junio de 2013 12:11:02 GMT+00:00" Explicit locale (with calendar) string(12) "IntlCalendar" string(70) "martes 28 de Khordad de 1392 14:11:02 Hora de verano de Europa Central" ``` ### See Also * [IntlGregorianCalendar::\_\_construct()](intlgregoriancalendar.construct) - Create the Gregorian Calendar class php imagecolorresolve imagecolorresolve ================= (PHP 4, PHP 5, PHP 7, PHP 8) imagecolorresolve — Get the index of the specified color or its closest possible alternative ### Description ``` imagecolorresolve( GdImage $image, int $red, int $green, int $blue ): int ``` This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative. If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `red` Value of red component. `green` Value of green component. `blue` Value of blue component. ### Return Values Returns a color index. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Using **imagecoloresolve()** to get colors from an image** ``` <?php // Load an image $im = imagecreatefromgif('phplogo.gif'); // Get closest colors from the image $colors = array(); $colors[] = imagecolorresolve($im, 255, 255, 255); $colors[] = imagecolorresolve($im, 0, 0, 200); // Output print_r($colors); imagedestroy($im); ?> ``` The above example will output something similar to: ``` Array ( [0] => 89 [1] => 85 ) ``` ### See Also * [imagecolorclosest()](function.imagecolorclosest) - Get the index of the closest color to the specified color php ldap_count_entries ldap\_count\_entries ==================== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_count\_entries — Count the number of entries in a search ### Description ``` ldap_count_entries(LDAP\Connection $ldap, LDAP\Result $result): int ``` Returns the number of entries stored in the result of previous search operations. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `result` An [LDAP\Result](class.ldap-result) instance, returned by [ldap\_list()](function.ldap-list) or [ldap\_search()](function.ldap-search). ### Return Values Returns number of entries in the result, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `result` parameter expects an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ldap\_count\_entries()** example** Retrieve number of entries in the result. ``` // $ds is a valid LDAP\Connection instance for a directory server      $dn        = 'ou=example,dc=org';      $filter    = '(|(sn=Doe*)(givenname=John*))';      $justthese = array('ou', 'sn', 'givenname', 'mail');      $sr = ldap_search($ds, $dn, $filter, $justthese);      var_dump(ldap_count_entries($ds, $sr)); ``` The above example will output something similar to: ``` int(1) ```
programming_docs
php ldap_control_paged_result ldap\_control\_paged\_result ============================ (PHP 5 >= 5.4.0, PHP 7) ldap\_control\_paged\_result — Send LDAP pagination control **Warning** This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Instead the `controls` parameter of [ldap\_search()](function.ldap-search) should be used. See also [LDAP Controls](https://www.php.net/manual/en/ldap.controls.php) for details. ### Description ``` ldap_control_paged_result( resource $link, int $pagesize, bool $iscritical = false, string $cookie = "" ): bool ``` Enable LDAP pagination by sending the pagination control (page size, cookie...). ### Parameters `link` An LDAP resource, returned by [ldap\_connect()](function.ldap-connect). `pagesize` The number of entries by page. `iscritical` Indicates whether the pagination is critical or not. If true and if the server doesn't support pagination, the search will return no result. `cookie` An opaque structure sent by the server ([ldap\_control\_paged\_result\_response()](function.ldap-control-paged-result-response)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function has been removed. | | 7.4.0 | This function has been deprecated. | ### Examples The example below show the retrieval of the first page of a search paginated with one entry by page. **Example #1 LDAP pagination** ``` <?php      // $ds is a valid link identifier (see ldap_connect)      ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);      $dn        = 'ou=example,dc=org';      $filter    = '(|(sn=Doe*)(givenname=John*))';      $justthese = array('ou', 'sn', 'givenname', 'mail');      // enable pagination with a page size of 1.      ldap_control_paged_result($ds, 1);      $sr = ldap_search($ds, $dn, $filter, $justthese);      $info = ldap_get_entries($ds, $sr);      echo $info['count'] . ' entries returned' . PHP_EOL; ``` The example below show the retrieval of all the result paginated with 100 entries by page. **Example #2 LDAP pagination** ``` <?php      // $ds is a valid link identifier (see ldap_connect)      ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);      $dn        = 'ou=example,dc=org';      $filter    = '(|(sn=Doe*)(givenname=John*))';      $justthese = array('ou', 'sn', 'givenname', 'mail');      // enable pagination with a page size of 100.      $pageSize = 100;      $cookie = '';      do {          ldap_control_paged_result($ds, $pageSize, true, $cookie);          $result  = ldap_search($ds, $dn, $filter, $justthese);          $entries = ldap_get_entries($ds, $result);                        foreach ($entries as $e) {              echo $e['dn'] . PHP_EOL;          }          ldap_control_paged_result_response($ds, $result, $cookie);              } while($cookie !== null && $cookie != ''); ``` ### Notes > > **Note**: > > > Pagination control is a LDAPv3 protocol feature. > > ### See Also * [ldap\_control\_paged\_result\_response()](function.ldap-control-paged-result-response) - Retrieve the LDAP pagination cookie * [» RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation](http://www.faqs.org/rfcs/rfc2696) php fdf_close fdf\_close ========== (PHP 4, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_close — Close an FDF document ### Description ``` fdf_close(resource $fdf_document): void ``` Closes the FDF document. ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). ### Return Values No value is returned. ### See Also * [fdf\_open()](function.fdf-open) - Open a FDF document php Parle\Parser::nonassoc Parle\Parser::nonassoc ====================== (PECL parle >= 0.5.1) Parle\Parser::nonassoc — Declare a token with no associativity ### Description ``` public Parle\Parser::nonassoc(string $tok): void ``` Declare a terminal, that cannot appear more than once in the row. ### Parameters `tok` Token name. ### Return Values No value is returned. php Gmagick::getimageiterations Gmagick::getimageiterations =========================== (PECL gmagick >= Unknown) Gmagick::getimageiterations — Gets the image iterations ### Description ``` public Gmagick::getimageiterations(): int ``` Gets the image iterations. ### Parameters This function has no parameters. ### Return Values Returns the image iterations as an integer. ### Errors/Exceptions Throws an **GmagickException** on error. php The ReflectionFunction class The ReflectionFunction class ============================ Introduction ------------ (PHP 5, PHP 7, PHP 8) The **ReflectionFunction** class reports information about a function. Class synopsis -------------- class **ReflectionFunction** extends [ReflectionFunctionAbstract](class.reflectionfunctionabstract) { /\* Constants \*/ public const int [IS\_DEPRECATED](class.reflectionfunction#reflectionfunction.constants.is-deprecated); /\* Inherited properties \*/ public string [$name](class.reflectionfunctionabstract#reflectionfunctionabstract.props.name); /\* Methods \*/ public [\_\_construct](reflectionfunction.construct)([Closure](class.closure)|string `$function`) ``` public static export(string $name, string $return = ?): string ``` ``` public getClosure(): Closure ``` ``` public invoke(mixed ...$args): mixed ``` ``` public invokeArgs(array $args): mixed ``` ``` public isAnonymous(): bool ``` ``` public isDisabled(): bool ``` ``` public __toString(): string ``` /\* Inherited methods \*/ ``` private ReflectionFunctionAbstract::__clone(): void ``` ``` public ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array ``` ``` public ReflectionFunctionAbstract::getClosureScopeClass(): ?ReflectionClass ``` ``` public ReflectionFunctionAbstract::getClosureThis(): ?object ``` ``` public ReflectionFunctionAbstract::getClosureUsedVariables(): array ``` ``` public ReflectionFunctionAbstract::getDocComment(): string|false ``` ``` public ReflectionFunctionAbstract::getEndLine(): int|false ``` ``` public ReflectionFunctionAbstract::getExtension(): ?ReflectionExtension ``` ``` public ReflectionFunctionAbstract::getExtensionName(): string|false ``` ``` public ReflectionFunctionAbstract::getFileName(): string|false ``` ``` public ReflectionFunctionAbstract::getName(): string ``` ``` public ReflectionFunctionAbstract::getNamespaceName(): string ``` ``` public ReflectionFunctionAbstract::getNumberOfParameters(): int ``` ``` public ReflectionFunctionAbstract::getNumberOfRequiredParameters(): int ``` ``` public ReflectionFunctionAbstract::getParameters(): array ``` ``` public ReflectionFunctionAbstract::getReturnType(): ?ReflectionType ``` ``` public ReflectionFunctionAbstract::getShortName(): string ``` ``` public ReflectionFunctionAbstract::getStartLine(): int|false ``` ``` public ReflectionFunctionAbstract::getStaticVariables(): array ``` ``` public ReflectionFunctionAbstract::getTentativeReturnType(): ?ReflectionType ``` ``` public ReflectionFunctionAbstract::hasReturnType(): bool ``` ``` public ReflectionFunctionAbstract::hasTentativeReturnType(): bool ``` ``` public ReflectionFunctionAbstract::inNamespace(): bool ``` ``` public ReflectionFunctionAbstract::isClosure(): bool ``` ``` public ReflectionFunctionAbstract::isDeprecated(): bool ``` ``` public ReflectionFunctionAbstract::isGenerator(): bool ``` ``` public ReflectionFunctionAbstract::isInternal(): bool ``` ``` public ReflectionFunctionAbstract::isUserDefined(): bool ``` ``` public ReflectionFunctionAbstract::isVariadic(): bool ``` ``` public ReflectionFunctionAbstract::returnsReference(): bool ``` ``` abstract public ReflectionFunctionAbstract::__toString(): void ``` } Predefined Constants -------------------- ReflectionFunction Modifiers ---------------------------- **`ReflectionFunction::IS_DEPRECATED`** Indicates deprecated functions. Table of Contents ----------------- * [ReflectionFunction::\_\_construct](reflectionfunction.construct) — Constructs a ReflectionFunction object * [ReflectionFunction::export](reflectionfunction.export) — Exports function * [ReflectionFunction::getClosure](reflectionfunction.getclosure) — Returns a dynamically created closure for the function * [ReflectionFunction::invoke](reflectionfunction.invoke) — Invokes function * [ReflectionFunction::invokeArgs](reflectionfunction.invokeargs) — Invokes function args * [ReflectionFunction::isAnonymous](reflectionfunction.isanonymous) — Checks if a function is anonymous * [ReflectionFunction::isDisabled](reflectionfunction.isdisabled) — Checks if function is disabled * [ReflectionFunction::\_\_toString](reflectionfunction.tostring) — To string php ArrayObject::offsetSet ArrayObject::offsetSet ====================== (PHP 5, PHP 7, PHP 8) ArrayObject::offsetSet — Sets the value at the specified index to newval ### Description ``` public ArrayObject::offsetSet(mixed $key, mixed $value): void ``` Sets the value at the specified index to newval. ### Parameters `key` The index being set. `value` The new value for the `key`. ### Return Values No value is returned. ### Examples **Example #1 **ArrayObject::offsetSet()** example** ``` <?php class Example {     public $property = 'prop:public'; } $arrayobj = new ArrayObject(new Example()); $arrayobj->offsetSet(4, 'four'); $arrayobj->offsetSet('group', array('g1', 'g2')); var_dump($arrayobj); $arrayobj = new ArrayObject(array('zero','one')); $arrayobj->offsetSet(null, 'last'); var_dump($arrayobj); ?> ``` The above example will output: ``` object(ArrayObject)#1 (3) { ["property"]=> string(11) "prop:public" [4]=> string(4) "four" ["group"]=> array(2) { [0]=> string(2) "g1" [1]=> string(2) "g2" } } object(ArrayObject)#3 (3) { [0]=> string(4) "zero" [1]=> string(3) "one" [2]=> string(4) "last" } ``` ### See Also * [ArrayObject::append()](arrayobject.append) - Appends the value php SolrCollapseFunction::__toString SolrCollapseFunction::\_\_toString ================================== (PECL solr >= 2.2.0) SolrCollapseFunction::\_\_toString — Returns a string representing the constructed collapse function ### Description ``` public SolrCollapseFunction::__toString(): string ``` Returns a string representing the constructed collapse function ### Parameters This function has no parameters. ### Return Values php socket_setopt socket\_setopt ============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_setopt — Alias of [socket\_set\_option()](function.socket-set-option) ### Description This function is an alias of: [socket\_set\_option()](function.socket-set-option). php shmop_write shmop\_write ============ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) shmop\_write — Write data into shared memory block ### Description ``` shmop_write(Shmop $shmop, string $data, int $offset): int ``` **shmop\_write()** will write a string into shared memory block. ### Parameters `shmop` The shared memory block identifier created by [shmop\_open()](function.shmop-open) `data` A string to write into shared memory block `offset` Specifies where to start writing data inside the shared memory segment. ### Return Values The size of the written `data`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Prior to PHP 8.0.0, **`false`** was returned on failure. | | 8.0.0 | `shmop` expects a [Shmop](class.shmop) instance now; previously, a resource was expected. | ### Examples **Example #1 Writing to shared memory block** ``` <?php $shm_bytes_written = shmop_write($shm_id, $my_string, 0); ?> ``` This example will write data inside `$my_string` into shared memory block, `$shm_bytes_written` will contain the number of bytes written. ### See Also * [shmop\_read()](function.shmop-read) - Read data from shared memory block php stream_socket_accept stream\_socket\_accept ====================== (PHP 5, PHP 7, PHP 8) stream\_socket\_accept — Accept a connection on a socket created by [stream\_socket\_server()](function.stream-socket-server) ### Description ``` stream_socket_accept(resource $socket, ?float $timeout = null, string &$peer_name = null): resource|false ``` Accept a connection on a socket previously created by [stream\_socket\_server()](function.stream-socket-server). ### Parameters `socket` The server socket to accept a connection from. `timeout` Override the default socket accept timeout. Time should be given in seconds. By default, [default\_socket\_timeout](https://www.php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout) is used. `peer_name` Will be set to the name (address) of the client which connected, if included and available from the selected transport. > > **Note**: > > > Can also be determined later using [stream\_socket\_get\_name()](function.stream-socket-get-name). > > ### Return Values Returns a stream to the accepted socket connection or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `timeout` is now nullable. | ### Notes **Warning** This function should not be used with UDP server sockets. Instead, use [stream\_socket\_recvfrom()](function.stream-socket-recvfrom) and [stream\_socket\_sendto()](function.stream-socket-sendto). ### See Also * [stream\_socket\_server()](function.stream-socket-server) - Create an Internet or Unix domain server socket * [stream\_socket\_get\_name()](function.stream-socket-get-name) - Retrieve the name of the local or remote sockets * [stream\_set\_blocking()](function.stream-set-blocking) - Set blocking/non-blocking mode on a stream * [stream\_set\_timeout()](function.stream-set-timeout) - Set timeout period on a stream * [fgets()](function.fgets) - Gets line from file pointer * [fgetss()](function.fgetss) - Gets line from file pointer and strip HTML tags * [fwrite()](function.fwrite) - Binary-safe file write * [fclose()](function.fclose) - Closes an open file pointer * [feof()](function.feof) - Tests for end-of-file on a file pointer * [cURL Functions](https://www.php.net/manual/en/ref.curl.php) php SolrQuery::setFacetSort SolrQuery::setFacetSort ======================= (PECL solr >= 0.9.2) SolrQuery::setFacetSort — Determines the ordering of the facet field constraints ### Description ``` public SolrQuery::setFacetSort(int $facetSort, string $field_override = ?): SolrQuery ``` Determines the ordering of the facet field constraints ### Parameters `facetSort` Use SolrQuery::FACET\_SORT\_INDEX for sorting by index order or SolrQuery::FACET\_SORT\_COUNT for sorting by count. `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php SplQueue::enqueue SplQueue::enqueue ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplQueue::enqueue — Adds an element to the queue ### Description ``` public SplQueue::enqueue(mixed $value): void ``` Enqueues `value` at the end of the queue. > > **Note**: > > > **SplQueue::enqueue()** is an alias of [SplDoublyLinkedList::push()](spldoublylinkedlist.push). > > ### Parameters `value` The value to enqueue. ### Return Values No value is returned. php ImagickDraw::circle ImagickDraw::circle =================== (PECL imagick 2, PECL imagick 3) ImagickDraw::circle — Draws a circle ### Description ``` public ImagickDraw::circle( float $ox, float $oy, float $px, float $py ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a circle on the image. ### Parameters `ox` origin x coordinate `oy` origin y coordinate `px` perimeter x coordinate `py` perimeter y coordinate ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::circle()** example** ``` <?php function circle($strokeColor, $fillColor, $backgroundColor, $originX, $originY, $endX, $endY) {     //Create a ImagickDraw object to draw into.     $draw = new \ImagickDraw();     $strokeColor = new \ImagickPixel($strokeColor);     $fillColor = new \ImagickPixel($fillColor);     $draw->setStrokeOpacity(1);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(2);     $draw->setFontSize(72);     $draw->circle($originX, $originY, $endX, $endY);     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php mysqli_result::fetch_field mysqli\_result::fetch\_field ============================ mysqli\_fetch\_field ==================== (PHP 5, PHP 7, PHP 8) mysqli\_result::fetch\_field -- mysqli\_fetch\_field — Returns the next field in the result set ### Description Object-oriented style ``` public mysqli_result::fetch_field(): object|false ``` Procedural style ``` mysqli_fetch_field(mysqli_result $result): object|false ``` Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set. ### Parameters `result` Procedural style only: A [mysqli\_result](class.mysqli-result) object returned by [mysqli\_query()](mysqli.query), [mysqli\_store\_result()](mysqli.store-result), [mysqli\_use\_result()](mysqli.use-result) or [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result). ### Return Values Returns an object which contains field definition information or **`false`** if no field information is available. **Object properties**| Property | Description | | --- | --- | | name | The name of the column | | orgname | Original column name if an alias was specified | | table | The name of the table this field belongs to (if not calculated) | | orgtable | Original table name if an alias was specified | | def | Reserved for default value, currently always "" | | db | The name of the database | | catalog | The catalog name, always "def" | | max\_length | The maximum width of the field for the result set. | | length | The width of the field, as specified in the table definition. | | charsetnr | The character set number for the field. | | flags | An integer representing the bit-flags for the field. | | type | The data type used for this field | | decimals | The number of decimals used (for integer fields) | ### Examples **Example #1 Object-oriented style** ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5"; if ($result = $mysqli->query($query)) {     /* Get field information for all columns */     while ($finfo = $result->fetch_field()) {         printf("Name:     %s\n", $finfo->name);         printf("Table:    %s\n", $finfo->table);         printf("max. Len: %d\n", $finfo->max_length);         printf("Flags:    %d\n", $finfo->flags);         printf("Type:     %d\n\n", $finfo->type);     }     $result->close(); } /* close connection */ $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5"; if ($result = mysqli_query($link, $query)) {     /* Get field information for all fields */     while ($finfo = mysqli_fetch_field($result)) {         printf("Name:     %s\n", $finfo->name);         printf("Table:    %s\n", $finfo->table);         printf("max. Len: %d\n", $finfo->max_length);         printf("Flags:    %d\n", $finfo->flags);         printf("Type:     %d\n\n", $finfo->type);     }     mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Name: Name Table: Country max. Len: 11 Flags: 1 Type: 254 Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 ``` ### See Also * [mysqli\_num\_fields()](mysqli-result.field-count) - Gets the number of fields in the result set * [mysqli\_fetch\_field\_direct()](mysqli-result.fetch-field-direct) - Fetch meta-data for a single field * [mysqli\_fetch\_fields()](mysqli-result.fetch-fields) - Returns an array of objects representing the fields in a result set * [mysqli\_field\_seek()](mysqli-result.field-seek) - Set result pointer to a specified field offset
programming_docs
php The SplFileObject class The SplFileObject class ======================= Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) The SplFileObject class offers an object-oriented interface for a file. Class synopsis -------------- class **SplFileObject** extends [SplFileInfo](class.splfileinfo) implements [RecursiveIterator](class.recursiveiterator), [SeekableIterator](class.seekableiterator) { /\* Constants \*/ public const int [DROP\_NEW\_LINE](class.splfileobject#splfileobject.constants.drop-new-line); public const int [READ\_AHEAD](class.splfileobject#splfileobject.constants.read-ahead); public const int [SKIP\_EMPTY](class.splfileobject#splfileobject.constants.skip-empty); public const int [READ\_CSV](class.splfileobject#splfileobject.constants.read-csv); /\* Methods \*/ public [\_\_construct](splfileobject.construct)( string `$filename`, string `$mode` = "r", bool `$useIncludePath` = **`false`**, ?resource `$context` = **`null`** ) ``` public current(): string|array|false ``` ``` public eof(): bool ``` ``` public fflush(): bool ``` ``` public fgetc(): string|false ``` ``` public fgetcsv(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|false ``` ``` public fgets(): string ``` ``` public fgetss(string $allowable_tags = ?): string ``` ``` public flock(int $operation, int &$wouldBlock = null): bool ``` ``` public fpassthru(): int ``` ``` public fputcsv( array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n" ): int|false ``` ``` public fread(int $length): string|false ``` ``` public fscanf(string $format, mixed &...$vars): array|int|null ``` ``` public fseek(int $offset, int $whence = SEEK_SET): int ``` ``` public fstat(): array ``` ``` public ftell(): int|false ``` ``` public ftruncate(int $size): bool ``` ``` public fwrite(string $data, int $length = 0): int|false ``` ``` public getChildren(): null ``` ``` public getCsvControl(): array ``` ``` public getFlags(): int ``` ``` public getMaxLineLen(): int ``` ``` public hasChildren(): false ``` ``` public key(): int ``` ``` public next(): void ``` ``` public rewind(): void ``` ``` public seek(int $line): void ``` ``` public setCsvControl(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): void ``` ``` public setFlags(int $flags): void ``` ``` public setMaxLineLen(int $maxLength): void ``` ``` public valid(): bool ``` /\* Inherited methods \*/ ``` public SplFileInfo::getATime(): int|false ``` ``` public SplFileInfo::getBasename(string $suffix = ""): string ``` ``` public SplFileInfo::getCTime(): int|false ``` ``` public SplFileInfo::getExtension(): string ``` ``` public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo ``` ``` public SplFileInfo::getFilename(): string ``` ``` public SplFileInfo::getGroup(): int|false ``` ``` public SplFileInfo::getInode(): int|false ``` ``` public SplFileInfo::getLinkTarget(): string|false ``` ``` public SplFileInfo::getMTime(): int|false ``` ``` public SplFileInfo::getOwner(): int|false ``` ``` public SplFileInfo::getPath(): string ``` ``` public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo ``` ``` public SplFileInfo::getPathname(): string ``` ``` public SplFileInfo::getPerms(): int|false ``` ``` public SplFileInfo::getRealPath(): string|false ``` ``` public SplFileInfo::getSize(): int|false ``` ``` public SplFileInfo::getType(): string|false ``` ``` public SplFileInfo::isDir(): bool ``` ``` public SplFileInfo::isExecutable(): bool ``` ``` public SplFileInfo::isFile(): bool ``` ``` public SplFileInfo::isLink(): bool ``` ``` public SplFileInfo::isReadable(): bool ``` ``` public SplFileInfo::isWritable(): bool ``` ``` public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject ``` ``` public SplFileInfo::setFileClass(string $class = SplFileObject::class): void ``` ``` public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void ``` ``` public SplFileInfo::__toString(): string ``` } Predefined Constants -------------------- **`SplFileObject::DROP_NEW_LINE`** Drop newlines at the end of a line. **`SplFileObject::READ_AHEAD`** Read on rewind/next. **`SplFileObject::SKIP_EMPTY`** Skips empty lines in the file. This requires the **`READ_AHEAD`** flag be enabled, to work as expected. **`SplFileObject::READ_CSV`** Read lines as CSV rows. Table of Contents ----------------- * [SplFileObject::\_\_construct](splfileobject.construct) — Construct a new file object * [SplFileObject::current](splfileobject.current) — Retrieve current line of file * [SplFileObject::eof](splfileobject.eof) — Reached end of file * [SplFileObject::fflush](splfileobject.fflush) — Flushes the output to the file * [SplFileObject::fgetc](splfileobject.fgetc) — Gets character from file * [SplFileObject::fgetcsv](splfileobject.fgetcsv) — Gets line from file and parse as CSV fields * [SplFileObject::fgets](splfileobject.fgets) — Gets line from file * [SplFileObject::fgetss](splfileobject.fgetss) — Gets line from file and strip HTML tags * [SplFileObject::flock](splfileobject.flock) — Portable file locking * [SplFileObject::fpassthru](splfileobject.fpassthru) — Output all remaining data on a file pointer * [SplFileObject::fputcsv](splfileobject.fputcsv) — Write a field array as a CSV line * [SplFileObject::fread](splfileobject.fread) — Read from file * [SplFileObject::fscanf](splfileobject.fscanf) — Parses input from file according to a format * [SplFileObject::fseek](splfileobject.fseek) — Seek to a position * [SplFileObject::fstat](splfileobject.fstat) — Gets information about the file * [SplFileObject::ftell](splfileobject.ftell) — Return current file position * [SplFileObject::ftruncate](splfileobject.ftruncate) — Truncates the file to a given length * [SplFileObject::fwrite](splfileobject.fwrite) — Write to file * [SplFileObject::getChildren](splfileobject.getchildren) — No purpose * [SplFileObject::getCsvControl](splfileobject.getcsvcontrol) — Get the delimiter, enclosure and escape character for CSV * [SplFileObject::getCurrentLine](splfileobject.getcurrentline) — Alias of SplFileObject::fgets * [SplFileObject::getFlags](splfileobject.getflags) — Gets flags for the SplFileObject * [SplFileObject::getMaxLineLen](splfileobject.getmaxlinelen) — Get maximum line length * [SplFileObject::hasChildren](splfileobject.haschildren) — SplFileObject does not have children * [SplFileObject::key](splfileobject.key) — Get line number * [SplFileObject::next](splfileobject.next) — Read next line * [SplFileObject::rewind](splfileobject.rewind) — Rewind the file to the first line * [SplFileObject::seek](splfileobject.seek) — Seek to specified line * [SplFileObject::setCsvControl](splfileobject.setcsvcontrol) — Set the delimiter, enclosure and escape character for CSV * [SplFileObject::setFlags](splfileobject.setflags) — Sets flags for the SplFileObject * [SplFileObject::setMaxLineLen](splfileobject.setmaxlinelen) — Set maximum line length * [SplFileObject::\_\_toString](splfileobject.tostring) — Alias of SplFileObject::fgets * [SplFileObject::valid](splfileobject.valid) — Not at EOF php sodium_crypto_core_ristretto255_scalar_random sodium\_crypto\_core\_ristretto255\_scalar\_random ================================================== (PHP 8 >= 8.1.0) sodium\_crypto\_core\_ristretto255\_scalar\_random — Generates a random key ### Description ``` sodium_crypto_core_ristretto255_scalar_random(): string ``` Generates a random key. Available as of libsodium 1.0.18. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns a 32-byte random string. ### Examples **Example #1 **sodium\_crypto\_core\_ristretto255\_scalar\_random()** example** ``` <?php $foo = sodium_crypto_core_ristretto255_scalar_random(); $bar = sodium_crypto_core_ristretto255_scalar_random(); $value = sodium_crypto_core_ristretto255_scalar_add($foo, $bar); $value = sodium_crypto_core_ristretto255_scalar_sub($value, $bar); var_dump(hash_equals($foo, $value)); ?> ``` The above example will output: ``` bool(true) ``` ### See Also * [sodium\_crypto\_core\_ristretto255\_scalar\_add()](function.sodium-crypto-core-ristretto255-scalar-add) - Adds a scalar value * [sodium\_crypto\_core\_ristretto255\_scalar\_sub()](function.sodium-crypto-core-ristretto255-scalar-sub) - Subtracts a scalar value php Yaf_Route_Supervar::__construct Yaf\_Route\_Supervar::\_\_construct =================================== (Yaf >=1.0.0) Yaf\_Route\_Supervar::\_\_construct — The \_\_construct purpose ### Description public **Yaf\_Route\_Supervar::\_\_construct**(string `$supervar_name`) [Yaf\_Route\_Supervar](class.yaf-route-supervar) is similar with [Yaf\_Route\_Static](class.yaf-route-static), the difference is [Yaf\_Route\_Supervar](class.yaf-route-supervar) will look for path info in query string, and the parameter supervar\_name is the key. ### Parameters `supervar_name` The name of key. ### Return Values ### Examples **Example #1 **Yaf\_Route\_Supervar()**example** ``` <?php    /**     * Add a supervar route to Yaf_Router route stack     */     Yaf_Dispatcher::getInstance()->getRouter()->addRoute(         "name",         new Yaf_Route_Supervar("r")     ); ?> ``` The above example will output something similar to: ``` /** for request: http://yourdomain.com/xx/oo/?r=/ctr/act/var/value * will result in following: */ array ( "module" => index(default), "controller" => ctr, "action" => act, "params" => array( "var" => value, ) ) ``` ### See Also * [Yaf\_Router::addRoute()](yaf-router.addroute) - Add new Route into Router * [Yaf\_Router::addConfig()](yaf-router.addconfig) - Add config-defined routes into Router * [Yaf\_Route\_Static](class.yaf-route-static) * [Yaf\_Route\_Regex](class.yaf-route-regex) * [Yaf\_Route\_Simple](class.yaf-route-simple) * [Yaf\_Route\_Rewrite](class.yaf-route-rewrite) * [Yaf\_Route\_Map](class.yaf-route-map) php Yaf_Request_Abstract::getEnv Yaf\_Request\_Abstract::getEnv ============================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::getEnv — Retrieve ENV varialbe ### Description ``` public Yaf_Request_Abstract::getEnv(string $name, string $default = ?): void ``` Retrieve ENV variable ### Parameters `name` the variable name `default` if this parameter is provide, this will be returned if the varialbe can not be found ### Return Values Returns string ### See Also * [Yaf\_Request\_Abstract::getServer()](yaf-request-abstract.getserver) - Retrieve SERVER variable * [Yaf\_Request\_Abstract::getParam()](yaf-request-abstract.getparam) - Retrieve calling parameter php trigger_error trigger\_error ============== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) trigger\_error — Generates a user-level error/warning/notice message ### Description ``` trigger_error(string $message, int $error_level = E_USER_NOTICE): bool ``` Used to trigger a user error condition, it can be used in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler ([set\_error\_handler()](function.set-error-handler)). This function is useful when you need to generate a particular response to an exception at runtime. ### Parameters `message` The designated error message for this error. It's limited to 1024 bytes in length. Any additional characters beyond 1024 bytes will be truncated. `error_level` The designated error type for this error. It only works with the E\_USER family of constants, and will default to **`E_USER_NOTICE`**. ### Return Values This function returns **`false`** if wrong `error_level` is specified, **`true`** otherwise. ### Examples **Example #1 **trigger\_error()** example** See [set\_error\_handler()](function.set-error-handler) for a more extensive example. ``` <?php if ($divisor == 0) {     trigger_error("Cannot divide by zero", E_USER_ERROR); } ?> ``` ### Notes **Warning** HTML entities in `message` are not escaped. Use [htmlentities()](function.htmlentities) on the message if the error is to be displayed in a browser. ### See Also * [error\_reporting()](function.error-reporting) - Sets which PHP errors are reported * [set\_error\_handler()](function.set-error-handler) - Sets a user-defined error handler function * [restore\_error\_handler()](function.restore-error-handler) - Restores the previous error handler function * The [error level constants](https://www.php.net/manual/en/errorfunc.constants.php) php None elseif/else if -------------- (PHP 4, PHP 5, PHP 7, PHP 8) `elseif`, as its name suggests, is a combination of `if` and `else`. Like `else`, it extends an `if` statement to execute a different statement in case the original `if` expression evaluates to **`false`**. However, unlike `else`, it will execute that alternative expression only if the `elseif` conditional expression evaluates to **`true`**. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b: ``` <?php if ($a > $b) {     echo "a is bigger than b"; } elseif ($a == $b) {     echo "a is equal to b"; } else {     echo "a is smaller than b"; } ?> ``` There may be several `elseif`s within the same `if` statement. The first `elseif` expression (if any) that evaluates to **`true`** would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior. The `elseif` statement is only executed if the preceding `if` expression and any preceding `elseif` expressions evaluated to **`false`**, and the current `elseif` expression evaluated to **`true`**. > **Note**: Note that `elseif` and `else if` will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your `if`/`elseif` conditions, you must not separate `else if` into two words, or PHP will fail with a parse error. > > ``` <?php /* Incorrect Method: */ if ($a > $b):     echo $a." is greater than ".$b; else if ($a == $b): // Will not compile.     echo "The above line causes a parse error."; endif; /* Correct Method: */ if ($a > $b):     echo $a." is greater than ".$b; elseif ($a == $b): // Note the combination of the words.     echo $a." equals ".$b; else:     echo $a." is neither greater than or equal to ".$b; endif; ?> ``` php Closure::bindTo Closure::bindTo =============== (PHP 5 >= 5.4.0, PHP 7, PHP 8) Closure::bindTo — Duplicates the closure with a new bound object and class scope ### Description ``` public Closure::bindTo(?object $newThis, object|string|null $newScope = "static"): ?Closure ``` Create and return a new [anonymous function](functions.anonymous) with the same body and bound variables as this one, but possibly with a different bound object and a new class scope. The “bound object” determines the value `$this` will have in the function body and the “class scope” represents a class which determines which private and protected members the anonymous function will be able to access. Namely, the members that will be visible are the same as if the anonymous function were a method of the class given as value of the `newScope` parameter. Static closures cannot have any bound object (the value of the parameter `newThis` should be **`null`**), but this function can nevertheless be used to change their class scope. This function will ensure that for a non-static closure, having a bound instance will imply being scoped and vice-versa. To this end, non-static closures that are given a scope but a **`null`** instance are made static and non-static non-scoped closures that are given a non-null instance are scoped to an unspecified class. > > **Note**: > > > If you only want to duplicate the anonymous functions, you can use [cloning](language.oop5.cloning) instead. > > ### Parameters `newThis` The object to which the given anonymous function should be bound, or **`null`** for the closure to be unbound. `newScope` The class scope to which the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object. It is not allowed to pass (an object of) an internal class as this parameter. ### Return Values Returns the newly created [Closure](class.closure) object or **`null`** on failure. ### Examples **Example #1 **Closure::bindTo()** example** ``` <?php class A {     private $val;     function __construct($val) {         $this->val = $val;     }     function getClosure() {         //returns closure bound to this object and scope         return function() { return $this->val; };     } } $ob1 = new A(1); $ob2 = new A(2); $cl = $ob1->getClosure(); echo $cl(), "\n"; $cl = $cl->bindTo($ob2); echo $cl(), "\n"; ?> ``` The above example will output something similar to: ``` 1 2 ``` ### See Also * [Anonymous functions](functions.anonymous) * [Closure::bind()](closure.bind) - Duplicates a closure with a specific bound object and class scope php ImagickPixelIterator::getCurrentIteratorRow ImagickPixelIterator::getCurrentIteratorRow =========================================== (PECL imagick 2, PECL imagick 3) ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects ### Description ``` public ImagickPixelIterator::getCurrentIteratorRow(): array ``` **Warning**This function is currently not documented; only its argument list is available. Returns the current row as an array of ImagickPixel objects from the pixel iterator. ### Return Values Returns a row as an array of ImagickPixel objects that can themselves be iterated. php gnupg_getprotocol gnupg\_getprotocol ================== (PECL gnupg >= 0.1) gnupg\_getprotocol — Returns the currently active protocol for all operations ### Description ``` gnupg_getprotocol(resource $identifier): int ``` ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. ### Return Values Returns the currently active protocol, which can be one of **`GNUPG_PROTOCOL_OpenPGP`** or **`GNUPG_PROTOCOL_CMS`**. ### Examples **Example #1 Procedural **gnupg\_getprotocol()** example** ``` <?php $res = gnupg_init(); echo gnupg_getprotocol($res); ?> ``` **Example #2 OO **gnupg\_getprotocol()** example** ``` <?php $gpg = new gnupg(); echo $gpg->getprotocol(); ?> ``` php None Objects ------- ### Object Initialization To create a new object, use the `new` statement to instantiate a class: ``` <?php class foo {     function do_foo()     {         echo "Doing foo.";      } } $bar = new foo; $bar->do_foo(); ?> ``` For a full discussion, see the [Classes and Objects](https://www.php.net/manual/en/language.oop5.php) 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](class.stdclass) built-in class is created. If the value was **`null`**, the new instance will be empty. An array converts to an object with properties named by keys and corresponding values. Note that in this case before PHP 7.2.0 numeric keys have been inaccessible unless iterated. ``` <?php $obj = (object) array('1' => 'foo'); var_dump(isset($obj->{'1'})); // outputs 'bool(true)' as of PHP 7.2.0; 'bool(false)' previously var_dump(key($obj)); // outputs 'string(1) "1"' as of PHP 7.2.0; 'int(1)' previously ?> ``` For any other value, a member variable named `scalar` will contain the value. ``` <?php $obj = (object) 'ciao'; echo $obj->scalar;  // outputs 'ciao' ?> ```
programming_docs
php ReflectionParameter::canBePassedByValue ReflectionParameter::canBePassedByValue ======================================= (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value ### Description ``` public ReflectionParameter::canBePassedByValue(): bool ``` ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the parameter can be passed by value, **`false`** otherwise. Returns **`null`** in case of an error. php gmp_prob_prime gmp\_prob\_prime ================ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_prob\_prime — Check if number is "probably prime" ### Description ``` gmp_prob_prime(GMP|int|string $num, int $repetitions = 10): int ``` The function uses Miller-Rabin's probabilistic test to check if a number is a prime. ### Parameters `num` The number being checked as a prime. A [GMP](class.gmp) object, an int or a numeric string. `repetitions` Reasonable values of `repetitions` vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime. A [GMP](class.gmp) object, an int or a numeric string. ### Return Values If this function returns 0, `num` is definitely not prime. If it returns 1, then `num` is "probably" prime. If it returns 2, then `num` is surely prime. ### Examples **Example #1 **gmp\_prob\_prime()** example** ``` <?php // definitely not a prime echo gmp_prob_prime("6") . "\n"; // probably a prime echo gmp_prob_prime("1111111111111111111") . "\n"; // definitely a prime echo gmp_prob_prime("11") . "\n"; ?> ``` The above example will output: ``` 0 1 2 ``` php The BackedEnum interface The BackedEnum interface ======================== Introduction ------------ (PHP 8 >= 8.1.0) The **BackedEnum** interface is automatically applied to backed enumerations by the engine. It may not be implemented by user-defined classes. Enumerations may not override its methods, as default implementations are provided by the engine. It is available only for type checks. Interface synopsis ------------------ interface **BackedEnum** extends [UnitEnum](class.unitenum) { /\* Methods \*/ ``` public static from(int|string $value): static ``` ``` public static tryFrom(int|string $value): ?static ``` /\* Inherited methods \*/ ``` public static UnitEnum::cases(): array ``` } Table of Contents ----------------- * [BackedEnum::from](backedenum.from) — Maps a scalar to an enum instance * [BackedEnum::tryFrom](backedenum.tryfrom) — Maps a scalar to an enum instance or null php TypeError TypeError ========= Introduction ------------ (PHP 7, PHP 8) A **TypeError** may be thrown when: * The value being set for a class property does not match the property's corresponding declared type. * The argument type being passed to a function does not match its corresponding declared parameter type. * A value being returned from a function does not match the declared function return type. Class synopsis -------------- class **TypeError** extends [Error](class.error) { /\* Inherited properties \*/ protected string [$message](class.error#error.props.message) = ""; private string [$string](class.error#error.props.string) = ""; protected int [$code](class.error#error.props.code); protected string [$file](class.error#error.props.file) = ""; protected int [$line](class.error#error.props.line); private array [$trace](class.error#error.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.error#error.props.previous) = null; /\* Inherited methods \*/ ``` final public Error::getMessage(): string ``` ``` final public Error::getPrevious(): ?Throwable ``` ``` final public Error::getCode(): int ``` ``` final public Error::getFile(): string ``` ``` final public Error::getLine(): int ``` ``` final public Error::getTrace(): array ``` ``` final public Error::getTraceAsString(): string ``` ``` public Error::__toString(): string ``` ``` private Error::__clone(): void ``` } Changelog --------- | Version | Description | | --- | --- | | 7.1.0 | A **TypeError** is no longer thrown when an invalid number of arguments are passed to a built-in PHP function in strict mode. Instead, an [ArgumentCountError](class.argumentcounterror) is raised. | php The ArrayObject class The ArrayObject class ===================== Introduction ------------ (PHP 5, PHP 7, PHP 8) This class allows objects to work as arrays. Class synopsis -------------- class **ArrayObject** implements [IteratorAggregate](class.iteratoraggregate), [ArrayAccess](class.arrayaccess), [Serializable](class.serializable), [Countable](class.countable) { /\* Constants \*/ const int [STD\_PROP\_LIST](class.arrayobject#arrayobject.constants.std-prop-list); const int [ARRAY\_AS\_PROPS](class.arrayobject#arrayobject.constants.array-as-props); /\* Methods \*/ public [\_\_construct](arrayobject.construct)(array|object `$array` = [], int `$flags` = 0, string `$iteratorClass` = ArrayIterator::class) ``` public append(mixed $value): void ``` ``` public asort(int $flags = SORT_REGULAR): bool ``` ``` public count(): int ``` ``` public exchangeArray(array|object $array): array ``` ``` public getArrayCopy(): array ``` ``` public getFlags(): int ``` ``` public getIterator(): Iterator ``` ``` public getIteratorClass(): string ``` ``` public ksort(int $flags = SORT_REGULAR): bool ``` ``` public natcasesort(): bool ``` ``` public natsort(): bool ``` ``` public offsetExists(mixed $key): bool ``` ``` public offsetGet(mixed $key): mixed ``` ``` public offsetSet(mixed $key, mixed $value): void ``` ``` public offsetUnset(mixed $key): void ``` ``` public serialize(): string ``` ``` public setFlags(int $flags): void ``` ``` public setIteratorClass(string $iteratorClass): void ``` ``` public uasort(callable $callback): bool ``` ``` public uksort(callable $callback): bool ``` ``` public unserialize(string $data): void ``` } Predefined Constants -------------------- ArrayObject Flags ----------------- **`ArrayObject::STD_PROP_LIST`** Properties of the object have their normal functionality when accessed as list (var\_dump, foreach, etc.). **`ArrayObject::ARRAY_AS_PROPS`** Entries can be accessed as properties (read and write). Table of Contents ----------------- * [ArrayObject::append](arrayobject.append) — Appends the value * [ArrayObject::asort](arrayobject.asort) — Sort the entries by value * [ArrayObject::\_\_construct](arrayobject.construct) — Construct a new array object * [ArrayObject::count](arrayobject.count) — Get the number of public properties in the ArrayObject * [ArrayObject::exchangeArray](arrayobject.exchangearray) — Exchange the array for another one * [ArrayObject::getArrayCopy](arrayobject.getarraycopy) — Creates a copy of the ArrayObject * [ArrayObject::getFlags](arrayobject.getflags) — Gets the behavior flags * [ArrayObject::getIterator](arrayobject.getiterator) — Create a new iterator from an ArrayObject instance * [ArrayObject::getIteratorClass](arrayobject.getiteratorclass) — Gets the iterator classname for the ArrayObject * [ArrayObject::ksort](arrayobject.ksort) — Sort the entries by key * [ArrayObject::natcasesort](arrayobject.natcasesort) — Sort an array using a case insensitive "natural order" algorithm * [ArrayObject::natsort](arrayobject.natsort) — Sort entries using a "natural order" algorithm * [ArrayObject::offsetExists](arrayobject.offsetexists) — Returns whether the requested index exists * [ArrayObject::offsetGet](arrayobject.offsetget) — Returns the value at the specified index * [ArrayObject::offsetSet](arrayobject.offsetset) — Sets the value at the specified index to newval * [ArrayObject::offsetUnset](arrayobject.offsetunset) — Unsets the value at the specified index * [ArrayObject::serialize](arrayobject.serialize) — Serialize an ArrayObject * [ArrayObject::setFlags](arrayobject.setflags) — Sets the behavior flags * [ArrayObject::setIteratorClass](arrayobject.setiteratorclass) — Sets the iterator classname for the ArrayObject * [ArrayObject::uasort](arrayobject.uasort) — Sort the entries with a user-defined comparison function and maintain key association * [ArrayObject::uksort](arrayobject.uksort) — Sort the entries by keys using a user-defined comparison function * [ArrayObject::unserialize](arrayobject.unserialize) — Unserialize an ArrayObject php zip_entry_compressionmethod zip\_entry\_compressionmethod ============================= (PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0) zip\_entry\_compressionmethod — Retrieve the compression method of a directory entry **Warning**This function has been *DEPRECATED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` zip_entry_compressionmethod(resource $zip_entry): string|false ``` Returns the compression method of the directory entry specified by `zip_entry`. ### Parameters `zip_entry` A directory entry returned by [zip\_read()](function.zip-read). ### Return Values The compression method, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function is deprecated in favor of the Object API, see [ZipArchive::statIndex()](ziparchive.statindex). | ### See Also * [zip\_open()](function.zip-open) - Open a ZIP file archive * [zip\_read()](function.zip-read) - Read next entry in a ZIP file archive php Imagick::nextImage Imagick::nextImage ================== (PECL imagick 2, PECL imagick 3) Imagick::nextImage — Moves to the next image ### Description ``` public Imagick::nextImage(): bool ``` Associates the next image in the image list with an Imagick object. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. php base64_encode base64\_encode ============== (PHP 4, PHP 5, PHP 7, PHP 8) base64\_encode — Encodes data with MIME base64 ### Description ``` base64_encode(string $string): string ``` Encodes the given `string` with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies. Base64-encoded data takes about 33% more space than the original data. ### Parameters `string` The data to encode. ### Return Values The encoded data, as a string. ### Examples **Example #1 **base64\_encode()** example** ``` <?php $str = 'This is an encoded string'; echo base64_encode($str); ?> ``` The above example will output: ``` VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw== ``` ### See Also * [base64\_decode()](function.base64-decode) - Decodes data encoded with MIME base64 * [chunk\_split()](function.chunk-split) - Split a string into smaller chunks * [convert\_uuencode()](function.convert-uuencode) - Uuencode a string * [» RFC 2045](http://www.faqs.org/rfcs/rfc2045) section 6.8 php timezone_version_get timezone\_version\_get ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) timezone\_version\_get — Gets the version of the timezonedb ### Description ``` timezone_version_get(): string ``` Returns the current version of the timezonedb. ### Parameters This function has no parameters. ### Return Values Returns a string in the format `YYYY.increment`, such as `2022.2`. If you have a timezone database version that is old (for example, it doesn't show the current year), then you can update the timezone information by either upgrading your PHP version, or installing the [» timezonedb](https://pecl.php.net/package/timezonedb) PECL package. Some Linux distributions patch PHP's date/time support to use an alternative source for timezone information. In which case this function will return `0.system`. You are encouraged to install the [» timezonedb](https://pecl.php.net/package/timezonedb) PECL package in that case as well. ### Examples **Example #1 Getting the timezonedb version** ``` <?php echo timezone_version_get(); ?> ``` The above example will output something similar to: ``` 2022.2 ``` ### See Also * [List of Supported Timezones](https://www.php.net/manual/en/timezones.php) php SQLite3Stmt::readOnly SQLite3Stmt::readOnly ===================== (PHP 5 >= 5.3.6, PHP 7, PHP 8) SQLite3Stmt::readOnly — Returns whether a statement is definitely read only ### Description ``` public SQLite3Stmt::readOnly(): bool ``` Returns whether a statement is definitely read only. A statement is considered read only, if it makes no *direct* changes to the content of the database file. Note that user defined SQL functions might change the database *indirectly* as a side effect. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if a statement is definitely read only, **`false`** otherwise. php ssh2_fingerprint ssh2\_fingerprint ================= (PECL ssh2 >= 0.9.0) ssh2\_fingerprint — Retrieve fingerprint of remote server ### Description ``` ssh2_fingerprint(resource $session, int $flags = SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX): string ``` Returns a server hostkey hash from an active session. ### Parameters `session` An SSH connection link identifier, obtained from a call to [ssh2\_connect()](function.ssh2-connect). `flags` `flags` may be either of **`SSH2_FINGERPRINT_MD5`** or **`SSH2_FINGERPRINT_SHA1`** logically ORed with **`SSH2_FINGERPRINT_HEX`** or **`SSH2_FINGERPRINT_RAW`**. ### Return Values Returns the hostkey hash as a string. ### Examples **Example #1 Checking the fingerprint against a known value** ``` <?php $known_host = '6F89C2F0A719B30CC38ABDF90755F2E4'; $connection = ssh2_connect('shell.example.com', 22); $fingerprint = ssh2_fingerprint($connection,                SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX); if ($fingerprint != $known_host) {   die("HOSTKEY MISMATCH!\n" .       "Possible Man-In-The-Middle Attack?"); } ?> ``` php tidy::diagnose tidy::diagnose ============== tidy\_diagnose ============== (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy::diagnose -- tidy\_diagnose — Run configured diagnostics on parsed and repaired markup ### Description Object-oriented style ``` public tidy::diagnose(): bool ``` Procedural style ``` tidy_diagnose(tidy $tidy): bool ``` Runs diagnostic tests on the given tidy `tidy`, adding some more information about the document in the error buffer. ### Parameters `tidy` The [Tidy](class.tidy) object. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **tidy::diagnose()** example** ``` <?php $html = <<< HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <p>paragraph</p> HTML; $tidy = tidy_parse_string($html); $tidy->cleanRepair(); // note the difference between the two outputs echo $tidy->errorBuffer . "\n"; $tidy->diagnose(); echo $tidy->errorBuffer; ?> ``` The above example will output: ``` line 4 column 1 - Warning: <p> isn't allowed in <head> elements line 4 column 1 - Warning: inserting missing 'title' element line 4 column 1 - Warning: <p> isn't allowed in <head> elements line 4 column 1 - Warning: inserting missing 'title' element Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN" Info: Document content looks like XHTML 1.0 Strict 2 warnings, 0 errors were found! ``` ### See Also * **tidy::errorBuffer()** php QuickHashIntStringHash::set QuickHashIntStringHash::set =========================== (PECL quickhash >= Unknown) QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist ### Description ``` public QuickHashIntStringHash::set(int $key, string $value): int ``` This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK\_FOR\_DUPES during hash creation to prevent duplicate keys from being part of the hash. ### Parameters `key` The key of the entry to add or update. `value` The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible. ### Return Values 2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error. ### Examples **Example #1 **QuickHashIntStringHash::set()** example** ``` <?php $hash = new QuickHashIntStringHash( 1024 ); echo "Set->Add\n"; var_dump( $hash->get( 46692 ) ); var_dump( $hash->set( 46692, "sixteen thousand ninety one" ) ); var_dump( $hash->get( 46692 ) ); echo "Set->Update\n"; var_dump( $hash->set( 46692, "twenty nine thousand nine hundred six" ) ); var_dump( $hash->get( 46692 ) ); ?> ``` The above example will output something similar to: ``` Set->Add bool(false) int(2) string(27) "sixteen thousand ninety one" Set->Update int(1) string(37) "twenty nine thousand nine hundred six" ``` php Componere\Value::setPrivate Componere\Value::setPrivate =========================== (Componere 2 >= 2.1.0) Componere\Value::setPrivate — Accessibility Modification ### Description ``` public Componere\Value::setPrivate(): Value ``` ### Return Values The current Value ### Exceptions **Warning** Shall throw [RuntimeException](class.runtimeexception) if access level was previously set php odbc_statistics odbc\_statistics ================ (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_statistics — Retrieve statistics about a table ### Description ``` odbc_statistics( resource $odbc, ?string $catalog, string $schema, string $table, int $unique, int $accuracy ): resource|false ``` Get statistics about a table and its indexes. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `catalog` The catalog ('qualifier' in ODBC 2 parlance). `schema` The schema ('owner' in ODBC 2 parlance). `table` The table name. `unique` The type of the index. One of **`SQL_INDEX_UNIQUE`** or **`SQL_INDEX_ALL`**. `accuracy` One of **`SQL_ENSURE`** or **`SQL_QUICK`**. The latter requests that the driver retrieve the `CARDINALITY` and `PAGES` only if they are readily available from the server. ### Return Values Returns an ODBC result identifier or **`false`** on failure. The result set has the following columns: * `TABLE_CAT` * `TABLE_SCHEM` * `TABLE_NAME` * `NON_UNIQUE` * `INDEX_QUALIFIER` * `INDEX_NAME` * `TYPE` * `ORDINAL_POSITION` * `COLUMN_NAME` * `ASC_OR_DESC` * `CARDINALITY` * `PAGES` * `FILTER_CONDITION` Drivers can report additional columns. The result set is ordered by `NON_UNIQUE`, `TYPE`, `INDEX_QUALIFIER`, `INDEX_NAME` and `ORDINAL_POSITION`. ### Examples **Example #1 List Statistics of a Table** ``` <?php $conn = odbc_connect($dsn, $user, $pass); $statistics = odbc_statistics($conn, 'TutorialDB', 'dbo', 'TEST', SQL_INDEX_UNIQUE, SQL_QUICK); while (($row = odbc_fetch_array($statistics))) {     print_r($row);     break; // further rows omitted for brevity } ?> ``` The above example will output something similar to: ``` Array ( [TABLE_CAT] => TutorialDB [TABLE_SCHEM] => dbo [TABLE_NAME] => TEST [NON_UNIQUE] => [INDEX_QUALIFIER] => [INDEX_NAME] => [TYPE] => 0 [ORDINAL_POSITION] => [COLUMN_NAME] => [ASC_OR_DESC] => [CARDINALITY] => 15 [PAGES] => 3 [FILTER_CONDITION] => ) ``` ### See Also * [odbc\_tables()](function.odbc-tables) - Get the list of table names stored in a specific data source
programming_docs
php Yaf_Request_Abstract::isRouted Yaf\_Request\_Abstract::isRouted ================================ (Yaf >=1.0.0) Yaf\_Request\_Abstract::isRouted — Determin if request has been routed ### Description ``` public Yaf_Request_Abstract::isRouted(): bool ``` ### Parameters This function has no parameters. ### Return Values boolean php SolrQuery::addFacetDateField SolrQuery::addFacetDateField ============================ (PECL solr >= 0.9.2) SolrQuery::addFacetDateField — Maps to facet.date ### Description ``` public SolrQuery::addFacetDateField(string $dateField): SolrQuery ``` This method allows you to specify a field which should be treated as a facet. It can be used multiple times with different field names to indicate multiple facet fields ### Parameters `dateField` The name of the date field. ### Return Values Returns a SolrQuery object. php ldap_get_attributes ldap\_get\_attributes ===================== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_get\_attributes — Get attributes from a search result entry ### Description ``` ldap_get_attributes(LDAP\Connection $ldap, LDAP\ResultEntry $entry): array ``` Reads attributes and values from an entry in the search result. Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held. ``` return_value["count"] = number of attributes in the entry return_value[0] = first attribute return_value[n] = nth attribute return_value["attribute"]["count"] = number of values for attribute return_value["attribute"][0] = first value of the attribute return_value["attribute"][i] = (i+1)th value of the attribute ``` ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `entry` An [LDAP\ResultEntry](class.ldap-result-entry) instance. ### Return Values Returns a complete entry information in a multi-dimensional array on success and **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `entry` parameter expects an [LDAP\ResultEntry](class.ldap-result-entry) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Show the list of attributes held for a particular directory entry** ``` <?php // $ds is a valid LDAP\Connection instance for a directory server // $sr is a valid search result from a prior call to // one of the ldap directory search calls $entry = ldap_first_entry($ds, $sr); $attrs = ldap_get_attributes($ds, $entry); echo $attrs["count"] . " attributes held for this entry:<p>"; for ($i=0; $i < $attrs["count"]; $i++) {     echo $attrs[$i] . "<br />"; } ?> ``` ### See Also * [ldap\_first\_attribute()](function.ldap-first-attribute) - Return first attribute * [ldap\_next\_attribute()](function.ldap-next-attribute) - Get the next attribute in result php DivisionByZeroError DivisionByZeroError =================== Introduction ------------ (PHP 7, PHP 8) **DivisionByZeroError** is thrown when an attempt is made to divide a number by zero. Class synopsis -------------- class **DivisionByZeroError** extends [ArithmeticError](class.arithmeticerror) { /\* Inherited properties \*/ protected string [$message](class.error#error.props.message) = ""; private string [$string](class.error#error.props.string) = ""; protected int [$code](class.error#error.props.code); protected string [$file](class.error#error.props.file) = ""; protected int [$line](class.error#error.props.line); private array [$trace](class.error#error.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.error#error.props.previous) = null; /\* Inherited methods \*/ ``` final public Error::getMessage(): string ``` ``` final public Error::getPrevious(): ?Throwable ``` ``` final public Error::getCode(): int ``` ``` final public Error::getFile(): string ``` ``` final public Error::getLine(): int ``` ``` final public Error::getTrace(): array ``` ``` final public Error::getTraceAsString(): string ``` ``` public Error::__toString(): string ``` ``` private Error::__clone(): void ``` } php mysqli::$protocol_version mysqli::$protocol\_version ========================== mysqli\_get\_proto\_info ======================== (PHP 5, PHP 7, PHP 8) mysqli::$protocol\_version -- mysqli\_get\_proto\_info — Returns the version of the MySQL protocol used ### Description Object-oriented style int [$mysqli->protocol\_version](mysqli.get-proto-info); Procedural style ``` mysqli_get_proto_info(mysqli $mysql): int ``` Returns an integer representing the MySQL protocol version used by the connection represented by the `mysql` parameter. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) ### Return Values Returns an integer representing the protocol version. ### Examples **Example #1 $mysqli->protocol\_version example** Object-oriented style ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* print protocol version */ printf("Protocol version: %d\n", $mysqli->protocol_version); /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* print protocol version */ printf("Protocol version: %d\n", mysqli_get_proto_info($link)); /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Protocol version: 10 ``` ### See Also * [mysqli\_get\_host\_info()](mysqli.get-host-info) - Returns a string representing the type of connection used php ob_implicit_flush ob\_implicit\_flush =================== (PHP 4, PHP 5, PHP 7, PHP 8) ob\_implicit\_flush — Turn implicit flush on/off ### Description ``` ob_implicit_flush(bool $enable = true): void ``` **ob\_implicit\_flush()** will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every output call, so that explicit calls to [flush()](function.flush) will no longer be needed. ### Parameters `enable` `true` to turn implicit flushing on, `false` otherwise. ### Return Values No value is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | The `enable` expects a bool value now; previously, an int was expected. | ### See Also * [flush()](function.flush) - Flush system output buffer * [ob\_start()](function.ob-start) - Turn on output buffering * [ob\_end\_flush()](function.ob-end-flush) - Flush (send) the output buffer and turn off output buffering php stream_filter_append stream\_filter\_append ====================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) stream\_filter\_append — Attach a filter to a stream ### Description ``` stream_filter_append( resource $stream, string $filtername, int $read_write = ?, mixed $params = ? ): resource ``` Adds `filtername` to the list of filters attached to `stream`. ### Parameters `stream` The target stream. `filtername` The filter name. `read_write` By default, **stream\_filter\_append()** will attach the filter to the `read filter chain` if the file was opened for reading (i.e. File Mode: `r`, and/or `+`). The filter will also be attached to the `write filter chain` if the file was opened for writing (i.e. File Mode: `w`, `a`, and/or `+`). **`STREAM_FILTER_READ`**, **`STREAM_FILTER_WRITE`**, and/or **`STREAM_FILTER_ALL`** can also be passed to the `read_write` parameter to override this behavior. `params` This filter will be added with the specified `params` to the *end* of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use [stream\_filter\_prepend()](function.stream-filter-prepend). ### Return Values Returns a resource on success or **`false`** on failure. The resource can be used to refer to this filter instance during a call to [stream\_filter\_remove()](function.stream-filter-remove). **`false`** is returned if `stream` is not a resource or if `filtername` cannot be located. ### Examples **Example #1 Controlling where filters are applied** ``` <?php /* Open a test file for reading and writing */ $fp = fopen('test.txt', 'w+'); /* Apply the ROT13 filter to the  * write filter chain, but not the  * read filter chain */ stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE); /* Write a simple string to the file  * it will be ROT13 transformed on the  * way out */ fwrite($fp, "This is a test\n"); /* Back up to the beginning of the file */ rewind($fp); /* Read the contents of the file back out.  * Had the filter been applied to the  * read filter chain as well, we would see  * the text ROT13ed back to its original state */ fpassthru($fp); fclose($fp); /* Expected Output    --------------- Guvf vf n grfg  */ ?> ``` ### Notes > **Note**: **When using custom (user) filters** > [stream\_filter\_register()](function.stream-filter-register) must be called first in order to register the desired user filter to `filtername`. > > > **Note**: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of [stream\_filter\_prepend()](function.stream-filter-prepend). > > > **Note**: When a filter is added for read and write, two instances of the filter are created. **stream\_filter\_append()** must be called twice with **`STREAM_FILTER_READ`** and **`STREAM_FILTER_WRITE`** to get both filter resources. > > ### See Also * [stream\_filter\_register()](function.stream-filter-register) - Register a user defined stream filter * [stream\_filter\_prepend()](function.stream-filter-prepend) - Attach a filter to a stream * [stream\_get\_filters()](function.stream-get-filters) - Retrieve list of registered filters php IntlBreakIterator::getLocale IntlBreakIterator::getLocale ============================ (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlBreakIterator::getLocale — Get the locale associated with the object ### Description ``` public IntlBreakIterator::getLocale(int $type): string|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `type` ### Return Values php posix_getgid posix\_getgid ============= (PHP 4, PHP 5, PHP 7, PHP 8) posix\_getgid — Return the real group ID of the current process ### Description ``` posix_getgid(): int ``` Return the numeric real group ID of the current process. ### Parameters This function has no parameters. ### Return Values Returns the real group id, as an int. ### Examples **Example #1 **posix\_getgid()** example** This example will print out the real group id, even once the effective group id has been changed. ``` <?php echo 'My real group id is '.posix_getgid(); //20 posix_setegid(40); echo 'My real group id is '.posix_getgid(); //20 echo 'My effective group id is '.posix_getegid(); //40 ?> ``` ### See Also * [posix\_getgrgid()](function.posix-getgrgid) - Return info about a group by group id * [posix\_getegid()](function.posix-getegid) - Return the effective group ID of the current process * [posix\_setgid()](function.posix-setgid) - Set the GID of the current process * POSIX man page GETGID(2) php pg_field_size pg\_field\_size =============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_field\_size — Returns the internal storage size of the named field ### Description ``` pg_field_size(PgSql\Result $result, int $field): int ``` **pg\_field\_size()** returns the internal storage size (in bytes) of the field number in the given PostgreSQL `result`. > > **Note**: > > > This function used to be called **pg\_fieldsize()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `field` Field number, starting from 0. ### Return Values The internal field storage size (in bytes). -1 indicates a variable length field. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Getting information about fields** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");   $i = pg_num_fields($res);   for ($j = 0; $j < $i; $j++) {       echo "column $j\n";       $fieldname = pg_field_name($res, $j);       echo "fieldname: $fieldname\n";       echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";       echo "storage length: " . pg_field_size($res, $j) . " bytes\n";       echo "field type: " . pg_field_type($res, $j) . " \n\n";   } ?> ``` The above example will output: ``` column 0 fieldname: author printed length: 6 characters storage length: -1 bytes field type: varchar column 1 fieldname: year printed length: 4 characters storage length: 2 bytes field type: int2 column 2 fieldname: title printed length: 24 characters storage length: -1 bytes field type: varchar ``` ### See Also * [pg\_field\_prtlen()](function.pg-field-prtlen) - Returns the printed length * [pg\_field\_type()](function.pg-field-type) - Returns the type name for the corresponding field number php mcrypt_list_modes mcrypt\_list\_modes =================== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_list\_modes — Gets an array of all supported modes **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_list_modes(string $lib_dir = ini_get("mcrypt.modes_dir")): array ``` Gets the list of all supported modes in the `lib_dir` parameter. ### Parameters `lib_dir` Specifies the directory where all modes are located. If not specified, the value of the `mcrypt.modes_dir` php.ini directive is used. ### Return Values Returns an array with all the supported modes. ### Examples **Example #1 **mcrypt\_list\_modes()** Example** ``` <?php     $modes = mcrypt_list_modes();     foreach ($modes as $mode) {         echo "$mode <br />\n";     } ?> ``` The example above will produce a list with all supported algorithms in the default mode directory. If it is not set with the `mcrypt.modes_dir` php.ini directive, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt). php socket_write socket\_write ============= (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_write — Write to a socket ### Description ``` socket_write(Socket $socket, string $data, ?int $length = null): int|false ``` The function **socket\_write()** writes to the `socket` from the given `data`. ### Parameters `socket` `data` The buffer to be written. `length` The optional parameter `length` can specify an alternate length of bytes written to the socket. If this length is greater than the buffer length, it is silently truncated to the length of the buffer. ### Return Values Returns the number of bytes successfully written to the socket or **`false`** on failure. The error code can be retrieved with [socket\_last\_error()](function.socket-last-error). This code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual explanation of the error. > > **Note**: > > > It is perfectly valid for **socket\_write()** to return zero which means no bytes have been written. Be sure to use the `===` operator to check for **`false`** in case of an error. > > ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | | 8.0.0 | `length` is nullable now. | ### Notes > > **Note**: > > > **socket\_write()** does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data. > > ### See Also * [socket\_accept()](function.socket-accept) - Accepts a connection on a socket * [socket\_bind()](function.socket-bind) - Binds a name to a socket * [socket\_connect()](function.socket-connect) - Initiates a connection on a socket * [socket\_listen()](function.socket-listen) - Listens for a connection on a socket * [socket\_read()](function.socket-read) - Reads a maximum of length bytes from a socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error php jdtojewish jdtojewish ========== (PHP 4, PHP 5, PHP 7, PHP 8) jdtojewish — Converts a Julian day count to a Jewish calendar date ### Description ``` jdtojewish(int $julian_day, bool $hebrew = false, int $flags = 0): string ``` Converts a Julian Day Count to the Jewish Calendar. ### Parameters `julian_day` A julian day number as integer `hebrew` If the `hebrew` parameter is set to **`true`**, the `flags` parameter is used for Hebrew, ISO-8859-8 encoded string based, output format. `flags` A bitmask which may consist of **`CAL_JEWISH_ADD_ALAFIM_GERESH`**, **`CAL_JEWISH_ADD_ALAFIM`** and **`CAL_JEWISH_ADD_GERESHAYIM`**. ### Return Values The Jewish date as a string in the form "month/day/year", or an ISO-8859-8 encoded Hebrew date string, according to the `hebrew` parameter. ### Examples **Example #1 **jdtojewish()** Example** ``` <?php $jd = gregoriantojd(10, 8, 2002); echo jdtojewish($jd, true), PHP_EOL,      jdtojewish($jd, true, CAL_JEWISH_ADD_GERESHAYIM), PHP_EOL,      jdtojewish($jd, true, CAL_JEWISH_ADD_ALAFIM), PHP_EOL,      jdtojewish($jd, true,CAL_JEWISH_ADD_ALAFIM_GERESH), PHP_EOL; ?> ``` The above example will output: ``` ב חשון התשסג ב' חשון התשס"ג ב חשון ה אלפים תשסג ב חשון ה'תשסג ``` ### See Also * [jewishtojd()](function.jewishtojd) - Converts a date in the Jewish Calendar to Julian Day Count * [cal\_from\_jd()](function.cal-from-jd) - Converts from Julian Day Count to a supported calendar php ip2long ip2long ======= (PHP 4, PHP 5, PHP 7, PHP 8) ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer ### Description ``` ip2long(string $ip): int|false ``` The function **ip2long()** generates a long integer representation of IPv4 Internet network address from its Internet standard format (dotted string) representation. **ip2long()** will also work with non-complete IP addresses. Read [» http://publibn.boulder.ibm.com/doc\_link/en\_US/a\_doc\_lib/libs/commtrf2/inet\_addr.htm](http://publibn.boulder.ibm.com/doc_link/en_US/a_doc_lib/libs/commtrf2/inet_addr.htm) for more info. ### Parameters `ip` A standard format address. ### Return Values Returns the long integer or **`false`** if `ip` is invalid. ### Examples **Example #1 **ip2long()** Example** ``` <?php $ip = gethostbyname('www.example.com'); $out = "The following URLs are equivalent:<br />\n"; $out .= 'http://www.example.com/, http://' . $ip . '/, and http://' . sprintf("%u", ip2long($ip)) . "/<br />\n"; echo $out; ?> ``` **Example #2 Displaying an IP address** This second example shows how to print a converted address with the [printf()](function.printf) function: ``` <?php $ip   = gethostbyname('www.example.com'); $long = ip2long($ip); if ($long == -1 || $long === FALSE) {     echo 'Invalid IP, please try again'; } else {     echo $ip   . "\n";            // 192.0.34.166     echo $long . "\n";            // 3221234342 (-1073732954 on 32-bit systems, due to integer overflow)     printf("%u\n", ip2long($ip)); // 3221234342 } ?> ``` ### Notes > > **Note**: > > > Because PHP's int type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the "%u" formatter of [sprintf()](function.sprintf) or [printf()](function.printf) to get the string representation of the unsigned IP address. > > > > **Note**: > > > **ip2long()** will return `-1` for the IP `255.255.255.255` on 32-bit systems due to the integer value overflowing. > > ### See Also * [long2ip()](function.long2ip) - Converts an long integer address into a string in (IPv4) Internet standard dotted format * [sprintf()](function.sprintf) - Return a formatted string
programming_docs
php Imagick::setImageGravity Imagick::setImageGravity ======================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::setImageGravity — Sets the image gravity ### Description ``` public Imagick::setImageGravity(int $gravity): bool ``` Sets the gravity property for the current image. This method can be used to set the gravity property for a single image sequence. This method is available if Imagick has been compiled against ImageMagick version 6.4.4 or newer. ### Parameters `gravity` The gravity property. Refer to the list of [gravity constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.gravity). ### Return Values No value is returned. php ZipArchive::setCompressionName ZipArchive::setCompressionName ============================== (PHP 7, PHP 8, PECL zip >= 1.13.0) ZipArchive::setCompressionName — Set the compression method of an entry defined by its name ### Description ``` public ZipArchive::setCompressionName(string $name, int $method, int $compflags = 0): bool ``` Set the compression method of an entry defined by its name. ### Parameters `name` Name of the entry. `method` The compression method, one of the **`ZipArchive::CM_*`** constants. `compflags` Compression level. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Add files with different compression methods to an archive** ``` <?php $zip = new ZipArchive; $res = $zip->open('test.zip', ZipArchive::CREATE); if ($res === TRUE) {     $zip->addFromString('foo', 'Some text');     $zip->addFromString('bar', 'Some other text');     $zip->setCompressionName('foo', ZipArchive::CM_STORE);     $zip->setCompressionName('bar', ZipArchive::CM_DEFLATE);     $zip->close();     echo 'ok'; } else {     echo 'failed'; } ?> ``` **Example #2 Add file and set compression method** ``` <?php $zip = new ZipArchive; $res = $zip->open('test.zip', ZipArchive::CREATE); if ($res === TRUE) {     $zip->addFile('foo.jpg', 'bar.jpg');     $zip->setCompressionName('bar.jpg', ZipArchive::CM_XZ);     $zip->close();     echo 'ok'; } else {     echo 'failed'; } ?> ``` php Gmagick::getimagemattecolor Gmagick::getimagemattecolor =========================== (PECL gmagick >= Unknown) Gmagick::getimagemattecolor — Returns the image matte color ### Description ``` public Gmagick::getimagemattecolor(): GmagickPixel ``` Returns GmagickPixel object on success. Throw an GmagickException on error. ### Parameters This function has no parameters. ### Return Values Returns GmagickPixel object on success. ### Errors/Exceptions Throws an **GmagickException** on error. php XSLTProcessor::importStylesheet XSLTProcessor::importStylesheet =============================== (PHP 5, PHP 7, PHP 8) XSLTProcessor::importStylesheet — Import stylesheet ### Description ``` public XSLTProcessor::importStylesheet(object $stylesheet): bool ``` This method imports the stylesheet into the [XSLTProcessor](class.xsltprocessor) for transformations. ### Parameters `stylesheet` The imported style sheet as a [DOMDocument](class.domdocument) or [SimpleXMLElement](class.simplexmlelement) object. ### Return Values Returns **`true`** on success or **`false`** on failure. php SplDoublyLinkedList::getIteratorMode SplDoublyLinkedList::getIteratorMode ==================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration ### Description ``` public SplDoublyLinkedList::getIteratorMode(): int ``` ### Parameters This function has no parameters. ### Return Values Returns the different modes and flags that affect the iteration. php SolrClient::system SolrClient::system ================== (PECL solr >= 2.0.0) SolrClient::system — Retrieve Solr Server information ### Description ``` public SolrClient::system(): void ``` Retrieve Solr Server information ### Parameters This function has no parameters. ### Return Values Returns a [SolrGenericResponse](class.solrgenericresponse) object on success. ### Errors/Exceptions Emits [SolrClientException](class.solrclientexception) if the client failed, or there was a connection issue. Emits [SolrServerException](class.solrserverexception) if the Solr Server failed to satisfy the query. php streamWrapper::__destruct streamWrapper::\_\_destruct =========================== (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) streamWrapper::\_\_destruct — Destructs an existing stream wrapper ### Description public **streamWrapper::\_\_destruct**() Called when closing the stream wrapper, right before [streamWrapper::stream\_flush()](streamwrapper.stream-flush). ### Parameters This function has no parameters. php posix_getcwd posix\_getcwd ============= (PHP 4, PHP 5, PHP 7, PHP 8) posix\_getcwd — Pathname of current directory ### Description ``` posix_getcwd(): string|false ``` Gets the absolute pathname of the script's current working directory. On error, it sets errno which can be checked using [posix\_get\_last\_error()](function.posix-get-last-error) ### Parameters This function has no parameters. ### Return Values Returns a string of the absolute pathname on success. On error, returns **`false`** and sets errno which can be checked with [posix\_get\_last\_error()](function.posix-get-last-error). ### Examples **Example #1 **posix\_getcwd()** example** This example will return the absolute path of the current working directory of the script. ``` <?php echo 'My current working directory is '.posix_getcwd(); ?> ``` ### Notes > > **Note**: > > > This function can fail on > > > * Read or Search permission was denied > * Pathname no longer exists > > php SyncSemaphore::unlock SyncSemaphore::unlock ===================== (PECL sync >= 1.0.0) SyncSemaphore::unlock — Increases the count of the semaphore ### Description ``` public SyncSemaphore::unlock(int &$prevcount = ?): bool ``` Increases the count of a [SyncSemaphore](class.syncsemaphore) object. ### Parameters `prevcount` Returns the previous count of the semaphore. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **SyncSemaphore::unlock()** example** ``` <?php $semaphore = new SyncSemaphore("LimitedResource_2clients", 2); if (!$semaphore->lock(3000)) {     echo "Unable to lock semaphore.";     exit(); } /* ... */ $semaphore->unlock(); ?> ``` ### See Also * [SyncSemaphore::lock()](syncsemaphore.lock) - Decreases the count of the semaphore or waits php stream_get_transports stream\_get\_transports ======================= (PHP 5, PHP 7, PHP 8) stream\_get\_transports — Retrieve list of registered socket transports ### Description ``` stream_get_transports(): array ``` Returns an indexed array containing the name of all socket transports available on the running system. ### Parameters This function has no parameters. ### Return Values Returns an indexed array of socket transports names. ### Examples **Example #1 Using **stream\_get\_transports()**** ``` <?php $xportlist = stream_get_transports(); print_r($xportlist); ?> ``` The above example will output something similar to: ``` Array ( [0] => tcp [1] => udp [2] => unix [3] => udg ) ``` ### See Also * [stream\_get\_filters()](function.stream-get-filters) - Retrieve list of registered filters * [stream\_get\_wrappers()](function.stream-get-wrappers) - Retrieve list of registered streams php fbird_fetch_row fbird\_fetch\_row ================= (PHP 5, PHP 7 < 7.4.0) fbird\_fetch\_row — Alias of [ibase\_fetch\_row()](function.ibase-fetch-row) ### Description This function is an alias of: [ibase\_fetch\_row()](function.ibase-fetch-row). ### See Also * [fbird\_fetch\_assoc()](function.fbird-fetch-assoc) - Alias of ibase\_fetch\_assoc * [fbird\_fetch\_object()](function.fbird-fetch-object) - Alias of ibase\_fetch\_object php IntlBreakIterator::createSentenceInstance IntlBreakIterator::createSentenceInstance ========================================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks ### Description ``` public static IntlBreakIterator::createSentenceInstance(?string $locale = null): ?IntlBreakIterator ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `locale` ### Return Values php SplDoublyLinkedList::unshift SplDoublyLinkedList::unshift ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element ### Description ``` public SplDoublyLinkedList::unshift(mixed $value): void ``` Prepends `value` at the beginning of the doubly linked list. ### Parameters `value` The value to unshift. ### Return Values No value is returned. php Phar::mapPhar Phar::mapPhar ============= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest ### Description ``` final public static Phar::mapPhar(?string $alias = null, int $offset = 0): bool ``` This static method can only be used inside a Phar archive's loader stub in order to initialize the phar when it is directly executed, or when it is included in another script. ### Parameters `alias` The alias that can be used in `phar://` URLs to refer to this archive, rather than its full path. `offset` Unused variable, here for compatibility with PEAR's PHP\_Archive. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions [PharException](class.pharexception) is thrown if not called directly within PHP execution, if no \_\_HALT\_COMPILER(); token is found in the current source file, or if the file cannot be opened for reading. ### Examples **Example #1 A **Phar::mapPhar()** example** mapPhar should be used only inside a phar's loader stub. Use loadPhar to load an external phar into memory. Here is a sample Phar loader stub that uses mapPhar. ``` <?php function __autoload($class) {     include 'phar://me.phar/' . str_replace('_', '/', $class) . '.php'; } try {     Phar::mapPhar('me.phar');     include 'phar://me.phar/startup.php'; } catch (PharException $e) {     echo $e->getMessage();     die('Cannot initialize Phar'); } __HALT_COMPILER(); ``` ### See Also * [Phar::loadPhar()](phar.loadphar) - Loads any phar archive with an alias php Ev::embeddableBackends Ev::embeddableBackends ====================== (PECL ev >= 0.2.0) Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops ### Description ``` final public static Ev::embeddableBackends(): int ``` Returns the set of backends that are embeddable in other event loops. ### Parameters This function has no parameters. ### Return Values Returns a bit mask which can containing [backend flags](class.ev#ev.constants.watcher-backends) combined using bitwise *OR* operator. ### Examples **Example #1 Embedding loop created with kqueue backend into the default loop** ``` <?php /* * Check if kqueue is available but not recommended and create a kqueue backend * for use with sockets (which usually work with any kqueue implementation). * Store the kqueue/socket-only event loop in loop_socket. (One might optionally * use EVFLAG_NOENV, too) * * Example borrowed from * http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9 */ $loop        = EvLoop::defaultLoop(); $socket_loop = NULL; $embed       = NULL; if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {  if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {   $embed = new EvEmbed($loop);  } } if (!$socket_loop) {  $socket_loop = $loop; } // Now use $socket_loop for all sockets, and $loop for anything else ?> ``` ### See Also * [EvEmbed](class.evembed) * [Ev::recommendedBackends()](ev.recommendedbackends) - Returns a bit mask of recommended backends for current platform * [Ev::supportedBackends()](ev.supportedbackends) - Returns the set of backends supported by current libev configuration * [Backend flags](class.ev#ev.constants.watcher-backends) * [Examples](https://www.php.net/manual/en/ev.examples.php) php ssh2_sftp_stat ssh2\_sftp\_stat ================ (PECL ssh2 >= 0.9.0) ssh2\_sftp\_stat — Stat a file on a remote filesystem ### Description ``` ssh2_sftp_stat(resource $sftp, string $path): array ``` Stats a file on the remote filesystem following any symbolic links. This function is similar to using the [stat()](function.stat) function with the [ssh2.sftp://](https://www.php.net/manual/en/wrappers.ssh2.php) wrapper and returns the same values. ### Parameters `sftp` An SSH2 SFTP resource opened by [ssh2\_sftp()](function.ssh2-sftp). `path` ### Return Values See the documentation for [stat()](function.stat) for details on the values which may be returned. ### Examples **Example #1 Stating a file via SFTP** ``` <?php $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $sftp = ssh2_sftp($connection); $statinfo = ssh2_sftp_stat($sftp, '/path/to/file'); $filesize = $statinfo['size']; $group = $statinfo['gid']; $owner = $statinfo['uid']; $atime = $statinfo['atime']; $mtime = $statinfo['mtime']; $mode = $statinfo['mode']; ?> ``` ### See Also * [ssh2\_sftp\_lstat()](function.ssh2-sftp-lstat) - Stat a symbolic link * [lstat()](function.lstat) - Gives information about a file or symbolic link * [stat()](function.stat) - Gives information about a file php Gmagick::stripimage Gmagick::stripimage =================== (PECL gmagick >= Unknown) Gmagick::stripimage — Strips an image of all profiles and comments ### Description ``` public Gmagick::stripimage(): Gmagick ``` Strips an image of all profiles and comments. ### Parameters This function has no parameters. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php stats_rand_gen_f stats\_rand\_gen\_f =================== (PECL stats >= 1.0.0) stats\_rand\_gen\_f — Generates a random deviate from the F distribution ### Description ``` stats_rand_gen_f(float $dfn, float $dfd): float ``` Generates a random deviate from the F (variance ratio) distribution with "dfn" degrees of freedom in the numerator and "dfd" degrees of freedom in the denominator. Method : directly generates ratio of chisquare variates. ### Parameters `dfn` The degrees of freedom in the numerator `dfd` The degrees of freedom in the denominator ### Return Values A random deviate php CURLFile::getFilename CURLFile::getFilename ===================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) CURLFile::getFilename — Get file name ### Description ``` public CURLFile::getFilename(): string ``` ### Parameters This function has no parameters. ### Return Values Returns file name. php SolrClientException::getInternalInfo SolrClientException::getInternalInfo ==================================== (PECL solr >= 0.9.2) SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown ### Description ``` public SolrClientException::getInternalInfo(): array ``` Returns internal information where the Exception was thrown. ### Parameters This function has no parameters. ### Return Values Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers. php SolrCollapseFunction::getField SolrCollapseFunction::getField ============================== (PECL solr >= 2.2.0) SolrCollapseFunction::getField — Returns the field that is being collapsed on ### Description ``` public SolrCollapseFunction::getField(): string ``` Returns the field that is being collapsed on. ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrCollapseFunction::setField()](solrcollapsefunction.setfield) - Sets the field to collapse on php EventHttpConnection::__construct EventHttpConnection::\_\_construct ================================== (PECL event >= 1.2.6-beta) EventHttpConnection::\_\_construct — Constructs EventHttpConnection object ### Description ``` public EventHttpConnection::__construct( EventBase $base , EventDnsBase $dns_base , string $address , int $port , EventSslContext $ctx = null ) ``` Constructs EventHttpConnection object. ### Parameters `base` Associated event base. `dns_base` If `dns_base` is **`null`**, hostname resolution will block. `address` The address to connect to. `port` The port to connect to. `ctx` [EventSslContext](class.eventsslcontext) class object. Enables OpenSSL. > > **Note**: > > > This parameter is available only if `Event` is compiled with OpenSSL support and only with `Libevent > 2.1.0-alpha` and higher. > > ### Return Values Returns [EventHttpConnection](class.eventhttpconnection) object. ### Changelog | Version | Description | | --- | --- | | PECL event 1.9.0 | OpenSSL support (`ctx`) added. | php ssh2_shell ssh2\_shell =========== (PECL ssh2 >= 0.9.0) ssh2\_shell — Request an interactive shell ### Description ``` ssh2_shell( resource $session, string $termtype = "vanilla", ?array $env = null, int $width = 80, int $height = 25, int $width_height_type = SSH2_TERM_UNIT_CHARS ): resource|false ``` Open a shell at the remote end and allocate a stream for it. ### Parameters `session` An SSH connection link identifier, obtained from a call to [ssh2\_connect()](function.ssh2-connect). `termtype` `termtype` should correspond to one of the entries in the target system's `/etc/termcap` file. `env` `env` may be passed as an associative array of name/value pairs to set in the target environment. `width` Width of the virtual terminal. `height` Height of the virtual terminal. `width_height_type` `width_height_type` should be one of **`SSH2_TERM_UNIT_CHARS`** or **`SSH2_TERM_UNIT_PIXELS`**. ### Return Values Returns a stream [resource](language.types.resource) on success, or **`false`** on failure. ### Examples **Example #1 Requesting an interactive shell** ``` <?php $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $stream = ssh2_shell($connection, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS); ?> ``` ### See Also * [ssh2\_exec()](function.ssh2-exec) - Execute a command on a remote server * [ssh2\_tunnel()](function.ssh2-tunnel) - Open a tunnel through a remote server * [ssh2\_fetch\_stream()](function.ssh2-fetch-stream) - Fetch an extended data stream php sodium_crypto_shorthash_keygen sodium\_crypto\_shorthash\_keygen ================================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_shorthash\_keygen — Get random bytes for key ### Description ``` sodium_crypto_shorthash_keygen(): string ``` Generate a key for use with [sodium\_crypto\_shorthash()](function.sodium-crypto-shorthash). **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values
programming_docs
php Ds\Pair::clear Ds\Pair::clear ============== (No version information available, might only be in Git) Ds\Pair::clear — Removes all values ### Description ``` public Ds\Pair::clear(): void ``` Removes all values from the pair. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Pair::clear()** example** ``` <?php $pair = new \Ds\Pair("a", 1); print_r($pair); $pair->clear(); print_r($pair); ?> ``` The above example will output something similar to: ``` Ds\Pair Object ( [0] => 1 [1] => 2 [2] => 3 ) Ds\Pair Object ( ) ``` php ibase_rollback_ret ibase\_rollback\_ret ==================== (PHP 5, PHP 7 < 7.4.0) ibase\_rollback\_ret — Roll back a transaction without closing it ### Description ``` ibase_rollback_ret(resource $link_or_trans_identifier = null): bool ``` Rolls back a transaction without closing it. ### Parameters `link_or_trans_identifier` If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. ### Return Values Returns **`true`** on success or **`false`** on failure. php Yaf_Controller_Abstract::forward Yaf\_Controller\_Abstract::forward ================================== (Yaf >=1.0.0) Yaf\_Controller\_Abstract::forward — Forward to another action ### Description ``` public Yaf_Controller_Abstract::forward(string $action, array $paramters = ?): bool ``` ``` public Yaf_Controller_Abstract::forward(string $controller, string $action, array $paramters = ?): bool ``` ``` public Yaf_Controller_Abstract::forward( string $module, string $controller, string $action, array $paramters = ? ): bool ``` forward current execution process to other action. > > **Note**: > > > this method doesn't switch to the destination action immediately, it will take place after current flow finish. > > ### Parameters `module` destination module name, if NULL was given, then default module name is assumed `controller` destination controller name `action` destination action name `paramters` calling arguments ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **Yaf\_Controller\_Abstract::forward()**example** ``` <?php class IndexController extends Yaf_Controller_Abstract {     public function indexAction(){             $logined = $_SESSION["login"];          if (!$logined) {              $this->forward("login", array("from" => "Index")); // forward to login action              return FALSE;  // this is important, this finish current working flow                             // and tell the Yaf do not doing auto-render          }          // other processes     }     public function loginAction() {          echo "login, redirected from ", $this->_request->getParam("from") , " action";     } } ?> ``` The above example will output something similar to: ``` login, redirected from Index action ``` ### See Also * **Yaf\_Request\_Abstrace::getParam()** php Parle\RParser::reset Parle\RParser::reset ==================== (PECL parle >= 0.7.1) Parle\RParser::reset — Reset parser state ### Description ``` public Parle\RParser::reset(int $tokenId = ?): void ``` Reset parser state using the given token id. ### Parameters `tokenId` Token id. ### Return Values No value is returned. php Imagick::steganoImage Imagick::steganoImage ===================== (PECL imagick 2, PECL imagick 3) Imagick::steganoImage — Hides a digital watermark within the image ### Description ``` public Imagick::steganoImage(Imagick $watermark_wand, int $offset): Imagick ``` Hides a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark. ### Parameters `watermark_wand` `offset` ### Return Values Returns **`true`** on success. php snmpwalkoid snmpwalkoid =========== (PHP 4, PHP 5, PHP 7, PHP 8) snmpwalkoid — Query for a tree of information about a network entity ### Description ``` snmpwalkoid( string $hostname, string $community, array|string $object_id, int $timeout = -1, int $retries = -1 ): array|false ``` **snmpwalkoid()** function is used to read all object ids and their respective values from an SNMP agent specified by `hostname`. The existence of **snmpwalkoid()** and [snmpwalk()](function.snmpwalk) has historical reasons. Both functions are provided for backward compatibility. Use [snmprealwalk()](function.snmprealwalk) instead. ### Parameters `hostname` The SNMP agent. `community` The read community. `object_id` If **`null`**, `object_id` is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If `object_id` is specified, all the SNMP objects below that `object_id` are returned. `timeout` The number of microseconds until the first timeout. `retries` The number of times to retry if timeouts occur. ### Return Values Returns an associative array with object ids and their respective object value starting from the `object_id` as root or **`false`** on error. ### Examples **Example #1 **snmpwalkoid()** Example** ``` <?php $a = snmpwalkoid("127.0.0.1", "public", "");  for (reset($a); $i = key($a); next($a)) {     echo "$i: $a[$i]<br />\n"; } ?> ``` Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop ### See Also * [snmpwalk()](function.snmpwalk) - Fetch all the SNMP objects from an agent php jpeg2wbmp jpeg2wbmp ========= (PHP 4 >= 4.0.5, PHP 5, PHP 7) jpeg2wbmp — Convert JPEG image file to WBMP image file **Warning**This function has been *DEPRECATED* as of PHP 7.2.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` jpeg2wbmp( string $jpegname, string $wbmpname, int $dest_height, int $dest_width, int $threshold ): bool ``` Converts a JPEG file into a WBMP file. ### Parameters `jpegname` Path to JPEG file. `wbmpname` Path to destination WBMP file. `dest_height` Destination image height. `dest_width` Destination image width. `threshold` Threshold value, between 0 and 8 (inclusive). ### Return Values Returns **`true`** on success or **`false`** on failure. **Caution**However, if libgd fails to output the image, this function returns **`true`**. ### Examples **Example #1 **jpeg2wbmp()** example** ``` <?php // Path to the target jpeg $path = './test.jpg'; // Get the image sizes $image = getimagesize($path); // Convert image jpeg2wbmp($path, './test.wbmp', $image[1], $image[0], 5); ?> ``` ### See Also * [png2wbmp()](function.png2wbmp) - Convert PNG image file to WBMP image file php gzdeflate gzdeflate ========= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gzdeflate — Deflate a string ### Description ``` gzdeflate(string $data, int $level = -1, int $encoding = ZLIB_ENCODING_RAW): string|false ``` This function compresses the given string using the `DEFLATE` data format. For details on the DEFLATE compression algorithm see the document "[» DEFLATE Compressed Data Format Specification version 1.3](http://www.faqs.org/rfcs/rfc1951)" (RFC 1951). ### Parameters `data` The data to deflate. `level` The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library. `encoding` One of **`ZLIB_ENCODING_*`** constants. ### Return Values The deflated string or **`false`** if an error occurred. ### Examples **Example #1 **gzdeflate()** example** ``` <?php $compressed = gzdeflate('Compress me', 9); echo $compressed; ?> ``` ### See Also * [gzinflate()](function.gzinflate) - Inflate a deflated string * [gzcompress()](function.gzcompress) - Compress a string * [gzuncompress()](function.gzuncompress) - Uncompress a compressed string * [gzencode()](function.gzencode) - Create a gzip compressed string php sodium_crypto_scalarmult_base sodium\_crypto\_scalarmult\_base ================================ (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_scalarmult\_base — Alias of [sodium\_crypto\_box\_publickey\_from\_secretkey()](function.sodium-crypto-box-publickey-from-secretkey) ### Description This function is an alias of: [sodium\_crypto\_box\_publickey\_from\_secretkey()](function.sodium-crypto-box-publickey-from-secretkey). php Serializable::unserialize Serializable::unserialize ========================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) Serializable::unserialize — Constructs the object ### Description ``` public Serializable::unserialize(string $data): void ``` Called during unserialization of the object. > > **Note**: > > > This method acts as the [constructor](language.oop5.decon#language.oop5.decon.constructor) of the object. The [\_\_construct()](language.oop5.decon#object.construct) method will *not* be called after this method. > > ### Parameters `data` The string representation of the object. ### Return Values The return value from this method is ignored. ### See Also * [\_\_wakeup()](language.oop5.magic#object.wakeup) * [\_\_unserialize()](language.oop5.magic#object.unserialize) php Imagick::clone Imagick::clone ============== (PECL imagick 2, PECL imagick 3) Imagick::clone — Makes an exact copy of the Imagick object ### Description ``` public Imagick::clone(): Imagick ``` Makes an exact copy of the Imagick object. **Warning** This function has been *DEPRECATED* as of imagick 3.1.0 in favour of using the [clone](language.oop5.cloning) keyword. ### Parameters This function has no parameters. ### Return Values A copy of the Imagick object is returned. ### Changelog | Version | Description | | --- | --- | | PECL imagick 3.1.0 | The method was deprecated in favour of the [clone](language.oop5.cloning) keyword. | ### Examples **Example #1 Imagick object cloning in different versions of imagick** ``` <?php // Cloning an Imagick object in imagick 2.x and 3.0: $newImage = $image->clone(); // Cloning an Imagick object from 3.1.0 on: $newImage = clone $image; ?> ``` php mb_strrchr mb\_strrchr =========== (PHP 5 >= 5.2.0, PHP 7, PHP 8) mb\_strrchr — Finds the last occurrence of a character in a string within another ### Description ``` mb_strrchr( string $haystack, string $needle, bool $before_needle = false, ?string $encoding = null ): string|false ``` **mb\_strrchr()** finds the last occurrence of `needle` in `haystack` and returns the portion of `haystack`. If `needle` is not found, it returns **`false`**. ### Parameters `haystack` The string from which to get the last occurrence of `needle` `needle` The string to find in `haystack` `before_needle` Determines which portion of `haystack` this function returns. If set to **`true`**, it returns all of `haystack` from the beginning to the last occurrence of `needle`. If set to **`false`**, it returns all of `haystack` from the last occurrence of `needle` to the end, `encoding` Character encoding name to use. If it is omitted, internal character encoding is used. ### Return Values Returns the portion of `haystack`. or **`false`** if `needle` is not found. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `needle` now accepts an empty string. | | 8.0.0 | `encoding` is nullable now. | ### See Also * [strrchr()](function.strrchr) - Find the last occurrence of a character in a string * [mb\_strstr()](function.mb-strstr) - Finds first occurrence of a string within another * [mb\_strrichr()](function.mb-strrichr) - Finds the last occurrence of a character in a string within another, case insensitive php Ds\Set::sort Ds\Set::sort ============ (PECL ds >= 1.0.0) Ds\Set::sort — Sorts the set in-place ### Description ``` public Ds\Set::sort(callable $comparator = ?): void ``` Sorts the set in-place, using an optional `comparator` function. ### Parameters `comparator` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` **Caution** Returning *non-integer* values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Set::sort()** example** ``` <?php $set = new \Ds\Set([4, 5, 1, 3, 2]); $set->sort(); print_r($set); ?> ``` The above example will output something similar to: ``` Ds\Set Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) ``` **Example #2 **Ds\Set::sort()** example using a comparator** ``` <?php $set = new \Ds\Set([4, 5, 1, 3, 2]); $set->sort(function($a, $b) {     return $b <=> $a; }); print_r($set); ?> ``` The above example will output something similar to: ``` Ds\Set Object ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 ) ``` php The ReflectionReference class The ReflectionReference class ============================= Introduction ------------ (PHP 7 >= 7.4.0, PHP 8) The **ReflectionReference** class provides information about a reference. Class synopsis -------------- final class **ReflectionReference** { /\* Methods \*/ private [\_\_construct](reflectionreference.construct)() ``` public static fromArrayElement(array $array, int|string $key): ?ReflectionReference ``` ``` public getId(): string ``` } Table of Contents ----------------- * [ReflectionReference::\_\_construct](reflectionreference.construct) — Private constructor to disallow direct instantiation * [ReflectionReference::fromArrayElement](reflectionreference.fromarrayelement) — Create a ReflectionReference from an array element * [ReflectionReference::getId](reflectionreference.getid) — Get unique ID of a reference php IntlChar::isJavaIDStart IntlChar::isJavaIDStart ======================= (PHP 7, PHP 8) IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier ### Description ``` public static IntlChar::isJavaIDStart(int|string $codepoint): ?bool ``` Determines if the specified character is permissible as the start of a Java identifier. In addition to [IntlChar::isIDStart()](intlchar.isidstart), **`true`** for characters with general categories "Sc" (currency symbols) and "Pc" (connecting punctuation). ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` may start a Java identifier, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isJavaIDStart("A")); var_dump(IntlChar::isJavaIDStart("$")); var_dump(IntlChar::isJavaIDStart("\n")); var_dump(IntlChar::isJavaIDStart("\u{2603}")); ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) bool(false) ``` ### See Also * [IntlChar::isIDStart()](intlchar.isidstart) - Check if code point is permissible as the first character in an identifier * [IntlChar::isJavaIDPart()](intlchar.isjavaidpart) - Check if code point is permissible in a Java identifier * [IntlChar::isalpha()](intlchar.isalpha) - Check if code point is a letter character php shmop_open shmop\_open =========== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) shmop\_open — Create or open shared memory block ### Description ``` shmop_open( int $key, string $mode, int $permissions, int $size ): Shmop|false ``` **shmop\_open()** can create or open a shared memory block. ### Parameters `key` System's id for the shared memory block. Can be passed as a decimal or hex. `mode` The flags that you can use: * "a" for access (sets SHM\_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only * "c" for create (sets IPC\_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write * "w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases. * "n" create a new memory segment (sets IPC\_CREATE|IPC\_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits. `permissions` The permissions that you wish to assign to your memory segment, those are the same as permission for a file. Permissions need to be passed in octal form, like for example `0644` `size` The size of the shared memory block you wish to create in bytes > > **Note**: > > > Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment. > > ### Return Values On success **shmop\_open()** will return a [Shmop](class.shmop) instance that you can use to access the shared memory segment you've created. **`false`** is returned on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns an [Shmop](class.shmop) instance now; previously, a resource was returned. | ### Examples **Example #1 Create a new shared memory block** ``` <?php $shm_key = ftok(__FILE__, 't'); $shm_id = shmop_open($shm_key, "c", 0644, 100); ?> ``` This example opened a shared memory block with a system id returned by [ftok()](function.ftok). ### See Also * [shmop\_close()](function.shmop-close) - Close shared memory block * [shmop\_delete()](function.shmop-delete) - Delete shared memory block php Yaf_View_Simple::render Yaf\_View\_Simple::render ========================= (Yaf >=1.0.0) Yaf\_View\_Simple::render — Render template ### Description ``` public Yaf_View_Simple::render(string $tpl, array $tpl_vars = ?): string ``` Render a template and return the result. ### Parameters `tpl` `tpl_vars` ### Return Values php Phar::__destruct Phar::\_\_destruct ================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::\_\_destruct — Destructs a Phar archive object ### Description public **Phar::\_\_destruct**() ### Parameters This function has no parameters. php imagecolorclosesthwb imagecolorclosesthwb ==================== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness ### Description ``` imagecolorclosesthwb( GdImage $image, int $red, int $green, int $blue ): int ``` Get the index of the color which has the hue, white and blackness nearest the given color. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `red` Value of red component. `green` Value of green component. `blue` Value of blue component. ### Return Values Returns an integer with the index of the color which has the hue, white and blackness nearest the given color. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Example of using **imagecolorclosesthwb()**** ``` <?php $im = imagecreatefromgif('php.gif'); echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152); imagedestroy($im); ?> ``` The above example will output something similar to: ``` HWB: 33 ``` ### See Also * [imagecolorclosest()](function.imagecolorclosest) - Get the index of the closest color to the specified color
programming_docs
php Memcached::cas Memcached::cas ============== (PECL memcached >= 0.1.0) Memcached::cas — Compare and swap an item ### Description ``` public Memcached::cas( float $cas_token, string $key, mixed $value, int $expiration = ? ): bool ``` **Memcached::cas()** performs a "check and set" operation, so that the item will be stored only if no other client has updated it since it was last fetched by this client. The check is done via the `cas_token` parameter which is a unique 64-bit value assigned to the existing item by memcache. See the documentation for **Memcached::get\*()** methods for how to obtain this token. Note that the token is represented as a float due to the limitations of PHP's integer space. ### Parameters `cas_token` Unique value associated with the existing item. Generated by memcache. `key` The key under which to store the value. `value` The value to store. `expiration` The expiration time, defaults to 0. See [Expiration Times](https://www.php.net/manual/en/memcached.expiration.php) for more info. ### Return Values Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_DATA_EXISTS`** if the item you are trying to store has been modified since you last fetched it. ### Examples **Example #1 **Memcached::cas()** example** ``` <?php $m = new Memcached(); $m->addServer('localhost', 11211); do {     /* fetch IP list and its token */     $ips = $m->get('ip_block', null, $cas);     /* if list doesn't exist yet, create it and do        an atomic add which will fail if someone else already added it */     if ($m->getResultCode() == Memcached::RES_NOTFOUND) {         $ips = array($_SERVER['REMOTE_ADDR']);         $m->add('ip_block', $ips);     /* otherwise, add IP to the list and store via compare-and-swap        with the token, which will fail if someone else updated the list */     } else {          $ips[] = $_SERVER['REMOTE_ADDR'];         $m->cas($cas, 'ip_block', $ips);     }    } while ($m->getResultCode() != Memcached::RES_SUCCESS); ?> ``` ### See Also * [Memcached::casByKey()](memcached.casbykey) - Compare and swap an item on a specific server php Ds\Pair::toArray Ds\Pair::toArray ================ (PECL ds >= 1.0.0) Ds\Pair::toArray — Converts the pair to an array ### Description ``` public Ds\Pair::toArray(): array ``` Converts the pair to an array. > > **Note**: > > > Casting to an array is not supported yet. > > ### Parameters This function has no parameters. ### Return Values An array containing all the values in the same order as the pair. ### Examples **Example #1 **Ds\Pair::toArray()** example** ``` <?php $pair = new \Ds\Pair("a", 1); var_dump($pair->toArray()); ?> ``` The above example will output something similar to: ``` array(2) { ["key"]=> string(1) "a" ["value"]=> int(1) } ``` php mb_strcut mb\_strcut ========== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_strcut — Get part of string ### Description ``` mb_strcut( string $string, int $start, ?int $length = null, ?string $encoding = null ): string ``` **mb\_strcut()** extracts a substring from a string similarly to [mb\_substr()](function.mb-substr), but operates on bytes instead of characters. If the cut position happens to be between two bytes of a multi-byte character, the cut is performed starting from the first byte of that character. This is also the difference to the [substr()](function.substr) function, which would simply cut the string between the bytes and thus result in a malformed byte sequence. ### Parameters `string` The string being cut. `start` If `start` is non-negative, the returned string will start at the `start`'th *byte* position in `string`, counting from zero. For instance, in the string '`abcdef`', the byte at position `0` is '`a`', the byte at position `2` is '`c`', and so forth. If `start` is negative, the returned string will start at the `start`'th byte counting back from the end of `string`. However, if the magnitude of a negative `start` is greater than the length of the string, the returned portion will start from the beginning of `string`. `length` Length in *bytes*. If omitted or `NULL` is passed, extract all bytes to the end of the string. If `length` is negative, the returned string will end at the `length`'th byte counting back from the end of `string`. However, if the magnitude of a negative `length` is greater than the number of characters after the `start` position, an empty string will be returned. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values **mb\_strcut()** returns the portion of `string` specified by the `start` and `length` parameters. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | ### See Also * [mb\_substr()](function.mb-substr) - Get part of string * [mb\_internal\_encoding()](function.mb-internal-encoding) - Set/Get internal character encoding php SolrQuery::__construct SolrQuery::\_\_construct ======================== (PECL solr >= 0.9.2) SolrQuery::\_\_construct — Constructor ### Description public **SolrQuery::\_\_construct**(string `$q` = ?) Constructor. ### Parameters `q` Optional search query ### Return Values None ### Errors/Exceptions Emits [SolrIllegalArgumentException](class.solrillegalargumentexception) in case of an invalid parameter was passed. ### Changelog | Version | Description | | --- | --- | | PECL solr 2.0.0 | If `q` was invalid, then a [SolrIllegalArgumentException](class.solrillegalargumentexception) is now thrown. Previously an error was emitted. | php Ds\Queue::allocate Ds\Queue::allocate ================== (PECL ds >= 1.0.0) Ds\Queue::allocate — Allocates enough memory for a required capacity ### Description ``` public Ds\Queue::allocate(int $capacity): void ``` Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added. > > **Note**: > > > Capacity will always be rounded up to the nearest power of 2. > > ### Parameters `capacity` The number of values for which capacity should be allocated. > > **Note**: > > > Capacity will stay the same if this value is less than or equal to the current capacity. > > > > **Note**: > > > Capacity will always be rounded up to the nearest power of 2. > > ### Return Values No value is returned. ### Examples **Example #1 **Ds\Queue::allocate()** example** ``` <?php $queue = new \Ds\Queue(); var_dump($queue->capacity()); $queue->allocate(100); var_dump($queue->capacity()); ?> ``` The above example will output something similar to: ``` int(8) int(128) ``` php SolrQuery::setTermsLimit SolrQuery::setTermsLimit ======================== (PECL solr >= 0.9.2) SolrQuery::setTermsLimit — Sets the maximum number of terms to return ### Description ``` public SolrQuery::setTermsLimit(int $limit): SolrQuery ``` Sets the maximum number of terms to return ### Parameters `limit` The maximum number of terms to return. All the terms will be returned if the limit is negative. ### Return Values Returns the current SolrQuery object, if the return value is used. php EventDnsBase::addNameserverIp EventDnsBase::addNameserverIp ============================= (PECL event >= 1.2.6-beta) EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base ### Description ``` public EventDnsBase::addNameserverIp( string $ip ): bool ``` Adds a nameserver to the evdns\_base. ### Parameters `ip` The nameserver string, either as an IPv4 address, an IPv6 address, an IPv4 address with a port ( `IPv4:Port` ), or an IPv6 address with a port ( `[IPv6]:Port` ). ### Return Values Returns **`true`** on success or **`false`** on failure. php sodium_hex2bin sodium\_hex2bin =============== (PHP 7 >= 7.2.0, PHP 8) sodium\_hex2bin — Decodes a hexadecimally encoded binary string ### Description ``` sodium_hex2bin(string $string, string $ignore = ""): string ``` Decodes a hexadecimally encoded binary string. Like [sodium\_bin2hex()](function.sodium-bin2hex), **sodium\_hex2bin()** is resistant to side-channel attacks while [hex2bin()](function.hex2bin) is not. ### Parameters `string` Hexadecimal representation of data. `ignore` Optional string argument for characters to ignore. ### Return Values Returns the binary representation of the given `string` data. php xmlrpc_server_call_method xmlrpc\_server\_call\_method ============================ (PHP 4 >= 4.1.0, PHP 5, PHP 7) xmlrpc\_server\_call\_method — Parses XML requests and call methods ### Description ``` xmlrpc_server_call_method( resource $server, string $xml, mixed $user_data, array $output_options = ? ): string ``` **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. **Warning**This function is currently not documented; only its argument list is available. php The RangeException class The RangeException class ======================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of [DomainException](class.domainexception). Class synopsis -------------- class **RangeException** extends [RuntimeException](class.runtimeexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php radius_cvt_addr radius\_cvt\_addr ================= (PECL radius >= 1.1.0) radius\_cvt\_addr — Converts raw data to IP-Address ### Description ``` radius_cvt_addr(string $data): string ``` Converts raw data to IP-Address ### Parameters `data` Input data ### Return Values Returns the IP-Address. ### Examples **Example #1 **radius\_cvt\_addr()** example** ``` <?php while ($resa = radius_get_attr($res)) {     if (!is_array($resa)) {         printf ("Error getting attribute: %s\n",  radius_strerror($res));         exit;     }     $attr = $resa['attr'];     $data = $resa['data'];          switch ($attr) {     case RADIUS_FRAMED_IP_ADDRESS:         $ip = radius_cvt_addr($data);         echo "IP: $ip<br>\n";         break;     case RADIUS_FRAMED_IP_NETMASK:         $mask = radius_cvt_addr($data);         echo "MASK: $mask<br>\n";         break;     } } ?> ``` ### See Also * [radius\_cvt\_int()](function.radius-cvt-int) - Converts raw data to integer * [radius\_cvt\_string()](function.radius-cvt-string) - Converts raw data to string php gmp_or gmp\_or ======= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_or — Bitwise OR ### Description ``` gmp_or(GMP|int|string $num1, GMP|int|string $num2): GMP ``` Calculates bitwise inclusive OR of two GMP numbers. ### Parameters `num1` A [GMP](class.gmp) object, an int or a numeric string. `num2` A [GMP](class.gmp) object, an int or a numeric string. ### Return Values A [GMP](class.gmp) object. ### Examples **Example #1 **gmp\_or()** example** ``` <?php $or1 = gmp_or("0xfffffff2", "4"); echo gmp_strval($or1, 16) . "\n"; $or2 = gmp_or("0xfffffff2", "2"); echo gmp_strval($or2, 16) . "\n"; ?> ``` The above example will output: ``` fffffff6 fffffff2 ``` php stats_dens_pmf_binomial stats\_dens\_pmf\_binomial ========================== (PECL stats >= 1.0.0) stats\_dens\_pmf\_binomial — Probability mass function of the binomial distribution ### Description ``` stats_dens_pmf_binomial(float $x, float $n, float $pi): float ``` Returns the probability mass at `x`, where the random variable follows the binomial distribution of which the number of trials is `n` and the success rate is `pi`. ### Parameters `x` The value at which the probability mass is calculated `n` The number of trials of the distribution `pi` The success rate of the distribution ### Return Values The probability mass at `x` or **`false`** for failure. php gmp_sign gmp\_sign ========= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_sign — Sign of number ### Description ``` gmp_sign(GMP|int|string $num): int ``` Checks the sign of a number. ### Parameters `num` Either a [GMP](class.gmp) object, or a numeric string provided that it is possible to convert the latter to an int. ### Return Values Returns 1 if `num` is positive, -1 if `num` is negative, and 0 if `num` is zero. ### Examples **Example #1 **gmp\_sign()** example** ``` <?php // positive echo gmp_sign("500") . "\n"; // negative echo gmp_sign("-500") . "\n"; // zero echo gmp_sign("0") . "\n"; ?> ``` The above example will output: ``` 1 -1 0 ``` ### See Also * [gmp\_abs()](function.gmp-abs) - Absolute value * [abs()](function.abs) - Absolute value php Imagick::getImageInterlaceScheme Imagick::getImageInterlaceScheme ================================ (PECL imagick 2, PECL imagick 3) Imagick::getImageInterlaceScheme — Gets the image interlace scheme ### Description ``` public Imagick::getImageInterlaceScheme(): int ``` Gets the image interlace scheme. ### Parameters This function has no parameters. ### Return Values Returns the interlace scheme as an integer on success. Throw an **ImagickException** on error. php Error::__clone Error::\_\_clone ================ (PHP 7, PHP 8) Error::\_\_clone — Clone the error ### Description ``` private Error::__clone(): void ``` Error can not be cloned, so this method results in fatal error. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Errors/Exceptions Errors are *not* clonable. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | **Error::\_\_clone()** is no longer final. | php preg_replace_callback_array preg\_replace\_callback\_array ============================== (PHP 7, PHP 8) preg\_replace\_callback\_array — Perform a regular expression search and replace using callbacks ### Description ``` preg_replace_callback_array( array $pattern, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0 ): string|array|null ``` The behavior of this function is similar to [preg\_replace\_callback()](function.preg-replace-callback), except that callbacks are executed on a per-pattern basis. ### Parameters `pattern` An associative array mapping patterns (keys) to [callable](language.types.callable)s (values). `subject` The string or an array with strings to search and replace. `limit` The maximum possible replacements for each pattern in each `subject` string. Defaults to `-1` (no limit). `count` If specified, this variable will be filled with the number of replacements done. `flags` `flags` can be a combination of the **`PREG_OFFSET_CAPTURE`** and **`PREG_UNMATCHED_AS_NULL`** flags, which influence the format of the matches array. See the description in [preg\_match()](function.preg-match) for more details. ### Return Values **preg\_replace\_callback\_array()** returns an array if the `subject` parameter is an array, or a string otherwise. On errors the return value is **`null`** If matches are found, the new subject will be returned, otherwise `subject` will be returned unchanged. ### Errors/Exceptions If the regex pattern passed does not compile to a valid regex, an **`E_WARNING`** is emitted. ### Changelog | Version | Description | | --- | --- | | 7.4.0 | The `flags` parameter was added. | ### Examples **Example #1 **preg\_replace\_callback\_array()** example** ``` <?php $subject = 'Aaaaaa Bbb'; preg_replace_callback_array(     [         '~[a]+~i' => function ($match) {             echo strlen($match[0]), ' matches for "a" found', PHP_EOL;         },         '~[b]+~i' => function ($match) {             echo strlen($match[0]), ' matches for "b" found', PHP_EOL;         }     ],     $subject ); ?> ``` The above example will output: ``` 6 matches for "a" found 3 matches for "b" found ``` ### See Also * [PCRE Patterns](https://www.php.net/manual/en/pcre.pattern.php) * [preg\_replace\_callback()](function.preg-replace-callback) - Perform a regular expression search and replace using a callback * [preg\_quote()](function.preg-quote) - Quote regular expression characters * [preg\_replace()](function.preg-replace) - Perform a regular expression search and replace * [preg\_last\_error()](function.preg-last-error) - Returns the error code of the last PCRE regex execution * [Anonymous functions](functions.anonymous) php mysqli::ping mysqli::ping ============ mysqli\_ping ============ (PHP 5, PHP 7, PHP 8) mysqli::ping -- mysqli\_ping — Pings a server connection, or tries to reconnect if the connection has gone down ### Description Object-oriented style ``` public mysqli::ping(): bool ``` Procedural style ``` mysqli_ping(mysqli $mysql): bool ``` Checks whether the connection to the server is working. If it has gone down and global option [mysqli.reconnect](https://www.php.net/manual/en/mysqli.configuration.php#ini.mysqli.reconnect) is enabled, an automatic reconnection is attempted. > **Note**: The php.ini setting mysqli.reconnect is ignored by the mysqlnd driver, so automatic reconnection is never attempted. > > This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **mysqli::ping()** example** Object-oriented style ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if ($mysqli->connect_errno) {     printf("Connect failed: %s\n", $mysqli->connect_error);     exit(); } /* check if server is alive */ if ($mysqli->ping()) {     printf ("Our connection is ok!\n"); } else {     printf ("Error: %s\n", $mysqli->error); } /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* check if server is alive */ if (mysqli_ping($link)) {     printf ("Our connection is ok!\n"); } else {     printf ("Error: %s\n", mysqli_error($link)); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Our connection is ok! ```
programming_docs
php IntlChar::ispunct IntlChar::ispunct ================= (PHP 7, PHP 8) IntlChar::ispunct — Check if code point is punctuation character ### Description ``` public static IntlChar::ispunct(int|string $codepoint): ?bool ``` Determines whether the specified code point is a punctuation character. **`true`** for characters with general categories "P" (punctuation). ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` is a punctuation character, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::ispunct(".")); var_dump(IntlChar::ispunct(",")); var_dump(IntlChar::ispunct("\n")); var_dump(IntlChar::ispunct("$")); ``` The above example will output: ``` bool(true) bool(true) bool(false) bool(false) ``` php The SoapHeader class The SoapHeader class ==================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Represents a SOAP header. Class synopsis -------------- class **SoapHeader** { /\* Properties \*/ public string [$namespace](class.soapheader#soapheader.props.namespace); public string [$name](class.soapheader#soapheader.props.name); public [mixed](language.types.declarations#language.types.declarations.mixed) [$data](class.soapheader#soapheader.props.data) = null; public bool [$mustUnderstand](class.soapheader#soapheader.props.mustunderstand); public string|int|null [$actor](class.soapheader#soapheader.props.actor); /\* Methods \*/ public [\_\_construct](soapheader.construct)( string `$namespace`, string `$name`, [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = ?, bool `$mustunderstand` = ?, string `$actor` = ? ) } Properties ---------- actor data mustUnderstand name namespace Table of Contents ----------------- * [SoapHeader::\_\_construct](soapheader.construct) — SoapHeader constructor php imap_utf8_to_mutf7 imap\_utf8\_to\_mutf7 ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) imap\_utf8\_to\_mutf7 — Encode a UTF-8 string to modified UTF-7 ### Description ``` imap_utf8_to_mutf7(string $string): string|false ``` Encode a UTF-8 string to modified UTF-7 (as specified in RFC 2060, section 5.1.3). > > **Note**: > > > This function is only available, if libcclient exports utf8\_to\_mutf7(). > > ### Parameters `string` A UTF-8 encoded string. ### Return Values Returns `string` converted to modified UTF-7, or **`false`** on failure. ### See Also * [imap\_mutf7\_to\_utf8()](function.imap-mutf7-to-utf8) - Decode a modified UTF-7 string to UTF-8 php XMLWriter::writeElement XMLWriter::writeElement ======================= xmlwriter\_write\_element ========================= (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::writeElement -- xmlwriter\_write\_element — Write full element tag ### Description Object-oriented style ``` public XMLWriter::writeElement(string $name, ?string $content = null): bool ``` Procedural style ``` xmlwriter_write_element(XMLWriter $writer, string $name, ?string $content = null): bool ``` Writes a full element tag. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `name` The element name. `content` The element contents. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::startElement()](xmlwriter.startelement) - Create start element tag * [XMLWriter::endElement()](xmlwriter.endelement) - End current element * [XMLWriter::writeElementNs()](xmlwriter.writeelementns) - Write full namespaced element tag php ReflectionAttribute::isRepeated ReflectionAttribute::isRepeated =============================== (PHP 8) ReflectionAttribute::isRepeated — Returns whether the attribute of this name has been repeated on a code element ### Description ``` public ReflectionAttribute::isRepeated(): bool ``` Returns whether the attribute of this name has been repeated on a code element. ### Parameters This function has no parameters. ### Return Values Returns **`true`** when attribute is used repeatedly, otherwise **`false`**. php Gmagick::getimageextrema Gmagick::getimageextrema ======================== (PECL gmagick >= Unknown) Gmagick::getimageextrema — Gets the extrema for the image ### Description ``` public Gmagick::getimageextrema(): array ``` Returns an associative array with the keys "min" and "max". Throws an **GmagickException** on error. ### Parameters This function has no parameters. ### Return Values Returns an associative array with the keys "min" and "max". ### Errors/Exceptions Throws an **GmagickException** on error. php Gmagick::resampleimage Gmagick::resampleimage ====================== (PECL gmagick >= Unknown) Gmagick::resampleimage — Resample image to desired resolution ### Description ``` public Gmagick::resampleimage( float $xResolution, float $yResolution, int $filter, float $blur ): Gmagick ``` Resample image to desired resolution. ### Parameters `xResolution` The new image x resolution. `yResolution` The new image y resolution. `filter` Image filter to use. `blur` The blur factor where larger than 1 is blurry, smaller than 1 is sharp. ### Return Values The Gmagick object on success ### Errors/Exceptions Throws an **GmagickException** on error. php imap_reopen imap\_reopen ============ (PHP 4, PHP 5, PHP 7, PHP 8) imap\_reopen — Reopen IMAP stream to new mailbox ### Description ``` imap_reopen( IMAP\Connection $imap, string $mailbox, int $flags = 0, int $retries = 0 ): bool ``` Reopens the specified stream to a new `mailbox` on an IMAP or NNTP server. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `mailbox` The mailbox name, see [imap\_open()](function.imap-open) for more information **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. `flags` The `flags` are a bit mask with one or more of the following: * **`OP_READONLY`** - Open mailbox read-only * **`OP_ANONYMOUS`** - Don't use or update a .newsrc for news (NNTP only) * **`OP_HALFOPEN`** - For IMAP and NNTP names, open a connection but don't open a mailbox. * **`OP_EXPUNGE`** - Silently expunge recycle stream * **`CL_EXPUNGE`** - Expunge mailbox automatically upon mailbox close (see also [imap\_delete()](function.imap-delete) and [imap\_expunge()](function.imap-expunge)) `retries` Number of maximum connect attempts ### Return Values Returns **`true`** if the stream is reopened, **`false`** otherwise. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_reopen()** example** ``` <?php $mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors())); // ... imap_reopen($mbox, "{imap.example.org:143}INBOX.Sent") or die(implode(", ", imap_errors())); // .. ?> ``` php EventBase::stop EventBase::stop =============== (PECL event >= 1.2.6-beta) EventBase::stop — Tells event\_base to stop dispatching events ### Description ``` public EventBase::stop(): bool ``` Tells event\_base to stop dispatching events ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventBase::exit()](eventbase.exit) - Stop dispatching events * [EventBase::gotStop()](eventbase.gotstop) - Checks if the event loop was told to exit php RecursiveTreeIterator::setPostfix RecursiveTreeIterator::setPostfix ================================= (PHP 5 >= 5.5.3, PHP 7, PHP 8) RecursiveTreeIterator::setPostfix — Set postfix ### Description ``` public RecursiveTreeIterator::setPostfix(string $postfix): void ``` Sets postfix as used in [RecursiveTreeIterator::getPostfix()](recursivetreeiterator.getpostfix). **Warning**This function is currently not documented; only its argument list is available. ### Parameters `postfix` ### Return Values No value is returned. php imageantialias imageantialias ============== (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) imageantialias — Should antialias functions be used or not ### Description ``` imageantialias(GdImage $image, bool $enable): bool ``` Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images. Thickness and styled are not supported. Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `enable` Whether to enable antialiasing or not. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | | 7.2.0 | **imageantialias()** is now generally available. Formerly it was only available if PHP was compiled with the bundled version of the GD library. | ### Examples **Example #1 A comparison of two lines, one with anti-aliasing switched on** ``` <?php // Setup an anti-aliased image and a normal image $aa = imagecreatetruecolor(400, 100); $normal = imagecreatetruecolor(200, 100); // Switch antialiasing on for one image imageantialias($aa, true); // Allocate colors $red = imagecolorallocate($normal, 255, 0, 0); $red_aa = imagecolorallocate($aa, 255, 0, 0); // Draw two lines, one with AA enabled imageline($normal, 0, 0, 200, 100, $red); imageline($aa, 0, 0, 200, 100, $red_aa); // Merge the two images side by side for output (AA: left, Normal: Right) imagecopymerge($aa, $normal, 200, 0, 0, 0, 200, 100, 100); // Output image header('Content-type: image/png'); imagepng($aa); imagedestroy($aa); imagedestroy($normal); ?> ``` The above example will output something similar to: ### See Also * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image php sodium_crypto_sign_keypair sodium\_crypto\_sign\_keypair ============================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_sign\_keypair — Randomly generate a secret key and a corresponding public key ### Description ``` sodium_crypto_sign_keypair(): string ``` Generate a random Ed25519 keypair as one string. ### Parameters This function has no parameters. ### Return Values Ed25519 keypair. php Yaf_Loader::getLibraryPath Yaf\_Loader::getLibraryPath =========================== (Yaf >=2.1.4) Yaf\_Loader::getLibraryPath — Get the library path ### Description ``` public Yaf_Loader::getLibraryPath(bool $is_global = false): Yaf_Loader ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php fbird_free_result fbird\_free\_result =================== (PHP 5, PHP 7 < 7.4.0) fbird\_free\_result — Alias of [ibase\_free\_result()](function.ibase-free-result) ### Description This function is an alias of: [ibase\_free\_result()](function.ibase-free-result). php array_key_exists array\_key\_exists ================== (PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8) array\_key\_exists — Checks if the given key or index exists in the array ### Description ``` array_key_exists(string|int $key, array $array): bool ``` **array\_key\_exists()** returns **`true`** if the given `key` is set in the array. `key` can be any value possible for an array index. ### Parameters `key` Value to check. `array` An array with keys to check. ### Return Values Returns **`true`** on success or **`false`** on failure. > > **Note**: > > > **array\_key\_exists()** will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found. > > ### Examples **Example #1 **array\_key\_exists()** example** ``` <?php $search_array = array('first' => 1, 'second' => 4); if (array_key_exists('first', $search_array)) {     echo "The 'first' element is in the array"; } ?> ``` **Example #2 **array\_key\_exists()** vs [isset()](function.isset)** [isset()](function.isset) does not return **`true`** for array keys that correspond to a **`null`** value, while **array\_key\_exists()** does. ``` <?php $search_array = array('first' => null, 'second' => 4); // returns false isset($search_array['first']); // returns true array_key_exists('first', $search_array); ?> ``` ### Notes > > **Note**: > > > For backward compatibility reasons, **array\_key\_exists()** will also return **`true`** if `key` is a property defined within an object given as `array`. This behaviour is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0. > > To check whether a property exists in an object, [property\_exists()](function.property-exists) should be used. > > ### See Also * [isset()](function.isset) - Determine if a variable is declared and is different than null * [array\_keys()](function.array-keys) - Return all the keys or a subset of the keys of an array * [in\_array()](function.in-array) - Checks if a value exists in an array * [property\_exists()](function.property-exists) - Checks if the object or class has a property php Yaf_Session::next Yaf\_Session::next ================== (Yaf >=1.0.0) Yaf\_Session::next — The next purpose ### Description ``` public Yaf_Session::next(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php tidy::parseFile tidy::parseFile =============== tidy\_parse\_file ================= (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy::parseFile -- tidy\_parse\_file — Parse markup in file or URI ### Description Object-oriented style ``` public tidy::parseFile( string $filename, array|string|null $config = null, ?string $encoding = null, bool $useIncludePath = false ): bool ``` Procedural style ``` tidy_parse_file( string $filename, array|string|null $config = null, ?string $encoding = null, bool $useIncludePath = false ): tidy|false ``` Parses the given file. ### Parameters `filename` If the `filename` parameter is given, this function will also read that file and initialize the object with the file, acting like **tidy\_parse\_file()**. `config` The config `config` can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves. For an explanation about each option, see [» http://api.html-tidy.org/#quick-reference](http://api.html-tidy.org/#quick-reference). `encoding` The `encoding` parameter sets the encoding for input/output documents. The possible values for encoding are: `ascii`, `latin0`, `latin1`, `raw`, `utf8`, `iso2022`, `mac`, `win1252`, `ibm858`, `utf16`, `utf16le`, `utf16be`, `big5`, and `shiftjis`. `useIncludePath` Search for the file in the [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path). ### Return Values **tidy::parseFile()** returns **`true`** on success. **tidy\_parse\_file()** returns a new [tidy](class.tidy) instance on success. Both, the method and the function return **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `config` and `encoding` are nullable now. | ### Examples **Example #1 **tidy::parseFile()** example** ``` <?php $tidy = new tidy(); $tidy->parseFile('file.html'); $tidy->cleanRepair(); if(!empty($tidy->errorBuffer)) {     echo "The following errors or warnings occurred:\n";     echo $tidy->errorBuffer; } ?> ``` ### See Also * [tidy::parsestring()](tidy.parsestring) - Parse a document stored in a string * [tidy::repairfile()](tidy.repairfile) - Repair a file and return it as a string * [tidy::repairstring()](tidy.repairstring) - Repair a string using an optionally provided configuration file php mailparse_determine_best_xfer_encoding mailparse\_determine\_best\_xfer\_encoding ========================================== (PECL mailparse >= 0.9.0) mailparse\_determine\_best\_xfer\_encoding — Gets the best way of encoding ### Description ``` mailparse_determine_best_xfer_encoding(resource $fp): string ``` Figures out the best way of encoding the content read from the given file pointer. ### Parameters `fp` A valid file pointer, which must be seek-able. ### Return Values Returns one of the character encodings supported by the [mbstring](https://www.php.net/manual/en/ref.mbstring.php) module. ### Examples **Example #1 **mailparse\_determine\_best\_xfer\_encoding()** example** ``` <?php $fp = fopen('somemail.eml', 'r'); echo 'Best encoding: ' . mailparse_determine_best_xfer_encoding($fp); ?> ``` The above example will output something similar to: ``` Best encoding: 7bit ``` php The CurlShareHandle class The CurlShareHandle class ========================= Introduction ------------ (PHP 8) A fully opaque class which replaces `curl_share` resources as of PHP 8.0.0. Class synopsis -------------- final class **CurlShareHandle** { } php spl_classes spl\_classes ============ (PHP 5, PHP 7, PHP 8) spl\_classes — Return available SPL classes ### Description ``` spl_classes(): array ``` This function returns an array with the current available SPL classes. ### Parameters This function has no parameters. ### Return Values Returns an array containing the currently available SPL classes. ### Examples **Example #1 **spl\_classes()** example** ``` <?php print_r(spl_classes()); ?> ``` The above example will output something similar to: ``` Array ( [ArrayObject] => ArrayObject [ArrayIterator] => ArrayIterator [CachingIterator] => CachingIterator [RecursiveCachingIterator] => RecursiveCachingIterator [DirectoryIterator] => DirectoryIterator [FilterIterator] => FilterIterator [LimitIterator] => LimitIterator [ParentIterator] => ParentIterator [RecursiveDirectoryIterator] => RecursiveDirectoryIterator [RecursiveIterator] => RecursiveIterator [RecursiveIteratorIterator] => RecursiveIteratorIterator [SeekableIterator] => SeekableIterator [SimpleXMLIterator] => SimpleXMLIterator ) ```
programming_docs
php geoip_region_by_name geoip\_region\_by\_name ======================= (PECL geoip >= 0.2.0) geoip\_region\_by\_name — Get the country code and region ### Description ``` geoip_region_by_name(string $hostname): array ``` The **geoip\_region\_by\_name()** function will return the country and region corresponding to a hostname or an IP address. This function is currently only available to users who have bought a commercial GeoIP Region Edition. A warning will be issued if the proper database cannot be located. The names of the different keys of the returning associative array are as follows: * "country\_code" -- Two letter country code (see [geoip\_country\_code\_by\_name()](function.geoip-country-code-by-name)) * "region" -- The region code (ex: CA for California) ### Parameters `hostname` The hostname or IP address whose region is to be looked-up. ### Return Values Returns the associative array on success, or **`false`** if the address cannot be found in the database. ### Examples **Example #1 A **geoip\_region\_by\_name()** example** This will print the array containing the country code and region of the host example.com. ``` <?php $region = geoip_region_by_name('www.example.com'); if ($region) {     print_r($region); } ?> ``` The above example will output: ``` Array ( [country_code] => US [region] => CA ) ``` php None do-while -------- (PHP 4, PHP 5, PHP 7, PHP 8) `do-while` loops are very similar to `while` loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular `while` loops is that the first iteration of a `do-while` loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular `while` loop (the truth expression is checked at the beginning of each iteration, if it evaluates to **`false`** right from the beginning, the loop execution would end immediately). There is just one syntax for `do-while` loops: ``` <?php $i = 0; do {     echo $i; } while ($i > 0); ?> ``` The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to **`false`** ($i is not bigger than 0) and the loop execution ends. Advanced C users may be familiar with a different usage of the `do-while` loop, to allow stopping execution in the middle of code blocks, by encapsulating them with `do-while` (0), and using the [`break`](control-structures.break) statement. The following code fragment demonstrates this: ``` <?php do {     if ($i < 5) {         echo "i is not big enough";         break;     }     $i *= $factor;     if ($i < $minimum_limit) {         break;     }    echo "i is ok";     /* process i */ } while (0); ?> ``` It is possible to use the [`goto`](control-structures.goto) operator instead of this hack. php Yaf_Plugin_Abstract::routerShutdown Yaf\_Plugin\_Abstract::routerShutdown ===================================== (Yaf >=1.0.0) Yaf\_Plugin\_Abstract::routerShutdown — The routerShutdown purpose ### Description ``` public Yaf_Plugin_Abstract::routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void ``` This hook will be trigged after the route process finished, this hook is usually used for login check. ### Parameters `request` `response` ### Return Values ### Examples **Example #1 **Yaf\_Plugin\_Abstract::routerShutdown()**example** ``` <?php class UserInitPlugin extends Yaf_Plugin_Abstract {     public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {         $controller = $request->getControllerName();         /**          * Use access controller is unecessary for APIs          */         if (in_array(strtolower($controller), array(             'api',           ))) {             return TRUE;         }                 if (Yaf_Session::getInstance()->has("login")) {             return TRUE;         }           /* Use access check failed, need to login */         $response->setRedirect("http://yourdomain.com/login/");         return FALSE;     } } ?> ``` ### See Also * [Yaf\_Plugin\_Abstract::routerStartup()](yaf-plugin-abstract.routerstartup) - RouterStartup hook * [Yaf\_Plugin\_Abstract::dispatchLoopStartup()](yaf-plugin-abstract.dispatchloopstartup) - Hook before dispatch loop * [Yaf\_Plugin\_Abstract::preDispatch()](yaf-plugin-abstract.predispatch) - The preDispatch purpose * [Yaf\_Plugin\_Abstract::postDispatch()](yaf-plugin-abstract.postdispatch) - The postDispatch purpose * [Yaf\_Plugin\_Abstract::dispatchLoopShutdown()](yaf-plugin-abstract.dispatchloopshutdown) - The dispatchLoopShutdown purpose php SolrQuery::addHighlightField SolrQuery::addHighlightField ============================ (PECL solr >= 0.9.2) SolrQuery::addHighlightField — Maps to hl.fl ### Description ``` public SolrQuery::addHighlightField(string $field): SolrQuery ``` Maps to hl.fl. This is used to specify that highlighted snippets should be generated for a particular field ### Parameters `field` Name of the field ### Return Values Returns the current SolrQuery object, if the return value is used. php unixtojd unixtojd ======== (PHP 4, PHP 5, PHP 7, PHP 8) unixtojd — Convert Unix timestamp to Julian Day ### Description ``` unixtojd(?int $timestamp = null): int|false ``` Return the Julian Day for a Unix `timestamp` (seconds since 1.1.1970), or for the current day if no `timestamp` is given. Either way, the time is regarded as local time (not UTC). ### Parameters `timestamp` A unix timestamp to convert. ### Return Values A julian day number as integer, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `timestamp` is nullable now. | ### See Also * [jdtounix()](function.jdtounix) - Convert Julian Day to Unix timestamp php SplSubject::detach SplSubject::detach ================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplSubject::detach — Detach an observer ### Description ``` public SplSubject::detach(SplObserver $observer): void ``` Detaches an observer from the subject to no longer notify it of updates. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `observer` The [SplObserver](class.splobserver) to detach. ### Return Values No value is returned. php Zookeeper::setWatcher Zookeeper::setWatcher ===================== (PECL zookeeper >= 0.1.0) Zookeeper::setWatcher — Set a watcher function ### Description ``` public Zookeeper::setWatcher(callable $watcher_cb): bool ``` ### Parameters `watcher_cb` A watch will be set at the server to notify the client if the node changes. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions This method emits PHP error/warning when parameters count or types are wrong or fail to set watcher. **Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives. ### See Also * [Zookeeper::exists()](zookeeper.exists) - Checks the existence of a node in zookeeper synchronously * [Zookeeper::get()](zookeeper.get) - Gets the data associated with a node synchronously * [ZookeeperException](class.zookeeperexception) php EventHttpRequest::getOutputBuffer EventHttpRequest::getOutputBuffer ================================= (PECL event >= 1.4.0-beta) EventHttpRequest::getOutputBuffer — Returns the output buffer of the request ### Description ``` public EventHttpRequest::getOutputBuffer(): EventBuffer ``` Returns the output buffer of the request. ### Parameters This function has no parameters. ### Return Values Returns the output buffer of the request. ### See Also * [EventHttpRequest::getInputBuffer()](eventhttprequest.getinputbuffer) - Returns the input buffer php ibase_fetch_object ibase\_fetch\_object ==================== (PHP 5, PHP 7 < 7.4.0) ibase\_fetch\_object — Get an object from a InterBase database ### Description ``` ibase_fetch_object(resource $result_id, int $fetch_flag = 0): object ``` Fetches a row as a pseudo-object from a given result identifier. Subsequent calls to **ibase\_fetch\_object()** return the next row in the result set. ### Parameters `result_id` An InterBase result identifier obtained either by [ibase\_query()](function.ibase-query) or [ibase\_execute()](function.ibase-execute). `fetch_flag` `fetch_flag` is a combination of the constants **`IBASE_TEXT`** and **`IBASE_UNIXTIME`** ORed together. Passing **`IBASE_TEXT`** will cause this function to return BLOB contents instead of BLOB ids. Passing **`IBASE_UNIXTIME`** will cause this function to return date/time values as Unix timestamps instead of as formatted strings. ### Return Values Returns an object with the next row information, or **`false`** if there are no more rows. ### Examples **Example #1 **ibase\_fetch\_object()** example** ``` <?php $dbh = ibase_connect($host, $username, $password); $stmt = 'SELECT * FROM tblname'; $sth = ibase_query($dbh, $stmt); while ($row = ibase_fetch_object($sth)) {     echo $row->email . "\n"; } ibase_close($dbh); ?> ``` ### See Also * [ibase\_fetch\_row()](function.ibase-fetch-row) - Fetch a row from an InterBase database * [ibase\_fetch\_assoc()](function.ibase-fetch-assoc) - Fetch a result row from a query as an associative array php SolrIllegalArgumentException::getInternalInfo SolrIllegalArgumentException::getInternalInfo ============================================= (PECL solr >= 0.9.2) SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown ### Description ``` public SolrIllegalArgumentException::getInternalInfo(): array ``` Returns internal information where the Exception was thrown. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers. php SyncReaderWriter::readlock SyncReaderWriter::readlock ========================== (PECL sync >= 1.0.0) SyncReaderWriter::readlock — Waits for a read lock ### Description ``` public SyncReaderWriter::readlock(int $wait = -1): bool ``` Obtains a read lock on a [SyncReaderWriter](class.syncreaderwriter) object. ### Parameters `wait` The number of milliseconds to wait for a lock. A value of -1 is infinite. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **SyncReaderWriter::readlock()** example** ``` <?php $readwrite = new SyncReaderWriter("FileCacheLock"); $readwrite->readlock(); /* ... */ $readwrite->readunlock(); ?> ``` ### See Also * [SyncReaderWriter::readunlock()](syncreaderwriter.readunlock) - Releases a read lock php Yaf_Request_Abstract::isOptions Yaf\_Request\_Abstract::isOptions ================================= (Yaf >=1.0.0) Yaf\_Request\_Abstract::isOptions — Determine if request is OPTIONS request ### Description ``` public Yaf_Request_Abstract::isOptions(): bool ``` ### Parameters This function has no parameters. ### Return Values boolean php jdtofrench jdtofrench ========== (PHP 4, PHP 5, PHP 7, PHP 8) jdtofrench — Converts a Julian Day Count to the French Republican Calendar ### Description ``` jdtofrench(int $julian_day): string ``` Converts a Julian Day Count to the French Republican Calendar. ### Parameters `julian_day` A julian day number as integer ### Return Values The french revolution date as a string in the form "month/day/year" ### See Also * [frenchtojd()](function.frenchtojd) - Converts a date from the French Republican Calendar to a Julian Day Count * [cal\_from\_jd()](function.cal-from-jd) - Converts from Julian Day Count to a supported calendar php The Collection interface The Collection interface ======================== Introduction ------------ (No version information available, might only be in Git) **Collection** is the base interface which covers functionality common to all the data structures in this library. It guarantees that all structures are traversable, countable, and can be converted to json using [json\_encode()](function.json-encode). Interface synopsis ------------------ class **Ds\Collection** implements [Countable](class.countable), [IteratorAggregate](class.iteratoraggregate), [JsonSerializable](class.jsonserializable) { /\* Methods \*/ ``` abstract public clear(): void ``` ``` abstract public copy(): Ds\Collection ``` ``` abstract public isEmpty(): bool ``` ``` abstract public toArray(): array ``` } Changelog --------- | Version | Description | | --- | --- | | PECL ds 1.4.0 | **Collection** implements [IteratorAggregate](class.iteratoraggregate) now instead of just [Traversable](class.traversable). (This change came to the polyfill in 1.4.1.) | Table of Contents ----------------- * [Ds\Collection::clear](ds-collection.clear) — Removes all values * [Ds\Collection::copy](ds-collection.copy) — Returns a shallow copy of the collection * [Ds\Collection::isEmpty](ds-collection.isempty) — Returns whether the collection is empty * [Ds\Collection::toArray](ds-collection.toarray) — Converts the collection to an array php IntlChar::isxdigit IntlChar::isxdigit ================== (PHP 7, PHP 8) IntlChar::isxdigit — Check if code point is a hexadecimal digit ### Description ``` public static IntlChar::isxdigit(int|string $codepoint): ?bool ``` Determines whether the specified code point is a hexadecimal digit. **`true`** for characters with general category "Nd" (decimal digit numbers) as well as Latin letters a-f and A-F in both ASCII and Fullwidth ASCII. (That is, for letters with code points 0041..0046, 0061..0066, FF21..FF26, FF41..FF46.) This is equivalent to `IntlChar::digit($codepoint, 16) >= 0`. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` is a hexadecimal character, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isxdigit("A")); var_dump(IntlChar::isxdigit("1")); var_dump(IntlChar::isxdigit("\u{2603}")); ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) ``` ### Notes > > **Note**: > > > In order to narrow the definition of hexadecimal digits to only ASCII characters use: > > > ``` > <?php > $isASCIIHexadecimal = IntlChar::ord($codepoint) <= 0x7F && IntlChar::isxdigit($codepoint); > ?> > ``` > ### See Also * [IntlChar::isdigit()](intlchar.isdigit) - Check if code point is a digit character php ImagickDraw::setStrokeLineCap ImagickDraw::setStrokeLineCap ============================= (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked ### Description ``` public ImagickDraw::setStrokeLineCap(int $linecap): bool ``` **Warning**This function is currently not documented; only its argument list is available. Specifies the shape to be used at the end of open subpaths when they are stroked. ### Parameters `linecap` One of the [LINECAP](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.linecap) constant (`imagick::LINECAP_*`). ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setStrokeLineCap()** example** ``` <?php function setStrokeLineCap($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(25);     $lineTypes = [\Imagick::LINECAP_BUTT, \Imagick::LINECAP_ROUND, \Imagick::LINECAP_SQUARE,];     $offset = 0;     foreach ($lineTypes as $lineType) {         $draw->setStrokeLineCap($lineType);         $draw->line(50 + $offset, 50, 50 + $offset, 250);         $offset += 50;     }     $imagick = new \Imagick();     $imagick->newImage(300, 300, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php ReflectionFunctionAbstract::hasReturnType ReflectionFunctionAbstract::hasReturnType ========================================= (PHP 7, PHP 8) ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type ### Description ``` public ReflectionFunctionAbstract::hasReturnType(): bool ``` Checks whether the reflected function has a return type specified. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the function is a specified return type, otherwise **`false`**. ### Examples **Example #1 **ReflectionFunctionAbstract::hasReturnType()** example** ``` <?php function to_int($param) : int {     return (int) $param; } $reflection1 = new ReflectionFunction('to_int'); var_dump($reflection1->hasReturnType()); ``` The above example will output: ``` bool(true) ``` **Example #2 Usage on built-in functions** ``` <?php $reflection2 = new ReflectionFunction('array_merge'); var_dump($reflection2->hasReturnType()); ``` The above example will output: ``` bool(false) ``` This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions. ### See Also * [ReflectionFunctionAbstract::getReturnType()](reflectionfunctionabstract.getreturntype) - Gets the specified return type of a function php filter_id filter\_id ========== (PHP 5 >= 5.2.0, PHP 7, PHP 8) filter\_id — Returns the filter ID belonging to a named filter ### Description ``` filter_id(string $name): int|false ``` ### Parameters `name` Name of a filter to get. ### Return Values ID of a filter on success or **`false`** if filter doesn't exist. ### See Also * [filter\_list()](function.filter-list) - Returns a list of all supported filters php Yaf_Application::__destruct Yaf\_Application::\_\_destruct ============================== (Yaf >=1.0.0) Yaf\_Application::\_\_destruct — The \_\_destruct purpose ### Description public **Yaf\_Application::\_\_destruct**() ### Parameters This function has no parameters. ### Return Values php Spoofchecker::setChecks Spoofchecker::setChecks ======================= (PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0) Spoofchecker::setChecks — Set the checks to run ### Description ``` public Spoofchecker::setChecks(int $checks): void ``` Sets the checks that will be performed by [SpoofChecker::isSuspicious()](spoofchecker.issuspicious). ### Parameters `checks` The checks that will be performed by [SpoofChecker::isSuspicious()](spoofchecker.issuspicious). A bitmask of **`Spoofchecker::SINGLE_SCRIPT_CONFUSABLE`**, **`Spoofchecker::MIXED_SCRIPT_CONFUSABLE`**, **`Spoofchecker::WHOLE_SCRIPT_CONFUSABLE`**, **`Spoofchecker::ANY_CASE`**, **`Spoofchecker::SINGLE_SCRIPT`**, **`Spoofchecker::INVISIBLE`**, or **`Spoofchecker::CHAR_LIMIT`**. Defaults to all checks as of ICU 58; prior to that version, **`Spoofchecker::SINGLE_SCRIPT`** was excluded. ### Return Values No value is returned.
programming_docs
php Ds\Deque::count Ds\Deque::count =============== (PECL ds >= 1.0.0) Ds\Deque::count — Returns the number of values in the collection See [Countable::count()](countable.count) php The SplPriorityQueue class The SplPriorityQueue class ========================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) The SplPriorityQueue class provides the main functionalities of a prioritized queue, implemented using a max heap. > **Note**: The order of elements with identical priority is *undefined*. It may differ from the order in which they have been inserted. > > Class synopsis -------------- class **SplPriorityQueue** implements [Iterator](class.iterator), [Countable](class.countable) { /\* Methods \*/ ``` public compare(mixed $priority1, mixed $priority2): int ``` ``` public count(): int ``` ``` public current(): mixed ``` ``` public extract(): mixed ``` ``` public getExtractFlags(): int ``` ``` public insert(mixed $value, mixed $priority): bool ``` ``` public isCorrupted(): bool ``` ``` public isEmpty(): bool ``` ``` public key(): int ``` ``` public next(): void ``` ``` public recoverFromCorruption(): bool ``` ``` public rewind(): void ``` ``` public setExtractFlags(int $flags): int ``` ``` public top(): mixed ``` ``` public valid(): bool ``` } Table of Contents ----------------- * [SplPriorityQueue::compare](splpriorityqueue.compare) — Compare priorities in order to place elements correctly in the heap while sifting up * [SplPriorityQueue::count](splpriorityqueue.count) — Counts the number of elements in the queue * [SplPriorityQueue::current](splpriorityqueue.current) — Return current node pointed by the iterator * [SplPriorityQueue::extract](splpriorityqueue.extract) — Extracts a node from top of the heap and sift up * [SplPriorityQueue::getExtractFlags](splpriorityqueue.getextractflags) — Get the flags of extraction * [SplPriorityQueue::insert](splpriorityqueue.insert) — Inserts an element in the queue by sifting it up * [SplPriorityQueue::isCorrupted](splpriorityqueue.iscorrupted) — Tells if the priority queue is in a corrupted state * [SplPriorityQueue::isEmpty](splpriorityqueue.isempty) — Checks whether the queue is empty * [SplPriorityQueue::key](splpriorityqueue.key) — Return current node index * [SplPriorityQueue::next](splpriorityqueue.next) — Move to the next node * [SplPriorityQueue::recoverFromCorruption](splpriorityqueue.recoverfromcorruption) — Recover from the corrupted state and allow further actions on the queue * [SplPriorityQueue::rewind](splpriorityqueue.rewind) — Rewind iterator back to the start (no-op) * [SplPriorityQueue::setExtractFlags](splpriorityqueue.setextractflags) — Sets the mode of extraction * [SplPriorityQueue::top](splpriorityqueue.top) — Peeks at the node from the top of the queue * [SplPriorityQueue::valid](splpriorityqueue.valid) — Check whether the queue contains more nodes php DirectoryIterator::isExecutable DirectoryIterator::isExecutable =============================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable ### Description ``` public DirectoryIterator::isExecutable(): bool ``` Determines if the current [DirectoryIterator](class.directoryiterator) item is executable. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the entry is executable, otherwise **`false`** ### Examples **Example #1 **DirectoryIterator::isExecutable()** example** This example lists files in the directory containing the script which are executable. ``` <?php $iterator = new DirectoryIterator(dirname(__FILE__)); foreach ($iterator as $fileinfo) {     if ($fileinfo->isExecutable()) {         echo $fileinfo->getFilename() . "\n";     } } ?> ``` The above example will output something similar to: ``` example.php myscript.sh ``` ### See Also * [DirectoryIterator::isReadable()](directoryiterator.isreadable) - Determine if current DirectoryIterator item can be read * [DirectoryIterator::isWritable()](directoryiterator.iswritable) - Determine if current DirectoryIterator item can be written to * [DirectoryIterator::getPerms()](directoryiterator.getperms) - Get the permissions of current DirectoryIterator item php IntlChar::iscntrl IntlChar::iscntrl ================= (PHP 7, PHP 8) IntlChar::iscntrl — Check if code point is a control character ### Description ``` public static IntlChar::iscntrl(int|string $codepoint): ?bool ``` Determines whether the specified code point is a control character. A control character is one of the following: * ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f) * **`IntlChar::CHAR_CATEGORY_CONTROL_CHAR`** (Cc) * **`IntlChar::CHAR_CATEGORY_FORMAT_CHAR`** (Cf) * **`IntlChar::CHAR_CATEGORY_LINE_SEPARATOR`** (Zl) * **`IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR`** (Zp) ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` is a control character, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::iscntrl("A")); var_dump(IntlChar::iscntrl(" ")); var_dump(IntlChar::iscntrl("\n")); var_dump(IntlChar::iscntrl("\u{200e}")); ?> ``` The above example will output: ``` bool(false) bool(false) bool(true) bool(true) ``` ### See Also * [IntlChar::isprint()](intlchar.isprint) - Check if code point is a printable character * **`IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT`** php SplPriorityQueue::compare SplPriorityQueue::compare ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up ### Description ``` public SplPriorityQueue::compare(mixed $priority1, mixed $priority2): int ``` Compare `priority1` with `priority2`. ### Parameters `priority1` The priority of the first node being compared. `priority2` The priority of the second node being compared. ### Return Values Result of the comparison, positive integer if `priority1` is greater than `priority2`, 0 if they are equal, negative integer otherwise. > > **Note**: > > > Multiple elements with the same priority will get dequeued in no particular order. > > php SolrQuery::getHighlightSimplePre SolrQuery::getHighlightSimplePre ================================ (PECL solr >= 0.9.2) SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term ### Description ``` public SolrQuery::getHighlightSimplePre(string $field_override = ?): string ``` Returns the text which appears before a highlighted term. Accepts an optional field override ### Parameters `field_override` The name of the field ### Return Values Returns a string on success and **`null`** if not set. php gmp_sqrt gmp\_sqrt ========= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_sqrt — Calculate square root ### Description ``` gmp_sqrt(GMP|int|string $num): GMP ``` Calculates square root of `num`. ### Parameters `num` A [GMP](class.gmp) object, an int or a numeric string. ### Return Values The integer portion of the square root, as a GMP number. ### Examples **Example #1 **gmp\_sqrt()** example** ``` <?php $sqrt1 = gmp_sqrt("9"); $sqrt2 = gmp_sqrt("7"); $sqrt3 = gmp_sqrt("1524157875019052100"); echo gmp_strval($sqrt1) . "\n"; echo gmp_strval($sqrt2) . "\n"; echo gmp_strval($sqrt3) . "\n"; ?> ``` The above example will output: ``` 3 2 1234567890 ``` php IntlBreakIterator::isBoundary IntlBreakIterator::isBoundary ============================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlBreakIterator::isBoundary — Tell whether an offset is a boundaryʼs offset ### Description ``` public IntlBreakIterator::isBoundary(int $offset): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `offset` ### Return Values php imageconvolution imageconvolution ================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset ### Description ``` imageconvolution( GdImage $image, array $matrix, float $divisor, float $offset ): bool ``` Applies a convolution matrix on the image, using the given coefficient and offset. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `matrix` A 3x3 matrix: an array of three arrays of three floats. `divisor` The divisor of the result of the convolution, used for normalization. `offset` Color offset. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Embossing the PHP.net logo** ``` <?php $image = imagecreatefromgif('http://www.php.net/images/php.gif'); $emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1)); imageconvolution($image, $emboss, 1, 127); header('Content-Type: image/png'); imagepng($image, null, 9); ?> ``` The above example will output: **Example #2 Gaussian blur** ``` <?php $image = imagecreatetruecolor(180,40); // Writes the text and apply a gaussian blur on the image imagestring($image, 5, 10, 8, 'Gaussian Blur Text', 0x00ff00); $gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0)); imageconvolution($image, $gaussian, 16, 0); // Rewrites the text for comparison imagestring($image, 5, 10, 18, 'Gaussian Blur Text', 0x00ff00); header('Content-Type: image/png'); imagepng($image, null, 9); ?> ``` The above example will output: ### See Also * [imagefilter()](function.imagefilter) - Applies a filter to an image php Memcached::incrementByKey Memcached::incrementByKey ========================= (PECL memcached >= 2.0.0) Memcached::incrementByKey — Increment numeric item's value, stored on a specific server ### Description ``` public Memcached::incrementByKey( string $server_key, string $key, int $offset = 1, int $initial_value = 0, int $expiry = 0 ): int|false ``` **Memcached::incrementByKey()** increments a numeric item's value by the specified `offset`. If the item's value is not numeric, an error will result. **Memcached::incrementByKey()** will set the item to the `initial_value` parameter if the key doesn't exist. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `key` The key of the item to increment. `offset` The amount by which to increment the item's value. `initial_value` The value to set the item to if it doesn't currently exist. `expiry` The expiry time to set on the item. ### Return Values Returns new item's value on success or **`false`** on failure. ### See Also * [Memcached::decrement()](memcached.decrement) - Decrement numeric item's value * [Memcached::decrementByKey()](memcached.decrementbykey) - Decrement numeric item's value, stored on a specific server * [Memcached::increment()](memcached.increment) - Increment numeric item's value php sodium_crypto_sign_seed_keypair sodium\_crypto\_sign\_seed\_keypair =================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_sign\_seed\_keypair — Deterministically derive the key pair from a single key ### Description ``` sodium_crypto_sign_seed_keypair(string $seed): string ``` Clamps the seed to form a secret key, derives the public key, and returns the two as a keypair. The `*_seed_keypair` functions are ideal for generating a keypair from a password and salt. Use the result as a `seed` to generate the desired keys. ### Parameters `seed` Some cryptographic input. Must be 32 bytes. ### Return Values Keypair (secret key and public key) php PDOStatement::nextRowset PDOStatement::nextRowset ======================== (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0) PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle ### Description ``` public PDOStatement::nextRowset(): bool ``` Some database servers support stored procedures that return more than one rowset (also known as a result set). **PDOStatement::nextRowset()** enables you to access the second and subsequent rowsets associated with a PDOStatement object. Each rowset can have a different set of columns from the preceding rowset. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Fetching multiple rowsets returned from a stored procedure** The following example shows how to call a stored procedure, `MULTIPLE_ROWSETS`, which returns three rowsets. We use a [do-while](control-structures.do.while) loop to call the **PDOStatement::nextRowset()** method until it returns **`false`** and terminates the loop when no more rowsets are available. ``` <?php $sql = 'CALL multiple_rowsets()'; $stmt = $conn->query($sql); $i = 1; do {     $rowset = $stmt->fetchAll(PDO::FETCH_NUM);     if ($rowset) {         printResultSet($rowset, $i);     }     $i++; } while ($stmt->nextRowset()); function printResultSet(&$rowset, $i) {     print "Result set $i:\n";     foreach ($rowset as $row) {         foreach ($row as $col) {             print $col . "\t";         }         print "\n";     }     print "\n"; } ?> ``` The above example will output: ``` Result set 1: apple red banana yellow Result set 2: orange orange 150 banana yellow 175 Result set 3: lime green apple red banana yellow ``` ### See Also * [PDOStatement::columnCount()](pdostatement.columncount) - Returns the number of columns in the result set * [PDOStatement::execute()](pdostatement.execute) - Executes a prepared statement * [PDOStatement::getColumnMeta()](pdostatement.getcolumnmeta) - Returns metadata for a column in a result set * [PDO::query()](pdo.query) - Prepares and executes an SQL statement without placeholders php None Logical Operators ----------------- **Logical Operators**| Example | Name | Result | | --- | --- | --- | | $a and $b | And | **`true`** if both $a and $b are **`true`**. | | $a or $b | Or | **`true`** if either $a or $b is **`true`**. | | $a xor $b | Xor | **`true`** if either $a or $b is **`true`**, but not both. | | ! $a | Not | **`true`** if $a is not **`true`**. | | $a && $b | And | **`true`** if both $a and $b are **`true`**. | | $a || $b | Or | **`true`** if either $a or $b is **`true`**. | The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See [Operator Precedence](language.operators.precedence).) **Example #1 Logical operators illustrated** ``` <?php // -------------------- // foo() will never get called as those operators are short-circuit $a = (false && foo()); $b = (true  || foo()); $c = (false and foo()); $d = (true  or  foo()); // -------------------- // "||" has a greater precedence than "or" // The result of the expression (false || true) is assigned to $e // Acts like: ($e = (false || true)) $e = false || true; // The constant false is assigned to $f before the "or" operation occurs // Acts like: (($f = false) or true) $f = false or true; var_dump($e, $f); // -------------------- // "&&" has a greater precedence than "and" // The result of the expression (true && false) is assigned to $g // Acts like: ($g = (true && false)) $g = true && false; // The constant true is assigned to $h before the "and" operation occurs // Acts like: (($h = true) and false) $h = true and false; var_dump($g, $h); ?> ``` The above example will output something similar to: ``` bool(true) bool(false) bool(false) bool(true) ``` php PharData::setSignatureAlgorithm PharData::setSignatureAlgorithm =============================== (No version information available, might only be in Git) PharData::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it ### Description ``` public PharData::setSignatureAlgorithm(int $algo, ?string $privateKey = null): void ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > Set the signature algorithm for a phar and apply it. The signature algorithm must be one of `Phar::MD5`, `Phar::SHA1`, `Phar::SHA256`, `Phar::SHA512`, or `Phar::OPENSSL`. ### Parameters `algo` One of `Phar::MD5`, `Phar::SHA1`, `Phar::SHA256`, `Phar::SHA512`, or `Phar::OPENSSL` ### Return Values No value is returned. ### Errors/Exceptions Throws [UnexpectedValueException](class.unexpectedvalueexception) for many errors, [BadMethodCallException](class.badmethodcallexception) if called for a zip- or a tar-based phar archive, and a [PharException](class.pharexception) if any problems occur flushing changes to disk. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `privateKey` is now nullable. | ### See Also * [Phar::getSupportedSignatures()](phar.getsupportedsignatures) - Return array of supported signature types * [Phar::getSignature()](phar.getsignature) - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive php EventBase::priorityInit EventBase::priorityInit ======================= (PECL event >= 1.2.6-beta) EventBase::priorityInit — Sets number of priorities per event base ### Description ``` public EventBase::priorityInit( int $n_priorities ): bool ``` Sets number of priorities per event base. ### Parameters `n_priorities` The number of priorities per event base. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [Event::setPriority()](event.setpriority) - Set event priority php imagegammacorrect imagegammacorrect ================= (PHP 4, PHP 5, PHP 7, PHP 8) imagegammacorrect — Apply a gamma correction to a GD image ### Description ``` imagegammacorrect(GdImage $image, float $input_gamma, float $output_gamma): bool ``` Applies gamma correction to the given gd `image` given an input and an output gamma. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `input_gamma` The input gamma. `output_gamma` The output gamma. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagegammacorrect()** usage** ``` <?php // Create image instance $im = imagecreatefromgif('php.gif'); // Correct gamma, out = 1.537 imagegammacorrect($im, 1.0, 1.537); // Save and free image imagegif($im, './php_gamma_corrected.gif'); imagedestroy($im); ?> ```
programming_docs
php ZipArchive::__construct ZipArchive::\_\_construct ========================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0) ZipArchive::\_\_construct — Construct a new ZipArchive instance ### Description public **ZipArchive::\_\_construct**() Constructs a new [ZipArchive](class.ziparchive) instance. ### Parameters This function has no parameters. php Ds\Map::hasValue Ds\Map::hasValue ================ (PECL ds >= 1.0.0) Ds\Map::hasValue — Determines whether the map contains a given value ### Description ``` public Ds\Map::hasValue(mixed $value): bool ``` Determines whether the map contains a given value. ### Parameters `value` The value to look for. ### Return Values Returns **`true`** if the value could found, **`false`** otherwise. ### Examples **Example #1 **Ds\Map::hasValue()** example** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); var_dump($map->hasValue(1)); // true var_dump($map->hasValue(4)); // false ?> ``` The above example will output something similar to: ``` bool(true) bool(false) ``` php session_start session\_start ============== (PHP 4, PHP 5, PHP 7, PHP 8) session\_start — Start new or resume existing session ### Description ``` session_start(array $options = []): bool ``` **session\_start()** creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When **session\_start()** is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by [session\_set\_save\_handler()](function.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()](function.session-name) before calling **session\_start()**. When [session.use\_trans\_sid](https://www.php.net/manual/en/session.configuration.php#ini.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()](function.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](https://www.php.net/manual/en/session.configuration.php). The keys should not include the `session.` prefix. In addition to the normal set of configuration directives, a `read_and_close` option may also be provided. If set to **`true`**, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed. ### Return Values This function returns **`true`** if a session was successfully started, otherwise **`false`**. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | **session\_start()** now returns **`false`** and no longer initializes [$\_SESSION](reserved.variables.session) when it failed to start the session. | ### Examples #### A basic session example **Example #1 page1.php** ``` <?php // page1.php session_start(); echo 'Welcome to page #1'; $_SESSION['favcolor'] = 'green'; $_SESSION['animal']   = 'cat'; $_SESSION['time']     = time(); // Works if session cookie was accepted echo '<br /><a href="page2.php">page 2</a>'; // Or maybe pass along the session id, if needed echo '<br /><a href="page2.php?' . SID . '">page 2</a>'; ?> ``` After viewing page1.php, the second page page2.php will magically contain the session data. Read the [session reference](https://www.php.net/manual/en/ref.session.php) for information on [propagating session ids](https://www.php.net/manual/en/session.idpassing.php) as it, for example, explains what the constant **`SID`** is all about. **Example #2 page2.php** ``` <?php // page2.php session_start(); echo 'Welcome to page #2<br />'; echo $_SESSION['favcolor']; // green echo $_SESSION['animal'];   // cat echo date('Y m d H:i:s', $_SESSION['time']); // You may want to use SID here, like we did in page1.php echo '<br /><a href="page1.php">page 1</a>'; ?> ``` #### Providing options to **session\_start()** **Example #3 Overriding the cookie lifetime** ``` <?php // This sends a persistent cookie that lasts a day. session_start([     'cookie_lifetime' => 86400, ]); ?> ``` **Example #4 Reading the session and closing it** ``` <?php // If we know we don't need to change anything in the // session, we can just read and close rightaway to avoid // locking the session file and blocking other pages session_start([     'cookie_lifetime' => 86400,     'read_and_close'  => true, ]); ``` ### Notes > > **Note**: > > > To use cookie-based sessions, **session\_start()** must be called before outputting anything to the browser. > > > > **Note**: > > > Use of [zlib.output\_compression](https://www.php.net/manual/en/zlib.configuration.php#ini.zlib.output-compression) is recommended instead of [ob\_gzhandler()](function.ob-gzhandler) > > > > **Note**: > > > This function sends out several HTTP headers depending on the configuration. See [session\_cache\_limiter()](function.session-cache-limiter) to customize these headers. > > ### See Also * [$\_SESSION](reserved.variables.session) * The [session.auto\_start](https://www.php.net/manual/en/session.configuration.php#ini.session.auto-start) configuration directive * [session\_id()](function.session-id) - Get and/or set the current session id php sodium_crypto_stream_xchacha20 sodium\_crypto\_stream\_xchacha20 ================================= (PHP 8 >= 8.1.0) sodium\_crypto\_stream\_xchacha20 — Expands the key and nonce into a keystream of pseudorandom bytes ### Description ``` sodium_crypto_stream_xchacha20(int $length, string $nonce, string $key): string ``` Expands the `key` and `nonce` into a keystream of pseudorandom bytes. ### Parameters `length` Number of bytes desired. `nonce` 24-byte nonce. `key` Key, possibly generated from [sodium\_crypto\_stream\_xchacha20\_keygen()](function.sodium-crypto-stream-xchacha20-keygen). ### Return Values Returns a pseudorandom stream that can be used with [sodium\_crypto\_stream\_xchacha20\_xor()](function.sodium-crypto-stream-xchacha20-xor). php WeakMap::offsetUnset WeakMap::offsetUnset ==================== (PHP 8) WeakMap::offsetUnset — Removes an entry from the map ### Description ``` public WeakMap::offsetUnset(object $object): void ``` Removes an entry from the map. ### Parameters `object` The key object to remove from the map. ### Return Values No value is returned. php APCUIterator::current APCUIterator::current ===================== (PECL apcu >= 5.0.0) APCUIterator::current — Get current item ### Description ``` public APCUIterator::current(): mixed ``` Gets the current item from the [APCUIterator](class.apcuiterator) stack. ### Parameters This function has no parameters. ### Return Values Returns the current item on success, or **`false`** if no more items or exist, or on failure. ### See Also * [APCUIterator::next()](apcuiterator.next) - Move pointer to next item * [Iterator::current()](iterator.current) - Return the current element php SolrResponse::getHttpStatus SolrResponse::getHttpStatus =========================== (PECL solr >= 0.9.2) SolrResponse::getHttpStatus — Returns the HTTP status of the response ### Description ``` public SolrResponse::getHttpStatus(): int ``` Returns the HTTP status of the response. ### Parameters This function has no parameters. ### Return Values Returns the HTTP status of the response. php None Character classes ----------------- An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash. A character class matches a single character in the subject; the character must be in the set of characters defined by the class, unless the first character in the class is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash. For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters which are in the class by enumerating those that are not. It is not an assertion: it still consumes a character from the subject string, and fails if the current pointer is at the end of the string. When case-insensitive (caseless) matching is set, any letters in a class represent both their upper case and lower case versions, so for example, an insensitive [aeiou] matches "A" as well as "a", and an insensitive [^aeiou] does not match "A", whereas a sensitive (caseful) version would. The newline character is never treated in any special way in character classes, whatever the setting of the [PCRE\_DOTALL](reference.pcre.pattern.modifiers) or [PCRE\_MULTILINE](reference.pcre.pattern.modifiers) options is. A class such as [^a] will always match a newline. The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class. It is not possible to have the literal character "]" as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so it would match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a single class containing a range followed by two separate characters. The octal or hexadecimal representation of "]" can also be used to end a range. Ranges operate in ASCII collating sequence. They can also be used for characters specified numerically, for example [\000-\037]. If a range that includes letters is used when case-insensitive (caseless) matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^\_`wxyzabc], matched case-insensitively, and if character tables for the "fr" locale are in use, [\xc8-\xcb] matches accented E characters in both cases. The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W\_] matches any letter or digit, but not underscore. All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped. The pattern terminator is always special and must be escaped when used within an expression. Perl supports the POSIX notation for character classes. This uses names enclosed by `[:` and `:]` within the enclosing square brackets. PCRE also supports this notation. For example, `[01[:alpha:]%]` matches "0", "1", any alphabetic character, or "%". The supported class names are: **Character classes**| `alnum` | letters and digits | | `alpha` | letters | | `ascii` | character codes 0 - 127 | | `blank` | space or tab only | | `cntrl` | control characters | | `digit` | decimal digits (same as \d) | | `graph` | printing characters, excluding space | | `lower` | lower case letters | | `print` | printing characters, including space | | `punct` | printing characters, excluding letters and digits | | `space` | white space (not quite the same as \s) | | `upper` | upper case letters | | `word` | "word" characters (same as \w) | | `xdigit` | hexadecimal digits | The `space` characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this list includes the VT character (code 11). This makes "space" different to `\s`, which does not include VT (for Perl compatibility). The name `word` is a Perl extension, and `blank` is a GNU extension from Perl 5.8. Another Perl extension is negation, which is indicated by a `^` character after the colon. For example, `[12[:^digit:]]` matches "1", "2", or any non-digit. In UTF-8 mode, characters with values greater than 128 do not match any of the POSIX character classes. As of libpcre 8.10 some character classes are changed to use Unicode character properties, in which case the mentioned restriction does not apply. Refer to the [» PCRE(3) manual](http://www.pcre.org/pcre.txt) for details. Unicode character properties can appear inside a character class. They can not be part of a range. The minus (hyphen) character after a Unicode character class will match literally. Trying to end a range with a Unicode character property will result in a warning. php SolrDocument::reset SolrDocument::reset =================== (PECL solr >= 0.9.2) SolrDocument::reset — Alias of [SolrDocument::clear()](solrdocument.clear) ### Description ``` public SolrDocument::reset(): bool ``` This is an alias to SolrDocument::clear() ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. php Imagick::compareImages Imagick::compareImages ====================== (PECL imagick 2, PECL imagick 3) Imagick::compareImages — Compares an image to a reconstructed image ### Description ``` public Imagick::compareImages(Imagick $compare, int $metric): array ``` Returns an array containing a reconstructed image and the difference between images. ### Parameters `compare` An image to compare to. `metric` Provide a valid metric type constant. Refer to this list of [metric constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.metric). ### Return Values Returns an array containing a reconstructed image and the difference between images. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::compareImages()**:** Compare images and display the reconstructed image ``` <?php $image1 = new imagick("image1.png"); $image2 = new imagick("image2.png"); $result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR); $result[0]->setImageFormat("png"); header("Content-Type: image/png"); echo $result[0]; ?> ``` php openssl_sign openssl\_sign ============= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) openssl\_sign — Generate signature ### Description ``` openssl_sign( string $data, string &$signature, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key, string|int $algorithm = OPENSSL_ALGO_SHA1 ): bool ``` **openssl\_sign()** computes a signature for the specified `data` by generating a cryptographic digital signature using the private key associated with `private_key`. Note that the data itself is not encrypted. ### Parameters `data` The string of data you wish to sign `signature` If the call was successful the signature is returned in `signature`. `private_key` [OpenSSLAsymmetricKey](class.opensslasymmetrickey) - a key, returned by [openssl\_get\_privatekey()](function.openssl-get-privatekey) string - a PEM formatted key `algorithm` int - one of these [Signature Algorithms](https://www.php.net/manual/en/openssl.signature-algos.php). string - a valid string returned by [openssl\_get\_md\_methods()](function.openssl-get-md-methods) example, "sha256WithRSAEncryption" or "sha384". ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `private_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) or [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` or `OpenSSL X.509` was accepted. | ### Examples **Example #1 **openssl\_sign()** example** ``` <?php // $data is assumed to contain the data to be signed // fetch private key from file and ready it $pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/demos/sign/key.pem"); // compute signature openssl_sign($data, $signature, $pkeyid); // free the key from memory openssl_free_key($pkeyid); ?> ``` **Example #2 **openssl\_sign()** example** ``` <?php //data you want to sign $data = 'my data'; //create new private and public key $new_key_pair = openssl_pkey_new(array(     "private_key_bits" => 2048,     "private_key_type" => OPENSSL_KEYTYPE_RSA, )); openssl_pkey_export($new_key_pair, $private_key_pem); $details = openssl_pkey_get_details($new_key_pair); $public_key_pem = $details['key']; //create signature openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256); //save for later file_put_contents('private_key.pem', $private_key_pem); file_put_contents('public_key.pem', $public_key_pem); file_put_contents('signature.dat', $signature); //verify signature $r = openssl_verify($data, $signature, $public_key_pem, "sha256WithRSAEncryption"); var_dump($r); ?> ``` ### See Also * [openssl\_verify()](function.openssl-verify) - Verify signature php DOMDocument::registerNodeClass DOMDocument::registerNodeClass ============================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) DOMDocument::registerNodeClass — Register extended class used to create base node type ### Description ``` public DOMDocument::registerNodeClass(string $baseClass, ?string $extendedClass): bool ``` This method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension. This method is not part of the DOM standard. ### Parameters `baseClass` The DOM class that you want to extend. You can find a list of these classes in the [chapter introduction](https://www.php.net/manual/en/book.dom.php). `extendedClass` Your extended class name. If **`null`** is provided, any previously registered class extending `baseClass` will be removed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Adding a new method to DOMElement to ease our code** ``` <?php class myElement extends DOMElement {    function appendElement($name) {        return $this->appendChild(new myElement($name));    } } class myDocument extends DOMDocument {    function setRoot($name) {        return $this->appendChild(new myElement($name));    } } $doc = new myDocument(); $doc->registerNodeClass('DOMElement', 'myElement'); // From now on, adding an element to another costs only one method call !  $root = $doc->setRoot('root'); $child = $root->appendElement('child'); $child->setAttribute('foo', 'bar'); echo $doc->saveXML(); ?> ``` The above example will output: ``` <?xml version="1.0"?> <root><child foo="bar"/></root> ``` **Example #2 Retrieving elements as custom class** ``` <?php class myElement extends DOMElement {     public function __toString() {         return $this->nodeValue;     } } $doc = new DOMDocument; $doc->loadXML("<root><element><child>text in child</child></element></root>"); $doc->registerNodeClass("DOMElement", "myElement"); $element = $doc->getElementsByTagName("child")->item(0); var_dump(get_class($element)); // And take advantage of the __toString method.. echo $element; ?> ``` The above example will output: ``` string(9) "myElement" text in child ``` **Example #3 Retrieving owner document** When instantiating a custom [DOMDocument](class.domdocument) the ownerDocument property will refer to the instantiated class. However, if all references to that class are removed, it will be destroyed and new [DOMDocument](class.domdocument) will be created instead. For that reason you might use **DOMDocument::registerNodeClass()** with [DOMDocument](class.domdocument) ``` <?php class MyDOMDocument extends DOMDocument { } class MyOtherDOMDocument extends DOMDocument { } // Create MyDOMDocument with some XML $doc = new MyDOMDocument; $doc->loadXML("<root><element><child>text in child</child></element></root>"); $child = $doc->getElementsByTagName("child")->item(0); // The current owner of the node is MyDOMDocument var_dump(get_class($child->ownerDocument)); // MyDOMDocument is destroyed unset($doc); // And new DOMDocument instance is created var_dump(get_class($child->ownerDocument)); // Import a node from MyDOMDocument $newdoc = new MyOtherDOMDocument; $child = $newdoc->importNode($child); // Register custom DOMDocument $newdoc->registerNodeClass("DOMDocument", "MyOtherDOMDocument"); var_dump(get_class($child->ownerDocument)); unset($doc); // New MyOtherDOMDocument is created var_dump(get_class($child->ownerDocument)); ?> ``` The above example will output: ``` string(13) "MyDOMDocument" string(11) "DOMDocument" string(18) "MyOtherDOMDocument" string(18) "MyOtherDOMDocument" ``` **Example #4 Custom objects are transient** **Caution** Objects of the registered node classes are transient, i.e. they are destroyed when they are no longer referenced from PHP code, and recreated when being retrieved again. That implies that custom property values will be lost after recreation. ``` <?php class MyDOMElement extends DOMElement {     public $myProp = 'default value'; } $doc = new DOMDocument(); $doc->registerNodeClass('DOMElement', 'MyDOMElement'); $node = $doc->createElement('a'); $node->myProp = 'modified value'; $doc->appendChild($node); echo $doc->childNodes[0]->myProp, PHP_EOL; unset($node); echo $doc->childNodes[0]->myProp, PHP_EOL; ?> ``` The above example will output: ``` modified value default value ```
programming_docs
php ReflectionProperty::getDeclaringClass ReflectionProperty::getDeclaringClass ===================================== (PHP 5, PHP 7, PHP 8) ReflectionProperty::getDeclaringClass — Gets declaring class ### Description ``` public ReflectionProperty::getDeclaringClass(): ReflectionClass ``` Gets the declaring class. ### Parameters This function has no parameters. ### Return Values A [ReflectionClass](class.reflectionclass) object. ### See Also * [ReflectionProperty::getName()](reflectionproperty.getname) - Gets property name php Zookeeper::get Zookeeper::get ============== (PECL zookeeper >= 0.1.0) Zookeeper::get — Gets the data associated with a node synchronously ### Description ``` public Zookeeper::get( string $path, callable $watcher_cb = null, array &$stat = null, int $max_size = 0 ): string ``` ### Parameters `path` The name of the node. Expressed as a file name with slashes separating ancestors of the node. `watcher_cb` If nonzero, a watch will be set at the server to notify the client if the node changes. `stat` If not NULL, will hold the value of stat for the path on return. `max_size` Max size of the data. If 0 is used, this method will return the whole data. ### Return Values Returns the data on success, and false on failure. ### Errors/Exceptions This method emits PHP error/warning when parameters count or types are wrong or fail to get value from node. **Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives. ### Examples **Example #1 **Zookeeper::get()** example** Get value from node. ``` <?php $zookeeper = new Zookeeper('locahost:2181'); $path = '/path/to/node'; $value = 'nodevalue'; $zookeeper->set($path, $value); $r = $zookeeper->get($path); if ($r)   echo $r; else   echo 'ERR'; ?> ``` The above example will output: ``` nodevalue ``` **Example #2 **Zookeeper::get()** stat example** Get node stat info. ``` <?php $zookeeper = new Zookeeper('localhost:2181'); $path = '/path/to/node'; $stat = []; $zookeeper->get($path, null, $stat); var_dump($stat); ?> ``` The above example will output: ``` array(11) { ["czxid"]=> float(0) ["mzxid"]=> float(0) ["ctime"]=> float(0) ["mtime"]=> float(0) ["version"]=> int(0) ["cversion"]=> int(-2) ["aversion"]=> int(0) ["ephemeralOwner"]=> float(0) ["dataLength"]=> int(0) ["numChildren"]=> int(2) ["pzxid"]=> float(0) } ``` ### See Also * [Zookeeper::set()](zookeeper.set) - Sets the data associated with a node * [ZookeeperException](class.zookeeperexception) php openal_context_suspend openal\_context\_suspend ======================== (PECL openal >= 0.1.0) openal\_context\_suspend — Suspend the specified context ### Description ``` openal_context_suspend(resource $context): bool ``` ### Parameters `context` An [Open AL(Context)](https://www.php.net/manual/en/openal.resources.php) resource (previously created by [openal\_context\_create()](function.openal-context-create)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [openal\_context\_create()](function.openal-context-create) - Create an audio processing context * [openal\_context\_current()](function.openal-context-current) - Make the specified context current * [openal\_context\_process()](function.openal-context-process) - Process the specified context php stats_rand_gen_ibinomial stats\_rand\_gen\_ibinomial =========================== (PECL stats >= 1.0.0) stats\_rand\_gen\_ibinomial — Generates a random deviate from the binomial distribution ### Description ``` stats_rand_gen_ibinomial(int $n, float $pp): int ``` Returns a random deviate from the binomial distribution whose number of trials is `n` and whose probability of an event in each trial is `pp`. ### Parameters `n` The number of trials `pp` The probability of an event in each trial ### Return Values A random deviate php readline_callback_handler_remove readline\_callback\_handler\_remove =================================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) readline\_callback\_handler\_remove — Removes a previously installed callback handler and restores terminal settings ### Description ``` readline_callback_handler_remove(): bool ``` Removes a previously installed callback handler and restores terminal settings. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if a previously installed callback handler was removed, or **`false`** if one could not be found. ### Examples See [readline\_callback\_handler\_install()](function.readline-callback-handler-install) for an example of how to use the readline callback interface. ### See Also * [readline\_callback\_handler\_install()](function.readline-callback-handler-install) - Initializes the readline callback interface and terminal, prints the prompt and returns immediately * [readline\_callback\_read\_char()](function.readline-callback-read-char) - Reads a character and informs the readline callback interface when a line is received php The Yaf_Request_Http class The Yaf\_Request\_Http class ============================ Introduction ------------ (Yaf >=1.0.0) Any request from client is initialized as a **Yaf\_Request\_Http**. you can get the request information like, uri query and post parameters via methods of this class. > > **Note**: > > > For security, $\_GET/$\_POST are readonly in Yaf, which means if you set a value to these global variables, you can not get it from [Yaf\_Request\_Http::getQuery()](yaf-request-http.getquery) or [Yaf\_Request\_Http::getPost()](yaf-request-http.getpost). > > But there do is some usage need such feature, like unit testing. thus Yaf can be built with --enable-yaf-debug, which will allow Yaf read the value user set via script. > > in such case, Yaf will throw a E\_STRICT warning to remind you about that: Strict Standards: you are running yaf in debug mode > > Class synopsis -------------- class **Yaf\_Request\_Http** extends [Yaf\_Request\_Abstract](class.yaf-request-abstract) { /\* Properties \*/ /\* Methods \*/ public [\_\_construct](yaf-request-http.construct)(string `$request_uri` = ?, string `$base_uri` = ?) ``` public get(string $name, string $default = ?): mixed ``` ``` public getCookie(string $name, string $default = ?): mixed ``` ``` public getFiles(): void ``` ``` public getPost(string $name, string $default = ?): mixed ``` ``` public getQuery(string $name, string $default = ?): mixed ``` ``` public getRaw(): mixed ``` ``` public getRequest(): void ``` ``` public isXmlHttpRequest(): bool ``` /\* Inherited methods \*/ ``` public Yaf_Request_Abstract::clearParams(): bool ``` ``` public Yaf_Request_Abstract::getActionName(): void ``` ``` public Yaf_Request_Abstract::getBaseUri(): void ``` ``` public Yaf_Request_Abstract::getControllerName(): void ``` ``` public Yaf_Request_Abstract::getEnv(string $name, string $default = ?): void ``` ``` public Yaf_Request_Abstract::getException(): void ``` ``` public Yaf_Request_Abstract::getLanguage(): void ``` ``` public Yaf_Request_Abstract::getMethod(): string ``` ``` public Yaf_Request_Abstract::getModuleName(): void ``` ``` public Yaf_Request_Abstract::getParam(string $name, string $default = ?): mixed ``` ``` public Yaf_Request_Abstract::getParams(): array ``` ``` public Yaf_Request_Abstract::getRequestUri(): void ``` ``` public Yaf_Request_Abstract::getServer(string $name, string $default = ?): void ``` ``` public Yaf_Request_Abstract::isCli(): bool ``` ``` public Yaf_Request_Abstract::isDispatched(): bool ``` ``` public Yaf_Request_Abstract::isGet(): bool ``` ``` public Yaf_Request_Abstract::isHead(): bool ``` ``` public Yaf_Request_Abstract::isOptions(): bool ``` ``` public Yaf_Request_Abstract::isPost(): bool ``` ``` public Yaf_Request_Abstract::isPut(): bool ``` ``` public Yaf_Request_Abstract::isRouted(): bool ``` ``` public Yaf_Request_Abstract::isXmlHttpRequest(): bool ``` ``` public Yaf_Request_Abstract::setActionName(string $action, bool $format_name = true): void ``` ``` public Yaf_Request_Abstract::setBaseUri(string $uir): bool ``` ``` public Yaf_Request_Abstract::setControllerName(string $controller, bool $format_name = true): void ``` ``` public Yaf_Request_Abstract::setDispatched(): void ``` ``` public Yaf_Request_Abstract::setModuleName(string $module, bool $format_name = true): void ``` ``` public Yaf_Request_Abstract::setParam(string $name, string $value = ?): bool ``` ``` public Yaf_Request_Abstract::setRequestUri(string $uir): void ``` ``` public Yaf_Request_Abstract::setRouted(string $flag = ?): void ``` } Properties ---------- module controller action method params language \_exception \_base\_uri uri dispatched routed Table of Contents ----------------- * [Yaf\_Request\_Http::\_\_construct](yaf-request-http.construct) — Constructor of Yaf\_Request\_Http * [Yaf\_Request\_Http::get](yaf-request-http.get) — Retrieve variable from client * [Yaf\_Request\_Http::getCookie](yaf-request-http.getcookie) — Retrieve Cookie variable * [Yaf\_Request\_Http::getFiles](yaf-request-http.getfiles) — The getFiles purpose * [Yaf\_Request\_Http::getPost](yaf-request-http.getpost) — Retrieve POST variable * [Yaf\_Request\_Http::getQuery](yaf-request-http.getquery) — Fetch a query parameter * [Yaf\_Request\_Http::getRaw](yaf-request-http.getraw) — Retrieve Raw request body * [Yaf\_Request\_Http::getRequest](yaf-request-http.getrequest) — The getRequest purpose * [Yaf\_Request\_Http::isXmlHttpRequest](yaf-request-http.isxmlhttprequest) — Determin if request is Ajax Request php PharFileInfo::getCRC32 PharFileInfo::getCRC32 ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified ### Description ``` public PharFileInfo::getCRC32(): int ``` This returns the [crc32()](function.crc32) checksum of the file within the Phar archive. ### Parameters This function has no parameters. ### Return Values The [crc32()](function.crc32) checksum of the file within the Phar archive. ### Errors/Exceptions Throws [BadMethodCallException](class.badmethodcallexception) if the file has not yet had its CRC32 verified. This should be impossible with normal use, as the CRC is verified upon opening the file for reading or writing. ### Examples **Example #1 A **PharFileInfo::getCRC32()** example** ``` <?php try {     $p = new Phar('/path/to/my.phar', 0, 'my.phar');     $p['myfile.txt'] = 'hi';     $file = $p['myfile.txt'];     echo $file->getCRC32(); } catch (Exception $e) {     echo 'Write operations on my.phar.phar failed: ', $e; } ?> ``` The above example will output: ``` 3633523372 ``` php strcspn strcspn ======= (PHP 4, PHP 5, PHP 7, PHP 8) strcspn — Find length of initial segment not matching mask ### Description ``` strcspn( string $string, string $characters, int $offset = 0, ?int $length = null ): int ``` Returns the length of the initial segment of `string` which does *not* contain any of the characters in `characters`. If `offset` and `length` are omitted, then all of `string` will be examined. If they are included, then the effect will be the same as calling `strcspn(substr($string, $offset, $length), $characters)` (see [substr](function.substr) for more information). ### Parameters `string` The string to examine. `characters` The string containing every disallowed character. `offset` The position in `string` to start searching. If `offset` is given and is non-negative, then **strcspn()** will begin examining `string` at the `offset`'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 `offset` is given and is negative, then **strcspn()** will begin examining `string` at the `offset`'th position from the end of `string`. `length` The length of the segment from `string` to examine. If `length` is given and is non-negative, then `string` will be examined for `length` characters after the starting position. If `length` is given and is negative, then `string` will be examined from the starting position up to `length` characters from the end of `string`. ### Return Values Returns the length of the initial segment of `string` which consists entirely of characters *not* in `characters`. > > **Note**: > > > When a `offset` parameter is set, the returned length is counted starting from this position, not from the beginning of `string`. > > ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `length` is nullable now. | ### Examples **Example #1 **strcspn()** example** ``` <?php $a = strcspn('abcd',  'apple'); $b = strcspn('abcd',  'banana'); $c = strcspn('hello', 'l'); $d = strcspn('hello', 'world'); $e = strcspn('abcdhelloabcd', 'abcd', -9); $f = strcspn('abcdhelloabcd', 'abcd', -9, -5); var_dump($a); var_dump($b); var_dump($c); var_dump($d); var_dump($e); var_dump($f); ?> ``` The above example will output: ``` int(0) int(0) int(2) int(2) int(5) int(4) ``` ### Notes > **Note**: This function is binary-safe. > > ### See Also * [strspn()](function.strspn) - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask php array_map array\_map ========== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) array\_map — Applies the callback to the elements of the given arrays ### Description ``` array_map(?callable $callback, array $array, array ...$arrays): array ``` **array\_map()** returns an array containing the results of applying the `callback` to the corresponding value of `array` (and `arrays` if more arrays are provided) used as arguments for the callback. The number of parameters that the `callback` function accepts should match the number of arrays passed to **array\_map()**. Excess input arrays are ignored. An [ArgumentCountError](class.argumentcounterror) is thrown if an insufficient number of arguments is provided. ### Parameters `callback` A [callable](language.types.callable) to run for each element in each array. **`null`** can be passed as a value to `callback` to perform a zip operation on multiple arrays. If only `array` is provided, **array\_map()** will return the input array. `array` An array to run through the `callback` function. `arrays` Supplementary variable list of array arguments to run through the `callback` function. ### Return Values Returns an array containing the results of applying the `callback` function to the corresponding value of `array` (and `arrays` if more arrays are provided) used as arguments for the callback. The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | If `callback` expects a parameter to be passed by reference, this function will now emit an **`E_WARNING`**. | ### Examples **Example #1 **array\_map()** example** ``` <?php function cube($n) {     return ($n * $n * $n); } $a = [1, 2, 3, 4, 5]; $b = array_map('cube', $a); print_r($b); ?> ``` This makes $b have: ``` Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 ) ``` **Example #2 **array\_map()** using a lambda function** ``` <?php $func = function(int $value): int {     return $value * 2; }; print_r(array_map($func, range(1, 5))); // Or as of PHP 7.4.0: print_r(array_map(fn($value): int => $value * 2, range(1, 5))); ?> ``` ``` Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 ) ``` **Example #3 **array\_map()** - using more arrays** ``` <?php function show_Spanish(int $n, string $m): string {     return "The number {$n} is called {$m} in Spanish"; } function map_Spanish(int $n, string $m): array {     return [$n => $m]; } $a = [1, 2, 3, 4, 5]; $b = ['uno', 'dos', 'tres', 'cuatro', 'cinco']; $c = array_map('show_Spanish', $a, $b); print_r($c); $d = array_map('map_Spanish', $a , $b); print_r($d); ?> ``` The above example will output: ``` // printout of $c Array ( [0] => The number 1 is called uno in Spanish [1] => The number 2 is called dos in Spanish [2] => The number 3 is called tres in Spanish [3] => The number 4 is called cuatro in Spanish [4] => The number 5 is called cinco in Spanish ) // printout of $d Array ( [0] => Array ( [1] => uno ) [1] => Array ( [2] => dos ) [2] => Array ( [3] => tres ) [3] => Array ( [4] => cuatro ) [4] => Array ( [5] => cinco ) ) ``` Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, shorter ones will be extended with empty elements to match the length of the longest. An interesting use of this function is to construct an array of arrays, which can be easily performed by using **`null`** as the name of the callback function **Example #4 Performing a zip operation of arrays** ``` <?php $a = [1, 2, 3, 4, 5]; $b = ['one', 'two', 'three', 'four', 'five']; $c = ['uno', 'dos', 'tres', 'cuatro', 'cinco']; $d = array_map(null, $a, $b, $c); print_r($d); ?> ``` The above example will output: ``` Array ( [0] => Array ( [0] => 1 [1] => one [2] => uno ) [1] => Array ( [0] => 2 [1] => two [2] => dos ) [2] => Array ( [0] => 3 [1] => three [2] => tres ) [3] => Array ( [0] => 4 [1] => four [2] => cuatro ) [4] => Array ( [0] => 5 [1] => five [2] => cinco ) ) ``` **Example #5 **`null`** `callback` with only `array`** ``` <?php $array = [1, 2, 3]; var_dump(array_map(null, $array)); ?> ``` The above example will output: ``` array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } ``` **Example #6 **array\_map()** - with string keys** ``` <?php $arr = ['stringkey' => 'value']; function cb1($a) {     return [$a]; } function cb2($a, $b) {     return [$a, $b]; } var_dump(array_map('cb1', $arr)); var_dump(array_map('cb2', $arr, $arr)); var_dump(array_map(null,  $arr)); var_dump(array_map(null, $arr, $arr)); ?> ``` The above example will output: ``` array(1) { ["stringkey"]=> array(1) { [0]=> string(5) "value" } } array(1) { [0]=> array(2) { [0]=> string(5) "value" [1]=> string(5) "value" } } array(1) { ["stringkey"]=> string(5) "value" } array(1) { [0]=> array(2) { [0]=> string(5) "value" [1]=> string(5) "value" } } ``` **Example #7 **array\_map()** - associative arrays** While **array\_map()** does not directly support using the array key as an input, that may be simulated using [array\_keys()](function.array-keys). ``` <?php $arr = [     'v1' => 'First release',     'v2' => 'Second release',     'v3' => 'Third release', ]; // Note: Before 7.4.0, use the longer syntax for anonymous functions instead. $callback = fn(string $k, string $v): string => "$k was the $v"; $result = array_map($callback, array_keys($arr), array_values($arr)); var_dump($result); ?> ``` The above example will output: ``` array(3) { [0]=> string(24) "v1 was the First release" [1]=> string(25) "v2 was the Second release" [2]=> string(24) "v3 was the Third release" } ``` ### See Also * [array\_filter()](function.array-filter) - Filters elements of an array using a callback function * [array\_reduce()](function.array-reduce) - Iteratively reduce the array to a single value using a callback function * [array\_walk()](function.array-walk) - Apply a user supplied function to every member of an array
programming_docs
php Imagick::getImageAttribute Imagick::getImageAttribute ========================== (PECL imagick 2, PECL imagick 3) Imagick::getImageAttribute — Returns a named attribute **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::getImageAttribute(string $key): string ``` Returns a named attribute. ### Parameters `key` The key of the attribute to get. ### Return Values php IntlBreakIterator::following IntlBreakIterator::following ============================ (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset ### Description ``` public IntlBreakIterator::following(int $offset): int ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `offset` ### Return Values php XMLWriter::setIndentString XMLWriter::setIndentString ========================== xmlwriter\_set\_indent\_string ============================== (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::setIndentString -- xmlwriter\_set\_indent\_string — Set string used for indenting ### Description Object-oriented style ``` public XMLWriter::setIndentString(string $indentation): bool ``` Procedural style ``` xmlwriter_set_indent_string(XMLWriter $writer, string $indentation): bool ``` Sets the string which will be used to indent each element/attribute of the resulting xml. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `indentation` The indentation string. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### Notes > > **Note**: > > > The indent is reset when an xmlwriter is opened. > > ### See Also * [XMLWriter::setIndent()](xmlwriter.setindent) - Toggle indentation on/off php array_uintersect array\_uintersect ================= (PHP 5, PHP 7, PHP 8) array\_uintersect — Computes the intersection of arrays, compares data by a callback function ### Description ``` array_uintersect(array $array, array ...$arrays, callable $value_compare_func): array ``` Computes the intersection of arrays, compares data by a callback function. ### Parameters `array` The first array. `arrays` Arrays to compare against. `value_compare_func` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` ### Return Values Returns an array containing all the values of `array` that are present in all the arguments. ### Examples **Example #1 **array\_uintersect()** example** ``` <?php $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); print_r(array_uintersect($array1, $array2, "strcasecmp")); ?> ``` The above example will output: ``` Array ( [a] => green [b] => brown [0] => red ) ``` ### See Also * [array\_intersect()](function.array-intersect) - Computes the intersection of arrays * [array\_intersect\_assoc()](function.array-intersect-assoc) - Computes the intersection of arrays with additional index check * [array\_uintersect\_assoc()](function.array-uintersect-assoc) - Computes the intersection of arrays with additional index check, compares data by a callback function * [array\_uintersect\_uassoc()](function.array-uintersect-uassoc) - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions php GearmanClient::doNormal GearmanClient::doNormal ======================= (No version information available, might only be in Git) GearmanClient::doNormal — Run a single task and return a result ### Description ``` public GearmanClient::doNormal(string $function_name, string $workload, string $unique = ?): string ``` Runs a single task and returns a string representation of the result. It is up to the [GearmanClient](class.gearmanclient) and [GearmanWorker](class.gearmanworker) to agree on the format of the result. ### Parameters `function_name` A registered function the worker is to execute `workload` Serialized data to be processed `unique` A unique ID used to identify a particular task ### Return Values A string representing the results of running a task. ### Examples **Example #1 Simple job submission with immediate return** ``` <?php ?> ``` ``` <?php # Client code echo "Starting\n"; # Create our client object. $gmclient= new GearmanClient(); # Add default server (localhost). $gmclient->addServer(); echo "Sending job\n"; $result = $gmclient->doNormal("reverse", "Hello!"); echo "Success: $result\n"; ?> ``` ``` <?php echo "Starting\n"; # Create our worker object. $gmworker= new GearmanWorker(); # Add default server (localhost). $gmworker->addServer(); # Register function "reverse" with the server. Change the worker function to # "reverse_fn_fast" for a faster worker with no output. $gmworker->addFunction("reverse", "reverse_fn"); print "Waiting for job...\n"; while($gmworker->work()) {   if ($gmworker->returnCode() != GEARMAN_SUCCESS)   {     echo "return_code: " . $gmworker->returnCode() . "\n";     break;   } } function reverse_fn($job) {   return strrev($job->workload()); } ?> ``` The above example will output something similar to: ``` Starting Sending job Success: !olleH ``` **Example #2 Submitting a job and retrieving incremental status** A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to **GearmanClient::doNormal()** produces status information on the running job. ``` <?php # Client code # Create our client object. $gmclient= new GearmanClient(); # Add default server (localhost). $gmclient->addServer(); echo "Sending job\n"; # Send reverse job do {   $result = $gmclient->doNormal("reverse", "Hello!");   # Check for various return packets and errors.   switch($gmclient->returnCode())   {     case GEARMAN_WORK_DATA:       echo "Data: $result\n";       break;     case GEARMAN_WORK_STATUS:       list($numerator, $denominator)= $gmclient->doStatus();       echo "Status: $numerator/$denominator complete\n";       break;     case GEARMAN_WORK_FAIL:       echo "Failed\n";       exit;     case GEARMAN_SUCCESS:       break;     default:       echo "RET: " . $gmclient->returnCode() . "\n";       echo "Error: " . $gmclient->error() . "\n";       echo "Errno: " . $gmclient->getErrno() . "\n";       exit;   } } while($gmclient->returnCode() != GEARMAN_SUCCESS); echo "Success: $result\n"; ?> ``` ``` <?php # Worker code echo "Starting\n"; # Create our worker object. $gmworker= new GearmanWorker(); # Add default server (localhost). $gmworker->addServer(); # Register function "reverse" with the server. $gmworker->addFunction("reverse", "reverse_fn"); print "Waiting for job...\n"; while($gmworker->work()) {   if ($gmworker->returnCode() != GEARMAN_SUCCESS)   {     echo "return_code: " . $gmworker->returnCode() . "\n";     break;   } } function reverse_fn($job) {   echo "Received job: " . $job->handle() . "\n";   $workload = $job->workload();   $workload_size = $job->workloadSize();   echo "Workload: $workload ($workload_size)\n";   # This status loop is not needed, just showing how it works   for ($x= 0; $x < $workload_size; $x++)   {     echo "Sending status: " + $x + 1 . "/$workload_size complete\n";     $job->sendStatus($x+1, $workload_size);     $job->sendData(substr($workload, $x, 1));     sleep(1);   }   $result= strrev($workload);   echo "Result: $result\n";   # Return what we want to send back to the client.   return $result; } ?> ``` The above example will output something similar to: Worker output: ``` Starting Waiting for job... Received job: H:foo.local:106 Workload: Hello! (6) 1/6 complete 2/6 complete 3/6 complete 4/6 complete 5/6 complete 6/6 complete Result: !olleH ``` Client output: ``` Starting Sending job Status: 1/6 complete Data: H Status: 2/6 complete Data: e Status: 3/6 complete Data: l Status: 4/6 complete Data: l Status: 5/6 complete Data: o Status: 6/6 complete Data: ! Success: !olleH ``` ### See Also * [GearmanClient::doHigh()](gearmanclient.dohigh) - Run a single high priority task * [GearmanClient::doLow()](gearmanclient.dolow) - Run a single low priority task * [GearmanClient::doBackground()](gearmanclient.dobackground) - Run a task in the background * [GearmanClient::doHighBackground()](gearmanclient.dohighbackground) - Run a high priority task in the background * [GearmanClient::doLowBackground()](gearmanclient.dolowbackground) - Run a low priority task in the background php EventHttpRequest::sendReplyChunk EventHttpRequest::sendReplyChunk ================================ (PECL event >= 1.4.0-beta) EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply ### Description ``` public EventHttpRequest::sendReplyChunk( EventBuffer $buf ): void ``` Send another data chunk as part of an ongoing chunked reply. After calling this method `buf` will be empty. ### Parameters `buf` The data chunk to send as part of the reply. ### Return Values No value is returned. ### See Also * [EventHttpRequest::sendReplyStart()](eventhttprequest.sendreplystart) - Initiate a chunked reply * [EventHttpRequest::sendReplyEnd()](eventhttprequest.sendreplyend) - Complete a chunked reply, freeing the request as appropriate php The EvTimer class The EvTimer class ================= Introduction ------------ (PECL ev >= 0.2.0) **EvTimer** watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that. The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to *January last year* , it will still time out after(roughly) one hour. "Roughly" because detecting time jumps is hard, and some inaccuracies are unavoidable. The callback is guaranteed to be invoked only after its timeout has passed (not at, so on systems with very low-resolution clocks this might introduce a small delay). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values (but this is no longer true when a callback calls [EvLoop::run()](evloop.run) recursively). The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every **`10`** seconds, then it will normally trigger at exactly **`10`** second intervals. If, however, the script cannot keep up with the timer because it takes longer than those **`10`** seconds to do) the timer will not fire more than once per event loop iteration. Class synopsis -------------- class **EvTimer** extends [EvWatcher](class.evwatcher) { /\* Properties \*/ public [$repeat](class.evtimer#evtimer.props.repeat); public [$remaining](class.evtimer#evtimer.props.remaining); /\* Inherited properties \*/ public [$is\_active](class.evwatcher#evwatcher.props.is-active); public [$data](class.evwatcher#evwatcher.props.data); public [$is\_pending](class.evwatcher#evwatcher.props.is-pending); public [$priority](class.evwatcher#evwatcher.props.priority); /\* Methods \*/ public [\_\_construct](evtimer.construct)( float `$after` , float `$repeat` , [callable](language.types.callable) `$callback` , [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = **`null`** , int `$priority` = 0 ) ``` public again(): void ``` ``` final public static createStopped( float $after , float $repeat , callable $callback , mixed $data = null , int $priority = 0 ): EvTimer ``` ``` public set( float $after , float $repeat ): void ``` /\* Inherited methods \*/ ``` public EvWatcher::clear(): int ``` ``` public EvWatcher::feed( int $revents ): void ``` ``` public EvWatcher::getLoop(): EvLoop ``` ``` public EvWatcher::invoke( int $revents ): void ``` ``` public EvWatcher::keepalive( bool $value = ?): bool ``` ``` public EvWatcher::setCallback( callable $callback ): void ``` ``` public EvWatcher::start(): void ``` ``` public EvWatcher::stop(): void ``` } Properties ---------- repeat If repeat is **`0.0`** , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually. remaining Returns the remaining time until a timer fires. If the timer is active, then this time is relative to the current event loop time, otherwise it's the timeout value currently configured. That is, after instanciating an **EvTimer** with an `after` value of **`5.0`** and `repeat` value of **`7.0`** , remaining returns **`5.0`** . When the timer is started and one second passes, remaining will return **`4.0`** . When the timer expires and is restarted, it will return roughly **`7.0`** (likely slightly less as callback invocation takes some time too), and so on. Table of Contents ----------------- * [EvTimer::again](evtimer.again) — Restarts the timer watcher * [EvTimer::\_\_construct](evtimer.construct) — Constructs an EvTimer watcher object * [EvTimer::createStopped](evtimer.createstopped) — Creates EvTimer stopped watcher object * [EvTimer::set](evtimer.set) — Configures the watcher php IntlIterator::current IntlIterator::current ===================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlIterator::current — Get the current element ### Description ``` public IntlIterator::current(): mixed ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php EventHttpRequest::sendReply EventHttpRequest::sendReply =========================== (PECL event >= 1.4.0-beta) EventHttpRequest::sendReply — Send an HTML reply to the client ### Description ``` public EventHttpRequest::sendReply( int $code , string $reason , EventBuffer $buf = ?): void ``` Send an HTML reply to the client. The body of the reply consists of data in optional `buf` parameter. ### Parameters `code` The HTTP response code to send. `reason` A brief message to send with the response code. `buf` The body of the response. ### Return Values No value is returned. ### See Also * [EventHttpRequest::sendError()](eventhttprequest.senderror) - Send an HTML error message to the client * [EventHttpRequest::sendReplyChunk()](eventhttprequest.sendreplychunk) - Send another data chunk as part of an ongoing chunked reply php The VarnishLog class The VarnishLog class ==================== Introduction ------------ (PECL varnish >= 0.6) Class synopsis -------------- class **VarnishLog** { /\* Constants \*/ const int [TAG\_Debug](class.varnishlog#varnishlog.constants.tag-debug) = 0; const int [TAG\_Error](class.varnishlog#varnishlog.constants.tag-error) = 1; const int [TAG\_CLI](class.varnishlog#varnishlog.constants.tag-cli) = 2; const int [TAG\_StatSess](class.varnishlog#varnishlog.constants.tag-statsess) = 3; const int [TAG\_ReqEnd](class.varnishlog#varnishlog.constants.tag-reqend) = 4; const int [TAG\_SessionOpen](class.varnishlog#varnishlog.constants.tag-sessionopen) = 5; const int [TAG\_SessionClose](class.varnishlog#varnishlog.constants.tag-sessionclose) = 6; const int [TAG\_BackendOpen](class.varnishlog#varnishlog.constants.tag-backendopen) = 7; const int [TAG\_BackendXID](class.varnishlog#varnishlog.constants.tag-backendxid) = 8; const int [TAG\_BackendReuse](class.varnishlog#varnishlog.constants.tag-backendreuse) = 9; const int [TAG\_BackendClose](class.varnishlog#varnishlog.constants.tag-backendclose) = 10; const int [TAG\_HttpGarbage](class.varnishlog#varnishlog.constants.tag-httpgarbage) = 11; const int [TAG\_Backend](class.varnishlog#varnishlog.constants.tag-backend) = 12; const int [TAG\_Length](class.varnishlog#varnishlog.constants.tag-length) = 13; const int [TAG\_FetchError](class.varnishlog#varnishlog.constants.tag-fetcherror) = 14; const int [TAG\_RxRequest](class.varnishlog#varnishlog.constants.tag-rxrequest) = 15; const int [TAG\_RxResponse](class.varnishlog#varnishlog.constants.tag-rxresponse) = 16; const int [TAG\_RxStatus](class.varnishlog#varnishlog.constants.tag-rxstatus) = 17; const int [TAG\_RxURL](class.varnishlog#varnishlog.constants.tag-rxurl) = 18; const int [TAG\_RxProtocol](class.varnishlog#varnishlog.constants.tag-rxprotocol) = 19; const int [TAG\_RxHeader](class.varnishlog#varnishlog.constants.tag-rxheader) = 20; const int [TAG\_TxRequest](class.varnishlog#varnishlog.constants.tag-txrequest) = 21; const int [TAG\_TxResponse](class.varnishlog#varnishlog.constants.tag-txresponse) = 22; const int [TAG\_TxStatus](class.varnishlog#varnishlog.constants.tag-txstatus) = 23; const int [TAG\_TxURL](class.varnishlog#varnishlog.constants.tag-txurl) = 24; const int [TAG\_TxProtocol](class.varnishlog#varnishlog.constants.tag-txprotocol) = 25; const int [TAG\_TxHeader](class.varnishlog#varnishlog.constants.tag-txheader) = 26; const int [TAG\_ObjRequest](class.varnishlog#varnishlog.constants.tag-objrequest) = 27; const int [TAG\_ObjResponse](class.varnishlog#varnishlog.constants.tag-objresponse) = 28; const int [TAG\_ObjStatus](class.varnishlog#varnishlog.constants.tag-objstatus) = 29; const int [TAG\_ObjURL](class.varnishlog#varnishlog.constants.tag-objurl) = 30; const int [TAG\_ObjProtocol](class.varnishlog#varnishlog.constants.tag-objprotocol) = 31; const int [TAG\_ObjHeader](class.varnishlog#varnishlog.constants.tag-objheader) = 32; const int [TAG\_LostHeader](class.varnishlog#varnishlog.constants.tag-lostheader) = 33; const int [TAG\_TTL](class.varnishlog#varnishlog.constants.tag-ttl) = 34; const int [TAG\_Fetch\_Body](class.varnishlog#varnishlog.constants.tag-fetch-body) = 35; const int [TAG\_VCL\_acl](class.varnishlog#varnishlog.constants.tag-vcl-acl) = 36; const int [TAG\_VCL\_call](class.varnishlog#varnishlog.constants.tag-vcl-call) = 37; const int [TAG\_VCL\_trace](class.varnishlog#varnishlog.constants.tag-vcl-trace) = 38; const int [TAG\_VCL\_return](class.varnishlog#varnishlog.constants.tag-vcl-return) = 39; const int [TAG\_VCL\_error](class.varnishlog#varnishlog.constants.tag-vcl-error) = 40; const int [TAG\_ReqStart](class.varnishlog#varnishlog.constants.tag-reqstart) = 41; const int [TAG\_Hit](class.varnishlog#varnishlog.constants.tag-hit) = 42; const int [TAG\_HitPass](class.varnishlog#varnishlog.constants.tag-hitpass) = 43; const int [TAG\_ExpBan](class.varnishlog#varnishlog.constants.tag-expban) = 44; const int [TAG\_ExpKill](class.varnishlog#varnishlog.constants.tag-expkill) = 45; const int [TAG\_WorkThread](class.varnishlog#varnishlog.constants.tag-workthread) = 46; const int [TAG\_ESI\_xmlerror](class.varnishlog#varnishlog.constants.tag-esi-xmlerror) = 47; const int [TAG\_Hash](class.varnishlog#varnishlog.constants.tag-hash) = 48; const int [TAG\_Backend\_health](class.varnishlog#varnishlog.constants.tag-backend-health) = 49; const int [TAG\_VCL\_Log](class.varnishlog#varnishlog.constants.tag-vcl-log) = 50; const int [TAG\_Gzip](class.varnishlog#varnishlog.constants.tag-gzip) = 51; /\* Methods \*/ ``` public __construct(array $args = ?) ``` ``` public getLine(): array ``` ``` public static getTagName(int $index): string ``` } Predefined Constants -------------------- **`VarnishLog::TAG_Debug`** **`VarnishLog::TAG_Error`** **`VarnishLog::TAG_CLI`** **`VarnishLog::TAG_StatSess`** **`VarnishLog::TAG_ReqEnd`** **`VarnishLog::TAG_SessionOpen`** **`VarnishLog::TAG_SessionClose`** **`VarnishLog::TAG_BackendOpen`** **`VarnishLog::TAG_BackendXID`** **`VarnishLog::TAG_BackendReuse`** **`VarnishLog::TAG_BackendClose`** **`VarnishLog::TAG_HttpGarbage`** **`VarnishLog::TAG_Backend`** **`VarnishLog::TAG_Length`** **`VarnishLog::TAG_FetchError`** **`VarnishLog::TAG_RxRequest`** **`VarnishLog::TAG_RxResponse`** **`VarnishLog::TAG_RxStatus`** **`VarnishLog::TAG_RxURL`** **`VarnishLog::TAG_RxProtocol`** **`VarnishLog::TAG_RxHeader`** **`VarnishLog::TAG_TxRequest`** **`VarnishLog::TAG_TxResponse`** **`VarnishLog::TAG_TxStatus`** **`VarnishLog::TAG_TxURL`** **`VarnishLog::TAG_TxProtocol`** **`VarnishLog::TAG_TxHeader`** **`VarnishLog::TAG_ObjRequest`** **`VarnishLog::TAG_ObjResponse`** **`VarnishLog::TAG_ObjStatus`** **`VarnishLog::TAG_ObjURL`** **`VarnishLog::TAG_ObjProtocol`** **`VarnishLog::TAG_ObjHeader`** **`VarnishLog::TAG_LostHeader`** **`VarnishLog::TAG_TTL`** **`VarnishLog::TAG_Fetch_Body`** **`VarnishLog::TAG_VCL_acl`** **`VarnishLog::TAG_VCL_call`** **`VarnishLog::TAG_VCL_trace`** **`VarnishLog::TAG_VCL_return`** **`VarnishLog::TAG_VCL_error`** **`VarnishLog::TAG_ReqStart`** **`VarnishLog::TAG_Hit`** **`VarnishLog::TAG_HitPass`** **`VarnishLog::TAG_ExpBan`** **`VarnishLog::TAG_ExpKill`** **`VarnishLog::TAG_WorkThread`** **`VarnishLog::TAG_ESI_xmlerror`** **`VarnishLog::TAG_Hash`** **`VarnishLog::TAG_Backend_health`** **`VarnishLog::TAG_VCL_Log`** **`VarnishLog::TAG_Gzip`** Table of Contents ----------------- * [VarnishLog::\_\_construct](varnishlog.construct) — Varnishlog constructor * [VarnishLog::getLine](varnishlog.getline) — Get next log line * [VarnishLog::getTagName](varnishlog.gettagname) — Get the log tag string representation by its index
programming_docs
php posix_setuid posix\_setuid ============= (PHP 4, PHP 5, PHP 7, PHP 8) posix\_setuid — Set the UID of the current process ### Description ``` posix_setuid(int $user_id): bool ``` Set the real user ID of the current process. This is a privileged function that needs appropriate privileges (usually root) on the system to be able to perform this function. ### Parameters `user_id` The user id. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **posix\_setuid()** example** This example will show the current user id and then set it to a different value. ``` <?php echo posix_getuid()."\n"; //10001 echo posix_geteuid()."\n"; //10001 posix_setuid(10000); echo posix_getuid()."\n"; //10000 echo posix_geteuid()."\n"; //10000 ?> ``` ### See Also * [posix\_setgid()](function.posix-setgid) - Set the GID of the current process * [posix\_seteuid()](function.posix-seteuid) - Set the effective UID of the current process * [posix\_getuid()](function.posix-getuid) - Return the real user ID of the current process * [posix\_geteuid()](function.posix-geteuid) - Return the effective user ID of the current process php ImagickPixel::setHSL ImagickPixel::setHSL ==================== (PECL imagick 2, PECL imagick 3) ImagickPixel::setHSL — Sets the normalized HSL color ### Description ``` public ImagickPixel::setHSL(float $hue, float $saturation, float $luminosity): bool ``` Sets the color described by the ImagickPixel object using normalized values for hue, saturation and luminosity. ### Parameters `hue` The normalized value for hue, described as a fractional arc (between 0 and 1) of the hue circle, where the zero value is red. `saturation` The normalized value for saturation, with 1 as full saturation. `luminosity` The normalized value for luminosity, on a scale from black at 0 to white at 1, with the full HS value at 0.5 luminosity. ### Return Values Returns **`true`** on success. ### Examples **Example #1 Use **ImagickPixel::setHSL()** to modify a color** ``` <?php //Create an almost pure red color $color = new ImagickPixel('rgb(90%, 10%, 10%)'); //Get it's HSL values $colorInfo = $color->getHSL(); //Rotate the hue by 180 degrees $newHue = $colorInfo['hue'] + 0.5; if ($newHue > 1) {     $newHue = $newHue - 1; } //Set the ImagickPixel to the new color $colorInfo = $color->setHSL($newHue, $colorInfo['saturation'], $colorInfo['luminosity']); //Check that the new color is blue/green $colorInfo = $color->getcolor(); print_r($colorInfo); ?> ``` The above example will output: ``` Array ( [r] => 26 [g] => 230 [b] => 230 [a] => 255 ) ``` ### Notes > > **Note**: > > > Available with ImageMagick library version 6.2.9 and higher. > > php The Yaf_Router class The Yaf\_Router class ===================== Introduction ------------ (Yaf >=1.0.0) **Yaf\_Router** is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URI: see [Yaf\_Request\_Abstract::setBaseUri()](yaf-request-abstract.setbaseuri)) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request. This values of the module, controller, action and other parameters are packaged into a [Yaf\_Request\_Abstract](class.yaf-request-abstract) object which is then processed by [Yaf\_Dispatcher](class.yaf-dispatcher). Routing occurs only once: when the request is initially received and before the first controller is dispatched. **Yaf\_Router** is designed to allow for mod\_rewrite-like functionality using pure PHP structures. It is very loosely based on Ruby on Rails routing and does not require any prior knowledge of webserver URL rewriting. It is designed to work with a single Apache mod\_rewrite rule (one of): **Example #1 Rewrite rule for Apache** ``` RewriteEngine on RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php ``` or (preferred): **Example #2 Rewrite rule for Apache** ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] ``` If using Lighttpd, the following rewrite rule is valid: **Example #3 Rewrite rule for Lighttpd** ``` url.rewrite-once = ( ".*\?(.*)$" => "/index.php?$1", ".*\.(js|ico|gif|jpg|png|css|html)$" => "$0", "" => "/index.php" ) ``` If using Nginx, use the following rewrite rule: **Example #4 Rewrite rule for Nginx** ``` server { listen ****; server_name yourdomain.com; root document_root; index index.php index.html; if (!-e $request_filename) { rewrite ^/(.*) /index.php/$1 last; } } ``` Default route ------------- **Yaf\_Router** comes preconfigured with a default route [Yaf\_Route\_Static](class.yaf-route-static), which will match URIs in the shape of controller/action. Additionally, a module name may be specified as the first path element, allowing URIs of the form module/controller/action. Finally, it will also match any additional parameters appended to the URI by default - controller/action/var1/value1/var2/value2. > > **Note**: > > > Module name must be defined in config, considering application.module="Index,Foo,Bar", in this case, only index, foo and bar can be considered as a module name. if doesn't config, there is only one module named "Index". > > Some examples of how such routes are matched: **Example #5 [Yaf\_Route\_Static](class.yaf-route-static)(default route)example** ``` // Assuming the following configure: $conf = array( "application" => array( "modules" => "Index,Blog", ), ); Controller only: http://example/news controller == news Action only(when defined yaf.action_prefer=1 in php.ini) action == news Invalid module maps to controller name: http://example/foo controller == foo Module + controller: http://example/blog/archive module == blog controller == archive Module + controller + action: http://example/blog/archive/list module == blog controller == archive action == list Module + controller + action + params: http://example/blog/archive/list/sort/alpha/date/desc module == blog controller == archive action == list sort == alpha date == desc ``` Class synopsis -------------- class **Yaf\_Router** { /\* Properties \*/ protected [$\_routes](class.yaf-router#yaf-router.props.routes); protected [$\_current](class.yaf-router#yaf-router.props.current); /\* Methods \*/ public [\_\_construct](yaf-router.construct)() ``` public addConfig(Yaf_Config_Abstract $config): bool ``` ``` public addRoute(string $name, Yaf_Route_Abstract $route): bool ``` ``` public getCurrentRoute(): string ``` ``` public getRoute(string $name): Yaf_Route_Interface ``` ``` public getRoutes(): mixed ``` ``` public route(Yaf_Request_Abstract $request): bool ``` } Properties ---------- \_routes registered routes stack \_current after routing phase, this indicated the name of which route is used to route current request. you can get this name by [Yaf\_Router::getCurrentRoute()](yaf-router.getcurrentroute). Table of Contents ----------------- * [Yaf\_Router::addConfig](yaf-router.addconfig) — Add config-defined routes into Router * [Yaf\_Router::addRoute](yaf-router.addroute) — Add new Route into Router * [Yaf\_Router::\_\_construct](yaf-router.construct) — Yaf\_Router constructor * [Yaf\_Router::getCurrentRoute](yaf-router.getcurrentroute) — Get the effective route name * [Yaf\_Router::getRoute](yaf-router.getroute) — Retrieve a route by name * [Yaf\_Router::getRoutes](yaf-router.getroutes) — Retrieve registered routes * [Yaf\_Router::route](yaf-router.route) — The route purpose php stream_copy_to_stream stream\_copy\_to\_stream ======================== (PHP 5, PHP 7, PHP 8) stream\_copy\_to\_stream — Copies data from one stream to another ### Description ``` stream_copy_to_stream( resource $from, resource $to, ?int $length = null, int $offset = 0 ): int|false ``` Makes a copy of up to `length` bytes of data from the current position (or from the `offset` position, if specified) in `from` to `to`. If `length` is **`null`**, all remaining content in `from` will be copied. ### Parameters `from` The source stream `to` The destination stream `length` Maximum bytes to copy. By default all bytes left are copied. `offset` The offset where to start to copy data ### Return Values Returns the total count of bytes copied, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `length` is now nullable. | ### Examples **Example #1 A **stream\_copy\_to\_stream()** example** ``` <?php $src = fopen('http://www.example.com', 'r'); $dest1 = fopen('first1k.txt', 'w'); $dest2 = fopen('remainder.txt', 'w'); echo stream_copy_to_stream($src, $dest1, 1024) . " bytes copied to first1k.txt\n"; echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n"; ?> ``` ### See Also * [copy()](function.copy) - Copies file php The Componere\Abstract\Definition class The Componere\Abstract\Definition class ======================================= Introduction ------------ (Componere 2 >= 2.1.0) This final abstract represents a class entry, and should not be used by the programmer. Class synopsis -------------- final abstract class **Componere\Abstract\Definition** { /\* Methods \*/ ``` public addInterface(string $interface): Definition ``` ``` public addMethod(string $name, Componere\Method $method): Definition ``` ``` public addTrait(string $trait): Definition ``` ``` public getReflector(): ReflectionClass ``` } Table of Contents ----------------- * [Componere\Abstract\Definition::addInterface](componere-abstract-definition.addinterface) — Add Interface * [Componere\Abstract\Definition::addMethod](componere-abstract-definition.addmethod) — Add Method * [Componere\Abstract\Definition::addTrait](componere-abstract-definition.addtrait) — Add Trait * [Componere\Abstract\Definition::getReflector](componere-abstract-definition.getreflector) — Reflection php gnupg_verify gnupg\_verify ============= (PECL gnupg >= 0.1) gnupg\_verify — Verifies a signed text ### Description ``` gnupg_verify( resource $identifier, string $signed_text, string $signature, string &$plaintext = ? ): array ``` Verifies the given `signed_text` and returns information about the signature. ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. `signed_text` The signed text. `signature` The signature. To verify a clearsigned text, set signature to **`false`**. `plaintext` The plain text. If this optional parameter is passed, it is filled with the plain text. ### Return Values On success, this function returns information about the signature. On failure, this function returns **`false`**. ### Examples **Example #1 Procedural **gnupg\_verify()** example** ``` <?php $plaintext = ""; $res = gnupg_init(); // clearsigned $info = gnupg_verify($res,$signed_text,false,$plaintext); print_r($info); // detached signature $info = gnupg_verify($res,$signed_text,$signature); print_r($info); ?> ``` **Example #2 OO **gnupg\_verify()** example** ``` <?php $plaintext = ""; $gpg = new gnupg(); // clearsigned $info = $gpg->verify($signed_text,false,$plaintext); print_r($info); // detached signature $info = $gpg->verify($signed_text,$signature); print_r($info); ?> ``` php SolrDisMaxQuery::setTrigramPhraseFields SolrDisMaxQuery::setTrigramPhraseFields ======================================= (No version information available, might only be in Git) SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter) ### Description ``` public SolrDisMaxQuery::setTrigramPhraseFields(string $fields): SolrDisMaxQuery ``` Directly Sets Trigram Phrase Fields (pf3 parameter) ### Parameters `fields` Trigram Phrase Fields ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::setTrigramPhraseFields()** example** ``` <?php $dismaxQuery = new SolrDisMaxQuery('lucene'); $dismaxQuery->setTrigramPhraseFields('cat~5.1^2 feature^4.5'); echo $dismaxQuery.PHP_EOL; ?> ``` The above example will output: ``` q=lucene&defType=edismax&pf3=cat~5.1^2 feature^4.5 ``` ### See Also * [SolrDisMaxQuery::addTrigramPhraseField()](solrdismaxquery.addtrigramphrasefield) - Adds a Trigram Phrase Field (pf3 parameter) * [SolrDisMaxQuery::removeTrigramPhraseField()](solrdismaxquery.removetrigramphrasefield) - Removes a Trigram Phrase Field (pf3 parameter) * [SolrDisMaxQuery::setTrigramPhraseSlop()](solrdismaxquery.settrigramphraseslop) - Sets Trigram Phrase Slop (ps3 parameter) php Ds\Set::reversed Ds\Set::reversed ================ (PECL ds >= 1.0.0) Ds\Set::reversed — Returns a reversed copy ### Description ``` public Ds\Set::reversed(): Ds\Set ``` Returns a reversed copy of the set. ### Parameters This function has no parameters. ### Return Values A reversed copy of the set. > > **Note**: > > > The current instance is not affected. > > ### Examples **Example #1 **Ds\Set::reversed()** example** ``` <?php $set = new \Ds\Set(["a", "b", "c"]); print_r($set->reversed()); print_r($set); ?> ``` The above example will output something similar to: ``` Ds\Set Object ( [0] => c [1] => b [2] => a ) Ds\Set Object ( [0] => a [1] => b [2] => c ) ``` php The DOMXPath class The DOMXPath class ================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Supports XPath 1.0 Class synopsis -------------- class **DOMXPath** { /\* Properties \*/ public readonly [DOMDocument](class.domdocument) [$document](class.domxpath#domxpath.props.document); public bool [$registerNodeNamespaces](class.domxpath#domxpath.props.registernodenamespaces); /\* Methods \*/ public [\_\_construct](domxpath.construct)([DOMDocument](class.domdocument) `$document`, bool `$registerNodeNS` = **`true`**) ``` public evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed ``` ``` public query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed ``` ``` public registerNamespace(string $prefix, string $namespace): bool ``` ``` public registerPhpFunctions(string|array|null $restrict = null): void ``` } Properties ---------- document registerNodeNamespaces When set to **`true`**, namespaces in the node are registered. Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | The registerNodeNamespaces property has been added. | Table of Contents ----------------- * [DOMXPath::\_\_construct](domxpath.construct) — Creates a new DOMXPath object * [DOMXPath::evaluate](domxpath.evaluate) — Evaluates the given XPath expression and returns a typed result if possible * [DOMXPath::query](domxpath.query) — Evaluates the given XPath expression * [DOMXPath::registerNamespace](domxpath.registernamespace) — Registers the namespace with the DOMXPath object * [DOMXPath::registerPhpFunctions](domxpath.registerphpfunctions) — Register PHP functions as XPath functions php Imagick::embossImage Imagick::embossImage ==================== (PECL imagick 2, PECL imagick 3) Imagick::embossImage — Returns a grayscale image with a three-dimensional effect ### Description ``` public Imagick::embossImage(float $radius, float $sigma): bool ``` Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you. ### Parameters `radius` The radius of the effect `sigma` The sigma of the effect ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::embossImage()**** ``` <?php function embossImage($imagePath, $radius, $sigma) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->embossImage($radius, $sigma);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php dio_open dio\_open ========= (PHP 4 >= 4.2.0, PHP 5 < 5.1.0) dio\_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow ### Description ``` dio_open(string $filename, int $flags, int $mode = 0): resource ``` **dio\_open()** opens a file and returns a new file descriptor for it. ### Parameters `filename` The pathname of the file to open. `flags` The `flags` parameter is a bitwise-ORed value comprising flags from the following list. This value *must* include one of **`O_RDONLY`**, **`O_WRONLY`**, or **`O_RDWR`**. Additionally, it may include any combination of the other flags from this list. * **`O_RDONLY`** - opens the file for read access. * **`O_WRONLY`** - opens the file for write access. * **`O_RDWR`** - opens the file for both reading and writing. * **`O_CREAT`** - creates the file, if it doesn't already exist. * **`O_EXCL`** - if both **`O_CREAT`** and **`O_EXCL`** are set and the file already exists, **dio\_open()** will fail. * **`O_TRUNC`** - if the file exists and is opened for write access, the file will be truncated to zero length. * **`O_APPEND`** - write operations write data at the end of the file. * **`O_NONBLOCK`** - sets non blocking mode. * **`O_NOCTTY`** - prevent the OS from assigning the opened file as the process's controlling terminal when opening a TTY device file. `mode` If `flags` contains **`O_CREAT`**, `mode` will set the permissions of the file (creation permissions). `mode` is required for correct operation when **`O_CREAT`** is specified in `flags` and is ignored otherwise. The actual permissions assigned to the created file will be affected by the process's *umask* setting as per usual. ### Return Values A file descriptor or **`false`** on error. ### Examples **Example #1 Opening a file descriptor** ``` <?php $fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK); dio_close($fd); ?> ``` ### See Also * [dio\_close()](function.dio-close) - Closes the file descriptor given by fd php XMLReader::next XMLReader::next =============== (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::next — Move cursor to next node skipping all subtrees ### Description ``` public XMLReader::next(?string $name = null): bool ``` Positions cursor on the next node skipping all subtrees. If no such node exists, the cursor is moved to the end of the document. ### Parameters `name` The name of the next node to move to. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `name` is nullable now. | ### See Also * [XMLReader::moveToNextAttribute()](xmlreader.movetonextattribute) - Position cursor on the next Attribute * [XMLReader::moveToElement()](xmlreader.movetoelement) - Position cursor on the parent Element of current Attribute * [XMLReader::moveToAttribute()](xmlreader.movetoattribute) - Move cursor to a named attribute php gmp_setbit gmp\_setbit =========== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_setbit — Set bit ### Description ``` gmp_setbit(GMP $num, int $index, bool $value = true): void ``` Sets bit `index` in `num`. ### Parameters `num` The value to modify. A [GMP](class.gmp) object, an int or a numeric string. `index` The index of the bit to set. Index 0 represents the least significant bit. `value` True to set the bit (set it to 1/on); false to clear the bit (set it to 0/off). ### Return Values A [GMP](class.gmp) object. ### Examples **Example #1 **gmp\_setbit()** example - 0 index** ``` <?php $a = gmp_init("2"); // echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n"; gmp_setbit($a, 0); // 0b10 now becomes 0b11 echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n"; ?> ``` The above example will output: ``` 2 -> 0b10 3 -> 0b11 ``` **Example #2 **gmp\_setbit()** example - 1 index** ``` <?php $a = gmp_init("0xfd"); echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n"; gmp_setbit($a, 1); // index starts at 0 echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n"; ?> ``` The above example will output: ``` 253 -> 0b11111101 255 -> 0b11111111 ``` **Example #3 **gmp\_setbit()** example - clearing a bit** ``` <?php $a = gmp_init("0xff"); echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n"; gmp_setbit($a, 0, false); // clear bit at index 0 echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n"; ?> ``` The above example will output: ``` 255 -> 0b11111111 254 -> 0b11111110 ``` ### Notes > > **Note**: > > > Unlike most of the other GMP functions, **gmp\_setbit()** must be called with a GMP object that already exists (using [gmp\_init()](function.gmp-init) for example). One will not be automatically created. > > ### See Also * [gmp\_clrbit()](function.gmp-clrbit) - Clear bit * [gmp\_testbit()](function.gmp-testbit) - Tests if a bit is set
programming_docs
php Yaf_Application::run Yaf\_Application::run ===================== (Yaf >=1.0.0) Yaf\_Application::run — Start Yaf\_Application ### Description ``` public Yaf_Application::run(): void ``` Run a Yaf\_Application, let the Yaf\_Application accept a request and route this request, dispatch to controller/action and render response. Finally, return the response to the client. ### Parameters This function has no parameters. ### Return Values php Imagick::distortImage Imagick::distortImage ===================== (PECL imagick 2 >= 2.0.1, PECL imagick 3) Imagick::distortImage — Distorts an image using various distortion methods ### Description ``` public Imagick::distortImage(int $method, array $arguments, bool $bestfit): bool ``` Distorts an image using various distortion methods, by mapping color lookups of the source image to a new destination image usually of the same size as the source image, unless 'bestfit' is set to **`true`**. If 'bestfit' is enabled, and distortion allows it, the destination image is adjusted to ensure the whole source 'image' will just fit within the final destination image, which will be sized and offset accordingly. Also in many cases the virtual offset of the source image will be taken into account in the mapping. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer. ### Parameters `method` The method of image distortion. See [distortion constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.distortion) `arguments` The arguments for this distortion method `bestfit` Attempt to resize destination to fit distorted source ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::distortImage()**:** Distort an image and display to the browser. ``` <?php /* Create new object */ $im = new Imagick(); /* Create new checkerboard pattern */ $im->newPseudoImage(100, 100, "pattern:checkerboard"); /* Set the image format to png */ $im->setImageFormat('png'); /* Fill new visible areas with transparent */ $im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT); /* Activate matte */ $im->setImageMatte(true); /* Control points for the distortion */ $controlPoints = array( 10, 10,                          10, 5,                         10, $im->getImageHeight() - 20,                         10, $im->getImageHeight() - 5,                         $im->getImageWidth() - 10, 10,                         $im->getImageWidth() - 10, 20,                         $im->getImageWidth() - 10, $im->getImageHeight() - 10,                         $im->getImageWidth() - 10, $im->getImageHeight() - 30); /* Perform the distortion */                        $im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true); /* Ouput the image */ header("Content-Type: image/png"); echo $im; ?> ``` The above example will output something similar to: ### See Also * [Imagick::blurImage()](imagick.blurimage) - Adds blur filter to image * [Imagick::motionBlurImage()](imagick.motionblurimage) - Simulates motion blur * [Imagick::radialBlurImage()](imagick.radialblurimage) - Radial blurs an image php Imagick::getImageCompose Imagick::getImageCompose ======================== (PECL imagick 2, PECL imagick 3) Imagick::getImageCompose — Returns the composite operator associated with the image ### Description ``` public Imagick::getImageCompose(): int ``` Returns the composite operator associated with the image. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. php Imagick::selectiveBlurImage Imagick::selectiveBlurImage =========================== (PECL imagick 3 >= 3.3.0) Imagick::selectiveBlurImage — Description ### Description ``` public Imagick::selectiveBlurImage( float $radius, float $sigma, float $threshold, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` Selectively blur an image within a contrast threshold. It is similar to the unsharpen mask that sharpens everything with contrast above a certain threshold. ### Parameters `radius` `sigma` `threshold` `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) using bitwise operators. Defaults to **`Imagick::CHANNEL_DEFAULT`**. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::selectiveBlurImage()**** ``` <?php function selectiveBlurImage($imagePath, $radius, $sigma, $threshold, $channel) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->selectiveBlurImage($radius, $sigma, $threshold, $channel);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php sodium_crypto_core_ristretto255_scalar_reduce sodium\_crypto\_core\_ristretto255\_scalar\_reduce ================================================== (PHP 8 >= 8.1.0) sodium\_crypto\_core\_ristretto255\_scalar\_reduce — Reduces a scalar value ### Description ``` sodium_crypto_core_ristretto255_scalar_reduce(string $s): string ``` Reduces a scalar value. Available as of libsodium 1.0.18. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `s` Scalar value. ### Return Values Returns a 32-byte random string. ### See Also * [sodium\_crypto\_core\_ristretto255\_scalar\_random()](function.sodium-crypto-core-ristretto255-scalar-random) - Generates a random key php Gmagick::cyclecolormapimage Gmagick::cyclecolormapimage =========================== (PECL gmagick >= Unknown) Gmagick::cyclecolormapimage — Displaces an image's colormap ### Description ``` public Gmagick::cyclecolormapimage(int $displace): Gmagick ``` Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect. ### Parameters `displace` The amount to displace the colormap. ### Return Values Returns self on success. ### Errors/Exceptions Throws an **GmagickException** on error. php pg_last_error pg\_last\_error =============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_last\_error — Get the last error message string of a connection ### Description ``` pg_last_error(?PgSql\Connection $connection = null): string ``` **pg\_last\_error()** returns the last error message for a given `connection`. Error messages may be overwritten by internal PostgreSQL (libpq) function calls. It may not return an appropriate error message if multiple errors occur inside a PostgreSQL module function. Use [pg\_result\_error()](function.pg-result-error), [pg\_result\_error\_field()](function.pg-result-error-field), [pg\_result\_status()](function.pg-result-status) and [pg\_connection\_status()](function.pg-connection-status) for better error handling. > > **Note**: > > > This function used to be called **pg\_errormessage()**. > > ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is **`null`**, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. ### Return Values A string containing the last error message on the given `connection`. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `connection` is now nullable. | ### Examples **Example #1 **pg\_last\_error()** example** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   // Query that fails   $res = pg_query($dbconn, "select * from doesnotexist");      echo pg_last_error($dbconn); ?> ``` ### See Also * [pg\_result\_error()](function.pg-result-error) - Get error message associated with result * [pg\_result\_error\_field()](function.pg-result-error-field) - Returns an individual field of an error report php Imagick::getImageChannelKurtosis Imagick::getImageChannelKurtosis ================================ (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose ### Description ``` public Imagick::getImageChannelKurtosis(int $channel = Imagick::CHANNEL_DEFAULT): array ``` Get the kurtosis and skewness of a specific channel. This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer. ### Parameters `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) using bitwise operators. Defaults to **`Imagick::CHANNEL_DEFAULT`**. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) ### Return Values Returns an array with `kurtosis` and `skewness` members. ### Errors/Exceptions Throws ImagickException on error. php pg_put_line pg\_put\_line ============= (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) pg\_put\_line — Send a NULL-terminated string to PostgreSQL backend ### Description ``` pg_put_line(PgSql\Connection $connection = ?, string $data): bool ``` **pg\_put\_line()** sends a NULL-terminated string to the PostgreSQL backend server. This is needed in conjunction with PostgreSQL's `COPY FROM` command. `COPY` is a high-speed data loading interface supported by PostgreSQL. Data is passed in without being parsed, and in a single transaction. An alternative to using raw **pg\_put\_line()** commands is to use [pg\_copy\_from()](function.pg-copy-from). This is a far simpler interface. > > **Note**: > > > The application must explicitly send the two characters "\." on the last line to indicate to the backend that it has finished sending its data, before issuing [pg\_end\_copy()](function.pg-end-copy). > > **Warning** Use of the **pg\_put\_line()** causes most large object operations, including [pg\_lo\_read()](function.pg-lo-read) and [pg\_lo\_tell()](function.pg-lo-tell), to subsequently fail. You can use [pg\_copy\_from()](function.pg-copy-from) and [pg\_copy\_to()](function.pg-copy-to) instead. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `data` A line of text to be sent directly to the PostgreSQL backend. A `NULL` terminator is added automatically. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_put\_line()** example** ``` <?php    $conn = pg_pconnect("dbname=foo");   pg_query($conn, "create table bar (a int4, b char(16), d float8)");   pg_query($conn, "copy bar from stdin");   pg_put_line($conn, "3\thello world\t4.5\n");   pg_put_line($conn, "4\tgoodbye world\t7.11\n");   pg_put_line($conn, "\\.\n");   pg_end_copy($conn); ?> ``` ### See Also * [pg\_end\_copy()](function.pg-end-copy) - Sync with PostgreSQL backend php Phar::buildFromIterator Phar::buildFromIterator ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::buildFromIterator — Construct a phar archive from an iterator ### Description ``` public Phar::buildFromIterator(Traversable $iterator, ?string $baseDirectory = null): array ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > Populate a phar archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the phar to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required. ### Parameters `iterator` Any iterator that either associatively maps phar file to location or returns SplFileInfo objects `baseDirectory` For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive ### Return Values **Phar::buildFromIterator()** returns an associative array mapping internal path of file to the full path of the file on the filesystem. ### Errors/Exceptions This method returns [UnexpectedValueException](class.unexpectedvalueexception) when the iterator returns incorrect values, such as an integer key instead of a string, a [BadMethodCallException](class.badmethodcallexception) when an SplFileInfo-based iterator is passed without a `baseDirectory` parameter, or a [PharException](class.pharexception) if there were errors saving the phar archive. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | **Phar::buildFromIterator()** no longer returns **`false`**. | | 8.0.0 | `baseDirectory` is now nullable. | ### Examples **Example #1 A **Phar::buildFromIterator()** with SplFileInfo** For most phar archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a phar archive containing the files in this sample directory layout: ``` /path/to/project/ config/ dist.xml debug.xml lib/ file1.php file2.php src/ processthing.php www/ index.php cli/ index.php ``` This code could be used to add these files to the "project.phar" phar archive: ``` <?php // create with alias "project.phar" $phar = new Phar('project.phar', 0, 'project.phar'); $phar->buildFromIterator(     new RecursiveIteratorIterator(      new RecursiveDirectoryIterator('/path/to/project')),     '/path/to/project'); $phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php')); ?> ``` The file project.phar can then be used immediately. **Phar::buildFromIterator()** does not set values such as compression, metadata, and this can be done after creating the phar archive. As an interesting note, **Phar::buildFromIterator()** can also be used to copy the contents of an existing phar archive, as the Phar object descends from [DirectoryIterator](class.directoryiterator): ``` <?php // create with alias "project.phar" $phar = new Phar('project.phar', 0, 'project.phar'); $phar->buildFromIterator(     new RecursiveIteratorIterator(      new Phar('/path/to/anotherphar.phar')),     'phar:///path/to/anotherphar.phar/path/to/project'); $phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php')); ?> ``` **Example #2 A **Phar::buildFromIterator()** with other iterators** The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an [ArrayIterator](class.arrayiterator): ``` <?php // create with alias "project.phar" $phar = new Phar('project.phar', 0, 'project.phar'); $phar->buildFromIterator(     new ArrayIterator(      array(         'internal/file.php' => dirname(__FILE__) . '/somefile.php',         'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),      ))); $phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php')); ?> ``` ### See Also * [Phar::buildFromDirectory()](phar.buildfromdirectory) - Construct a phar archive from the files within a directory php SNMP::walk SNMP::walk ========== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SNMP::walk — Fetch SNMP object subtree ### Description ``` public SNMP::walk( array|string $objectId, bool $suffixAsKey = false, int $maxRepetitions = -1, int $nonRepeaters = -1 ): array|false ``` **SNMP::walk()** is used to read SNMP subtree rooted at specified `objectId`. ### Parameters `objectId` Root of subtree to be fetched `suffixAsKey` By default full OID notation is used for keys in output array. If set to **`true`** subtree prefix will be removed from keys leaving only suffix of object\_id. `nonRepeaters` This specifies the number of supplied variables that should not be iterated over. The default is to use this value from SNMP object. `maxRepetitions` This specifies the maximum number of iterations over the repeating variables. The default is to use this value from SNMP object. ### Return Values Returns an associative array of the SNMP object ids and their values on success or **`false`** on error. When a SNMP error occures [SNMP::getErrno()](snmp.geterrno) and [SNMP::getError()](snmp.geterror) can be used for retrieving error number (specific to SNMP extension, see class constants) and error message respectively. ### Errors/Exceptions This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter `exceptions_enabled` should be set to a corresponding value. See [`SNMP::$exceptions_enabled` explanation](class.snmp#snmp.props.exceptions-enabled) for more details. ### Examples **Example #1 **SNMP::walk()** example** ``` <?php   $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");   $fulltree = $session->walk(".");   print_r($fulltree);   $session->close(); ?> ``` The above example will output something similar to: ``` Array ( [SNMPv2-MIB::sysDescr.0] => STRING: Test server [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8 [DISMAN-EVENT-MIB::sysUpTimeInstance] => Timeticks: (1150681750) 133 days, 4:20:17.50 [SNMPv2-MIB::sysContact.0] => STRING: Nobody [SNMPv2-MIB::sysName.0] => STRING: server.localdomain ... ) ``` **Example #2 `suffixAsKey` example** `suffixAsKey` may be used when merging multiple SNMP subtrees into one. This example maps interface names to their type. ``` <?php   $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");   $session->valueretrieval = SNMP_VALUE_PLAIN;   $ifDescr = $session->walk(".1.3.6.1.2.1.2.2.1.2", TRUE);   $session->valueretrieval = SNMP_VALUE_LIBRARY;   $ifType = $session->walk(".1.3.6.1.2.1.2.2.1.3", TRUE);   print_r($ifDescr);   print_r($ifType);   $result = array();   foreach($ifDescr as $i => $n) {     $result[$n] = $ifType[$i];   }   print_r($result); ?> ``` The above example will output something similar to: ``` Array ( [1] => igb0 [2] => igb1 [3] => ipfw0 [4] => lo0 [5] => lagg0 ) Array ( [1] => INTEGER: ieee8023adLag(161) [2] => INTEGER: ieee8023adLag(161) [3] => INTEGER: ethernetCsmacd(6) [4] => INTEGER: softwareLoopback(24) [5] => INTEGER: ethernetCsmacd(6) ) Array ( [igb0] => INTEGER: ieee8023adLag(161) [igb1] => INTEGER: ieee8023adLag(161) [ipfw0] => INTEGER: ethernetCsmacd(6) [lo0] => INTEGER: softwareLoopback(24) [lagg0] => INTEGER: ethernetCsmacd(6) ) ``` ### See Also * [SNMP::getErrno()](snmp.geterrno) - Get last error code * [SNMP::getError()](snmp.geterror) - Get last error message
programming_docs
php mb_ereg_search_getpos mb\_ereg\_search\_getpos ======================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) mb\_ereg\_search\_getpos — Returns start point for next regular expression match ### Description ``` mb_ereg_search_getpos(): int ``` Returns the start point for the next regular expression match. ### Parameters This function has no parameters. ### Return Values **mb\_ereg\_search\_getpos()** returns the point to start regular expression match for [mb\_ereg\_search()](function.mb-ereg-search), [mb\_ereg\_search\_pos()](function.mb-ereg-search-pos), [mb\_ereg\_search\_regs()](function.mb-ereg-search-regs). The position is represented by bytes from the head of string. ### Notes > > **Note**: > > > The internal encoding or the character encoding specified by [mb\_regex\_encoding()](function.mb-regex-encoding) will be used as the character encoding for this function. > > > ### See Also * [mb\_regex\_encoding()](function.mb-regex-encoding) - Set/Get character encoding for multibyte regex * [mb\_ereg\_search\_setpos()](function.mb-ereg-search-setpos) - Set start point of next regular expression match php sapi_windows_vt100_support sapi\_windows\_vt100\_support ============================= (PHP 7 >= 7.2.0, PHP 8) sapi\_windows\_vt100\_support — Get or set VT100 support for the specified stream associated to an output buffer of a Windows console. ### Description ``` sapi_windows_vt100_support(resource $stream, ?bool $enable = null): bool ``` If `enable` is **`null`**, the function returns **`true`** if the stream `stream` has VT100 control codes enabled, **`false`** otherwise. If `enable` is a bool, the function will try to enable or disable the VT100 features of the stream `stream`. If the feature has been successfully enabled (or disabled), the function will return **`true`**, or **`false`** otherwise. At startup, PHP tries to enable the VT100 feature of the **`STDOUT`**/**`STDERR`** streams. By the way, if those streams are redirected to a file, the VT100 features may not be enabled. If VT100 support is enabled, it is possible to use control sequences as they are known from the VT100 terminal. They allow the modification of the terminal's output. On Windows these sequences are called Console Virtual Terminal Sequences. **Warning** This function uses the **`ENABLE_VIRTUAL_TERMINAL_PROCESSING`** flag implemented in the Windows 10 API, so the VT100 feature may not be available on older Windows versions. ### Parameters `stream` The stream on which the function will operate. `enable` If bool, the VT100 feature will be enabled (if **`true`**) or disabled (if **`false`**). ### Return Values If `enable` is **`null`**: returns **`true`** if the VT100 feature is enabled, **`false`** otherwise. If `enable` is a bool: Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `enable` is now nullable. | ### Examples **Example #1 **sapi\_windows\_vt100\_support()** default state** By default, **`STDOUT`** and **`STDERR`** have the VT100 feature enabled. ``` php -r "var_export(sapi_windows_vt100_support(STDOUT));echo ' ';var_export(sapi_windows_vt100_support(STDERR));" ``` The above example will output something similar to: ``` true true ``` By the way, if a stream is redirected, the VT100 feature will not be enabled: ``` php -r "var_export(sapi_windows_vt100_support(STDOUT));echo ' ';var_export(sapi_windows_vt100_support(STDERR));" 2>NUL ``` The above example will output something similar to: true false **Example #2 **sapi\_windows\_vt100\_support()** changing state** You won't be able to enable the VT100 feature of **`STDOUT`** or **`STDERR`** if the stream is redirected. ``` php -r "var_export(sapi_windows_vt100_support(STDOUT, true));echo ' ';var_export(sapi_windows_vt100_support(STDERR, true));" 2>NUL ``` The above example will output something similar to: ``` true false ``` **Example #3 Example usage of VT100 support enabled** ``` <?php $out = fopen('php://stdout','w'); fwrite($out, 'Just forgot a lettr.'); // Moves the cursor two characters backwards fwrite($out, "\033[2D"); // Inserts one blank, shifting existing text to the right -> Just forgot a lett r. fwrite($out, "\033[1@"); fwrite($out, 'e'); ?> ``` The above example will output: ``` Just forgot a letter. ``` php GearmanClient::runTasks GearmanClient::runTasks ======================= (PECL gearman >= 0.5.0) GearmanClient::runTasks — Run a list of tasks in parallel ### Description ``` public GearmanClient::runTasks(): bool ``` For a set of tasks previously added with [GearmanClient::addTask()](gearmanclient.addtask), [GearmanClient::addTaskHigh()](gearmanclient.addtaskhigh), [GearmanClient::addTaskLow()](gearmanclient.addtasklow), [GearmanClient::addTaskBackground()](gearmanclient.addtaskbackground), [GearmanClient::addTaskHighBackground()](gearmanclient.addtaskhighbackground), or [GearmanClient::addTaskLowBackground()](gearmanclient.addtasklowbackground), this call starts running the tasks in parallel. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanClient::addTask()](gearmanclient.addtask) - Add a task to be run in parallel php mysqli::init mysqli::init ============ mysqli\_init ============ (PHP 5, PHP 7, PHP 8) mysqli::init -- mysqli\_init — Initializes MySQLi and returns an object for use with mysqli\_real\_connect() ### Description Object-oriented style ``` public mysqli::init(): ?bool ``` Procedural style ``` mysqli_init(): mysqli|false ``` Allocates or initializes a MYSQL object suitable for [mysqli\_options()](mysqli.options) and [mysqli\_real\_connect()](mysqli.real-connect). > > **Note**: > > > Any subsequent calls to any mysqli function (except [mysqli\_options()](mysqli.options) and [mysqli\_ssl\_set()](mysqli.ssl-set)) will fail until [mysqli\_real\_connect()](mysqli.real-connect) was called. > > ### Parameters This function has no parameters. ### Return Values **mysqli::init()** returns **`null`** on success, or **`false`** on failure. **mysqli\_init()** returns an object on success, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The object-oriented style **mysqli::init()** method has been deprecated. Replace calls to **parent::init()** with **parent::\_\_construct()**. | ### Examples See [mysqli\_real\_connect()](mysqli.real-connect). ### See Also * [mysqli\_options()](mysqli.options) - Set options * [mysqli\_close()](mysqli.close) - Closes a previously opened database connection * [mysqli\_real\_connect()](mysqli.real-connect) - Opens a connection to a mysql server * [mysqli\_connect()](function.mysqli-connect) - Alias of mysqli::\_\_construct php mb_strwidth mb\_strwidth ============ (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_strwidth — Return width of string ### Description ``` mb_strwidth(string $string, ?string $encoding = null): int ``` Returns the width of string `string`, where halfwidth characters count as `1`, and fullwidth characters count as `2`. See [» http://www.unicode.org/reports/tr11/](http://www.unicode.org/reports/tr11/) for details regarding East Asian character widths. The fullwidth characters are: `U+1100`-`U+115F`, `U+11A3`-`U+11A7`, `U+11FA`-`U+11FF`, `U+2329`-`U+232A`, `U+2E80`-`U+2E99`, `U+2E9B`-`U+2EF3`, `U+2F00`-`U+2FD5`, `U+2FF0`-`U+2FFB`, `U+3000`-`U+303E`, `U+3041`-`U+3096`, `U+3099`-`U+30FF`, `U+3105`-`U+312D`, `U+3131`-`U+318E`, `U+3190`-`U+31BA`, `U+31C0`-`U+31E3`, `U+31F0`-`U+321E`, `U+3220`-`U+3247`, `U+3250`-`U+32FE`, `U+3300`-`U+4DBF`, `U+4E00`-`U+A48C`, `U+A490`-`U+A4C6`, `U+A960`-`U+A97C`, `U+AC00`-`U+D7A3`, `U+D7B0`-`U+D7C6`, `U+D7CB`-`U+D7FB`, `U+F900`-`U+FAFF`, `U+FE10`-`U+FE19`, `U+FE30`-`U+FE52`, `U+FE54`-`U+FE66`, `U+FE68`-`U+FE6B`, `U+FF01`-`U+FF60`, `U+FFE0`-`U+FFE6`, `U+1B000`-`U+1B001`, `U+1F200`-`U+1F202`, `U+1F210`-`U+1F23A`, `U+1F240`-`U+1F248`, `U+1F250`-`U+1F251`, `U+20000`-`U+2FFFD`, `U+30000`-`U+3FFFD`. All other characters are halfwidth characters. ### Parameters `string` The string being decoded. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values The width of string `string`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | ### Examples **Example #1 **mb\_strwidth()** example** ``` <?php var_dump(     mb_strwidth('a'),       // LATIN SMALL LETTER A     mb_strwidth("\u{ff41}") // FULLWIDTH LATIN SMALL LETTER A ); ?> ``` The above example will output: ``` int(1) int(2) ``` ### See Also * [mb\_strimwidth()](function.mb-strimwidth) - Get truncated string with specified width * [mb\_internal\_encoding()](function.mb-internal-encoding) - Set/Get internal character encoding php ReflectionEnumUnitCase::getEnum ReflectionEnumUnitCase::getEnum =============================== (PHP 8 >= 8.1.0) ReflectionEnumUnitCase::getEnum — Gets the reflection of the enum of this case ### Description ``` public ReflectionEnumUnitCase::getEnum(): ReflectionEnum ``` Gets the reflection of the enum of this case. ### Parameters This function has no parameters. ### Return Values A [ReflectionEnum](class.reflectionenum) instance describing the Enum this case belongs to. ### See Also * [Enumerations](https://www.php.net/manual/en/language.enumerations.php) php ImagickDraw::bezier ImagickDraw::bezier =================== (PECL imagick 2, PECL imagick 3) ImagickDraw::bezier — Draws a bezier curve ### Description ``` public ImagickDraw::bezier(array $coordinates): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a bezier curve through a set of points on the image. ### Parameters `coordinates` Multidimensional array like array( array( 'x' => 1, 'y' => 2 ), array( 'x' => 3, 'y' => 4 ) ) ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::bezier()** example** ``` <?php function bezier($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $strokeColor = new \ImagickPixel($strokeColor);     $fillColor = new \ImagickPixel($fillColor);     $draw->setStrokeOpacity(1);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(2);     $smoothPointsSet = [         [             ['x' => 10.0 * 5, 'y' => 10.0 * 5],             ['x' => 30.0 * 5, 'y' => 90.0 * 5],             ['x' => 25.0 * 5, 'y' => 10.0 * 5],             ['x' => 50.0 * 5, 'y' => 50.0 * 5],         ],          [             ['x' => 50.0 * 5, 'y' => 50.0 * 5],             ['x' => 75.0 * 5, 'y' => 90.0 * 5],             ['x' => 70.0 * 5, 'y' => 10.0 * 5],             ['x' => 90.0 * 5, 'y' => 40.0 * 5],         ],     ];     foreach ($smoothPointsSet as $points) {         $draw->bezier($points);     }     $disjointPoints = [         [             ['x' => 10 * 5, 'y' => 10 * 5],              ['x' => 30 * 5, 'y' => 90 * 5],              ['x' => 25 * 5, 'y' => 10 * 5],             ['x' => 50 * 5, 'y' => 50 * 5],         ],         [             ['x' => 50 * 5, 'y' => 50 * 5],              ['x' => 80 * 5, 'y' => 50 * 5],             ['x' => 70 * 5, 'y' => 10 * 5],             ['x' => 90 * 5, 'y' => 40 * 5],          ]     ];     $draw->translate(0, 200);     foreach ($disjointPoints as $points) {         $draw->bezier($points);     }     //Create an image object which the draw commands can be rendered into     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     //Render the draw commands in the ImagickDraw object      //into the image.     $imagick->drawImage($draw);     //Send the image to the browser     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php array_key_last array\_key\_last ================ (PHP 7 >= 7.3.0, PHP 8) array\_key\_last — Gets the last key of an array ### Description ``` array_key_last(array $array): int|string|null ``` Get the last key of the given `array` without affecting the internal array pointer. ### Parameters `array` An array. ### Return Values Returns the last key of `array` if the array is not empty; **`null`** otherwise. ### See Also * [array\_key\_first()](function.array-key-first) - Gets the first key of an array * [end()](function.end) - Set the internal pointer of an array to its last element php wincache_ucache_clear wincache\_ucache\_clear ======================= (PECL wincache >= 1.1.0) wincache\_ucache\_clear — Deletes entire content of the user cache ### Description ``` wincache_ucache_clear(): bool ``` Clears/deletes all the values stored in the user cache. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 using **wincache\_ucache\_clear()**** ``` <?php wincache_ucache_set('green', 1); wincache_ucache_set('red', 2); wincache_ucache_set('orange', 4); wincache_ucache_set('blue', 8); wincache_ucache_set('cyan', 16); $array1 = array('green', 'red', 'orange', 'blue', 'cyan'); var_dump(wincache_ucache_get($array1)); var_dump(wincache_ucache_clear()); var_dump(wincache_ucache_get($array1)); ?> ``` The above example will output: ``` array(5) { ["green"]=> int(1) ["red"]=> int(2) ["orange"]=> int(4) ["blue"]=> int(8) ["cyan"]=> int(16) } bool(true) bool(false) ``` ### See Also * [wincache\_ucache\_set()](function.wincache-ucache-set) - Adds a variable in user cache and overwrites a variable if it already exists in the cache * [wincache\_ucache\_add()](function.wincache-ucache-add) - Adds a variable in user cache only if variable does not already exist in the cache * [wincache\_ucache\_delete()](function.wincache-ucache-delete) - Deletes variables from the user cache * [wincache\_ucache\_get()](function.wincache-ucache-get) - Gets a variable stored in the user cache * [wincache\_ucache\_exists()](function.wincache-ucache-exists) - Checks if a variable exists in the user cache * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache php gc_mem_caches gc\_mem\_caches =============== (PHP 7, PHP 8) gc\_mem\_caches — Reclaims memory used by the Zend Engine memory manager ### Description ``` gc_mem_caches(): int ``` Reclaims memory used by the Zend Engine memory manager. ### Parameters This function has no parameters. ### Return Values Returns the number of bytes freed. ### See Also * [Garbage Collection](https://www.php.net/manual/en/features.gc.php) php Throwable::getPrevious Throwable::getPrevious ====================== (PHP 7, PHP 8) Throwable::getPrevious — Returns the previous Throwable ### Description ``` public Throwable::getPrevious(): ?Throwable ``` Returns any previous Throwable (for example, one provided as the third parameter to [Exception::\_\_construct()](exception.construct)). ### Parameters This function has no parameters. ### Return Values Returns the previous [Throwable](class.throwable) if available, or **`null`** otherwise. ### See Also * [Exception::getPrevious()](exception.getprevious) - Returns previous Throwable php The SplQueue class The SplQueue class ================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list. Class synopsis -------------- class **SplQueue** extends [SplDoublyLinkedList](class.spldoublylinkedlist) { /\* Inherited constants \*/ public const int [SplDoublyLinkedList::IT\_MODE\_LIFO](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-lifo); public const int [SplDoublyLinkedList::IT\_MODE\_FIFO](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-fifo); public const int [SplDoublyLinkedList::IT\_MODE\_DELETE](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-delete); public const int [SplDoublyLinkedList::IT\_MODE\_KEEP](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-keep); /\* Methods \*/ public [SplStack::\_\_construct](splstack.construct)() ``` public dequeue(): mixed ``` ``` public enqueue(mixed $value): void ``` ``` public setIteratorMode(int $mode): void ``` /\* Inherited methods \*/ ``` public SplDoublyLinkedList::add(int $index, mixed $value): void ``` ``` public SplDoublyLinkedList::bottom(): mixed ``` ``` public SplDoublyLinkedList::count(): int ``` ``` public SplDoublyLinkedList::current(): mixed ``` ``` public SplDoublyLinkedList::getIteratorMode(): int ``` ``` public SplDoublyLinkedList::isEmpty(): bool ``` ``` public SplDoublyLinkedList::key(): int ``` ``` public SplDoublyLinkedList::next(): void ``` ``` public SplDoublyLinkedList::offsetExists(int $index): bool ``` ``` public SplDoublyLinkedList::offsetGet(int $index): mixed ``` ``` public SplDoublyLinkedList::offsetSet(?int $index, mixed $value): void ``` ``` public SplDoublyLinkedList::offsetUnset(int $index): void ``` ``` public SplDoublyLinkedList::pop(): mixed ``` ``` public SplDoublyLinkedList::prev(): void ``` ``` public SplDoublyLinkedList::push(mixed $value): void ``` ``` public SplDoublyLinkedList::rewind(): void ``` ``` public SplDoublyLinkedList::serialize(): string ``` ``` public SplDoublyLinkedList::setIteratorMode(int $mode): int ``` ``` public SplDoublyLinkedList::shift(): mixed ``` ``` public SplDoublyLinkedList::top(): mixed ``` ``` public SplDoublyLinkedList::unserialize(string $data): void ``` ``` public SplDoublyLinkedList::unshift(mixed $value): void ``` ``` public SplDoublyLinkedList::valid(): bool ``` } Table of Contents ----------------- * [SplQueue::\_\_construct](splqueue.construct) — Constructs a new queue implemented using a doubly linked list * [SplQueue::dequeue](splqueue.dequeue) — Dequeues a node from the queue * [SplQueue::enqueue](splqueue.enqueue) — Adds an element to the queue * [SplQueue::setIteratorMode](splqueue.setiteratormode) — Sets the mode of iteration php EvFork::createStopped EvFork::createStopped ===================== (PECL ev >= 0.2.0) EvFork::createStopped — Creates a stopped instance of EvFork watcher class ### Description ``` final public static EvFork::createStopped( string $callback , string $data = ?, string $priority = ?): object ``` The same as [EvFork::\_\_construct()](evfork.construct) , but doesn't start the watcher automatically. ### Parameters `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### Return Values Returns EvFork(stopped) object on success. ### See Also * [EvFork::\_\_construct()](evfork.construct) - Constructs the EvFork watcher object php curl_strerror curl\_strerror ============== (PHP 5 >= 5.5.0, PHP 7, PHP 8) curl\_strerror — Return string describing the given error code ### Description ``` curl_strerror(int $error_code): ?string ``` Returns a text error message describing the given error code. ### Parameters `error_code` One of the [» cURL error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html) constants. ### Return Values Returns error description or **`null`** for invalid error code. ### Examples **Example #1 [curl\_errno()](function.curl-errno) example** ``` <?php // Create a curl handle with a misspelled protocol in URL $ch = curl_init("htp://example.com/"); // Send request curl_exec($ch); // Check for errors and display the error message if($errno = curl_errno($ch)) {     $error_message = curl_strerror($errno);     echo "cURL error ({$errno}):\n {$error_message}"; } // Close the handle curl_close($ch); ?> ``` The above example will output: ``` cURL error (1): Unsupported protocol ``` ### See Also * [curl\_errno()](function.curl-errno) - Return the last error number * [curl\_error()](function.curl-error) - Return a string containing the last error for the current session * [» Curl error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html)
programming_docs