Miscellaneous functions Misc. These functions were placed here because none of the other categories seemed to fit. connection_aborted Returns true if client disconnected Description int connection_aborted void Returns true if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation. connection_status Returns connection status bitfield Description int connection_status void Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation. connection_timeout Return true if script timed out Description int connection_timeout void Returns true if script timed out. See the Connection Handling description in the Features chapter for a complete explanation. define Defines a named constant. Description int define string name mixed value int case_insensitive Defines a named constant, which is similar to a variable except: Constants do not have a dollar sign '$' before them; Constants may be 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. The name of the constant is given by name; the value is given by value. The optional third parameter case_insensitive is also available. If the value 1 is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values. Defining Constants <?php define ("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." ?> Define returns TRUE on success and FALSE if an error occurs. See also defined and the section on Constants. defined Checks whether a given named constant exists Description int defined string name Returns true if the named constant given by name has been defined, false otherwise. See also define and the section on Constants. die Output a message and terminate the current script Description void die string message This language construct outputs a message and terminates parsing of the script. It does not return anything. die example <?php $filename = '/path/to/data-file'; $file = fopen ($filename, 'r') or die("unable to open file ($filename)"); ?> See also exit. eval Evaluate a string as PHP code Description void eval string code_str eval evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution. There are some factors to keep in mind when using eval. Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval, and properly escaping things in code_str. Also remember that variables given values under eval will retain these values in the main script afterwards. <function>Eval</function> example - simple text merge <?php $string = 'cup'; $name = 'coffee'; $str = 'This is a $string with my $name in it.<br>'; echo $str; eval ("\$str = \"$str\";"); echo $str; ?> The above example will show: This is a $string with my $name in it. This is a cup with my coffee in it. exit Terminate current script Description void exit This language construct terminates parsing of the script. It does not return. See also die. func_get_arg Return an item from the argument list Description int func_get_arg int arg_num Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. Func_get_arg will generate a warning if called from outside of a function definition. If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg will return FALSE. <?php function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs<br>\n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg (1) . "<br>\n"; } } foo (1, 2, 3); ?> Func_get_arg may be used in conjunction with func_num_args and func_get_args to allow user-defined functions to accept variable-length argument lists. This function was added in PHP 4. func_get_args Returns an array comprising a function's argument list Description int func_get_args void Returns an array in which each element is the corresponding member of the current user-defined function's argument list. Func_get_args will generate a warning if called from outside of a function definition. <?php function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs<br>\n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg (1) . "<br>\n"; } $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo "Argument $i is: " . $arg_list[$i] . "<br>\n"; } } foo (1, 2, 3); ?> Func_get_args may be used in conjunction with func_num_args and func_get_arg to allow user-defined functions to accept variable-length argument lists. This function was added in PHP 4. func_num_args Returns the number of arguments passed to the function Description int func_num_args void Returns the number of arguments passed into the current user-defined function. Func_num_args will generate a warning if called from outside of a function definition. <?php function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs\n"; } foo (1, 2, 3); // Prints 'Number of arguments: 3' ?> Func_num_args may be used in conjunction with func_get_arg and func_get_args to allow user-defined functions to accept variable-length argument lists. This function was added in PHP 4. function_exists Return true if the given function has been defined Description int function_exists string function_name Checks the list of defined functions for function_name. Returns true if the given function name was found, false otherwise. get_browser Tells what the user's browser is capable of Description object get_browser string user_agent get_browser attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. By default, the value of $HTTP_USER_AGENT is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser. The information is returned in an object, which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; true/false values for features such as frames, JavaScript, and cookies; and so forth. While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory. The following example shows how one might list all available information retrieved about the user's browser. <function>Get_browser</function> example <?php function list_array ($array) { while (list ($key, $value) = each ($array)) { $str .= "<b>$key:</b> $value<br>\n"; } return $str; } echo "$HTTP_USER_AGENT<hr>\n"; $browser = get_browser(); echo list_array ((array) $browser); ?> The output of the above script would look something like this: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr> <b>browser_name_pattern:</b> Mozilla/4\.5.*<br> <b>parent:</b> Netscape 4.0<br> <b>platform:</b> Unknown<br> <b>majorver:</b> 4<br> <b>minorver:</b> 5<br> <b>browser:</b> Netscape<br> <b>version:</b> 4<br> <b>frames:</b> 1<br> <b>tables:</b> 1<br> <b>cookies:</b> 1<br> <b>backgroundsounds:</b> <br> <b>vbscript:</b> <br> <b>javascript:</b> 1<br> <b>javaapplets:</b> 1<br> <b>activexcontrols:</b> <br> <b>beta:</b> <br> <b>crawler:</b> <br> <b>authenticodeupdate:</b> <br> <b>msn:</b> <br> In order for this to work, your browscap configuration file setting must point to the correct location of the browscap.ini file. For more information (including locations from which you may obtain a browscap.ini file), check the PHP FAQ at &url.php.faq;. Browscap support was added to PHP in version 3.0b2. ignore_user_abort Set whether a client disconnect should abort script execution Description int ignore_user_abort int setting This function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP. iptcparse Parse a binary IPTC &url.iptc; block into single tags. Description array iptcparse string iptcblock This function parses a binary IPTC block into its single tags. It returns an array using the tagmarker as an index and the value as the value. It returns false on error or if no IPTC data was found. See GetImageSize for a sample. leak Leak memory Description void leak int bytes Leak leaks the specified amount of memory. This is useful when debugging the memory manager, which automatically cleans up "leaked" memory when each request is completed. pack Pack data into binary string. Description string pack string format mixed args ... Pack given arguments into binary string according to format. Returns binary string containing data. The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are a NUL-padded string A SPACE-padded string h Hex string, low nibble first H Hex string, high nibble first c signed char C unsigned char s signed short (always 16 bit, machine byte order) S unsigned short (always 16 bit, machine byte order) n unsigned short (always 16 bit, big endian byte order) v unsigned short (always 16 bit, little endian byte order) i signed integer (machine dependant size and byte order) I unsigned integer (machine dependant size and byte order) l signed long (always 32 bit, machine byte order) L unsigned long (always 32 bit, machine byte order) N unsigned long (always 32 bit, big endian byte order) V unsigned long (always 32 bit, little endian byte order) f float (machine dependent size and representation) d double (machine dependent size and representation) x NUL byte X Back up one byte @ NUL-fill to absolute position <function>Pack</function> format string $binarydata = pack ("nvc*", 0x1234, 0x5678, 65, 66); The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42. Note that the distinction between signed and unsigned values only affects the function unpack, where as function pack gives the same result for signed and unsigned format codes. Also note that PHP internally stores integral values as signed values of a machine dependant size. If you give it an unsigned integral value too large to be stored that way it is converted to a double which often yields an undesired result. register_shutdown_function Register a function for execution on shutdown Description int register_shutdown_function string func Registers the function named by func to be executed when script processing is complete. Common Pitfalls: Since no output is allowed to the browser in this function, you will be unable to debug it using statements such as print or echo. serialize Generates a storable representation of a value Description string serialize mixed value Serialize returns a string containing a byte-stream representation of value that can be stored anywhere. This is useful for storing or passing PHP values around without losing their type and structure. To make the serialized string into a PHP value again, use unserialize. Serialize handles the types integer, double, string, array (multidimensional) and object (object properties will be serialized, but methods are lost). <function>Serialize</function> example // $session_data contains a multi-dimensional array with session // information for the current user. We use serialize() to store // it in a database at the end of the request. $conn = odbc_connect ("webdb", "php", "chicken"); $stmt = odbc_prepare ($conn, "UPDATE sessions SET data = ? WHERE id = ?"); $sqldata = array (serialize($session_data), $PHP_AUTH_USER); if (!odbc_execute ($stmt, &$sqldata)) { $stmt = odbc_prepare($conn, "INSERT INTO sessions (id, data) VALUES(?, ?)"); if (!odbc_execute($stmt, &$sqldata)) { /* Something went wrong. Bitch, whine and moan. */ } } sleep Delay execution Description void sleep int seconds The sleep function delays program execution for the given number of seconds. See also usleep. uniqid Generate a unique id Description int uniqid string prefix boolean lcg Uniqid returns a prefixed unique identifier based on the current time in microseconds. The prefix can be useful for instance if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Prefix can be up to 114 characters long. If the optional lcg parameter is true, uniqid will add additional "combined LCG" entropy at the end of the return value, which should make the results more unique. With an empty prefix, the returned string will be 13 characters long. If lcg is true, it will be 23 characters. The lcg parameter is only available in PHP 4 and PHP 3.0.13 and later. If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along the lines of $token = md5 (uniqid ("")); // no random portion $better_token = md5 (uniqid (rand())); // better, difficult to guess This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict. unpack Unpack data from binary string Description array unpack string format string data Unpack from binary string into array according to format. Returns array containing unpacked elements of binary string. Unpack works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /. <function>Unpack</function> format string $array = unpack ("c2chars/nint", $binarydata); The resulting array will contain the entries "chars1", "chars2" and "int". For an explanation of the format codes see also: pack Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified. unserialize Creates a PHP value from a stored representation Description mixed unserialize string str unserialize takes a single serialized variable (see serialize) and converts it back into a PHP value. The converted value is returned, and can be an integer, double, string, array or object. If an object was serialized, its methods are not preserved in the returned value. <function>Unserialize</function> example // Here, we use unserialize() to load session data from a database // into $session_data. This example complements the one described // with serialize. $conn = odbc_connect ("webdb", "php", "chicken"); $stmt = odbc_prepare ($conn, "SELECT data FROM sessions WHERE id = ?"); $sqldata = array ($PHP_AUTH_USER); if (!odbc_execute ($stmt, &$sqldata) || !odbc_fetch_into ($stmt, &$tmp)) { // if the execute or fetch fails, initialize to empty array $session_data = array(); } else { // we should now have the serialized data in $tmp[0]. $session_data = unserialize ($tmp[0]); if (!is_array ($session_data)) { // something went wrong, initialize to empty array $session_data = array(); } } usleep Delay execution in microseconds Description void usleep int micro_seconds The sleep function delays program execution for the given number of micro_seconds. See also sleep. This function does not work on Windows systems.