PHP 3 专题 -- 函数英文列表

---摘自互联网
Table of Contents
I. Adabas D Functions
II. Apache Specific Functions
III. Array Functions
IV. BC (Arbitrary Precision) Functions
V. Calendar Functions
VI. Date/Time Functions
VII. dBase Functions
VIII. dbm Functions
IX. Directory Functions
X. Dynamic Loading Functions
XI. Program Execution Functions
XII. filePro Functions
XIII. Filesystem Functions
XIV. Functions related to HTTP
XV. Hyperwave functions
XVI. Image functions
XVII. IMAP Functions
XVIII. PHP options & information
XIX. Informix Functions
XX. InterBase Functions
XXI. LDAP Functions
XXII. Mail Functions
XXIII. Mathematical Functions
XXIV. Miscellaneous Functions
XXV. mSQL Functions
XXVI. MySQL Functions
XXVII. Sybase Functions
XXVIII. Network Functions
XXIX. ODBC Functions
XXX. Oracle functions
XXXI. PDF functions
XXXII. PostgreSQL functions
XXXIII. Regular expression functions
XXXIV. Semaphore and Shared Memory Functions
XXXV. Solid Functions
XXXVI. SNMP Functions
XXXVII. String functions
XXXVIII. URL functions
XXXIX. Variable functions
XL. Vmailmgr Functions
XLI. Gz-file Functions
XLII. XML Parser Functions

I. Adabas D Functions

Table of Contents
ada_afetch
ada_autocommit
ada_close
ada_commit
ada_connect
ada_exec
ada_fetchrow
ada_fieldname
ada_fieldnum
ada_fieldtype
ada_freeresult
ada_numfields
ada_numrows
ada_result
ada_resultall
ada_rollback

The Adabas D functions are deprecated, you probably want to use the Unified ODBC functions instead.

ada_afetch

ada_afetch -- fetch a result row into an array

Description

See odbc_fetch_into()

ada_autocommit

ada_autocommit -- toggle autocommit behaviour

Description

See odbc_autocommit().

ada_close

ada_close -- close a connection to an Adabas D server

Description

See odbc_close().

ada_commit

ada_commit -- commit a transaction

Description

See odbc_commit()

ada_connect

ada_connect -- connect to an Adabas D datasource

Description

See odbc_connect().

ada_exec

ada_exec -- prepare and execute a SQL statement

Description

See odbc_exec() or odbc_do().

ada_fetchrow

ada_fetchrow -- fetch a row from a result

Description

See odbc_fetch_row().

ada_fieldname

ada_fieldname -- get the columnname

Description

See Odbc_field_name().

ada_fieldnum

ada_fieldnum -- get column number

Description

See odbc_field_num().

ada_fieldtype

ada_fieldtype -- get the datatype of a field

Description

See Odbc_field_type().

ada_freeresult

ada_freeresult -- >free resources associated with a result

Description

See odbc_free_result().

ada_numfields

ada_numfields -- get the number of columns in a result

Description

See Odbc_num_fields().

ada_numrows

ada_numrows -- number of rows in a result

Description

See odbc_num_rows().

ada_result

ada_result -- get data from results

Description

See odbc_result().

ada_resultall

ada_resultall -- print result as HTML table

Description

See odbc_result_all().

ada_rollback

ada_rollback -- rollback a transaction

Description

See odbc_rollback().

II. Apache Specific Functions

Table of Contents
Apache_lookup_uri
apache_note
getallheaders
Virtual

apache_lookup_uri

apache_lookup_uri -- Perform a partial request for the specified URI and return all info about it

Description

class apache_lookup_uri(string filename);

This performs a partial request for a URI. It goes just far enough to obtain all the important information about the given resource and returns this information in a class. The properties of the returned class are:
 

status
the_request
status_line
method
content_type
handler
uri
filename
path_info
args
boundary
no_cache
no_local_copy
allowed
send_bodyct
bytes_sent
byterange
clength
unparsed_uri
mtime
request_time

apache_note

apache_note -- Get and set apache request notes

Description

string apache_note(string note_name, string [note_value]);

apache_note() is an Apache-specific function which gets and sets values in a request's notes table. If called with one argument, it returns the current value of note note_name. If called with two arguments, it sets the value of note note_name to note_value and returns the previous value of note note_name.

getallheaders

getallheaders -- Fetch all HTTP request headers

Description

array getallheaders(void);

This function returns an associative array of all the HTTP headers in the current request.

Example 1. GetAllHeaders() Example

$headers = getallheaders();
while (list($header, $value) = each($headers)) {
    echo "$header: $value<br>\n";
}

This example will display all the request headers for the current request.

Note: GetAllHeaders() is currently only supported when PHP runs as an Apache module.

virtual

virtual -- Perform an Apache sub-request

Description

int virtual(string filename);

virtual() is an Apache-specific function which is equivalent to <!--#include virtual...--> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-type header. For PHP files, you should use include() or require().

III. Array Functions

Table of Contents
array
array_walk
arsort
asort
count
current
each
end
key
ksort
list
next
pos
prev
reset
rsort
sizeof
sort
uasort
uksort
usort

array

array -- Create an array

Description

array array(...);

Returns an array of the parameters. The parameters can be given an index with the => operator.

Note that array() really is a language construct used to represent literal arrays, and not a regular function.

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example 1. array() example

$fruits = array(
    "fruits"  => array("a"=>"orange","b"=>"banana","c"=>"apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6)
    "holes"   => array("first", 5 => "second", "third")
);

See also: list().

array_walk

array_walk -- Apply a function to every member of an array.

Description

int array_walk(array arr, string func);

Applies the function named by func to each element of arr. The elements are passed as the first argument of func; if func requires more than one argument, a warning will be generated each time array_walk() calls func. These warnings may be suppressed by prepending the '@' sign to the array_walk() call, or by using error_reporting().

Note that func will actually be working with the elements of arr, so any changes made to those elements will actually be made in the array itself.

Example 1. array_walk() example

$fruits = array("d"=>"lemon","a"=>"orange","b"=>"banana","c"=>"apple");

function test_alter( $item1 ) {
   $item1 = 'bogus';
}

function test_print( $item2 ) {
   echo "$item2<br>\n";
}

array_walk( $fruits, 'test_print' );
array_walk( $fruits, 'test_alter' );
array_walk( $fruits, 'test_print' );
      

See also each() and list().

arsort

arsort -- Sort an array in reverse order and maintain index association

Description

void arsort(array array);

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Example 1. arsort() example

$fruits = array("d"=>"lemon","a"=>"orange","b"=>"banana","c"=>"apple");
arsort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}

This example would display: fruits[a] = orange fruits[d] = lemon fruits[b] = banana fruits[c] = apple The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

See also: asort(), rsort(), ksort(), and sort().

asort

asort -- Sort an array and maintain index association

Description

void asort(array array);

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Example 1. asort() example

$fruits = array("d"=>"lemon","a"=>"orange","b"=>"banana","c"=>"apple");
asort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}

This example would display: fruits[c] = apple fruits[b] = banana fruits[d] = lemon fruits[a] = orange The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.

See also arsort(), rsort(), ksort(), and sort().

count

count -- count elements in a variable

Description

int count(mixed var);

Returns the number of elements in var, which is typically an array (since anything else will have one element).

Returns 0 if the variable is not set.

Returns 1 if the variable is not an array.

See also: sizeof(), isset(), and is_array().

current

current -- return the current element in an array

Description

mixed current(array array);

Each array variable has an internal pointer that points to one of its elements. In addition, all of the elements in the array are linked by a bidirectional linked list for traversing purposes. The internal pointer points to the first element that was inserted to the array until you run one of the functions that modify that pointer on that array.

The current() function simply returns the array element that's currently being pointed by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list, current() returns false.

Warning: if the array contains empty elements (0 or "", the empty string) then this function will return false for these elements as well. It is undecideable if the current element is just a zero-value or you have traversed beyond the end of the array. To properly traverse an array, use the each() function.

See also: end(), next(), prev() and reset().

each

each -- return next key/value pair from an array

Description

array each(array array);

Returns the current key/value pair from the array array and advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key each contain the key name of the array element, and 1 and value contain the data.

Example 1. each() examples

$foo = array( "bob", "fred", "jussi", "jouni" );
$bar = each( $foo );
      

$bar now contains the following key/value pairs: 

    0 => 0 

    1 => 'bob' 

    key => 0 

    value => 'bob' 

$foo = array( "Robert" => "Bob", "Seppo" => "Sepi" );
$bar = each( $foo );
       

$bar now contains the following key/value pairs: 

    0 => 'Robert' 

    1 => 'Bob' 

    key => 'Robert' 

    value => 'Bob' 

each() is typically used in conjunction with list() to traverse an array; for instance, $HTTP_POST_VARS:

Example 2. Traversing $HTTP_POST_VARS with each()

echo "Values submitted via POST method:<br>";
while ( list( $key, $val ) = each( $HTTP_POST_VARS ) ) {
   echo "$key => $val<br>";
}
      

See also key(), list(), current(), reset(), next(), and prev().

end

end -- set internal pointer of array to last element

Description

end(array array);

end() advances array's internal pointer to the last element.

See also: current(), each(), end() next() and reset()

key

key -- fetch a key from an associative array

Description

mixed key(array array);

key() returns the index element of the current array position.

See also: current(), next()

ksort

ksort -- Sort an array by key.

Description

int ksort(array array);

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Example 1. ksort() example

$fruits = array("d"=>"lemon","a"=>"orange","b"=>"banana","c"=>"apple");
ksort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}

This example would display: fruits[a] = orange fruits[b] = banana fruits[c] = apple fruits[d] = lemon

See also asort(), arsort(), sort(), and rsort().

list

list -- assign variables as if they were an array

Description

void list(...);

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Example 1. list() example

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>
<?php

$result = mysql($conn, "SELECT id, name, salary FROM employees");
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
    print(" <tr>\n".
          "  <td><a href=\"info.php3?id=$id\">$name</a></td>\n".
          "  <td>$salary</td>\n".
          " </tr>\n");
}

?></table>

See also: each(), array().

next

next -- advance the internal array pointer

Description

mixed next(array array);

Returns the array element in the next place that's pointed by the internal array pointer, or false if there are no more elements. Warning: if the array contains empty elements then this function will return false for these elements as well. To properly traverse an array which may contain empty elements see the each() function.

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element. That means it returns the next array element and advances the internal array pointer by one. If advancing the internal array pointer results in going beyond the end of the element list, next() returns false.

See also: current(), end() prev() and reset()

pos

pos -- return the current element in an array

Description

mixed pos(array array);

This is an alias for current().

See also: end(), next(), prev() and reset().

prev

prev -- rewind internal array pointer

Description

mixed prev(array array);

Returns the array element in the previous place that's pointed by the internal array pointer, or false if there are no more elements. Warning: if the array contains empty elements then this function will return false for these elements as well. To properly traverse an array which may contain empty elements see the each() function.

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.

See also: current(), end() next() and reset()

reset

reset -- set internal pointer of array to first element

Description

mixed reset(array array);

reset() rewinds array's internal pointer to the first element.

reset() returns the value of the first array element.

See also: current(), each(), next() prev() and reset()

rsort

rsort -- Sort an array in reverse order

Description

void rsort(array array);

This function sorts an array in reverse order (highest to lowest).

Example 1. rsort() example

    $fruits = array("lemon","orange","banana","apple");
    rsort($fruits);
    for(reset($fruits); ($key,$value) = each($fruits); ) {
        echo "fruits[$key] = ".$value."\n";
    }
        

This example would display: fruits[0] = orange fruits[1] = lemon fruits[2] = banana fruits[3] = apple The fruits have been sorted in reverse alphabetical order.

See also arsort(), asort(), ksort(), sort() and usort().

sizeof

sizeof -- get size of array

Description

int sizeof(array array);

Returns the number of elements in the array.

See also: count()

sort

sort -- Sort an array

Description

void sort(array array);

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

Example 1. sort() example

$fruits = array("lemon","orange","banana","apple");
sort($fruits);
for(reset($fruits); $key = key($fruits); next($fruits)) {
    echo "fruits[$key] = ".$fruits[$key]."\n";
}

This example would display: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange The fruits have been sorted in alphabetical order.

See also arsort(), asort(), ksort(), rsort(), and usort().

uasort

uasort -- Sort an array with a user-defined comparison function and maintain index association

Description

void uasort(array array, function cmp_function);

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. The comparison function is user-defined.

uksort

uksort -- Sort an array by keys using a user-defined comparison function

Description

void uksort(array array, function cmp_function);

This function will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Example 1. uksort() example

function mycompare($a, $b) {   
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}
$a = array(4 => "four", 3 => "three", 20 => "twenty", 10 => "ten");
uksort($a, mycompare);
while(list($key, $value) = each($a)) {
    echo "$key: $value\n";
}

This example would display: 20: twenty 10: ten 4: four 3: three

See also arsort(), asort(), uasort(), ksort(), rsort() and sort().

usort

usort -- Sort an array by values using a user-defined comparison function

Description

void usort(array array, function cmp_function);

This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Example 1. usort() example

function cmp($a,$b) {   
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}
$a = array(3,2,5,6,1);
usort($a, cmp);
while(list($key,$value) = each($a)) {
    echo "$key: $value\n";
}

This example would display: 0: 6 1: 5 2: 3 3: 2 4: 1 Obviously in this trivial case the rsort() function would be more appropriate.

See also arsort(), asort(), ksort(), rsort() and sort().

IV. BC (Arbitrary Precision) Functions

Table of Contents
bcadd
bccomp
bcdiv
bcmod
bcmul
bcpow
bcscale
bcsqrt
bcsub

These BC functions are only available if PHP was compiled with the --enable-bcmath configure option.

bcadd

bcadd -- Add two arbitrary precision numbers.

Description

string bcadd(string left operand, string right operand, int [scale]);

Adds the left operand to the right operand and returns the sum in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

See also bcsub().

bccomp

bccomp -- Compare two arbitrary precision numbers.

Description

int bccomp(string left operand, string right operand, int [scale]);

Compares the left operand to the right operand and returns the result as an integer. The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparion. The return value is 0 if the two operands are equal. If the left operand is larger than the right operand the return value is +1 and if the left operand is less than the right operand the return value is -1.

bcdiv

bcdiv -- Divide two arbitrary precision numbers.

Description

string bcdiv(string left operand, string right operand, int [scale]);

Divides the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.

See also bcmul().

bcmod

bcmod -- Get modulus of an arbitrary precision number.

Description

string bcmod(string left operand, string modulus);

Get the modulus of the left operand using modulus.

See also bcdiv().

bcmul

bcmul -- Multiply two arbitrary precision number.

Description

string bcmul(string left operand, string right operand, int [scale]);

Multiply the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.

See also bcdiv().

bcpow

bcpow -- Raise an arbitrary precision number to another.

Description

string bcpow(string x, string y, int [scale]);

Raise x to the power y. The scale can be used to set the number of digits after the decimal place in the result.

See also bcsqrt().

bcscale

bcscale -- Set default scale parameter for all bc math functions.

Description

string bcscale(int scale);

This function sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.

bcsqrt

bcsqrt -- Get the square root of an arbitray precision number.

Description

string bcsqrt(string operand, int scale);

Return the square root of the operand. The optional scale parameter sets the number of digits after the decimal place in the result.

See also bcpow().

bcsub

bcsub -- Subtract one arbitrary precision number from another.

Description

string bcsub(string left operand, string right operand, int [scale]);

Subtracts the right operand from the left operand and returns the result in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.

See also bcadd().

V. Calendar Functions

Table of Contents
JDToGregorian
GregorianToJD
JDToJulian
JulianToJD
JDToJewish
JewishToJD
JDToFrench
FrenchToJD
JDMonthName
JDDayOfWeek

The calendar functions are only available if you have compiled the calendar extension in dl/calendar. Read dl/README for instructions on using it.

The Calendar extension in PHP presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting way earlier than any date most people would need to track (somewhere around 4000bc). To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on calendar systems visit http://genealogy.org/~scottlee/cal-overview.html. Excerpts from this page are included in these instructions, and are in quotes

JDToGregorian

JDToGregorian -- Converts Julian Day Count to Gregorian date

Description

string jdtogregorian(int julianday);

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year"

GregorianToJD

GregorianToJD -- Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd(int month, int day, int year);

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this software can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Example 1. Calendar functions

<?php
$jd = GregorianToJD(10,11,1970);
echo("$jd\n");
$gregorian = JDToGregorian($jd);
echo("$gregorian\n");
?>

JDToJulian

JDToJulian -- Converts a Julian Calendar date to Julian Day Count

Description

string jdtojulian(int julianday);

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

JulianToJD

JulianToJD -- Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd(int month, int day, int year);

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this software can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

JDToJewish

JDToJewish -- Converts a Julian Day Count to the Jewish Calendar

Description

string jdtojewish(int julianday);

Converts a Julian Day Count the the Jewish Calendar.

JewishToJD

JewishToJD -- Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd(int month, int day, int year);

Valid Range Although this software can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful.

The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

JDToFrench

JDToFrench -- Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench(int month, int day, int year);

Converts a Julian Day Count to the French Republican Calendar.

FrenchToJD

FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd(int month, int day, int year);

Converts a date from the French Republican Calendar to a Julian Day Count

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

JDMonthName

JDMonthName -- Returns a month name

Description

string jdmonthname(int julianday, int mode);

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

Table 1. Calendar modes
 

Mode Meaning
0 Gregorian - apreviated
1 Gregorian
2 Julian - apreviated
3 Julian
4 Jewish
5 French Republican

JDDayOfWeek

JDDayOfWeek -- Returns the day of the week

Description

mixed jddayofweek(int julianday, int mode);

Returns the day of the week. Can return a string or an int depending on the mode.

Table 1. Calendar week modes
 

Mode Meaning
0 returns the day number as an int (0=sunday, 1=monday, etc)
1 returns string containing the day of week (english-gregorian)
2 returns a string containing the abreviated day of week (english-gregorian)

VI. Date/Time Functions

Table of Contents
checkdate
date
strftime
getdate
gmdate
mktime
gmmktime
time
microtime

checkdate

checkdate -- validate a date/time

Description

int checkdate(int month, int day, int year);

Returns true if the date given is valid; otherwise returns false. Checks the validity of the date formed by the arguments. A date is considered valid if:

date

date -- format a local time/date

Description

string date(string format, int timestamp);

Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given.

The following characters are recognized in the format string:

Unrecognized characters in the format string will be printed as-is.

Example 1. date() example

print(date( "l dS of F Y h:i:s A" ));
print("July 1, 2000 is on a " . date("l", mktime(0,0,0,7,1,2000)));

It is possible to use date() and mktime() together to find dates in the future or the past.

Example 2. date() and mktime() example

$tomorrow  = mktime(0,0,0,date("m")  ,date("d")+1,date("Y"));
$lastmonth = mktime(0,0,0,date("m")-1,date("d"),  date("Y"));
$nextyear  = mktime(0,0,0,date("m"),  date("d",   date("Y")+1);

To format dates in other languages, you should use the setlocale() and strftime() functions.

See also gmdate() and mktime().

strftime

strftime -- format a local time/date according to locale settings

Description

string strftime(string format, int timestamp);

Returns a string formatted according to the given format string 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().

The following conversion specifiers are recognized in the format string:

Example 1. strftime() example

setlocale ("LC_TIME", "C");
print(strftime("%A in Finnish is "));
setlocale ("LC_TIME", "fi");
print(strftime("%A, in French "));
setlocale ("LC_TIME", "fr");
print(strftime("%A and in German "));
setlocale ("LC_TIME", "de");
print(strftime("%A.\n"));

This example works if you have the respective locales installed in your system.

See also setlocale() and mktime().

getdate

getdate -- get date/time information

Description

array getdate(int timestamp);

Returns an associative array containing the date information of the timestamp as the following array elements:

gmdate

gmdate -- format a GMT/CUT date/time

Description

string gmdate(string format, int timestamp);

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT). For example, when run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".

Example 1. gmdate() example

echo date( "M d Y H:i:s",mktime(0,0,0,1,1,1998) );
echo gmdate( "M d Y H:i:s",mktime(0,0,0,1,1,1998) );

See also date(), mktime() and gmmktime().

mktime

mktime -- get UNIX timestamp for a date

Description

int mktime(int hour, int minute, int second, int month, int day, int year);

Warning: Note the strange order of arguments, which differs from the order of arguments in a regular UNIX mktime() call and which does not lend itself well to leaving out parameters from right to left (see below). It is a common error to mix these values up in a script.

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) and the time specified.

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

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".

Example 1. mktime() example

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) );

See also date() and time().

gmmktime

gmmktime -- get UNIX timestamp for a GMT date

Description

int gmmktime(int hour, int minute, int second, int month, int day, int year);

Identical to mktime() except the passed parameters represents a GMT date.

time

time -- return current UNIX timestamp

Description

int time(void);

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

See also date().

microtime

microtime -- return current UNIX timestamp with microseconds

Description

string microtime(void);

Returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. This function is only available on operating systems that support the gettimeofday() system call.

See also time().

VII. dBase Functions

Table of Contents
dbase_create
dbase_open
dbase_close
dbase_pack
dbase_add_record
dbase_delete_record
dbase_get_record
dbase_numfields
dbase_numrecords

These functions allow you to access records stored in dBase-format (dbf) databases.

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent webserver processes modifying the same dBase file will very likely ruin your database.

Unlike SQL databases, dBase "databases" cannot change the database definition afterwards. Once the file is created, the database definition is fixed. There are no indexes that speed searching or otherwise organize your data. dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack()().

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, since the file format is commonly understood with Windows spreadsheets and organizers. Import and export of data is about all that dBase support is good for.

dbase_create

dbase_create -- creates a dBase database

Description

int dbase_create(string filename, array fields);

The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.

The types of fields available are:

L


Boolean. These do not have a length or precision.

M


Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.

D


Date (stored as YYYYMMDD). These do not have a length or precision.

N


Number. These have both a length and a precision (the number of digits after the decimal point).

C


String.

If the database is successfully created, a dbase_identifier is returned, otherwise false is returned.

Example 1. Creating a dBase database file

// "database" name
$dbname = "/tmp/test.dbf";

// database "definition"
$def =
    array(
        array("date",     "D"),
        array("name",     "C",  50),
        array("age",      "N",   3, 0),
        array("email",    "C", 128),
        array("ismember", "L")
    );

// creation
if (!dbase_create($dbname, $def))
    print "<strong>Error!</strong>";

dbase_open

dbase_open -- opens a dBase database

Description

int dbase_open(string filename, int flags);

The flags correspond to those for the open() system call. (Typically 0 means read-only, 1 means write-only, and 2 means read and write.)

Returns a dbase_identifier for the opened database, or false if the database couldn't be opened.

dbase_close

dbase_close -- close a dBase database

Description

bool dbase_close(int dbase_identifier);

Closes the database associated with dbase_identifier.

dbase_pack

dbase_pack -- packs a dBase database

Description

bool dbase_pack(int dbase_identifier);

Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record().

dbase_add_record

dbase_add_record -- add a record to a dBase database

Description

bool dbase_add_record(int dbase_identifier, array record);

Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and false will be returned.

dbase_delete_record

dbase_delete_record -- deletes a record from a dBase database

Description

bool dbase_delete_record(int dbase_identifier, int record);

Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().

dbase_get_record

dbase_get_record -- gets a record from a dBase database

Description

array dbase_get_record(int dbase_identifier, int record);

Returns the data from record in an array. The array is indexed starting at 1, and includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record().

Each field is converted to the appropriate PHP type. (Dates are left as strings.)

dbase_numfields

dbase_numfields -- find out how many fields are in a dBase database

Description

int dbase_numfields(int dbase_identifier);

Returns the number of fields (columns) in the specified database. Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Example 1. Using dbase_numfields()

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i=0; $i < $nf; $i++) {
    print $rec[$i]."<br>\n";
}

dbase_numrecords

dbase_numrecords -- find out how many records are in a dBase database

Description

int dbase_numrecords(int dbase_identifier);

Returns the number of records (rows) in the specified database. Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

VIII. dbm Functions

Table of Contents
dbmopen
dbmclose
dbmexists
dbmfetch
dbminsert
dbmreplace
dbmdelete
dbmfirstkey
dbmnextkey
dblist

These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley db, gdbm, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).

Example 1. dbm example

$dbm = dbmopen("lastseen", "w");
if (dbmexists($dbm, $userid)) {
  $last_seen = dbmfetch($dbm, $userid);
} else {
  dbminsert($dbm, $userid, time());
}
do_stuff();
dbmreplace($dbm, $userid, time());
dbmclose($dbm);

dbmopen

dbmopen -- opens a dbm database

Description

int dbmopen(string filename, int flags);

The first argument is the full-path filename of the dbm file to be opened and the second is the file open mode which is one of "r", "n" or "w" for read-only, new (implies read-write, and may truncate an already-existing database of the same name) and read-write respectively.

Returns an identifer to be passed to the other dbm functions on success, or false on failure.

If ndbm support is used, ndbm will actually create filename.dir and filename.pag files. gdbm only uses one file, as does the internal flat-file support, and Berkeley db creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the dbm library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on dbm files, see your Unix man pages, or obtain GNU's gdbm from ftp://prep.ai.mit.edu/pub/gnu.

dbmclose

dbmclose -- closes a dbm database

Description

bool dbmclose(int dbm_identifier);

Unlocks and closes the specified database.

dbmexists

dbmexists -- tells if a value exists for a key in a dbm database

Description

bool dbmexists(int dbm_identifier, string key);

Returns true if there is a value associated with the key.

dbmfetch

dbmfetch -- fetches a value for a key from a dbm database

Description

string dbmfetch(int dbm_identifier, string key);

Returns the value associated with key.

dbminsert

dbminsert -- inserts a value for a key in a dbm database

Description

int dbminsert(int dbm_identifier, string key, string value);

Adds the value to the database with the specified key.

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

dbmreplace

dbmreplace -- replaces the value for a key in a dbm database

Description

bool dbmreplace(int dbm_identifier, string key, string value);

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

dbmdelete

dbmdelete -- deletes the value for a key from a dbm database

Description

bool dbmdelete(int dbm_identifier, string key);

Deletes the value for key in the database.

Returns false if the key didn't exist in the database.

dbmfirstkey

dbmfirstkey -- retrieves the first key from a dbm database

Description

string dbmfirstkey(int dbm_identifier);

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

dbmnextkey

dbmnextkey -- retrieves the next key from a dbm database

Description

string dbmnextkey(int dbm_identifier, string key);

Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

Example 1. Visiting every key/value pair in a dbm database.

$key = dbmfirstkey($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch($dbm_id, $key) . "\n";
    $key = dbmnextkey($dbm_id, $key);
}
     

dblist

dblist -- describes the dbm-compatible library being used

Description

string dblist(void);

IX. Directory Functions

Table of Contents
chdir
dir
closedir
opendir
readdir
rewinddir

chdir

chdir -- change directory

Description

int chdir(string directory);

Changes PHP's current directory to directory. Returns FALSE if unable to change directory, TRUE otherwise.

dir

dir -- directory class

Description

new dir(string directory);

A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.

Example 1. Dir() Example

$d = dir("/etc");
echo "Handle: ".$d->handle."<br>\n";
echo "Path: ".$d->path."<br>\n";
while($entry=$d->read()) {
    echo $entry."<br>\n";
}
$d->close();
        

closedir

closedir -- close directory handle

Description

void closedir(int dir_handle);

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

opendir

opendir -- open directory handle

Description

int opendir(string path);

Returns a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

readdir

readdir -- read entry from directory handle

Description

string readdir(int dir_handle);

Returns the filename of the next file from the directory. The filenames are not returned in any particular order.

Example 1. List all files in the current directory

<?php
    $handle=opendir('.');
    echo "Directory handle: $handle\n";
    echo "Files:\n";
    while ($file = readdir($handle)) {
        echo "$file\n";
    }
    closedir($handle); 
?>
    

rewinddir

rewinddir -- rewind directory handle

Description

void rewinddir(int dir_handle);

Resets the directory stream indicated by dir_handle to the beginning of the directory.

X. Dynamic Loading Functions

Table of Contents
dl

dl

dl -- load a PHP extension at runtime

Description

int dl(string library);

Loads the PHP extension defined in library. See also the extension_dir configuration directive.

XI. Program Execution Functions

Table of Contents
escapeshellcmd
exec
system
passthru

escapeshellcmd

escapeshellcmd -- escape shell metacharacters

Description

string escapeshellcmd(string command);

EscapeShellCmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions. A standard use would be:

system(EscapeShellCmd($cmd))

exec

exec -- Execute an external program

Description

string exec(string command, string [array], int [return_var]);

exec() executes the given command, however it does not output anything. It simply returns the last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the PassThru() function.

If the array argument is present, then the specified array will be filled with every line of output from the command. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

If the return_var argument is present along with the array argument, then the return status of the executed command will be written to this variable.

Note that if you are going to allow data coming from user input to be passed to this function, then you should be using EscapeShellCmd() to make sure that users cannot trick the system into executing arbitrary commands.

See also system(), PassThru(), popen() and EscapeShellCmd().

system

system -- Execute an external program and display output

Description

string system(string command, int [return_var]);

System() is just like the C version of the function in that it executes the given command and outputs the result. If a variable is provided as the second argument, then the return status code of the executed command will be written to this variable.

Note, that if you are going to allow data coming from user input to be passed to this function, then you should be using the EscapeShellCmd() function to make sure that users cannot trick the system into executing arbitrary commands.

The System() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the PassThru() function. See also the exec() and popen() functions.

passthru

passthru -- Execute an external program and display raw output

Description

string passthru(string command, int [return_var]);

The passthru() function is similar to the Exec() function in that it executes a command. If the return_var argument is present, the return status of the Unix command will be placed here. This function should be used in place of Exec() or System() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

See also exec() and fpassthru().

XII. filePro Functions

Table of Contents
filepro
filepro_fieldname
filepro_fieldtype
filepro_fieldwidth
filepro_retrieve
filepro_fieldcount
filepro_rowcount

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark by Fiserv, Inc. You can find more information about filePro at http://www.fileproplus.com/.

filepro

filepro -- read and verify the map file

Description

bool filepro(string directory);

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

filepro_fieldname

filepro_fieldname -- gets the name of a field

Description

string filepro_fieldname(int field_number);

Returns the name of the field corresponding to field_number.

filepro_fieldtype

filepro_fieldtype -- gets the type of a field

Description

string filepro_fieldtype(int field_number);

Returns the edit type of the field corresponding to field_number.

filepro_fieldwidth

filepro_fieldwidth -- gets the width of a field

Description

int filepro_fieldwidth(int field_number);

Returns the width of the field corresponding to field_number.

filepro_retrieve

filepro_retrieve -- retrieves data from a filePro database

Description

string filepro_retrieve(int row_number, int field_number);

Returns the data from the specified location in the database.

filepro_fieldcount

filepro_fieldcount -- find out how many fields are in a filePro database

Description

int filepro_fieldcount(void);

Returns the number of fields (columns) in the opened filePro database.

See also filepro().

filepro_rowcount

filepro_rowcount -- find out how many rows are in a filePro database

Description

int filepro_rowcount(void);

Returns the number of rows in the opened filePro database.

See also filepro().

XIII. Filesystem Functions

Table of Contents
basename
chgrp
chmod
chown
clearstatcache
copy
dirname
fclose
feof
fgetc
fgets
fgetss
file
file_exists
fileatime
filectime
filegroup
fileinode
filemtime
fileowner
fileperms
filesize
filetype
fopen
fpassthru
fputs
fread
fseek
ftell
fwrite
is_dir
is_executable
is_file
is_link
is_readable
is_writeable
link
linkinfo
mkdir
pclose
popen
readfile
readlink
rename
rewind
rmdir
stat
lstat
symlink
tempnam
touch
umask
unlink

basename

basename -- return filename component of path

Description

string basename(string path);

Given a string containing a path to a file, this function will return the base name of the file.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

Example 1. basename() example

$path = "/home/httpd/html/index.php3";
$file = basename($path); // $file is set to "index.php3"

See also: dirname()

chgrp

chgrp -- change file group

Description

int chgrp(string filename, mixed group);

Attempts to change the group of the file filename to group. Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.

Returns true on success; otherwise returns false.

On Windows, does nothing and returns true.

See also chown() and chmod().

chmod

chmod -- change file mode

Description

int chmod(string filename, int mode);

Attempts to change the mode of the file specified by filename to that given in mode.

Note that mode is not automatically assumed to be an octal value. To ensure the expected operation, you need to prefix mode with a zero (0):

chmod( "/somedir/somefile", 755 );   // decimal; probably incorrect       
chmod( "/somedir/somefile", 0755 );  // octal; correct value of mode

Returns true on success and false otherwise.

See also chown() and chgrp().

chown

chown -- change file owner

Description

int chown(string filename, mixed user);

Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Returns true on success; otherwise returns false.

Note: On Windows, does nothing and returns true.

See also chown() and chmod().

clearstatcache

clearstatcache -- clear file stat cache

Description

void clearstatcache(void);

Invoking the stat() or lstat() system call on most systems is quite expensive. Therefore, the result of the last call to any of the status functions (listed below) is stored for use on the next such call using the same filename. If you wish to force a new status check, for instance if the file is being checked many times and may change or disappear, use this function to clear the results of the last call from memory.

This value is only cached for the lifetime of a single request.

Affected functions include stat(), lstat(), file_exists(), is_writeable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

copy

copy -- copy file

Description

int copy(string source, string dest);

Makes a copy of a file. Returns true if the copy succeeded, false otherwise.

Example 1. copy() example

if (!copy($file, $file.'.bak')) {
    print("failed to copy $file...<br>\n");
}

See also: rename()

dirname

dirname -- return directory name component of path

Description

string dirname(string path);

Given a string containing a path to a file, this function will return the name of the directory.

On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).

Example 1. dirname() example

$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"

See also: basename()

fclose

fclose -- close an open file pointer

Description

int fclose(int fp);

The file pointed to by fp is closed.

Returns true on success and false on failure.

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

feof

feof -- test for end-of-file on a file pointer

Description

int feof(int fp);

Returns true if the file pointer is at EOF or an error occurs; otherwise returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

fgetc

fgetc -- get character from file pointer

Description

string fgetc(int fp);

Returns a string containing a single character read from the file pointed to by fp. Returns FALSE on EOF (as does feof()).

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

See also fopen(), popen(), fsockopen(), and fgets().

fgets

fgets -- get line from file pointer

Description

string fgets(int fp, int length);

Returns a string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first).

If an error occurs, returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

See also fopen(), popen(), fgetc(), and fsockopen().

fgetss

fgetss -- get line from file pointer and strip HTML tags

Description

string fgetss(int fp, int length);

Identical to fgets(), except that fgetss attempts to strip any HTML and PHP tags from the text it reads.

See also fgets(), fopen(), fsockopen(), and popen().

file

file -- read entire file into an array

Description

array file(string filename);

Identical to readfile(), except that file() returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.

See also readfile(), fopen(), and popen().

file_exists

file_exists -- Check whether a file exists.

Description

int file_exists(string filename);

Returns true if the file specified by filename exists; false otherwise.

See also clearstatcache().

fileatime

fileatime -- get last access time of file

Description

int fileatime(string filename);

Returns the time the file was last accessed, or false in case of an error.

filectime

filectime -- get inode modification time of file

Description

int filectime(string filename);

Returns the time the file was last changed, or false in case of an error.

filegroup

filegroup -- get file group

Description

int filegroup(string filename);

Returns the group ID of the owner of the file, or false in case of an error.

fileinode

fileinode -- get file inode

Description

int fileinode(string filename);

Returns the inode number of the file, or false in case of an error.

filemtime

filemtime -- get file modification time

Description

int filemtime(string filename);

Returns the time the file was last modified, or false in case of an error.

fileowner

fileowner -- get file owner

Description

int fileowner(string filename);

Returns the user ID of the owner of the file, or false in case of an error.

fileperms

fileperms -- get file permissions

Description

int fileperms(string filename);

Returns the permissions on the file, or false in case of an error.

filesize

filesize -- get file size

Description

int filesize(string filename);

Returns the size of the file, or false in case of an error.

filetype

filetype -- get file type

Description

string filetype(string filename);

Returns the type of the file. Possible values are fifo, char, dir, block, link, file, and unknown.

Returns false if an error occurs.

fopen

fopen -- open file or URL

Description

int fopen(string filename, string mode);

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and a file pointer is returned to the beginning of the text of the response.

Does not handle HTTP redirects, so you must include trailing slashes on directories.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and a pointer to the requested file is returned. If the server does not support passive mode ftp, this will fail. You can open files for either reading and writing via ftp (but not both simultaneously).

If filename begins with anything else, the file will be opened from the filesystem, and a file pointer to the file opened is returned.

If the open fails, the function returns false.

mode may be any of the following:

As well, mode may contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e., it's useless on Unix). If not needed, this will be ignored.

Example 1. fopen() example

$fp = fopen("/home/rasmus/file.txt", "r");
$fp = fopen("http://www.php.net/", "r");
$fp = fopen("ftp://user:password@example.com/", "w");

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

$fp = fopen("c:\\data\\info.txt", "r");

See also fclose(), fsockopen(), and popen().

fpassthru

fpassthru -- output all remaining data on a file pointer

Description

int fpassthru(int fp);

Reads to EOF on the given file pointer and writes the results to standard output.

If an error occurs, fpassthru() returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen(). The file is closed when fpassthru() is done reading it (leaving fp useless).

If you just want to dump the contents of a file to stdout you may want to use the readfile(), which saves you the fopen() call.

See also readfile(), fopen(), popen(), and fsockopen()

fputs

fputs -- write to a file pointer

Description

int fputs(int fp, string str, int [length]);

fputs() is an alias to fwrite(), and is identical in every way. Note that the length parameter is optional and if not specified the entire string will be written.

fread

fread -- Binary-safe file read

Description

string fread(int fp, int length);

fread() reads up to length bytes from the file pointer referenced by fp. Reading stops when length bytes have been read or EOF is reached, whichever comes first.

// get contents of a file into a string
$filename = "/usr/local/something.txt";
$fd = fopen( $filename, "r" );
$contents = fread( $fd, filesize( $filename ) );
fclose( $fd );

See also fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), file(), and fpassthru().

fseek

fseek -- seek on a file pointer

Description

int fseek(int fp, int offset);

Sets the file position indicator for the file referenced by fp to offset bytes into the file stream. Equivalent to calling (in C) fseek( fp, offset, SEEK_SET ).

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.

See also ftell() and rewind().

ftell

ftell -- tell file pointer read/write position

Description

int ftell(int fp);

Returns the position of the file pointer referenced by fp; i.e., its offset into the file stream.

If an error occurs, returns false.

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen().

See also fopen(), popen(), fseek() and rewind().

fwrite

fwrite -- Binary-safe file write

Description

int fwrite(int fp, string string, int [length]);

fwrite() writes the contents of string to the file stream pointed to by fp. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

See also fread(), fopen(), fsockopen(), popen(), and fputs().

is_dir

is_dir -- tells whether the filename is a directory

Description

bool is_dir(string filename);

Returns true if the filename exists and is a directory.

See also is_file() and is_link().

is_executable

is_executable -- tells whether the filename is executable

Description

bool is_executable(string filename);

Returns true if the filename exists and is executable.

See also is_file() and is_link().

is_file

is_file -- tells whether the filename is a regular file

Description

bool is_file(string filename);

Returns true if the filename exists and is a regular file.

See also is_dir() and is_link().

is_link

is_link -- tells whether the filename is a symbolic link

Description

bool is_link(string filename);

Returns true if the filename exists and is a symbolic link.

See also is_dir() and is_file().

is_readable

is_readable -- tells whether the filename is readable

Description

bool is_readable(string filename);

Returns true if the filename exists and is readable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

See also is_writeable().

is_writeable

is_writeable -- tells whether the filename is writeable

Description

bool is_readable(string filename);

Returns true if the filename exists and is writeable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

See also is_readable().

link

link -- Create a hard link

Description

int link(string target, string link);

Link() creates a hard link.

See also the symlink() to create soft links, and readlink() along with linkinfo().

linkinfo

linkinfo -- Get information about a link

Description

int linkinfo(string path);

Linkinfo() returns the st_dev field of the UNIX C stat structure returned by the lstat system call. 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). Returns 0 or FALSE in case of error.

See also symlink(), link(), and readlink().

mkdir

mkdir -- make directory

Description

int mkdir(string pathname, int mode);

Attempts to create the directory specified by pathname.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero.

mkdir("/path/to/my/dir", 0700);

Returns true on success and false on failure.

See also rmdir().

pclose

pclose -- close process file pointer

Description

int pclose(int fp);

Closes a file pointer to a pipe opened by popen().

The file pointer must be valid, and must have been returned by a successful call to popen().

Returns the termination status of the process that was run.

See also popen().

popen

popen -- open process file pointer

Description

int popen(string command, string mode);

Opens a pipe to a process executed by forking the command given by command.

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fputs().

If an error occurs, returns false.

       $fp = popen( "/bin/ls", "r" );

See also pclose().

readfile

readfile -- output a file

Description

int readfile(string filename);

Reads a file and writes it to standard output.

Returns the number of bytes read from the file. If an error occurs, false is returned and unless the function was called as @readfile, an error message is printed.

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and the text of the response is written to standard output.

Does not handle HTTP redirects, so you must include trailing slashes on directories.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and the requested file is written to standard output. If the server does not support passive mode ftp, this will fail.

If filename begins with neither of these strings, the file will be opened from the filesystem and its contents written to standard output.

See also fpassthru(), file(), fopen(), include(), require(), and virtual().

readlink

readlink -- Return the target of a symbolic link

Description

string readlink(string path);

Readlink() does the same as the readlink C function and returns the contents of the symbolic link path or 0 in case of error.

See also symlink(), readlink() and linkinfo().

rename

rename -- rename a file

Description

int rename(string oldname, string newname);

Attempts to rename oldname to newname.

Returns true on success and false on failure.

rewind

rewind -- rewind the position of a file pointer

Description

int rewind(int fp);

Sets the file position indicator for fp to the beginning of the file stream.

If an error occurs, returns 0.

The file pointer must be valid, and must point to a file successfully opened by fopen().

See also fseek() and ftell().

rmdir

rmdir -- remove directory

Description

int rmdir(string dirname);

Attempts to remove the directory named by pathname. The directory must be empty, and the relevant permissions must permit this.

If an error occurs, returns 0.

See also mkdir().

stat

stat -- give information about a file

Description

array stat(string filename);

Gathers the statistics of the file named by filename.

Returns an array with the statistics of the file with the following elements:

    device

    inode

    number of links

    user id of owner

    group id owner

    device type if inode device *

    size in bytes

    time of last access

    time of last modification

    time of last change

    blocksize for filesystem I/O *

    number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1

lstat

lstat -- give information about a file or symbolic link

Description

array lstat(string filename);

Gathers the statistics of the file or symbolic link named by filename. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Returns an array with the statistics of the file with the following elements:

    device

    inode

    number of links

    user id of owner

    group id owner

    device type if inode device *

    size in bytes

    time of last access

    time of last modification

    time of last change

    blocksize for filesystem I/O *

    number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1

symlink

symlink -- Create a symbolic link

Description

int symlink(string target, string link);

symlink() creates a symbolic link from the existing target with the specified name link.

See also link() to create hard links, and readlink() along with linkinfo().

tempnam

tempnam -- create unique file name

Description

string tempnam(string dir, string prefix);

Creates a unique temporary filename in the specified directory. If the directory does not exist, tempnam() may generate a filename in the system's temporary directory.

Returns the new temporary filename, or the null string on failure.

Example 1. tempnam() example

$tmpfname = tempnam( "/tmp", "FOO" );

touch

touch -- set modification time of file

Description

int touch(string filename, int time);

Attempts to set the modification time of the file named by filename to the value given by time. If the option time is not given, uses the present time.

If the file does not exist, it is created.

Returns true on success and false otherwise.

umask

umask -- changes the current umask

Description

int umask(int mask);

Umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

Umask() without arguments simply returns the current umask.

unlink

unlink -- Delete a file

Description

int unlink(string filename);

Deletes filename. Similar to the Unix C unlink() function.

Returns 0 or FALSE on an error.

See also rmdir() for removing directories.

XIV. Functions related to HTTP

Table of Contents
header
setcookie

These functions let you manipulate the output sent back to the remote browser right down to the HTTP protocol level.

header

header -- Send a raw HTTP header

Description

int header(string string);

The Header() function is used at the top of an HTML file to send raw HTTP header strings. See the HTTP 1.1 Specification for more information on raw http headers. Note: Remember that the Header() function must be called before any actual output is sent either by normal HTML tags or from PHP. It is a very common error to read code with include() or with auto_prepend and have spaces or empty lines in this code that force output before header() is called.

Header("Location: http://www.php.net");  /* Redirect browser to PHP web site */
exit;  /* Make sure that code below does not get executed when we redirect. */

PHP scripts o