[Top] [Prev] [Next] [Last]
Download PDF:   US   UK
Download Postscript:   US   UK
Stronghold Web Server 2.4.1 Administration Guide

Chapter 11

PHP Embedded Scripting

Stronghold supports embedded scripting with PHP, which originally stood for Personal Home Page and started out as a simple CGI wrapper. Although the acronym has stuck, PHP itself has expanded. It can now manipulate entire sites, not just single home pages. The PHP module does not implement CGI at all, but can execute embedded scripts that are as complex as any you might write for CGI. Simply put, it is a server-side, HTML-embedded scripting language and form interpreter, and an easy alternative to CGI. With PHP, you can

By default, the PHP module is compiled into the server without support for databases, access control, page logging, or file uploads. To recompile it with one or more of these features, see "PHP Configuration" on page 11-2.

This chapter explains the PHP scripting mechanism, including

The PHP Web site at http://php.iquest.net/ has additional information, including extra examples, archives, access to the PHP mailing list, and instructions for creating your own PHP functions.



To process HTML through PHP

  1. Add the following line to httpd.conf:

    AddType application/x-httpd-php .php

  2. Give the .php filename extension to any file you want to process with PHP.

    If a .php file contains no PHP script elements, PHP simply inserts access information at the foot of the file. If PHP script elements are present, PHP processes them each time the file is requested before sending it to the client.

By default, httpd.conf contains the following line:

AddType application/x-httpd-php .php

This line is necessary for Stronghold to recognize and process PHP files.

If you do not want footers appended to your .php files, you can turn them off globally or on a per-file basis. To turn them on or off globally, use the phpShowInfo configuration directive. To turn them off in individual files, add this tag:

<?setshowinfo(0)>




PHP Configuration

When you install Stronghold, you also install its PHP module. By default, the PHP module is installed without any of its special features. Although you can use the default PHP configuration for ordinary scripting, you must reconfigure it in order to use these features:

In order to reconfigure the PHP module to implement these special features, you must

The PHP source files are located in ServerRoot/src/php/. This directory also contains a script called install, which reconfigures the source. Its src/ subdirectory contains the PHP Makefile.



To reconfigure PHP

  1. Switch to the PHP source directory:

    # cd ServerRoot/src/php

  2. Run the install script:

    # ./install

    The program begins by asking whether any of the supported database systems are installed on your server, one at a time. If any are installed, you must also specify the path to its top-level directory. If you have one or more database systems but do not want to allow PHP access to them, you can answer "N."

  3. Enter "Y" if you have mSQL or "N" if you do not.

    If you answer "Y," the script prompts you for the path to its top-level directory next. Enter the full path or press Return to accept the default.

  4. Enter "Y" if you have Sybase libraries or "N" if you do not.

    If you answer "Y," the script prompts you for the path to its top-level directory next. Enter the full path or press Return to accept the default.

  5. Enter "Y" if you have Postgres or "N" if you do not.

    If you answer "Y," enter the full path to its top-level directory next, or press Return to accept the default.

  6. Enter "Y" if you have mysql or "N" if you do not.

    If you answer "Y," enter the full path to its top-level directory next, or press Return to accept the default.

  7. Enter "Y" if you have Solid or "N" if you do not.

    If you answer "Y," enter the full path to its top-level directory next, or press Return to accept the default.

  8. Enter "Y" if you have Oracle or "N" if you do not.

    If you answer "Y," the script prompts you for the path to its top-level directory next. Enter the full path or press Return to accept the default.

  9. Enter "Y" to compile PHP as an Apache module.

    Apache is Stronghold's server core. When you enter "Y," the script next asks whether you are compiling for Apache 1.1 or later. This version of Stronghold implements Apache 1.2.4.

  10. Enter "Y."

    The script asks whether you are using Stronghold.

  11. Enter "Y."

    The script asks whether your operating system supports ELF dynamic loading.

  12. Enter "Y" if you are running Linux with ELF dynamic loading support or "N" if you are not.

    The script prompts you for the path to Stronghold's include or source directory.

  13. Enter the path to Stronghold's source directory.

    This is ServerRoot/src.

  14. Enter "Y" to enable access control or "N" to disable it.

    If you enter "Y," you must next enter the path to the directory you want to use for access control.

  15. Enter "Y" to enable page logging or "N" to disable it.

    If you enter "Y," you must next enter

    • "D" to store the logs in DBM format or "M" to store them in mSQL format

    • the path to the directory where you want to store your PHP page logs

  16. Enter "Y" to enable file upload support or "N" to disable it.

  17. If you would like to include additional .h files, enter the paths to their directories.

    The program includes all files in the directories you specify.

  18. If you would like to include additional libraries, enter the paths to their directories.

    The program includes all files in the directories you specify, then checks for all the necessary files for installation.

    NOTE: Watch for error messages during this phase. When an error occurs, the script also gives instructions for rectifying the problem.

  19. Enter "Y" to use the Posix regex library that comes bundled with PHP or "N" to use your own.

    The install script ends here.

  20. Switch to the PHP src/ directory:

    # cd src

  21. Run make:

    # make

    Make creates new libphp.a and mod_php.* files and saves them in ServerRoot/src. Check that directory to make sure the new files were copied there; if not, you must copy them manually.

  22. Check your Configuration file to make sure it includes these three lines:

    Rule WANTHSREGEX=yes
    EXTRA_LIBS= . . . -lphp -lm . . .
    Module php_module mod_php.o

    If you are linking database connectivity or other libraries, the EXTRA_LIBS line must include those libraries.

  23. Recompile Stronghold as described in "Recompiling Stronghold" on page 8-9.




The PHP Scripting Language

The PHP scripting language resembles C, although it also has some Perl-like qualities and supports everything you normally need to write complex scripts. However, the PHP module does not use CGI; all scripts are processed by the server itself.

This section describes the elements of PHP scripts, including their syntax and available commands. For an alphabetical list of all internal PHP functions, see "Internal Function Reference" on page 11-17.



Syntax

HTML-embedded PHP uses the angled brackets of HTML tags (< and >), with a question mark (?) to distinguish PHP script elements from HTML. Since the server parses the PHP, these tags are cleared from the document during processing, and the client receives only pure HTML. In addition, PHP scripts follow these basic rules:

Thus, a valid PHP string might look like this:

<? $a = 5; echo $a /* sample string */ >

PHP treats all PHP script elements in a single HTML file as a unified script, regardless of intermittent HTML code and plain ASCII elements, which it ignores. You can split up the PHP elements by enclosing them in separate bracket pairs, and the parser will not treat them differently than if they were contained in a single bracket pair.



Control Commands

PHP supports the following commands for guiding the control flow through a file:

With while and endwhile, you can create loops in PHP. However, when using incremental and decremental operators in loops, note that variables are incremented immediately.

NOTE: This loop behavior deviates from C, where variables can be incremented or decremented before or after an operation.

The switch construct also deviates slightly from C in that PHP uses semicolons to terminate every line in a switch construct. For example:

<?
$a=0;
switch($a);
case 1;
echo "a is 1";
break;
case "hello";
echo "a is hello";
break;
default;
echo "a is unknown";
break;
endswitch
>

In addition, PHP supports these C-like conditional symbols:

Conditional Description
= = Tests for equality.
!= is not equal to
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
&& conditional AND
|| conditional OR

You can terminate conditional constructs with endif, endswitch, or endwhile, or you can enclose the fulfillment in curly braces. For example,

<?
if($a==5 && $b!=0 );
$c = 100 + $a / $b;
endif;
>

is the same as

<?
if($a==5 && $b!=0) {
$c = 100 + $a / $b;
}
>


Mathematical Expressions

PHP supports full mathematical expressions, using mathematical order of operations, bracket clustering, incremental operators, and bit-wise operators:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
+= Incremental addition
-= Incremental subtraction
& Bit-wise AND
| Bit-wise OR



Regular Expressions

PHP includes seven internal functions for regular expressions:

The EReg functions implement the Posix Extended regular expressions, defined by the POSIX 1003.2 Shell and Tools Interface standardization committee. The Reg functions implement Basic regular expressions. You can find complete information about both varieties in the regex(7) man page.



Escape Characters

PHP supports the following escape sequences in any quoted string argument:

Escape Sequence Description
\a Bell
\b Backspace
\n Line feed
\r Carriage return
\t Tab
\nnn Octal character code
\xxx hexagonal character code



Variables

PHP variables are prepended with dollar signs ($) and can take three types of values:

In the examples above, each variable is named a, but you can assign any name you like. All three integer types can be combined in a single operation, even though PHP handles each type differently. In an arithmetic expression, for example, consider this possibility:

$a = 1
$b = "1"
$d = $a + $b

The $a variable is an integer, and $b is a string. In a situation such as this one, PHP determines the variable type of the first variable in the operation, then treats all other variables in that operation as that type. In the example above, PHP treats both variables as integers, and $d is 2.

NOTE: For more complex expressions, you may need to force variables to conform to a certain type. To do so, use the function.

You can also construct variable variables, or variables whose names are variables. The name of a variable variable is set dynamically using a definitive variable. To construct such a variable, first set the variable that sets the name, then set the variable variables using double dollar signs ($$) to denote their relationship to the definitive variable:

$a = "hello"
$$a = "world"

This example sets and stores two variables: one called a, and one called hello, although hello is better referenced as $$a. The value of hello is "world," and either of the following would produce the output "hello world":

echo "$a $$a"
echo "$a $hello"

Any kind of variable can be treated as an array. Here, PHP deviates from C syntax and follows a Perl-like scheme by treating any array as an associative array, an array that does not require numerical, sequential index values. To denote an array, append [value] to the variable name, like this:

<?$a[0] = "hello world">

By default, normal variables are treated as single array entries that take the prime index entry [0]. This means, for example, that the following variable definitions are synonymous:

<?$a = 5>
<?$a[0] = 5>

By omitting the value from between the square brackets, you create a non-indexed array. PHP automatically generates an index for a non-indexed array as it accumulates items. Thus, if two variable items

$a[] = "hello"
$a[] = "world"

exist, then PHP interprets them as

$a[0] = "hello"
$a[1] = "world"

You can copy one array to another by assigning a new array as the value for the original array, like this:

$a = $b;

You can also append one array to another like this:

$a[] = $b;

If $a is a numbered array, the $b is appended to the end of the array. If $a is an associative array, and values in $b have the same index names as values in $a, then the values in $b overwrite matching values in $a.

Every variable also has a scope, or a context in which it is defined. There are three possible scopes for PHP variables:



User-Defined Functions

In addition to the library of internal functions that comes with PHP, you can define custom functions for your own specialized purposes. For example:

<?
Function Test (
echo "This is a test\n";
);
>

You can call a function at any time after the function definition. To call the function defined above, for example, you might use this:

<?
Test();
>

Although the parentheses may be empty if you are simply calling a function, they can also enclose arguments that you want to pass to the function. For example, this sequence defines and calls a function that adds the values of three variables and returns the sum:

<?
Function Sum $a,$b,$c (
return ($a+$b+$c);
);

echo Sum($a,$b,$c);
>



User File Uploads

PHP supports RFC 1867 form-based file uploads. By constructing an HTML form that looks something like this, you can allow users to upload files to your server:

<FORM ENCTYPE="multipart/form-data" ACTION="URL" METHOD=POST>
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000">
Send this file: <INPUT NAME="userfile" TYPE="file">
<INPUT TYPE="submit" VALUE="Send File">
</FORM>

MAX_FILE_SIZE is the maximum acceptable filesize in bytes, and it must precede the input field. URL should be the URL of the PHP/HTML response file, to be returned to the user after Stronghold completes the upload. In the response file, you can include the following variables, which PHP defines upon successful upload:

Variable Description
$userfile The uploaded file's temporary filename, which matches the string entered in the INPUT NAME field
$userfile_name The uploaded file's original name on the user's system
$userfile_size The size of the uploaded file, in bytes
$userfile_type The uploaded file's MIME type, if provided by the client

Use the phpUploadTmpDir directive to set the temporary directory for all user-uploaded files.

If you need more information about RFC 1867, you can find its text at http://sunsite.auc.dk/RFC/rfc/rfc1867.html.




PHP and Security

As a Stronghold module, PHP uses the existing access control parameters you set in the httpd.conf and .htaccess files. However, it faces the same security issues as CGI. This section offers security solutions.



Basic HTTP Authentication

Although you can set up basic authentication using your configuration files, you can also do this on a per-file basis with PHP's Header() function. However, using this function only works if it is the only authentication scheme set for a given file; PHP will not perform this function for a file that already has another authentication method.

NOTE: Although basic authentication provides some security, it also causes unencrypted usernames and passwords to pass from the client to Stronghold, allowing eavesdroppers to obtain them. If you use basic authentication, confine it to SSL-encrypted transactions.

For example, the following script fragment invokes basic authentication, then prints the user input:

<?
if(!$PHP_AUTH_USER) {
Header("WWW-authenticate: basic realm=\"My Realm\"");
Header("HTTP/1.0 401 Unauthorized");
exit;
} else {
echo "Hello $PHP_AUTH_USER.<P>";
echo "You entered $PHP_AUTH_PW as your password.<P>";
}
>

This is a simplified example, and in reality you should validate $PHP_AUTH_USER and $PHP_AUTH_PW by querying a database or checking a DBM file. You must also make sure the Header() function appears before any HTML elements in the file, so that authentication occurs before any content is transmitted.



GET and POST

One well-known characteristic of the GET method is that it can be used to append variables to a URL, thus manipulating server-side functions. Imagine, for example, that a user submits the following URL:

www.host.com/example.php?REMOTE_HOST=some.bogus.com

Without preventative measures, this URL implements the GET method to set REMOTE_HOST to "some.bogus.host," thereby faking an entry in your PHP log file.

PHP's built-in solution is to handle all POST method data before handling GET data, then reject all GET data that would otherwise circumvent the original POST data. Note that POST itself is not an intrinsically secure method, since an intruder can telnet to port 80 of your host and emulate POST data. Take any steps necessary to prevent such an intrusion.

An additional mechanism for eliminating the threat of a GET method attack is the SecureVar() function. In any script, you can use this function to mark variables as secure, using variable names, values, or regular expressions. For example:

<?SecureVar(".*data.*")>

This example secures any variable that contains the string "data."




Special Notes

PHP has a few characteristics that can affect how it handles HTML. This section explains how these peculiarities work.



Multiple-Selection Lists

HTML allows you to construct list boxes in forms, from which users can select multiple items. Normally, such a construct looks like this:

<SELECT NAME="listname" MULTIPLE>

Since a list box can have only one name, the multiple selections are passed to the same variable, in this case $listname. Each selection in turn overwrites the last one, such that the action handler receives only the last selection.

To solve this problem, use an array as the list name:

<SELECT NAME="listname[]" MULTIPLE>

This sets $listname[] as an array, and PHP adds each selection to the array with a different array index, such as $listname[0], $listname[1], $listname[2], and so on. In this way, you can preserve the multiple values and use functions such as count() and sort() to manipulate them.



Image Form Buttons

HTML allows you to use images as form submission buttons, using a tag like this one:

<INPUT TYPE=IMAGE SRC=image.gif NAME=submit>

When PHP processes a form containing an image button, it uses two extra variables, sub_x and sub_y, to denote the coordinate of the point clicked by the user. Although browsers call these variables sub.x and sub.y, PHP substitutes underscores for the periods. You can refer to the values of these variables as $sub_x and $sub_y for imagemap-like effects.



Self-Referential URLs

Occasionally, you may need to refer to the URL of the current page in a PHP script. The most obvious way to do this is to define a variable whose value is a string containing the URL. However, since scripts often need to be modular, PHP includes a pre-defined, global variable for this purpose: $PHP_SELF. Substitute this variable wherever you need to refer to the URL of the current page.




Internal Function Reference

This section provides a quick reference to all internal PHP functions.



Abs(arg)

Abs returns the absolute value of arg.



Ada_Close(connection_id)

Ada_Close() closes the connection to the Adabas server associated with the given connection identifier.

This function is only available if Adabas support has been enabled in PHP.



$connection = Ada_Connect(data-source-name, username, password)

Ada_Connect() opens a connection to a Adabas server and returns a connection identifier. This identifier is needed by other Adabas functions. Each of the arguments should be a quoted string. The data-source-name can be an empty string, resulting in a connection to the default server on the localhost. You can have multiple connections open at once. This function returns 0 on error.

This function is only available if Adabas support has been enabled in PHP.



$result = Ada_Exec(connection_id, query_string)

Ada_Exec() sends an SQL statement to the Adabas server specified by connection_id. The connection_id must be a valid identifier that was returned by Ada_Connect() or the special value 0. If connection_id is 0, Ada_Exec() tries to establish or use a connection with the parameters given by the configuration directives phpAdaDefDB, phpAdaUser, and phpAdaPW.

The return value of this function is an identifier to be used by other Adabas functions to access the results. It returns 0 on error and 1 when the command executed correctly but is not expected to return data (insert or update commands, for example). Note that selects which return no data still return a valid result greater than 1.

This function is only available if Adabas support has been enabled in PHP.



Ada_FetchRow(result_id [,row_number])

Ada_FetchRow() fetches a row of the data that was returned by Ada_Exec(). If no rownumber is given, Ada_FetchRow() tries to fetch the next row in the result set. After Ada_FetchRow() is called, the fields of that row can be accessed with Ada_Result(). Every time Ada_FetchRow() is called, a new row can be accessed by Ada_Result().

If Ada_FetchRow() was succesful (i.e., there was a row), 1 is returned. If there are no more rows, Ada_FetchRow() returns 0. The return value of Ada_FetchRow() can be used as the condition of a while loop. Calls to Ada_FetchRow() with and without row number can be mixed. To step through the result more than once, you can call Ada_FetchRow() with row number "1" and then continue with Ada_FetchRow() without row number to review the result.

This function is only available if Adabas support has been enabled in PHP.



Ada_FieldName(result_id, field_number)

Ada_FieldName() returns the name of the field occupying the given field number in the given Adabas result identifier. Field numbering starts from 0.

This function is only available if Adabas support has been enabled in PHP.



Ada_FieldNum(result_id, field_name)

Ada_FieldNum() returns the number of the column slot that corresponds to the named field in the given Adabas result identifier. Field numbering starts at 0. This function returns -1 on error.

This function is only available if Adabas support has been enabled in PHP.



Ada_FieldType(result_id, field_name|field_number)

Ada_FieldType() returns the SQL type of the field referenced by name or number in the given Adabas result identifier. Field numbering starts from 0.

This function is only available if Adabas support has been enabled in PHP.



Ada_FreeResult(result_id)

You only need Ada_FreeResult() if you are concerned about using too much memory while your script is running. Normally, all result memory is automatically freed when the script is finished. However, if you are sure you are not going to need the result data again, you may call Ada_FreeResult() with the result identifier as an argument. The associated result memory is freed.

This function is only available if Adabas support has been enabled in PHP.



Ada_NumFields(result_id)

Ada_NumFields() returns the number of fields (columns) in a Adabas result. The argument is a valid result identifier returned by Ada_Exec(). This function returns -1 on error.

This function is only available if Adabas support has been enabled in PHP.



Ada_NumRows(result_id)

Ada_NumRows() returns the number of rows in a Adabas result. The argument is a valid result identifier returned by Ada_Exec(). For INSERT, UPDATE, DELETE statements Ada_NumRows() returns the number of rows affected. For a SELECT clause this is the number of rows available. This function returns -1 on error.

This function is only available if Adabas support has been enabled in PHP.



Ada_Result(result_id, field name|index)

Ada_Result() returns values from a result identifier produced by Ada_Exec(). The field name specify what cell in the row to return. Instead of naming the field, you may use the field index as an unquoted number. Field indices start from 0.

This function is only available if Adabas support has been enabled in PHP.



Ada_ResultAll(result_id [,format])

Ada_ResultAll() prints all rows from a result identifier produced by Ada_Exec(). The result is printed in HTML table format. With the optional format string, you can add additional overall table formatting. The contents of format are inserted into the HTML table tag like this:

<table format>

This function is only available if Adabas support has been enabled in PHP.



AddSlashes(arg)

This function escapes any "$," "\," or "'" with a backslash if MAGIC_QUOTES is set. See also the StripSlashes(arg) function.



ARSort(array)

ARSort() sorts a PHP associative array in descending order. Unlike the Sort() function, ARSort() maintains index-value pairings. It understands the three variable types. It sorts reverse-alphabetically if the array contains strings and reverse-numerically if the array contains numbers. In the case of an array which contains a mixture of types, the first type in the array will specify the sort method.



ASort(array)

ASort() is used to sort a PHP associative array in ascending order. Use ARSort() for descending order. Unlike the Sort() function, ASort() maintains index-value pairings. It understands the three variable types. It sorts alphabetically if the array contains strings and numerically if the array contains numbers. In the case of an array which contains a mixture of types, the first type in the array will specify the sort method.

NOTE: If you are going to sort a non-associative array, you should use the Sort(array) function.



BinDec(binary_string)

BinDec returns the decimal equivalent of a binary number specified by the binary_string argument. The largest convertible number is 31 bits long, or 4294967295 in decimal. See also the DecBin(number) function.



ChDir(dir)

ChDir changes the current working directory to the directory specified by dir.



ChGrp(file,group)

ChGrp changes the group ID of the specified file to group.



ChMod(file,perms)

ChMod changes the file permissions of the specified file. The perms parameter must be specified in octal.



Chop(string)

Chop() removes all trailing whitespaces (including new-lines, tabs, and spaces) and returns the new string.



ChOwn(file,owner)

ChOwn changes the owner of file to owner.

NOTE: This function works only if Stronghold is running as root. Since running the server as root presents a security risk, avoid this function.



Chr(arg)

Chr returns the ASCII character represented by the integer argument.



ClearStack()

The ClearStack() function is a workaround for a deficiency in the PHP parser. PHP only has a single expression stack. When inside a user-defined function, this expression stack is never cleared because its contents may be needed within a complex expression in the context from which the user-defined function was called. This means that if you have a while loop with many iterations inside a user-defined function, you may be occupying too much stack space or reaching the data space limit.

To prevent this memory consumption, you can put a call to ClearStack() inside your while loop. However, you cannot use your function within any context-i.e., you must assign the output of the function to a temporary variable and then use this temporary variable in the context you need.



ClearStatCache()

If you call any of the File* functions with argument arg, then call a File* function again with the same argument, PHP uses the cached result of the last stat() call. ClearStatCache() clears the stat() cache.



closeDir()

This function closes a directory opened using the openDir(directory) function.



Cos(arg)

This function returns the cosine of arg in radians. See also Sin(arg) and Tan(arg).



Count(array)

This function returns the number of items in an array variable. If the variable is not an array, Count returns 1, because a normal variable has only one item. If the variable is not defined, Count returns 0.



Crypt(string,[salt])

Crypt encrypts a string using DES. Salt is an optional two-character salt string used to further randomize the output.

For more information about crypt(), see your UNIX man page.



Date(format,time)

The Date function displays dates and times. Time is an integer representing the number of seconds since the UNIX Epoch on 1 January 1970. If time is omitted, PHP uses the current time and date. The format string indicates which date and time components are displayed and how they are formatted. The following characters are recognized within the format string:

Format String Description
Y Four-digit year, such as "1997"
y Two-digit year, such as "97"
M Abbreviated month, such as "Oct"
m Numerical month, such as "10"
F Month name, such as "October"
D Abbreviated day of the week, such as "Fri"
l Day of the week, such as "Friday"
d Day of the month, such as "17"
z Day of the year, such as "299"
H Hours in 24-hour format, such as "13"
h Hours in 12-hour format, such as "1"
i Minutes, such as "5"
s Seconds, such as "40"
U Seconds since UNIX Epoch, such as "814807830"
A "AM" or "PM"
a "am" or "pm"

PHP prints any unrecognized character verbosely.



dbList()

dbList() prints information about the DB support compiled into PHP.



dbmClose(file)

dbmClose() simply closes the specified DBM file. It also unlocks all locked files, so it is important to close any opened DBM files.



dbmDelete(file,key)

dbmDelete() deletes the key/content pair specified by key from the file.



dbmExists(file,key)

dbmExists() returns 1 if the key exists in the file, and 0 otherwise.



dbmFetch(file,key)

dbmFetch() returns the content string associated with the given key.



dbmFirstKey(file)

dbmFirstKey() returns the first key in the DBM file. The order depends on hash table values calculated within the DBM implementation, and is therefore beyond the control of PHP. You can use the Sort(array) function to sort arrays of data from the DBM file.



dbmInsert(file,key,content)

dbmInsert() inserts a new key/content data pair into a DBM file. If the key already exists, insertion fails.



dbmNextKey(file,key)

dbmNextKey() returns the next key after the specified key in the DBM file. By calling dbmFirstkey() followed by successive calls to dbmNextkey(), a script can visit every key/content pair in the file.



dbmOpen(file,mode)

dbmOpen() opens a DBM file. File is the full path to the DBM file, and mode is the file open mode:

If you use NDBM support, it creates filename.dir and filename.pag files. GDBM uses one file (as does the internal flat ASCII file support) and Berkeley's libdb to create a filename.db file.

PHP does its own file locking in addition to any file locking done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files 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.



dbmReplace(file,key,content)

dbmReplace() resembles the dbmInsert(file,key,content) function, except that if the key already exists, the old content string is replaced with the new.



DecBin(number)

DecBin() returns a string containing a binary representation of the given number. The largest convertible number is 31 bits long, or 4294967295 in decimal. See also the BinDec(binary_string) function.



DecHex(number)

DecHex() converts a decimal number to a hexadecimal string. See also the HexDec(hex_string) function.



DecOct(number)

DecOct() converts a decimal number to an octal number. See also OctDec(octal_number).



doubleval(variable)

doubleval() returns the double (floating point) value of variable. See also the strval(variable) and intval(variable) functions.



Echo [format_string] expression [, expression [,...]]

Echo is not properly a function because its arguments are not bracketed. It is a command that displays the results of other PHP functions or variables. See "Escape Characters" on page 11-9 for a list of the special characters it supports.

The format_string is optional; if it is absent, the output is unformatted. The format_string resembles the format string of the C printf() function. A single Echo command can print up to five expressions. If you try to print more, PHP returns a parser error.

The types of the expressions are not relevant. PHP automatically converts the expressions to the appropriate types as specified by the format_string, if one is present. If you want to format something and assign the formatted string to a variable instead of displaying it, use the Sprintf(format,arg) function.

PHP supports the following conversion values for format_string:

Conversion Description
%d %i Print a signed decimal number
%o Print an octal number
%u Print an unsigned decimal number
%x %X Print a hexadecimal number
%f Print a floating-point number
%e %E Print a floating-point number in scientific notation
%g %G Print a floating-point number in scientific notation or normal notation, as appropriate
%c Print a single character
%s Print a string of characters
%% Print a literal percent-sign

The following flags are also valid:

Flag Description
- Left-justify the output within the field width
+ Ensure that all integers are signed with a plus/minus sign
Similar to "+" but uses a space instead of a plus sign
# Print prefixes in front of hex and octal numbers to designate them as such
' Separate the digits into groups, usually comma-separated groups of three
0 Pad the field-width with zeros

All of these flags depend on whether your C library's printf() function supports them. Most conversions accept a field width and a precision, as shown in the demo_echo.html file in the src/php/examples directory. You do not need to specify any type modifiers; they almost always cause PHP to generate errors. PHP does not accept any type modifiers that it does not recognize.

PHP ignores any extra arguments that are not required by format_string.



End(variable)

End() moves the internal array pointer for the given variable to the last item of the array and returns its value. This is useful for traversing an associative array in reverse order. The following example traverses an associative array in reverse order:

<?
Reset($array);
$first_key = key($array);
End($array);
$k = key($array);
while($k != $first_key);
echo $array[$k];
prev($array);
$k = key($array);
endwhile;
echo $array[$k];
>

See also Reset(variable) and Prev(variable).



ereg(expr,arg[,regex])

ereg() returns a non-zero value if the argument string matches the regex. For example, the condition

<?if (ereg("^This.*", "This is an example string")>

is true since the "^This.*" expression instructs PHP to match the word "This" at the beginning of the string and then match any characters afterwards. If the regex argument is present, then match registers are filled into positions 0-10 in the array named by the regs argument. Register 0 always contains the full matched string.

For information about regular expressions, see "Regular Expressions" on page 11-9.



eregi(expr,arg[,regex])

eregi() is identical to the ereg() function, except that the regular expression is case-insensitive.



ereg_replace(regex,replace,arg)

ereg_replace() scans the entire argument string and replaces any portions of the string matched by regex with the replace string. For example, in the string, "This is an example string," you can replace every space with a dash like this:

ereg_replace(" ","-","This is an example string")

For more information on regular expressions, see "Regular Expressions" on page 11-9.



eregi_replace(regex,replace,arg)

eregi_replace() is identical to the ereg_replace() function except that regex is case-insensitive.



EscapeShellCmd(string)

EscapeShellCmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. Use this function to sterilize any data originating with user input before PHP passes it to the Exec(command_string [, array [,return_var]]) or System(command_string [,return_var]) functions. For example:

<?system(EscapeShellCmd($cmd))>


Eval(string)

Eval() treats the contents of the string like a mini-script and executes it separately. Any variables set or accessed from inside the Eval() function are from the global reference frame in the current context of the Eval() statement in the script. PHP performs variable substitution on the string, so variables used in the string must be escaped. For example:

$a = "echo phpversion();";
eval($a);
eval("echo phpversion();");
eval("\$a=1; echo \$a;");


Exec(command_string [, array [,return_var]])

Exec() executes the given UNIX command_string, but generates no output. Instead, it returns the last line from the result of the command. If you need to execute a command and pass all the data from the command directly back without any interference, use the PassThru(command_string [,return_var]) function.

If the array argument is present, PHP fills the array with every line of output from the UNIX command, starting at the end of the array. Make sure you unset the array before the call if your array already contains elements and you want to start filling it at element 0. If the return_var argument is present along with the array argument, then PHP writes the return status of the executed UNIX command to this variable.

NOTE: If you allow PHP to pass data originating with user input to the Exec function, then you should use the EscapeShellCmd(string) function to make sure that users cannot execute commands.

See also the System(command_string [,return_var]) function.



Exit

The Exit command terminates parsing immediately after it is parsed.



Exp(arg)

Exp() returns e raised to the power of arg. See also pow(x,y).



fclose($fd)

fclose() closes a file opened by $fp = fopen(file,mode). The argument is a file pointer index as returned by fopen().



feof($fd)

Feof() returns "true" if the file referred to by the file pointer index argument has reached end-of-file.



fgets($fd,bytes)

fgets() reads a line from a file opened by $fp = fopen(file,mode). The arguments are a file pointer index as returned by fopen() and the maximum number of bytes to read. Reading ends when the maximum number of bytes have been read, or when an end-of-line has been reached. This is similar to the C fgets() call. See also fputs(fp,string).



fgetss($fd,bytes)

This is identical to the fgets() function, except that it strips any HTML tags or PHP script tags as it reads the file.



$array = File(file)

File() reads the entire file and returns an array, with each array element containing a line of the file starting with array index 0.



fileAtime(file)

fileAtime() returns the time of last data access. If the file does not exist, or if it cannot be accessed, this function returns -1.



fileCtime(file)

fileCtime() returns the time of last status change. If the file does not exist, or if it cannot be accessed, this function returns -1. If the file is repeatedly accessed and is dynamic, be sure to use ClearStatCache() to reset the cache.



fileGroup(file)

fileGroup() returns the group ID of the owner of the file. If the file does not exist, or if it cannot be accessed, this function returns -1. If the file is repeatedly accessed and is dynamic, be sure to use ClearStatCache() to reset the cache.



fileInode(file)

fileInode() returns the file's inode. If the file does not exist, or if it cannot be accessed, this function returns -1. If the file is repeatedly accessed and is dynamic, be sure to use ClearStatCache() to reset the cache.



fileMtime(file)

fileMtime() returns the time of last data modification. If the file does not exist, or if it cannot be accessed, this function returns -1. If the file is repeatedly accessed and is dynamic, be sure to use ClearStatCache() to reset the cache.



fileOwner(file)

fileOwner() returns the UID of the owner of the file. If the file does not exist, or if it cannot be accessed, this function returns -1. If the file is repeatedly accessed and is dynamic, be sure to use ClearStatCache() to reset the cache.



filePerms(file)

filePerms() returns the permission bits of the file. This is the st_mode field of the UNIX C stat structure. If the file does not exist, or if it cannot be accessed, this function returns -1. If the file is repeatedly accessed and is dynamic, be sure to use ClearStatCache()) to reset the cache.



fileSize(file)

fileSize returns the size of the file in bytes. If the file does not exist, or if it cannot be accessed, this function returns -1. If the file is repeatedly accessed and is dynamic, be sure to use ClearStatCache() to reset the cache.



fileType(filename)

This returns the type of the file filename. The return values are one of the following:

Value Description
dir directory
file regular file
fifo fifo special
char character special
block block special
link symbolic link



Flush()

The Flush() function is used to flush the output buffer.



$fp = fopen(file,mode)

fopen() opens a file and returns a file pointer index. If the file cannot be opened, the function returns -1. It is similar to the C fopen() call. The file argument is the relative or absolute path, and the mode argument is one of the following:

For example:

$fp = fopen("/home/rasmus/file.txt","r");

See the UNIX man page on the fopen() call for more information. See also the
fp = popen(command,mode) and the fclose($fd) function descriptions.



ForceType(variable,type)

ForceType() sets the type flag for the variable. The value for type can be one of the following:

See also intval(variable), doubleval(variable), strval(variable).



FPassThru(fp)

FPassThru() outputs all remaining data directly to fp and returns the number of bytes read and written. Unlike ReadFile(), it can also handle files opened with fsockopen(). Unlike PassThru(), it does not handle commands, but only opened files.



fputs(fp,string)

fputs() writes a line to a file opened by $fp = fopen(file,mode). The arguments are a file pointer index as returned by fopen() and the string to write. The string argument may contain escape characters. See also fgets($fd,bytes).



fseek(fp,pos)

fseek() positions a file pointer identified by the return value of the $fp = fopen(file,mode) call. The file pointer is positioned at the beginning of the file, plus the offset specified by the pos argument. See also pos = ftell(fp) and rewind($fd).



fp = fsockopen(hostname,port)

fsockopen() opens a socket connection and returns a file pointer index. This file pointer index can be used by fgets($fd,bytes), fputs(fp,string), and fclose($fd). Return values are

If the port number is 0, then PHP treats the hostname argument as the filename of a UNIX domain socket, assuming your operating system supports them.



pos = ftell(fp)

ftell() returns the position of a file pointer identified by the fp argument, which is the return value of the fopen() call. The position can later be used as an argument for fseek(). See also fseek(fp,pos) and rewind($fd).



getAccDir()

getAccDir() returns the directory where PHP access configuration files are kept. The access configuration filenames come from the numerical user ID of the user whose configurations they represent.



GetEnv(string)

GetEnv() returns the value of the environment variable specified by string. Normally, this function is not used because environment variables are directly available to the PHP module. If you make a reference to a variable that is not in the internal symbol table, then PHP automatically searches the environment space.

You should use GetEnv() when you must ensure that an environment variable has not been overwritten by a normal PHP variable. Security mechanisms that rely on server-defined variables like REMOTE_ADDR and REMOTE_HOST should load these variables with GetEnv(), as opposed to referencing them directly as $REMOTE_ADDR, to avoid allowing someone to make a fake form and post the data to your server, thereby bypassing your security mechanisms.



getHostByName(domain_name)

getHostByName() converts the given domain_name into an IP number.



getHostByAddr(IP_address)

getHostByAddr() converts the given IP_address, in NNN.NNN.NNN.NNN format, into a fully-qualified domain name.



GetImageSize(filename)

The GetImageSize() function takes either an absolute or relative path. If the path is relative, it is relative to the location of the calling script. It returns a 4-element array consisting of the following:

NOTE: The GD image library is not needed to use this function.



getLastAccess()

getLastAccess() returns the date and time, in UNIX time format, of the last time the current page was accessed. You can pass this value to the Date(format,time) function for formatting. This function is only available if PHP is compiled with access logging enabled, as described in "PHP Configuration" on page 11-2.



getLastbrowser()

getLastBrowser() returns the identification string of the browser last used to access the current page. This function is only available if PHP is compiled with access logging enabled, as described in "PHP Configuration" on page 11-2.



getLastEmail()

getLastEmail() returns the email address of the last user to access the current page. This function is only available if PHP is compiled with access logging enabled, as described in "PHP Configuration" on page 11-2.



getLastHost()

getLastHost() returns the hostname of the last user to access the current page. This function is only available if PHP is compiled with access logging enabled, as described in "PHP Configuration" on page 11-2.



getLastMod()

getLastMod() returns the date and time, in UNIX time format, of the last time the current page was modified. You can pass this value to the Date(format,time) function for formatting. This function is only available if PHP is compiled with access logging enabled, as described in "PHP Configuration" on page 11-2.



getLastref()

getLastRef() returns the URL of the referring document of the access of the current page. This function is only available if PHP is compiled with access logging enabled, as described in "PHP Configuration" on page 11-2.



getLogDir()

getLogDir() returns the top-level directory for PHP log files. The actual log files are in subdirectories of this directory. Each subdirectory is the numerical user ID of the user to whom the log files belong. Within each subdirectory is a series of DBM log files, each with the numerical inode of the file they represent as the primary component of the filename.



getMyInode()

getMyInode() returns the numerical inode of the current HTML file.



getMyPid()

getMyPid() returns the current process ID of the PHP parsing process.



getMyUid()

getMyUid() returns the numerical user ID of the owner of the current HTML file.



getRandMax()

getRandMax() returns the maximum random number that the Rand() function returns.

NOTE: If the value returned does not seem accurate, look at the ServerRoot/src/php/src/php.h source file in the PHP distribution for more information.



getStartLogging()

getStartLogging() returns the time and date, in UNIX time format, when logging commenced for the current page. This is more accurate with mSQL-based logging, since a time-stamp is kept in each log file. For DBM logging, the time returned is the time the user's log directory was created.



getToday()

getToday() returns the total number of hits the current page has received since midnight local time. This function is only available if PHP is compiled with access logging enabled, as described in "PHP Configuration" on page 11-2.



getTotal()

getTotal() returns the total number of hits the current page has received since access logging was started for the page. This function is only available if PHP is compiled with access logging enabled.



GetType(variable)

GetType() returns the type of the variable. The return value is a string and it is one of the following:

See also the SetType(variable,type) function.



gmDate(format,time)

gmDat() is identical to the Date(format,time) function except that it uses Greenwich Mean Time instead of the current local time.



Header("header_string")

The Header() command is used at the top of an HTML file to send raw HTTP header strings. See the HTTP Specification for more information on raw HTTP headers. Remember that the Header() command must be used before any actual HTML tags or PHP Echo() commands.



HexDec(hex_string)

HexDec() converts a hexadecimal string to a decimal number. See also the DecHex(number) function.



HtmlSpecialChars(string)

HtmlSpecialChars() converts any characters in the string with ASCII codes between 160 and 255 inclusive to their corresponding HTML Entity names. The function returns the converted string.



ImageSX(image)

ImageSX() returns the width of the image.



ImageSY(image)

ImageSY() returns the height of the image.



Include(filename)

The Include() command inserts other files into the current HTML file. This is handy for headers and footers which you need to include in many different HTML files. By using an Include() command, you only need to modify the header or footer file in one place when it needs to be changed.

Since the PHP module performs full PHP parsing on the included file, you can also use the Include() command to include your stock PHP scripts, like a primitive shared library. You can also use the phpIncludePath directive to set the path to your script library directory, then refer to scripts by filename only rather than by full paths.



intval(variable)

Intval() returns the long integer value of variable. See also the strval(variable) and doubleval(variable) functions.



IsSet(variable)

The IsSet() function returns 1 if the variable is defined, and 0 if it is undefined.



Key(variable)

Key() returns the key of the current array item. The current item is determined by the position of the array pointer for the variable. You can manipulate this array pointer with the Reset(variable), End(variable), Next(variable), and Prev(variable) functions. This function is mainly used for determining the key value for an item in an associative array, although it works for normal arrays as well.



Link(target,link)

Link() creates a hard link. See the Symlink(target,link) function for creating symbolic (soft) links. See also ReadLink(path) and LinkInfo(path) functions.



LinkInfo(path)

LinkInfo() returns the st_dev field of the UNIX C stat structure returned by the lstat system call. This function is used to determine whether a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). It returns -1 in case of error.



Log(arg)

Log() returns the natural logarithm of arg.



Log10(arg)

Log10() returns the base-10 logarithm of arg.



LogAs(filename)

The LogAs() function treats the hit on the current page as if it is actually received on the argument filename.



Max(array)

Max() returns the maximum value of a PHP array. It searches the entire array for the maximum element. If it is an array of strings, Max() returns the string which would be last in the array if it were sorted alphabetically.



Md5(string)

Md5 returns the MD5 hash of a string value.



$connection = mi_Connect(database, username, password)

mi_Connect() opens a connection to an Illustra database. Each of the arguments should be a quoted string. This function returns a connection_id. This identifier is needed by other Illustra functions. You can have multiple connections open at once. The host to connect to is governed by the MI_PARAMS file on the machine running the PHP executable. No support as yet for remote invocation This function returns -1 on error.

This function is only available if Illustra support has been enabled in PHP.



mi_DBname(connection_id)

mi_DBname() returns the name of the database that the given Illustra connection identifier is connected to.

This function is only available if Illustra support has been enabled in PHP.



$result = mi_Exec(connection_id, query_string)

mi_Exec() sends an SQL statement to the Illustra database specified by the connection_id. The connection_id must be a valid identifier that was returned by $connection = mi_Connect(database, username, password). The return value of this function is an identifier to be used to access the results from other Illustra functions. This function returns -1 on error.

This function is only available if Illustra support has been enabled in PHP.



mi_FieldName(connection_id, result_id, field_number)

mi_FieldName() returns the name of the field occupying the given column number with the given Illustra result and connection identifiers. Field numbering starts from 0. This function returns -1 on error.

This function is only available if Illustra support has been enabled in PHP.



mi_FieldNum(connection_id, result_id, field_name)

mi_FieldNum() returns the number of the column slot that corresponds to the named field in the given Illustra result identifier. Field numbering starts at 0. This function returns -1 on error.

This function is only available if Illustra support has been enabled in PHP.



mi_NumFields(connection_id, result_id)

mi_NumFields() returns the number of fields (columns) in an Illustra result. The argument is a valid result identifier returned by $result = mi_Exec(connection_id, query_string). This function returns -1 on error.

This function is only available if Illustra support has been enabled in PHP.



mi_NumRows(connection_id, result_id)

mi_NumRows() returns the number of rows in an Illustra result. The argument is a valid result identifier returned by $result = mi_Exec(connection_id, query_string). This function returns -1 on error.

This function is only available if Illustra support has been enabled in PHP.



mi_Result(connection_id, result_id, row_number, field_name/field_index)

mi_Result() returns values from a result identifier produced by $result = mi_Exec(connection_id, query_string). The row_number and field_name specify what cell in the table of results to return. Row numbering starts from 0. Instead of naming the field, you may use the field_index as an unquoted number. Field indices start from 0.

All values returned from the database are in String form, since no type-detection is available at the present.

This function is only available if Illustra support has been enabled in PHP.



Microtime()

Microtime() returns a string "msec sec," where sec is number of seconds since 00:00 GMT, Jan 1, 1970, and msec is the microseconds part (as fraction of seconds). For example, Microtime() might return "0.87633900 825010464." This function is only available on operating systems that support the gettimeofday() system call.



Min(array)

Min() returns the minimum value of a PHP array. It searches the entire array for the min element. If it is an array of strings, the returned string is the string which would be first in the array if it were sorted alphabetically.



MkDir(directory,mode)

MkDir() creates a directory. The mode parameter must be given in octal notation.



MkTime(hour,min,sec,mon,day,year)

MkTime() returns a time in UNIX time-stamp (long integer) format that corresponds to the date and time specified by the arguments. Arguments may be left out, in which case the given component is set to the current value according to the current local time and date. Arguments may only be left out from right to left. For example,

MkTime(hour,min,sec)

is valid, but

MkTime(mon,day,year)

is not.



$result = msql($database,$query)

msql() sends an mSQL query. Arguments are the database name and the query string. For example:

<?msql("MyDatabase" , "select * from table")>

The return value is a result identifier to be used to access the results from the other msql_* functions. A result identifier is a positive integer. The function returns 0 when no result identifier is created. This is the case with queries that do not return anything, such as create, update, drop, insert, and delete.

The function returns -1 if an error occurs. A string describing the error is placed in $phperrmsg, and unless the function was called as @msql(), then this error string is also printed. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_Close()

msql_Close() closes the socket connection to the msql daemon, if an open connection exists. Since only one concurrent mSQL session can be open at any one time, this function does not take an argument.



msql_connect($hostname)

msql_connect() specifies the hostname or IP on which the mSQL database engine resides. This is equivalent to the msqlconnect() function in the mSQL C API. The difference between this function and the C API equivalent is that if the function is not called, a connection to the local host is made by default on the first call to the msql() function. There is no need for an msql_close function, since only one connection may be active at any one time. If a second call to msql_connect() is made in the same file, then the connection to the first host is automatically closed. To explicitly connect to the mSQL daemon on the local host, use

<?msql_connect("localhost")>

This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_CreateDB($database)

msql_CreateDB() creates the given database. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_dbName($result,$i)

msql_dbName() returns the database name stored in position $i of the result pointer returned from the $result = msql_ListDBs() function. You can use the msql_NumRows($result) function to determine how many database names are available. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_DropDB($database)

msql_DropDB() deletes the given mSQL database. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.

NOTE: Use this with caution, as all data in the database will be lost.



msql_FieldFlags($result,$i)

msql_FieldFlags() returns the field flags of the specified field. The result is one of the following:

This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_FieldLen($result,$i)

msql_FieldLen() returns the length of the specified field. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_FieldName($result,$i)

msql_FieldName() returns the name of the specified field. Its arguments are the result identifier and the field index.For example,

msql_FieldName($result,2);

returns the name of the second field in the result associated with the result identifier. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_FieldType($result,$i)

msql_FieldType() is similar to the msql_FieldName() function. The arguments are identical, but the field type is returned as one of the following:

This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_FreeResult($result)

You only need to call msql_FreeResult() if you are concerned about using too much memory while your script is running. It causes all result memory to be freed automatically when the script is finished. However, if you are sure you will not need the result data later in a script, you may call msql_FreeResult() with the result identifier as an argument, and the associated result memory is freed. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = msql_ListDBs()

msql_ListDBs() returns a result pointer containing the databases available from the current mSQL daemon. Use the msql_dbName($result,$i) function to traverse this result pointer. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = msql_Listfields($database,$tablename)

msql_Listfields() retrieves information about the given tablename. Its arguments are the database name and the table name. A result pointer is returned, which can be used with msql_FieldFlags($result,$i), mysql_FieldLen($result,$i), msql_FieldName($result,$i), msql_FieldType($result,$i). A result identifier is a positive integer.

The function returns -1 if a error occurs. A string describing the error is placed in $phperrmsg, and unless the function was called as @msql(), in which case this error string is also printed. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = msql_ListTables($database)

msql_ListTables() takes a database name and result pointer, much like the msql() function. Use the msql_TableName($result,$i) function to extract the actual table names from the result pointer. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_NumFields($result)

msql_NumFields() returns the number of fields in a result. The argument is the result identifier returned by the $result = msql($database,$query) function. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_NumRows($result)

msql_NumRows() simply returns the number of rows in a result. The argument is the result identifier returned by the $result = msql($database,$query) function. This function is only available if mSQL support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_RegCase(string)

msql_RegCase() converts a string argument to the regular expression needed to send to mSQL in order to obtain a case-insensitive match. For example, this turns the string "abc" into "[Aa][Bb][Cc]". This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_Result($result,$i,field)

msql_Result() displays a field from a returned record. Its arguments are

The field argument supports the "table.field" syntax for handling results from a join. This function is perhaps best illustrated with a complete example:

<?
$name = "bob";
$result = msql($database,"select * from table where firstname='$name'");
$num = msql_numrows($result);
echo "$num records found!<p>";
$i=0;
while($i<$num);
echo msql_result($result,$i,"fullname");
echo "<br>";
echo msql_result($result,$i,"address");
echo "<br>";
$i++;
endwhile;
>

The above script

As you can see, it would be trivial to add HTML markup tags around the printed fields to format the results in whatever manner you prefer. Note that there is no msql_connect() call. msql_connect() need only be called if you need a connection to a remote database. This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



msql_TableName($result,$i)

msql_TableName() takes a result pointer returned by the $result = msql_ListTables($database) function as well as an integer index and returns the name of a table. The msql_NumRows($result) function can be used to determine the number of tables in the result pointer. For example:

<?
$result = msql_listtables("dbname");
$i=0;
while($i < msql_numrows($result));
$tb_names[$i]=msql_tablename($result, $i);
echo $tb_names[$i];
echo "<BR>";
$i++;
endwhile;
>

This function is only available if mSQL support is enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = mysql($database,$query)

mysql() sends a mysql query. Its arguments are the database name and the query string, for example,

<?mysql("MyDatabase" , "select * from table")>

The return value from this function is a result identifier to be used to access the results from the other mysql_* functions. A result identifier is a positive integer.

The function returns 0 when no result identifier is created. This is the case with queries that do not return anything, such as create, update, drop, insert and delete. The function returns -1 if an error occurs. A string describing the error is placed in $phperrmsg, and unless the function was called as @mysql() then this error string is also printed.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_affected_rows()

This returns number of rows affected by the last INSERT, UPDATE or DELETE query.



mysql_close()

mysql_close() closes the socket connection to the mysql daemon, if an open connection exists.



mysql_connect($hostname)

mysql_connect() specifies the hostname or IP on which the mysql database engine resides. This is equivalent to the mysqlconnect() function in the mysql C API. The difference between this function and the C API equivalent is that if the function is not called, a connection to the local host is made by default on the first call to the mysql() function. There is no need for an mysql_close() function, since only one connection may be active at any one time. If a second call to mysql_connect() is made in the same file, then the connection to the first host is automatically closed. To explicitly connect to the mysql daemon on the local host, use the following:

<?mysql_connect("localhost")>

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_CreateDB($database)

mysql_CreateDB() creates the given database.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_dbName($result,$i)

mysql_dbName() returns the database name stored in position $i of the result pointer returned from the $result = mysql_ListDBs() function. The mysql_NumRows($result) function can be used to determine how many database names are available.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_DropDB($database)

mysql_DropDB() deletes the given mysql database. This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.

NOTE: Use this with caution, as all data in the database will be lost.



mysql_FieldFlags($result,$i)

mysql_FieldFlags() returns the field flags of the specified field. The result is one of the following:

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_FieldLen($result,$i)

mysql_FieldLen() returns the length of the specified field.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_FieldName($result,$i)

mysql_FieldName() returns the name of the specified field. Its arguments are the result identifier and the field index. For example,

mysql_FieldName($result,2);

returns the name of the second field in the result associated with the result identifier.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_FieldType($result,$i)

mysql_FieldType() is similar to the mysql_FieldName() function. The arguments are identical, but the field type is returned. This is one of the following:

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_FreeResult($result)

You only need to call mysql_FreeResult() if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished. But, if you are sure you are not going to need the result data anymore in a script, you may call mysql_FreeResult() with the result identifier as an argument and the associated result memory is freed.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_insert_id()

This function returns the ID generated for an AUTO_INCREMENT field. It takes no arguments. It returns the auto-generated ID returned by the last INSERT query performed.



$result = mysql_ListDBs()

mysql_ListDBs() returns a result pointer containing the databases available from the current mysql daemon. Use the mysql_dbName($result,$i) function to traverse this result pointer.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = mysql_Listfields($database,$table)

mysql_listfields() retrieves information about the the given table. Its arguments are the database name and the table name. A result pointer is returned that can be used with mysql_FieldFlags($result,$i), mysql_FieldLen($result,$i), mysql_FieldName($result,$i), mysql_FieldType($result,$i). A result identifier is a positive integer.

The function returns -1 if an error occurs. A string describing the error is placed in $phperrmsg, and unless the function was called as @mysql(), then this error string is also printed.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = mysql_ListTables($database)

mysql_ListTables() takes a database name and result pointer, much like the $result = mysql($database,$query) function. Use the mysql_TableName($result,$i) function to extract the actual table names from the result pointer.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_NumFields($result)

mysql_NumFields() returns the number of fields in a result. Its argument is the result identifier returned by the $result = mysql($database,$query) function.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_NumRows($result)

mysql_NumRows() simply returns the number of rows in a result. The argument is the result identifier returned by the $result = mysql($database,$query) function.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_Result($result,$i,field)

mysql_Result() displays a field from a returned record. Its arguments are the result identifier returned by the $result = mysql($database,$query) function, an integer which is the index of the record to be viewed, and a field name. The field argument supports the "table.field" syntax for handling results from a join.

One difference between mSQL 1.0 and mysql is that mysql supports functions that can act on the result data. These functions can be applied in this function. This function is perhaps best illustrated with a complete example:

<?
$name = "bob";
$result = mysql($database,"select * from table where firstname='$name'");
$num = mysql_numrows($result);
echo "$num records found!<p>";
$i=0;
while($i<$num);
echo mysql_result($result,$i,"lcase(fullname)");
echo "<br>";
echo mysql_result($result,$i,"address");
echo "<br>";
$i++;
endwhile;
>

The above script

The lcase() call in the result function changes the returned string to lower case. For a complete set of functions that can be applied to the result data, see your mysql documentation.

As this example shows, it would be trivial to add HTML markup tags around the printed fields to format the results in whatever manner you prefer. Note that there is no mysql_connect() call. mysql_connect() need only be called if you need a connection to a remote database.

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



mysql_TableName($result,$i)

mysql_TableName() takes a result pointer returned by the $result = mysql_ListTables($database) function as well as an integer index, and returns the name of a table. Use the mysql_NumRows($result) function to determine the number of tables in the result pointer. For example:

<?
$result = mysql_listtables("dbname");
$i=0;
while($i < mysql_numrows($result));
$tb_names[$i]=mysql_tablename($result, $i);
echo $tb_names[$i];
echo "<BR>";
$i++;
endwhile;
>

This function is only available if mysql support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Next(variable)

Next() moves the internal array pointer to the next item in the array. This happens automatically when an array is accessed using the non-indexed method ($array[]). The function returns the value of the new item. It can be used to move the pointer forward without having to access the array explicitly. One use would be to traverse an associative array and only printing the keys of the array without the actual contents:

<?
Reset($array);
$i=0;
while($i < count($array));
echo key($array);
next($array);
$i++;
endwhile;
>


OctDec(octal_number)

OctDec() converts an octal number to a decimal number. See also DecOct(number).



openDir(directory)

openDir() opens the specified directory and places an internal pointer to the beginning of the directory. Directory entries are read using the readDir() function, and an opened directory should be closed with the closeDir() function.



Ord(arg)

Ord() returns the ASCII value of the first character of arg.



Ora_Close(conn_ind)

Ora_Close() closes the Oracle connection identified by conn_ind. It returns 0 upon success and -1 upon failure.



Ora_Commit(conn_ind)

This function commits the current transaction on conn_ind. The current transaction starts from the Ora_Logon() call or from the last Ora_Commit() or Ora_Rollback(), and lasts until an Ora_Commit(), Ora_Rollback(), or Ora_Logoff() call is issued. Ora_Commit() returns -1 (and an error message) upon failure.



Ora_CommitOff(conn_ind)

Ora_CommitOff() turns off autocommit (automatic commit of every SQL data manipulation statement) on the Oracle connection conn_ind.



Ora_CommitOn(conn_ind)

Ora_CommitOff() turns on autocommit (automatic commit of every SQL data manipulation statement) on the Oracle connection conn_ind.



Ora_Exec(cursor_ind)

Ora_Exec() executes the SQL statement associated with cursor_ind and prepares storage for select-list items. The return value is the number of columns for selects, or -1 on error.



Ora_Fetch(cursor_ind)

Ora_Fetch() retrieves a row from the database. Returns 1 if a column was retrieved, 0 if there are no more columns to retrieve or -1 on error.



Ora_GetColumn(cursor_ind, column)

Ora_GetColumn() fetches data for a single column in a returned row. Ora_Fetch(cursor_ind) must have been called prior to Ora_GetColumn().



Ora_Logoff(conn_ind)

Ora_Logoff() disconnects the logon data area belonging to conn_ind and frees used Oracle resources.



Ora_Logon(userID, password)

Ora_Logon() establishes a connection between PHP and an Oracle database with the given userID and password. It returns 0 on success and -1 on failure.



Ora_Open(conn_ind)

Ora_Open() opens a cursor in Oracle that maintains state information about the processing of a SQL statement. It returns a cursor index or -1 on error.



Ora_Parse(cursor_ind, sql_statement[, defer])

Ora_Parse() parses a SQL statement or PL/SQL block and associates it with a cursor. An optional third argument can be set to 1 to defer the parse. It returns 0 on success or -1 on error.



Ora_Rollback(cursor_ind)

Ora_Rollback() rolls back the current transaction. See Ora_Commit(conn_ind) for a definition of the current transaction.



PassThru(command_string [,return_var])

The PassThru() function is similar to the Exec() function in that it executes a UNIX command. If the return_var argument is present, the return status of the UNIX command is placed here.

This command 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 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/FI scripts that output images directly.



pclose(fp)

Pclose() closes a pipe opened using the fp = popen(command,mode) function.



pg_Close(connection_id)

pg_Close() closes the connection to a Postgres95 database associated with the given connection identifier. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



$connection = pg_Connect(host, port, options, tty, dbname)

pg_Connect() opens a connection to a Postgres95 database. Each of the arguments should be a quoted string and include a port number. The options and tty arguments are optional and can be empty.

This function returns a connection_id. This identifier is required by other Postgres95 functions. You can have multiple connections open at once. This function returns a 0 on error. It is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_DBname(connection_id)

pg_DBname() returns the name of the database that the given Postgres95 connection identifier is connected to. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_ErrorMessage(connection_id)

If an error occurred on the last database action for which a valid connection exists, this function returns a string containing the error message generated by the back-end server. This function is only available if Postgres95 support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = pg_Exec(connection_id, query_string)

pg_Exec() sends an SQL statement to the Postgres95 database specified by the connection_id. The connection_id must be a valid identifier returned by $connection = pg_Connect(host, port, options, tty, dbname). The return value of this function is an identifier to be used to access the results from other Postgres95 functions.

This function returns 0 on error. It returns 1 when the commands execute correctly but are not expected to returned data (insert or update commands, for example). Note that commands which return no data still return a valid result greater than 1. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_FieldName(result_id, field_number)

pg_FieldName() returns the name of the field occupying the given field_number in the given Postgres95 result identifier. Field numbering starts from 0. This function is only available if Postgres95 support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_FieldPrtLen(result_id, row_number, field_name)

pg_FieldPrtLen() returns the actual printed length (number of characters) of a specific value in a Postgres95 result. Row numbering starts at 0. This function returns -1 on an error. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_FieldNum(result_id, field_name)

pg_FieldNum() returns the number of the column slot that corresponds to the named field in the given Postgres95 result identifier. Field numbering starts at 0. This function returns -1 on error. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_FieldSize(result_id, field_name)

pg_FieldSize() returns the internal storage size (in bytes) of the named field in the given Postgres95 result. A field size of 0 indicates a variable-length field. This function returns -1 on error. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_FieldType(result_id, field_number)

pg_FieldType() returns a string containing the type name of the given field in the given Postgres95 result identifier. Field numbering starts at 0. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_FreeResult(result_id)

You only need pg_FreeResult() if you are worried about using too much memory while your script is running. All result memory is automatically freed when the script is finished. However, if you are sure you are not going to need the result data again in a script, you may call pg_FreeResult() with the result identifier as an argument, and the associated result memory is freed. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_GetLastOid()

pg_GetLastOid() can be used to retrieve the Oid assigned to an inserted tuple if the last command sent via pg_Exec() was an SQL Insert. This function returns a positive integer if there was a valid Oid. It returns -1 if an error occurred or the last command sent via pg_Exec() was not an Insert. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_Host(connection_id)

pg_Host() returns the host name the given Postgres95 connection identifier is connected to. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_NumFields(result_id)

pg_NumFields() returns the number of fields (columns) in a Postgres95 result. The argument is a valid result identifier returned by $result = pg_Exec(connection_id, query_string). This function returns -1 on error. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_NumRows(result_id)

pg_NumRows() returns the number of rows in a Postgres95 result. The argument is a valid result identifier returned by $result = pg_Exec(connection_id, query_string). This function returns -1 on error. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_Options(connection_id)

pg_Options() returns a string containing the options specified on the given Postgres95 connection identifier. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_Port(connection_id)

pg_Port() returns the port number that the given Postgres95 connection identifier is connected to. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_Result(result_id, row_number, field_name/index)

pg_Result() returns values from a result identifier produced by pg_Exec(). The row_number and field_name specify what cell in the table of results to return. Row numbering starts from 0. Instead of naming the field, you may use the field index as an unquoted number. Field indices start from 0. Postgres95 has many built-in types, and only the basic ones are directly supported here.

All forms of integer, boolean, and Oid types are returned as integer values. All forms of float and real types are returned as double values. All other types, including arrays, are returned as strings formatted in the same default Postgres95 manner that you see in the "monitor" or "psql" programs.

Support for returning PHP arrays of numerical and string data from a Postgres95 result is planned for a later date.

This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



pg_tty(connection_id)

pg_tty() returns the TTY name that server-side debugging output is sent to on the given Postgres95 connection identifier. This function is only available if Postgres95 support is enabled in PHP as described in "PHP Configuration" on page 11-2.



phpInfo()

phpInfo() prints the same page you get when adding "?info" to a PHP-parsed URL, or when you run the php.cgi binary by itself. It is especially useful for debugging scripts in the module, since it displays useful internal data.



phpVersion()

phpVersion() returns the version number of PHP/FI currently running.



fp = popen(command,mode)

Popen() opens a pipe to a command and returns a file pointer index. This file pointer index can be used by fgets($fd,bytes), fputs(fp,string), and fclose($fd). The function's arguments are the command to run and the mode. The mode can be either "r" for read or "w" for write. See the UNIX C library popen man page for more details. Any file opened with popen() should be closed using the pclose(fp) function.



pos(var)

The pos() function returns the numerical position of an array element within that array. This is not very useful for normal arrays, but it can be handy for associative arrays.



pow(x,y)

pow() valuates x raised to the power of y. See also Exp(arg).



Prev(variable)

Prev() moves the internal array pointer for the given variable to the previous item in the array. If already at the beginning of the list, the pointer points to the first item. The function returns the value of the new item. It is useful for traversing an associative array in reverse order. See the example in the End(variable) definition. See also Next(variable).



PutEnv(string)

PutEnv() puts the given string in the environment. This is not especially useful, since the local environment variables are wiped out when PHP is finished parsing a page, but it is useful if other things called from within a PHP script check environment variables. For example, if you want to run multiple mSQL daemon processes, you need to use PutEnv() to switch back and forth between the different sockets.



QuoteMeta(arg)

QuoteMeta() returns a string composed of arg with any regular expression special characters escaped with a backslash.



Rand()

Rand() returns a random number between 0 and RANDMAX. Be sure to seed your random number generator by calling Srand(integer) before you call rand(). You only need to do this once. You can determine RANDMAX using the getRandMax() function.



readDir()

readDir() reads the next entry from the currently open directory structure. Once an entry is read, the pointer advances to the next entry in the directory and the next call to this function returns the next entry in the directory. Use the openDir function to open a directory before calling this function.



$size = ReadFile(filename)

ReadFile() reads the file filename and outputs it directly. It also returns the number of bytes actually read. Unlike the File() command, it does not store the file in memory and is safe for use on binary files. ReadFile() is more efficient than PassThru("cat filename").



ReadLink(path)

ReadLink() does the same as the readlink C function and returns the contents of the symbolic link path, or -1 in case of error. See also LinkInfo(path).



reg_Match(regex,arg[,regs])

This function has been replaced by the ereg(expr,arg[,regex]) function. It is, however, still available for backward compatibility. reg_Match() returns non-zero if the regex is matched in the arg string. For example, the condition

<?if (reg_match("^This.*", "This is an example string")>

is true, since the "^This.*" expression instructs PHP to match the word "This" at the beginning of the string, then match any characters afterwards. If the regs argument is present, then match registers are filled into positions 0-10 in the array named by regs. Register 0 always contains the full matched string. For more information on regular expressions, see "Regular Expressions" on page 11-9.



reg_replace(expr,replace,arg)

This function has been replaced by the ereg_replace(regex,replace,arg) function. It is, however, still available for backward compatibility. reg_replace() scans the entire argument string and replaces any portions of the string matched by the given expression with the replacement string. For example, in the string, "This is an example string," you can replace every space with a dash with the command:

reg_replace(" ","-","This is an example string")

For more information on regular expressions, see "Regular Expressions" on page 11-9.



reg_Search(regex,arg[,regs])

This function has been replaced by the ereg(expr,arg[,regex]) function. It is, however, still available for backward compatibility. reg_Search() scans the entire argument string for any matches to the given regex. If a match is found, the fucntion returns the portion of the string starting where the match occurred. If no match is found, a zero-length string is returned. If the regs argument is present, then match registers are filled into positions 0-10 in the array named by the regs argument. Register 0 is always assigned the full matched string. For more information on regular expressions, see "Regular Expressions" on page 11-9.



Rename(old,new)

This function renames filename old to new, similar to the UNIX C rename() function.



Reset(variable)

Reset() moves the internal array pointer for the given array variable to the first item of the array and returns the value of this item. This is useful for traversing associative and non-indexed arrays. The following example traverses an associative array:

<?
Reset($array);
$i=0;
while($i < count($array));
echo $array[]; /* pointer automatically moves ahead one */
$i++;
endwhile;
>

See also End(variable) and Next(variable).



Return(value)

Return() exits the current function call and returns the specified value to the caller. See "User-Defined Functions" on page 11-13 for more information about user-defined functions.



rewind($fd)

rewind() resets a file pointer identified by the $fd argument, which is the return value of the $fp = fopen(file,mode) call. The file pointer is positioned at the beginning of the file. See also pos = ftell(fp) and fseek(fp,pos).



rewindDir()

rewindDir() moves the current directory pointer back to the beginning of the directory. Use the openDir(directory) function to open a directory before calling this function.



RmDir(dir)

RmDir() removes the given directory. See the Unlink(file) function to remove regular files.



RSort(array)

RSort() sorts a PHP array in descending order. It understands the three variable types and sorts reverse-alphabetically if the array contains strings and reverse-numerically if the array contains numbers. In the case of an array that contains a mixture of types, the first type in the array specifies the sort method.



SetCookie(name,value,expire,path,domain,secure)

SetCookie() defines a cookie to be sent along with the rest of the header information. All the arguments are optional except the name argument. If only the name argument is present, the server instructs the client to delete the cookie of that name. You can also replace any argument with an empty string ("") in order to skip it. The expire and secure arguments are integers and cannot be skipped with an empty string; use a zero (0) instead. The expire argument is a regular UNIX time integer as returned by the time() or mktime() functions. Some examples follow:

SetCookie("TestCookie","Test Value");
SetCookie("TestCookie",$value,time()+3600); /* expire in 1 hour */
SetCookie("TestCookie",$value,time()+3600,"/~rasmus/",".utoronto.ca",1);

The value portion of the cookie is automatically URL-encoded when you send the cookie. When it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. For example, to see the contents of our test cookie in a script, use

echo $TestCookie;


SetErrorReporting(arg)

SetErrorReporting() sets the current error reporting state to the value of arg. If the value is non-zero, errors are printed; if it is zero, they are not. The function returns the previous error reporting state. This is a more general way of disabling error reporting than by preceding individual functions with an "@" character.



SetLogging(arg)

SetLogging() either enables or disables the logging of access statistics for a page. If arg is non-zero, logging is enabled; if it is zero, logging is disabled.



SetShowInfo(arg)

SetShowInfo() either enables or disables the information footer at the bottom of all pages loaded through PHP. If arg is non-zero, the footers are enabled; if it is zero, footers are disabled.



SetType(variable,type)

SetType() sets the type of a variable. The type argument is one of the following:

See also the GetType(variable) function.



shl(n,b)

This shifts the value n left by b bits.



shr(n,b)

This shifts the value n right by b bits.



Sin(arg)

Sin() returns the sine of arg in radians. See also Cos(arg) and Tan(arg).



Sleep(secs)

Sleep delays for secs seconds. Similar to the UNIX C sleep() function. See also the USleep() function.



Solid_Close(connection_id)

Solid_Close() will close down the connection to the Solid server associated with the given connection identifier.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



$connection = Solid_Connect(data source name, username, password)

Solid_Connect() opens a connection to a Solid server. Each of the arguments is a quoted string. The first parameter (data source name) can be an empty string, resulting in a connection to the default server on the localhost. This function returns a connection_id which is needed by other Solid functions. You can have multiple connections open at once. This function returns 0 on error.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



$result = Solid_Exec(connection_id, query_string)

Solid_Exec() sends an SQL statement to the Solid server specified by the connection_id. The connection_id must be a valid identifier that was returned by Solid_Connect(). The return value of this function is an identifier to be used to access the results by other Solid functions. This function returns 0 on error. It returns 1 when the commands execute correctly but are not expected to returned data (insert or update commands, for example). Note that selects that return no data still return a valid result greater than 1.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Solid_FetchRow(result_id)

Solid_FetchRow() fetches a row of the data that was returned by Solid_Exec(). After Solid_FetchRow() is called, the fields of that row can be accessed with Solid_Result(result_id, field name|index). Every time Solid_FetchRow() is called, a new row can be accessed by Solid_Result(). If Solid_FetchRow() succeeds (there is a new row), 1 is returned. If there are no more rows, Solid_FetchRow() returns 0. The return value of Solid_FetchRow() can be used as the condition of a while loop.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Solid_FieldName(result_id, field_number)

Solid_FieldName() returns the name of the field occupying the given column number in the given Solid result identifier. Field numbering starts from 0.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Solid_FieldNum(result_id, field_name)

Solid_FieldNum() returns the number of the column slot that corresponds to the named field in the given Solid result identifier. Field numbering starts at 0. This function returns -1 on error.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Solid_FreeResult(result_id)

Solid_FreeResult() only needs to be called if you are concerned about using too much memory while your script is running. All result memory is automatically freed when the script is finished. However, if you are sure you are not going to need the result data again in a script, you can call Solid_FreeResult() with the result identifier as an argument, and the associated result memory is freed.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Solid_NumFields(result_id)

Solid_NumFields() returns the number of fields (columns) in a Solid result. The argument is a valid result identifier returned by $result = Solid_Exec(connection_id, query_string). This function returns -1 on error.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Solid_NumRows(result_id)

Solid_NumRows() returns the number of rows in a Solid result. The argument is a valid result identifier returned by $result = Solid_Exec(connection_id, query_string). This function returns -1 on error.

NOTE: The Solid SQL server uses ODBC as its primary (and only) interface. SolidNumRows() uses SQLRowCount() at a low level to get the number of rows. SQLRowCount() includes unnecessary limitations, strange exceptions, and other odd behaviors. This means that the function only returns the number of rows affected by an INSERT, an UPDATE, or a DELETE clause. As a workaround, you can try the count() statement of SQL or a while-loop that counts the number of rows.

If you need Solid_NumRows() to figure out how many records to read after a SELECT clause, try checking the return value from Solid_FetchRow(result_id) instead. For example, instead of

$num = Solid_NumRows();
$i=0;
while ($i < $num) {
/* print results... */
$i++;
}

try

while(Solid_FetchRow($result)) {
/* print results... */
}

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Solid_Result(result_id, field name|index)

Solid_Result() returns values from a result identifier produced by $result = Solid_Exec(connection_id, query_string). The field name specifies which cell in the row to return. Instead of naming the field, you may use the field index as an unquoted number. Field indices start from 0.

This function is only available if Solid support has been enabled in PHP as described in "PHP Configuration" on page 11-2.



Sort(array)

Sort() sorts a PHP array in ascending order. It understands the three variable types and sorts alphabetically if the array contains strings and numerically if the array contains numbers. In the case of an array that contains a mixture of types, the first type in the array specifies the sort method. See also RSort(array).



Soundex(string)

This function takes a string argument and returns the soundex key for that string. Words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where the user knows the pronunciation but not the spelling. This soundex function returns a 4-character key, starting with a letter.

For example:

String Soundex Key
Euler and Ellery E460
Gauss and Ghosh G200
Hilbert and Heilbronn H416
Knuth and Kant K530
Lloyd and Ladd L300
Lukasiewicz and Lissajous L222

This particular soundex function is described by Donald Knuth in The Art Of Computer Programming, vol. 3: Sorting And Searching.



Sprintf(format,arg)

Sprintf() returns the string created by the formatted output defined by the format and arg. It is similar to the formatted version of the Echo() command, except that this returns the string and Echo() displays it. It is also similar to the C function by the same name. The difference is that this version does not accept multiple arg arguments. If you need to format multiple arguments into a single string, simply call Sprintf() once for each argument. Note that the type of the argument does not affect the output. The argument type is automatically converted to match the type specified in the format string.



Sqrt(arg)

Sqrt() returns the square root of arg.



Srand(integer)

Srand() seeds the random number generator. This function takes any integer as an argument. One choice for a seed value is to use the Date(format,time) function to get the current number of seconds past the minute. Note that this function does not return a value. It simply seeds the random number generator for subsequent calls to the Rand() function. For example:

<?srand(date("s"))>


strchr(string,arg)

strchr() and strstr(string,arg) are identical functions. They can be used interchangeably, and both are included for completeness. They return the portion of the string argument starting at the point where the given sub-string arg is found. For example, in the string, "This is an example string," the call

<echo strstr($string,"an ")>

returns the string "an example string."



StripSlashes(arg)

StripSlashes() unescapes the string argument. See also AddSlashes(arg).



strlen(string)

strlen() returns the length of the string.



strrchr(string,arg)

strrchr() searches for a single character, starting at the end of the string and working its way backwards. It returns the string starting with the search character if the character was found and an empty string if it was not.



strstr(string,arg)

strstr() and strchr(string,arg) are identical functions. They can be used interchangeably, and both are included for completeness sake. They return the portion of the string argument starting at the point where the given sub-string arg is found. For example, in the string, "This is an example string," the call

<echo strstr($string,"an ")>

returns the string: "an example string."



strtok(string,arg)

strtok() tokenizes a string. For example, if you have a string "This is an example string," you can tokenize it into its individual words by using the space character as the token:

<?
$string = "This is an example string";
$tok = strtok($string," ");
while($tok);
echo "Word=$tok<br>";
$tok = strtok(" ");
endwhile;
>

Note that only the first call to strtok() uses the string argument. Every subsequent call to strtok() only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string, call strtok() with the string argument again to initialize it.

Arg can contain multiple tokens. PHP tokenizes the string if it finds one or more of the characters in arg.



strtolower(string)

strtolower() converts the string argument to all-lowercase characters.



strtoupper(string)

strtoupper() converts the string argument to all-uppercase characters.



strtr(input,set1,set2)

strtr() translates each character of string that is in set1 to the corresponding character in set2. Characters not in set1 are passed through unchanged. When a character appears more than once in set1 and the corresponding characters in set2 are not all the same, only the final one is used. When one of set1 or set2 is longer, the longer set is truncated to length of the shorter set.



strval(variable)

strval() returns the string value of the variable. See also the intval(variable) and doubleval(variable) functions.



substr(string, start, length)

substr() returns a part of the given string. The start argument specifies the start position. The first position in a string is position 0. The length argument specifies the number of characters to return from the start position.



sybSQL_CheckConnect()

This function returns 1 if the connection to the database has been established and 0 otherwise.



sybSQL_Connect()

This function opens a network connection to the sybase server. This function depends on several environment variables that must be set by the caller before calling this function.

The environment variables are as follows:

Variable Description
DSQUERY The alias of the Sybase server as defined in the Sybase interface file
DBUSER Connect to the Sybase server as this user
DBPW Password of the user

These variables can be set in several ways. If PHP/FI is running as a CGI program, then a shell wrapper can be used to set these variables or you can set these variables directly in the HTML page using the builtin PHP/FI function putenv(). Instead of using the values directly in putenv(), the values can be obtained from form input. The variables can be defined in a file and included in the html files with PHP/FI include statement.

The function returns 1 on success and 0 on failure.



sybSQL_DBuse(database)

This function issues a Sybase Transact-SQL use command for the specified database. For example:

sybsql_dbuse("pubs2");

The function returns 1 on success and 0 on failure.



sybSQL_Fieldname(index)

This function returns the field name of a regular result column. The argument is the field index. For example:

sybsql_fieldname(0);

The field index starts at 0. If the the result column does not have any name, the function returns an empty string.



sybSQL_GetField(field)

This function gets the value of a specific column of the current result row. The only argument to the function is the string specifying the field. For example:

$value=sybsql_getfield("@10");

NOTE: sybSQL_NextRow() must be called before calling this function. sybSQL_NextRow()) must be called if the row pointer needs to be incremented because this function only reads the current row in the row buffer.

If the specified column has a value, the function returns the value as a string otherwise the function returns an empty string.



sybSQL_IsRow()

This function indicates whether the current SQL command returned any rows.

The function returns 1 if the SQL command returned any rows, and 0 if the command did not.



sybSQL_NextRow()

This function increments the row pointer to the next result row.

The function returns 1 as long as there are rows left to read. If there are no more rows left to read, or in case of error, the function returns 0.



sybSQL_NumFields()

This function returns the number of fields in a current result row.

The function returns the number of rows in the current result row. If there are no fields, the function returns 0.



sybSQL_NumRows()

This function returns the number of rows in the current result buffer. If there are no rows in the result buffer, the function returns 0.

When this function is called, it seeks the first row right away, then it calls dbnextrow() until there are no more rows and increments an internal counter to calculate the number of rows in the result buffer. Then it points back to the first row. Therefore, after calling this function, the row counter always points to the first row.



sybSQL_Query()

This function submits a Sybase SQL query request to the server. The only argument to the function is the query string. For example:

$rc=sybsql_query("select * from authors");

The function returns 1 if the query is passed successfully, and 0 if the request fails.



sybSQL_Result(string)

This function prints specific fields of the current result row. The only argument to the function is a string which holds information about the fields to be printed. A field is specified with an @ followed by a number. The field number starts at 0. For example, "@0" means the first row, "@10" means the 11th row. The function is perhaps best illustrated with a complete example:

<?
/*
** assuming all the necessary variables for
** connection is already set. please note, NO error checking is
** done. You should always check return code of a function.
*/
/* connect */
$rc=sybsql_connect();
/* use the pub2 database */
$rc=sybsql_dbuse("pubs2");
/* send the SQL request */
$rc=sybsql_query("select * from authors");
$i=0;
/* find the no of rows returned */
$nrows=sybsql_numrows();
/* start table */
echo "<table border>\n";
/*
** print only first and 2nd field
*/
while($i<$nrows) {
sybsql_result("<tr><td>@0</td>@1</td></tr>\n");
$i++;
}
/* end table */
echo "</table>\n";
>

The above example uses an HTML table to format the output. Any other HTML tags are also valid.



sybSQL_Result_All()

This function prints all rows in the current result buffer. The result is printed in a hard-coded HTML table format. The function prints the name of the columns if there are any column headings in the output.

NOTE: This function should not be called inside a loop.



sybSQL_Seek(row)

This function sets the requested row number as the current row in the row buffer. The only argument to the function is the row number. Row numbering starts at 0. For example:

$rc=sybsql_seek(10);

The function returns 1 if the seek succeeds and 0 if the seek fails. When all of the rows in the current result buffer have been visited, the row pointer points to the last row. If it is necessary to go backward and visit some more rows, this function can be used for this purpose.



Symlink(target,link)

Symlink() creates a symbolic link. See the Link(target,link) function to create hard links.



System(command_string [,return_var])

System() is just like the C system() command in that it executes the given UNIX command and outputs the result. If a variable is provided as the second argument, then the return status code of the executed UNIX command is written to this variable. If you are going to allow data coming from user input to be passed to this System() function, then you should use the EscapeShellCmd(string) function to make sure that users cannot trick the system into executing commands. If you need to execute a command and have all the data from the command passed directly back without any interference, use the PassThru(command_string [,return_var]) function. See also the Exec(command_string [, array [,return_var]]) function.



Tan(arg)

Tan() returns the tangent of arg in radians. See also Sin(arg) and Cos(arg).



TempNam(path, prefix)

TempNam() returns a unique filename located in the directory indicated by path with the filename prefix. It is identical to the UNIX C tempnam() function.



Time()

Time() simply returns the current local time in seconds since the UNIX epoch (00:00:00 Jan. 1 1970). It is equivalent to calling Date("U"). If you need better than per-second granularity, use the Microtime() function.



Umask(mask)

Umask(mask) sets PHP's umask to "mask & 0777" and returns the old umask. The old umask is restored when PHP has finished. Mask must be specified in octal notation, as for ChMod(). Umask() without arguments simply returns the current umask.



Unlink(file)

Unlink() deletes the given file, similar to the UNIX C unlink() function. See the RmDir(dir) function for removing directories.



UnSet($var)

UnSet() undefines the given variable. In the case of an array, the entire array is cleared. Note that individual array elements cannot go undefined with this command.



UrlDecode(string)

UrlDecode() decodes a string encoded with the UrlEncode() function. Typically, it is not necessary to decode URL-encoded strings because these are automatically decoded when strings are passed between pages. However, this function has been included for completeness.



UrlEncode(string)

UrlEncode() encodes any characters from the string which are not one of "a-zA-Z0-9_-." by replacing them with "%xx," where xx is their ASCII value in hexadecimal. The encoded string is returned.



USleep(microsecs)

USleep() delays for the given number of microseconds, similar to the UNIX C usleep() function. See also the Sleep(secs) function.



Virtual(filename)

Virtual() is an Apache-specific function which is equivalent to <!--#include virtual...--> in server-side includes. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through the server. For .php files, use <?Include>.






[Top] [Prev] [Next] [Last]
© 1998 C2Net International
Feedback: stronghold-docs@c2.net
C2Net Logo