Miscellaneous functionsMisc.
These functions were placed here because none of the other
categories seemed to fit.
connection_abortedReturns true if client disconnectedDescriptionint connection_abortedvoid
Returns true if client disconnected. See the Connection Handling
description in the Features
chapter for a complete explanation.
connection_statusReturns connection status bitfieldDescriptionint connection_statusvoid
Returns the connection status bitfield. See the Connection Handling
description in the Features
chapter for a complete explanation.
connection_timeoutReturn true if script timed outDescriptionint connection_timeoutvoid
Returns true if script timed out. See the Connection Handling
description in the Features
chapter for a complete explanation.
defineDefines a named constant.Descriptionint definestring namemixed valueint
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
Descriptionint definedstring 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
Descriptionvoid diestring 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.
evalEvaluate a string as PHP codeDescriptionmixed evalstring code_streval 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.
A return statement will terminate the evaluation of
the string immediatley. In PHP4 you may use return
to return a value that will become the result of the
eval function while in PHP3
eval was of type void and did
never return anything.
Eval 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.
exitTerminate current scriptDescriptionvoid exit
This language construct terminates parsing of the script. It
does not return.
See also die.
get_browser
Tells what the user's browser is capable of
Descriptionobject get_browserstring
user_agentget_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.
Get_browser 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;.
highlight_fileSyntax highlighting of a fileDescriptionvoid highlight_filestring filename
The highlight_file function prints out a syntax
higlighted version of the code contained in filename
using the colors defined in the built-in syntax highlighter for PHP.
Creating a source highlighting URL
To setup a URL that can code hightlight any script that you pass to
it, we will make use of the "ForceType" directive in
Apache to generate a nice URL pattern, and use the
function highlight_file to show a nice looking
code list.
In your httpd.conf you can add the following:
<Location /source>
ForceType application/x-httpd-php
</Location>
And then make a file named "source" and put it in your
web root directory.
<HTML>
<HEAD>
<TITLE>Source Display</TITLE>
</HEAD>
<BODY BGCOLOR="white">
<?php
$script = getenv ("PATH_TRANSLATED");
if(!$script) {
echo "<BR><B>ERROR: Script Name needed</B><BR>";
} else {
if (ereg("(\.php|\.inc)$",$script)) {
echo "<H1>Source of: $PATH_INFO</H1>\n<HR>\n";
highlight_file($script);
} else {
echo "<H1>ERROR: Only PHP or include script names are allowed</H1>";
}
}
echo "<HR>Processed: ".date("Y/M/d H:i:s",time());
?>
</BODY>
</HTML>
Then you can use an URL like the one below to display a colorized
version of a script located in "/path/to/script.php"
in your web site.
http://your.server.com/source/path/to/script.php
See also highlight_string,
show_source.
highlight_stringSyntax highlighting of a stringDescriptionvoid highlight_stringstring str
The highlight_string function prints out a syntax
highlighted version of str using the colors defined
in the built-in syntax highlighter for PHP.
See also highlight_file,
show_source.
ignore_user_abort
Set whether a client disconnect should abort script execution
Descriptionint ignore_user_abortint
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.
Descriptionarray iptcparsestring 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.
leakLeak memoryDescriptionvoid leakint bytesLeak 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.
packPack data into binary string.Descriptionstring packstring formatmixed
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 dependent size and byte order)
I unsigned integer (machine dependent 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
Pack 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 dependent 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.
show_sourceSyntax highlighting of a fileDescriptionvoid show_sourcestring filename
The show_source function prints out a syntax
higlighted version of the code contained in filename
using the colors defined in the built-in syntax highlighter for PHP.
This function is an alias for the function
highlight_file
See also highlight_string,
highlight_file.
sleepDelay executionDescriptionvoid sleepint seconds
The sleep function delays program execution for the given number
of seconds.
See also usleep.
uniqidGenerate a unique idDescriptionint uniqidstring prefixboolean
lcgUniqid 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.
unpackUnpack data from binary stringDescriptionarray unpackstring formatstring dataUnpack 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 /.
Unpack 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.
usleepDelay execution in microsecondsDescriptionvoid usleepint micro_seconds
The usleep function delays program execution
for the given number of micro_seconds.
See also sleep.
This function does not work on Windows systems.