email . "\n";
}
ibase_close ($dbh);
?>
Subsequent call to ibase_fetch_object() would return the next row in the result set, or FALSE if there are no more rows.
See also ibase_fetch_row().
1468
ibase_fetch_row
(PHP 3>= 3.0.6, PHP 4 )
ibase_fetch_row - Fetch a row from an InterBase database
Description
array ibase_fetch_row (int result_identifier)
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
ibase_fetch_row() fetches one row of data from the result associated with the specified result_identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to ibase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
1469
ibase_field_info
(PHP 3>= 3.0.7, PHP 4 )
ibase_field_info - Get information about a field
Description
array ibase_field_info (int result, int field_number)
Returns an array with information about a field after a select query has been run. The array is in the form of name, alias, relation, length, type.
$rs=ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i=0; $i < $coln; $i++) {
$col_info = ibase_field_info($rs, $i);
echo "name: ".$col_info['name']."\n";
echo "alias: ".$col_info['alias']."\n";
echo "relation: ".$col_info['relation']."\n";
echo "length: ".$col_info['length']."\n";
echo "type: ".$col_info['type']."\n";
}
1470
ibase_free_query
(PHP 3>= 3.0.6, PHP 4 )
ibase_free_query - Free memory allocated by a prepared query
Description
int ibase_free_query (int query)
Free a query prepared by ibase_prepare().
1471
ibase_free_result
(PHP 3>= 3.0.6, PHP 4 )
ibase_free_result - Free a result set
Description
int ibase_free_result (int result_identifier)
Free's a result set the has been created by ibase_query().
1472
ibase_modify_user
(PHP 4 >= 4.2.0)
ibase_modify_user - Modify a user to a security database (only for IB6 or later)
Description
int ibase_add_user (string server, string dba_user_name, string dba_user_password, string user_name, string
password [, string first_name [, string middle_name [, string last_name]]])
Warning
This function is currently not documented; only the argument list is available.
1473
ibase_num_fields
(PHP 3>= 3.0.7, PHP 4 )
ibase_num_fields - Get the number of fields in a result set
Description
int ibase_num_fields (int result_id)
Returns an integer containing the number of fields in a result set.
0) {
while ($row = ibase_fetch_object ($sth)) {
print $row->email . "\n";
}
} else {
die ("No Results were found for your query");
}
ibase_close ($dbh);
?>
See also: ibase_field_info().
1474
ibase_pconnect
(PHP 3>= 3.0.6, PHP 4 )
ibase_pconnect - Creates an persistent connection to an InterBase database
Description
int ibase_pconnect (string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])
ibase_pconnect() acts very much like ibase_connect() with two major differences. First, when connecting, the function will
first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be
returned instead of opening a new connection. Second, the connection to the InterBase server will not be closed when the
execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established
by ibase_pconnect()). This type of link is therefore called 'persistent'.
Note: buffers was added in PHP4-RC2.
Note: dialect was added in PHP4-RC2. It is functional only with InterBase 6 and versions higher than that.
Note: role was added in PHP4-RC2. It is functional only with InterBase 5 and versions higher than that.
See also ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.
1475
ibase_prepare
(PHP 3>= 3.0.6, PHP 4 )
ibase_prepare - Prepare a query for later binding of parameter placeholders and execution
Description
int ibase_prepare ([int link_identifier, string query])
Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).
1476
ibase_query
(PHP 3>= 3.0.6, PHP 4 )
ibase_query - Execute a query on an InterBase database
Description
int ibase_query ([int link_identifier, string query [, int bind_args]])
Performs a query on an InterBase database. If the query is not successful, returns FALSE. If it is successful and there are resulting rows (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results,
returns TRUE. Returns FALSE if the query fails.
See also ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object(), and ibase_free_result().
1477
ibase_rollback
(PHP 3>= 3.0.7, PHP 4 )
ibase_rollback - Rolls back a transaction
Description
int ibase_rollback ([int link_identifier, int trans_number])
Rolls back transaction trans_number which was created with ibase_trans().
1478
ibase_timefmt
(PHP 3>= 3.0.6, PHP 4 )
ibase_timefmt - Sets the format of timestamp, date and time type columns returned from queries
Description
int ibase_timefmt (string format [, int columntype])
Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by cfunction strftime(), so refer to it's documentation regarding to the format of the string. columntype is one of the constants
IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards
compatibility.
You can also set defaults for these formats with PHP configuration directives ibase.timestampformat, ibase.dateformat and
ibase.timeformat.
Note: columntype was added in PHP 4.0. It has any meaning only with InterBase version 6 and higher.
Note: A backwards incompatible change happened in PHP 4.0 when PHP configuration directive ibase.timeformat
was renamed to ibase.timestampformat and directives ibase.dateformat and ibase.timeformat were added, so that
the names would match better their functionality.
1479
ibase_trans
(PHP 3>= 3.0.7, PHP 4 )
ibase_trans - Begin a transaction
Description
int ibase_trans ([int trans_args [, int link_identifier]])
Begins a transaction.
1480
Ingres II functions
Table of Contents
ingres_autocommit ........................................................................................................................... 1484
ingres_close .................................................................................................................................... 1485
ingres_commit ................................................................................................................................. 1486
ingres_connect ................................................................................................................................ 1487
ingres_fetch_array ............................................................................................................................ 1488
ingres_fetch_object .......................................................................................................................... 1489
ingres_fetch_row ............................................................................................................................. 1490
ingres_field_length ........................................................................................................................... 1491
ingres_field_name ............................................................................................................................ 1492
ingres_field_nullable ........................................................................................................................ 1493
ingres_field_precision ....................................................................................................................... 1494
ingres_field_scale ............................................................................................................................ 1495
ingres_field_type ............................................................................................................................. 1496
ingres_num_fields ............................................................................................................................ 1497
ingres_num_rows ............................................................................................................................. 1498
ingres_pconnect ............................................................................................................................... 1499
ingres_query ................................................................................................................................... 1500
ingres_rollback ................................................................................................................................ 1502
1481
Introduction
These functions allow you to access Ingres II database servers.
Note: If you already used PHP extensions to access other database servers, note that Ingres doesn't allow concurrent queries and/or transaction over one connection, thus you won't find any result or transaction handle in this extension. The result of a query must be treated before sending another query, and a transaction must be commited or
rolled back before opening another transaction (which is automaticaly done when sending the first query).
Warning
This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and
anything else documented about this extension -- may change without notice in a future release of PHP. Use this
extension at your own risk.
Requirements
To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.
Installation
In order to have these functions available, you must compile PHP with Ingres support by using the -with-ingres[=DIR] option, where DIR is the Ingres base directory, which defaults to /II/ingres. If the II_SYSTEM
environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.
When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environement variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 80. Ingres II configuration options
Name
Default
Changeable
ingres.allow_persistent
"1"
PHP_INI_SYSTEM
ingres.max_persistent
"-1"
PHP_INI_SYSTEM
ingres.max_links
"-1"
PHP_INI_SYSTEM
ingres.default_database
NULL
PHP_INI_ALL
ingres.default_user
NULL
PHP_INI_ALL
ingres.default_password
NULL
PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().
Resource Types
This extension has no resource types defined.
1482
Ingres II functions
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
INGRES_ASSOC (integer)
INGRES_NUM (integer)
INGRES_BOTH (integer)
1483
ingres_autocommit
(PHP 4 >= 4.0.2)
ingres_autocommit - Switch autocommit on or off
Description
bool ingres_autocommit ([resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the "autocommit" mode of the server on or off (when the script begins the
autocommit mode is off).
When the autocommit mode is on, every query is automaticaly commited by the server, as if ingres_commit() was called
after every call to ingres_query().
See also ingres_query(), ingres_rollback(), and ingres_commit().
1484
ingres_close
(PHP 4 >= 4.0.2)
ingres_close - Close an Ingres II database connection
Description
bool ingres_close ([resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Returns TRUE on success, or FALSE on failure.
ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't
specified, the last opened link is used.
ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.
See also ingres_connect() and ingres_pconnect().
1485
ingres_commit
(PHP 4 >= 4.0.2)
ingres_commit - Commit a transaction
Description
bool ingres_commit ([resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_commit() commits the currently open transaction, making all changes made to the database permanent.
This closes the transaction. A new one can be open by sending a query with ingres_query().
You can also have the server commit automaticaly after every query by calling ingres_autocommit() before opening the
transaction.
See also ingres_query(), ingres_rollback(), and ingres_autocommit().
1486
ingres_connect
(PHP 4 >= 4.0.2)
ingres_connect - Open a connection to an Ingres II database
Description
resource ingres_connect ([string database [, string username [, string password]]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Returns a Ingres II link resource on success, or FALSE on failure.
ingres_connect() opens a connection with the Ingres database designated by database, which follows the syntax
[node_id::]dbname[/svr_class].
If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user, and ingres.default_password.
The connection is closed when the script ends or when ingres_close() is called on this link.
All the other ingres functions use the last opened link as a default, so you need to store the returned value only if you use
more than one link at a time.
Example 407. ingres_connect() example
Example 408. ingres_connect() example using default link
See also ingres_pconnect() and ingres_close().
1487
ingres_fetch_array
(PHP 4 >= 4.0.2)
ingres_fetch_array - Fetch a row of result into an array
Description
array ingres_fetch_array ([int result_type [, resource link]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_fetch_array() Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other
column(s) of the same name, you must use the numeric index of the column or make an alias for the column.
ingres_query(select t1.f1 as foo t2.f1 as bar from t1, t2);
$result = ingres_fetch_array();
$foo = $result["foo"];
$bar = $result["bar"];
result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH
(default).
Speed-wise, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is
insignificant).
Example 409. ingres_fetch_array() example
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().
1488
ingres_fetch_object
(PHP 4 >= 4.0.2)
ingres_fetch_object - Fetch a row of result into an object.
Description
object ingres_fetch_object ([int result_type [, resource link]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_fetch_object() Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.
This function is similar to ingres_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly,
that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property
names).
The optional argument result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and
INGRES_BOTH.
Speed-wise, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is
insignificant).
Example 410. ingres_fetch_object() example
user_id;
echo $row->fullname;
}
?>
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().
1489
ingres_fetch_row
(PHP 4 >= 4.0.2)
ingres_fetch_row - Fetch a row of result into an enumerated array
Description
array ingres_fetch_row ([resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result
column is stored in an array offset, starting at offset 1.
Subsequent call to ingres_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
Example 411. ingres_fetch_row() example
See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_object().
1490
ingres_field_length
(PHP 4 >= 4.0.2)
ingres_field_length - Get the length of a field
Description
int ingres_field_length (int index [, resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
1491
ingres_field_name
(PHP 4 >= 4.0.2)
ingres_field_name - Get the name of a field in a query result.
Description
string ingres_field_name (int index [, resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_field_name() returns the name of a field in a query result, or FALSE on failure.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row().
1492
ingres_field_nullable
(PHP 4 >= 4.0.2)
ingres_field_nullable - Test if a field is nullable
Description
bool ingres_field_nullable (int index [, resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
1493
ingres_field_precision
(PHP 4 >= 4.0.2)
ingres_field_precision - Get the precision of a field
Description
int ingres_field_precision (int index [, resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data
types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
1494
ingres_field_scale
(PHP 4 >= 4.0.2)
ingres_field_scale - Get the scale of a field
Description
int ingres_field_scale (int index [, resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
1495
ingres_field_type
(PHP 4 >= 4.0.2)
ingres_field_type - Get the type of a field in a query result
Description
string ingres_field_type (int index [, resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_field_type() returns the type of a field in a query result, or FALSE on failure. Examples of types returned are
"IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", "IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE",
"IIAPI_VCH_TYPE". Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example "IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed information, see the Ingres/
OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
1496
ingres_num_fields
(PHP 4 >= 4.0.2)
ingres_num_fields - Get the number of fields returned by the last query
Description
int ingres_num_fields ([resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
1497
ingres_num_rows
(PHP 4 >= 4.0.2)
ingres_num_rows - Get the number of rows affected or returned by the last query
Description
int ingres_num_rows ([resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
For delete, insert or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.
Note: This function is mainly meant to get the number of rows modified in the database. If this function is called
before using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row() the server will delete the result's
data and the script won't be able to get them.
You should instead retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
1498
ingres_pconnect
(PHP 4 >= 4.0.2)
ingres_pconnect - Open a persistent connection to an Ingres II database
Description
resource ingres_pconnect ([string database [, string username [, string password]]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Returns a Ingres II link resource on success, or FALSE on failure.
See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : First, when connecting, the function will first try to find a (persistent) link that's already opened with the
same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for
future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called 'persistent'.
See also ingres_connect() and ingres_close().
1499
ingres_query
(PHP 4 >= 4.0.2)
ingres_query - Send a SQL query to Ingres II
Description
bool ingres_query (string query [, resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Returns TRUE on success, or FALSE on failure.
ingres_query() sends the given query to the Ingres server. This query must be a valid SQL query (see the Ingres SQL reference guide)
The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can either call ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediatly commited.
Some types of SQL queries can't be sent with this function:
•
close (see ingres_close())
•
commit (see ingres_commit())
•
connect (see ingres_connect())
•
disconnect (see ingres_close())
•
get dbevent
•
prepare to commit
•
rollback (see ingres_rollback())
•
savepoint
•
set autocommit (see ingres_autocommit())
•
all cursor related queries are unsupported
Example 412. ingres_query() example
See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().
1501
ingres_rollback
(PHP 4 >= 4.0.2)
ingres_rollback - Roll back a transaction
Description
bool ingres_rollback ([resource link])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
ingres_rollback() rolls back the currently open transaction, actually canceling all changes made to the database during the
transaction.
This closes the transaction. A new one can be open by sending a query with ingres_query().
See also ingres_query(), ingres_commit(), and ingres_autocommit().
1502
IRC Gateway Functions
Table of Contents
ircg_channel_mode .......................................................................................................................... 1505
ircg_disconnect ................................................................................................................................ 1506
ircg_fetch_error_msg ........................................................................................................................ 1507
ircg_get_username ........................................................................................................................... 1508
ircg_html_encode ............................................................................................................................. 1509
ircg_ignore_add ............................................................................................................................... 1510
ircg_ignore_del ................................................................................................................................ 1511
ircg_is_conn_alive ........................................................................................................................... 1512
ircg_join ......................................................................................................................................... 1513
ircg_kick ........................................................................................................................................ 1514
ircg_lookup_format_messages ............................................................................................................ 1515
ircg_msg ........................................................................................................................................ 1516
ircg_nick ........................................................................................................................................ 1517
ircg_nickname_escape ...................................................................................................................... 1518
ircg_nickname_unescape ................................................................................................................... 1519
ircg_notice ...................................................................................................................................... 1520
ircg_part ......................................................................................................................................... 1521
ircg_pconnect .................................................................................................................................. 1522
ircg_register_format_messages ........................................................................................................... 1523
ircg_set_current ............................................................................................................................... 1525
ircg_set_file .................................................................................................................................... 1526
ircg_set_on_die ............................................................................................................................... 1527
ircg_topic ....................................................................................................................................... 1528
ircg_whois ...................................................................................................................................... 1529
1503
Introduction
With IRCG you can rapidly stream XML data to thousands of concurrently connected users. This can be used to build
powerful, extensible interactive platforms such as online games and webchats. IRCG also features support for a nonstreaming mode where a helper application reformats incoming data and supplies static file snippets in special formats such
as cHTML (i-mode) or WML (WAP). These static files are then delivered by the high-performance web server.
Up to v3, IRCG runs under these platforms:
•
AIX
•
FreeBSD
•
HP-UX
•
Irix
•
Linux
•
Solaris
•
Tru64
Installation
Detailed installation instructions can be found here [http://lxr.php.net/source/php4/ext/ircg/README.txt]. We urge you to
use the provided installation script.
It is not recommended, but you can try enable IRCG support yourself. Provide the path to the ircg-config script, -with-ircg-config=path/to/irc-config and in addition add --with-ircg to your configure line.
Runtime Configuration
This extension has no configuration directives defined in php.ini.
Resource Types
Predefined Constants
This extension has no constants defined.
1504
ircg_channel_mode
(PHP 4 >= 4.0.5)
ircg_channel_mode - Set channel mode flags for user
Description
bool ircg_channel_mode (resource connection, string channel, string mode_spec, string nick)
Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.
Mode flags are set or cleared by specifying a mode character and prepending it with a plus or minus character, respectively.
E.g. operator mode is granted by '+o' and revoked by '-o', as passed as mode_spec.
1505
ircg_disconnect
(PHP 4 >= 4.0.4)
ircg_disconnect - Close connection to server
Description
bool ircg_disconnect (resource connection, string reason)
ircg_disconnect() will close a connection to a server previously established with ircg_pconnect().
See also: ircg_pconnect().
1506
ircg_fetch_error_msg
(PHP 4 >= 4.1.0)
ircg_fetch_error_msg - Returns the error from previous IRCG operation
Description
array ircg_fetch_error_msg (resource connection)
ircg_fetch_error_msg() returns the error from a failed connection.
Note: Error code is stored in first array element, error text in second. The error code is equivalent to IRC reply
codes as defined by RFC 2812.
Example 413. ircg_fetch_error_msg() example
if (!ircg_join ($id, "#php")) {
$error = ircg_fetch_error_msg($id);
print ("Can't join channel #php. Error code:
$error[0] Description: $error[1]");
}
1507
ircg_get_username
(PHP 4 >= 4.1.0)
ircg_get_username - Get username for connection
Description
string ircg_get_username (resource connection)
Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection
died or is not valid.
1508
ircg_html_encode
(PHP 4 >= 4.0.5)
ircg_html_encode - Encodes HTML preserving output
Description
bool ircg_html_encode (string html_string)
Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.
1509
ircg_ignore_add
(PHP 4 >= 4.0.5)
ircg_ignore_add - Add a user to your ignore list on a server
Description
bool ircg_ignore_add (resource connection, string nick)
This function adds user nick to the ignore list of connection connection. Afterwards, IRCG will suppress all messages from
this user through the associated connection.
See also: ircg_ignore_del().
1510
ircg_ignore_del
(PHP 4 >= 4.0.5)
ircg_ignore_del - Remove a user from your ignore list on a server
Description
bool ircg_ignore_del (resource connection, string nick)
This function removes user nick from the IRCG ignore list associated with connection.
See also: ircg_ignore_add().
1511
ircg_is_conn_alive
(PHP 4 >= 4.0.5)
ircg_is_conn_alive - Check connection status
Description
bool ircg_is_conn_alive (resource connection)
ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some
reason.
1512
ircg_join
(PHP 4 >= 4.0.4)
ircg_join - Join a channel on a connected server
Description
bool ircg_join (resource connection, string channel [, string key])
Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.
1513
ircg_kick
(PHP 4 >= 4.0.5)
ircg_kick - Kick a user out of a channel on server
Description
bool ircg_kick (resource connection, string channel, string nick, string reason)
Kick user nick from channel on server connected to by connection. reason should give a short message describing why this
action was performed.
1514
ircg_lookup_format_messages
(PHP 4 >= 4.0.5)
ircg_lookup_format_messages - Check for the existence of a format message set
Description
bool ircg_lookup_format_messages (string name)
Check for the existence of the format message set name. Sets may be registered with ircg_register_format_messages(), a
default set named ircg is always available. Returns TRUE, if the set exists and FALSE otherwise.
See also: ircg_register_format_messages()
1515
ircg_msg
(PHP 4 >= 4.0.4)
ircg_msg - Send message to channel or user on server
Description
bool ircg_msg (resource connection, string recipient, string message [, boolean suppress])
ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with #
or & will send the message to a channel, anything else will be interpreted as a username.
Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This
so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.
1516
ircg_nick
(PHP 4 >= 4.0.5)
ircg_nick - Change nickname on server
Description
bool ircg_nick (resource connection, string nick)
Change your nickname on the given connection to the one given in nick, if possible.
Will return TRUE on success and FALSE on failure.
1517
ircg_nickname_escape
(PHP 4 >= 4.0.6)
ircg_nickname_escape - Encode special characters in nickname to be IRC-compliant
Description
string ircg_nickname_escape (string nick)
Function ircg_nickname_escape() returns an encoded nickname specified by nick which is IRC-compliant.
See also: ircg_nickname_unescape()
1518
ircg_nickname_unescape
(PHP 4 >= 4.0.6)
ircg_nickname_unescape - Decodes encoded nickname
Description
string ircg_nickname_unescape (string nick)
Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.
See also: ircg_nickname_escape()
1519
ircg_notice
(PHP 4 >= 4.0.5)
ircg_notice - Send a notice to a user on server
Description
bool ircg_notice (resource connection, string , string message)
This function will send the message text to the user nick on the server connected to by connection. IRC servers and other
software will not automatically generate replies to NOTICEs in contrast to other message types.
1520
ircg_part
(PHP 4 >= 4.0.4)
ircg_part - Leave a channel on server
Description
bool ircg_part (resource connection, string channel)
Leave the channel channel on the server connected to by connection.
1521
ircg_pconnect
(PHP 4 >= 4.0.4)
ircg_pconnect - Connect to an IRC server
Description
resource ircg_pconnect (string username [, string server_ip [, int server_port [, string msg_format [, array
ctcp_messages [, array user_settings]]]]])
ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.
The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are
optional and default to 127.0.0.1 and 6667.
Note: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.
You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.
If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the
CTCP type and the respective value is the format message.
You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.
See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().
1522
ircg_register_format_messages
(PHP 4 >= 4.0.5)
ircg_register_format_messages - Register a format message set
Description
bool ircg_register_format_messages (string name, array messages)
With ircg_register_format_messages() you can customize the way your IRC output looks like or which script functions
are invoked on the client side.
•
Plain channel message
•
Private message received
•
Private message sent
•
Some user leaves channel
•
Some user enters channel
•
Some user was kicked from the channel
•
Topic has been changed
•
Error
•
Fatal error
•
Join list end(?)
•
Self part(?)
•
Some user changes his nick
•
Some user quits his connection
•
Mass join begin
•
Mass join element
•
Mass join end
•
Whois user
•
Whois server
•
Whois idle
•
Whois channel
•
Whois end
•
Voice status change on user
1523
ircg_register_format_messages
•
Operator status change on user
•
Banlist
•
Banlist end
•
%f - from
•
%t - to
•
%c - channel
•
%r - plain message
•
%m - encoded message
•
%j - js encoded message
•
1 - mod encode
•
2 - nickname decode
See also: ircg_lookup_format_messages().
1524
ircg_set_current
(PHP 4 >= 4.0.4)
ircg_set_current - Set current connection for output
Description
bool ircg_set_current (resource connection)
Select the current HTTP connection for output in this execution context. Every output sent from the server connected to by
connection will be copied to standard output while using default formatting or a format message set specified by ircg_register_format_messages().
See also: ircg_register_format_messages().
1525
ircg_set_file
(PHP 4 >= 4.2.0)
ircg_set_file - Set logfile for connection
Description
bool ircg_set_file (resource connection, string path)
Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns
TRUE on success, otherwise FALSE.
1526
ircg_set_on_die
(PHP 4 >= 4.2.0)
ircg_set_on_die - Set action to be executed when connection dies
Description
bool ircg_set_on_die (resource connection, string host, int port, string data)
In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address,
IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a PHP script for example.
This feature requires IRCG 3.
1527
ircg_topic
(PHP 4 >= 4.0.5)
ircg_topic - Set topic for channel on server
Description
bool ircg_topic (resource connection, string channel, string new_topic)
Change the topic for channel channel on the server connected to by connection to new_topic.
1528
ircg_whois
(PHP 4 >= 4.0.5)
ircg_whois - Query server for user information
Description
bool ircg_whois (resource connection, string nick)
Sends a query to the connected server connection to ask for information about the specified user nick.
1529
PHP / Java Integration
Table of Contents
java_last_exception_clear .................................................................................................................. 1534
java_last_exception_get .................................................................................................................... 1535
1530
Introduction
There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is
the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP.
The JVM is created using JNI, and everything runs in-process.
Warning
This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and
anything else documented about this extension -- may change without notice in a future release of PHP. Use this
extension at your own risk.
Requirements
You need a Java VM installed on your machine to use this extension.
Installation
To include Java support in your PHP build you must add the option --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared dl. More build instructions for this extension can be
found in php4/ext/java/README.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy jvm.dll from the
DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine.
(Ex:C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 81. Java configuration options
Name
Default
Changeable
java.class.path
NULL
PHP_INI_ALL
java.home
NULL
PHP_INI_ALL
java.library.path
NULL
PHP_INI_ALL
java.library
JAVALIB
PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().
Resource Types
This extension has no resource types defined.
Predefined Constants
This extension has no constants defined.
1531
PHP / Java Integration
Examples
Example 414. Java Example
getProperty('java.version').'
';
print 'Java vendor=' .$system->getProperty('java.vendor').'
';
print 'OS='.$system->getProperty('os.name').' '.
$system->getProperty('os.version').' on '.
$system->getProperty('os.arch').'
';
// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
"EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");
print $formatter->format(new Java('java.util.Date'));
?>
Example 415. AWT Example
add('North', $button);
$frame->validate();
$frame->pack();
$frame->visible = True;
$thread = new Java('java.lang.Thread');
$thread->sleep(10000);
$frame->dispose();
?>
Notes:
•
new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the
default constructor is useful as it provides access to classes like java.lang.System which expose most of their func-
tionallity through static methods.
•
Accessing a member of an instance will first look for bean properties then public fields. In other words, print
$date.time will first attempt to be resolved as $date.getTime(), then as $date.time.
•
Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is
of type java.lang.Class, then static members of the class (fields and methods) can be accessed.
•
Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method
call with an "@" sign. The following APIs may be used to retrieve and reset the last error:
•
java_last_exception_get()
1532
PHP / Java Integration
•
•
java_last_exception_clear()
Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP
Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.
Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.
Once a method is selected, the parameters are cooerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).
•
In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may
only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these
constructs are passed by value, so may be expensive in terms of memory and time.
Java Servlet SAPI
The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be
run as a servlet. The primary advanatage of this from a PHP perspective is that web servers which support servlets typically
take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in
php4/sapi/README. Notes:
•
While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to
date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.
•
PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running
the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.
1533
java_last_exception_clear
(PHP 4 >= 4.0.2)
java_last_exception_clear - Clear last Java exception
Description
void java_last_exception_clear (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
See java_last_exception_get() for an example.
1534
java_last_exception_get
(PHP 4 >= 4.0.2)
java_last_exception_get - Get last Java exception
Description
exception java_last_exception_get (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
The following example demonstrates the usage of Java's exception handler from within PHP:
Example 416. Java exception handler
push(1);
// This should succeed
$result = $stack->pop();
$ex = java_last_exception_get();
if (!$ex) print "$result\n";
// This should fail (error suppressed by @)
$result = @$stack->pop();
$ex = java_last_exception_get();
if ($ex) print $ex->toString();
// Clear last exception
java_last_exception_clear();
?>
1535
LDAP functions
Table of Contents
ldap_8859_to_t61 ............................................................................................................................ 1541
ldap_add ........................................................................................................................................ 1542
ldap_bind ....................................................................................................................................... 1543
ldap_close ...................................................................................................................................... 1545
ldap_compare .................................................................................................................................. 1546
ldap_connect ................................................................................................................................... 1547
ldap_count_entries ........................................................................................................................... 1548
ldap_delete ..................................................................................................................................... 1549
ldap_dn2ufn .................................................................................................................................... 1550
ldap_err2str ..................................................................................................................................... 1551
ldap_errno ...................................................................................................................................... 1552
ldap_error ....................................................................................................................................... 1553
ldap_explode_dn .............................................................................................................................. 1554
ldap_first_attribute ........................................................................................................................... 1555
ldap_first_entry ............................................................................................................................... 1556
ldap_first_reference .......................................................................................................................... 1557
ldap_free_result ............................................................................................................................... 1558
ldap_get_attributes ........................................................................................................................... 1559
ldap_get_dn .................................................................................................................................... 1560
ldap_get_entries ............................................................................................................................... 1561
ldap_get_option ............................................................................................................................... 1562
ldap_get_values_len ......................................................................................................................... 1563
ldap_get_values ............................................................................................................................... 1564
ldap_list ......................................................................................................................................... 1565
ldap_mod_add ................................................................................................................................. 1566
ldap_mod_del .................................................................................................................................. 1567
ldap_mod_replace ............................................................................................................................ 1568
ldap_modify .................................................................................................................................... 1569
ldap_next_attribute ........................................................................................................................... 1570
ldap_next_entry ............................................................................................................................... 1571
ldap_next_reference ......................................................................................................................... 1572
ldap_parse_reference ........................................................................................................................ 1573
ldap_parse_result ............................................................................................................................. 1574
ldap_read ........................................................................................................................................ 1575
ldap_rename ................................................................................................................................... 1576
ldap_search ..................................................................................................................................... 1577
ldap_set_option ............................................................................................................................... 1579
ldap_set_rebind_proc ........................................................................................................................ 1580
ldap_sort ........................................................................................................................................ 1581
ldap_start_tls ................................................................................................................................... 1582
ldap_t61_to_8859 ............................................................................................................................ 1583
ldap_unbind .................................................................................................................................... 1584
1536
Introduction
LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is
a special kind of database that holds information in a tree structure.
The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and
the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.
To refer to a file in a subdirectory on your hard disk, you might use something like:
/usr/local/myapp/docs
The forwards slash marks each division in the reference, and the sequence is read from left to right.
The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:
cn=John
Smith,ou=Accounts,o=My
Company,c=US
The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:
country
organization
organizationalUnit
commonName
=
=
My
=
=
John
US
Company
Accounts
Smith
In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server
manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The
message is that you can not write code to access a directory server unless you know something about its structure, any more
than you can use a database without some knowledge of what is available.
Lots of information about LDAP can be found at
•
Netscape [http://developer.netscape.com/tech/directory/]
•
OpenLDAP Project [http://www.openldap.org/]
•
LDAP World [http://www.innosoft.com/ldapworld/]
The Netscape SDK contains a helpful Programmer's Guide [http://docs.sun.com/source/816-5616-10/] in HTML format.
Requirements
You will need to get and compile LDAP client libraries from either the University of Michigan ldap-3.3 package [ftp://terminator.rs.itd.umich.edu/ ldap/ ldap-3.3.tar.Z], Netscape Directory SDK 3.0 [http:/ / developer.netscape.com/ tech/ directory/
1537
LDAP functions
downloads.html] or OpenLDAP [ftp://ftp.openldap.org/pub/openldap/openldap-stable.tgz] to compile PHP with LDAP support.
Installation
LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when
compiling PHP to enable LDAP support. DIR is the LDAP base install directory.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libsasl.dll from
the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex:
C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 82. LDAP configuration options
Name
Default
Changeable
ldap.max_links
"-1"
PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().
Resource Types
This extension has no resource types defined.
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
LDAP_DEREF_NEVER (integer)
LDAP_DEREF_SEARCHING (integer)
LDAP_DEREF_FINDING (integer)
LDAP_DEREF_ALWAYS (integer)
LDAP_OPT_DEREF (integer)
LDAP_OPT_SIZELIMIT (integer)
LDAP_OPT_TIMELIMIT (integer)
LDAP_OPT_PROTOCOL_VERSION (integer)
LDAP_OPT_ERROR_NUMBER (integer)
LDAP_OPT_REFERRALS (integer)
LDAP_OPT_RESTART (integer)
1538
LDAP functions
LDAP_OPT_HOST_NAME (integer)
LDAP_OPT_ERROR_STRING (integer)
LDAP_OPT_MATCHED_DN (integer)
LDAP_OPT_SERVER_CONTROLS (integer)
LDAP_OPT_CLIENT_CONTROLS (integer)
LDAP_OPT_DEBUG_LEVEL (integer)
GSLC_SSL_NO_AUTH (integer)
GSLC_SSL_ONEWAY_AUTH (integer)
GSLC_SSL_TWOWAY_AUTH (integer)
Examples
Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with
name and email address.
Example 417. LDAP search example
LDAP query test";
echo "Connecting ...";
$ds=ldap_connect("localhost"); // must be a valid LDAP server!
echo "connect result is ".$ds."";
if ($ds) {
echo "Binding ...";
$r=ldap_bind($ds);
// this is an "anonymous" bind, typically
// read-only access
echo "Bind result is ".$r."
";
echo "Searching for (sn=S*) ...";
// Search surname entry
$sr=ldap_search($ds,"o=My Company, c=US", "sn=S*");
echo "Search result is ".$sr."
";
echo "Number of entires returned is ".ldap_count_entries($ds,$sr)."
";
echo "Getting entries ...
";
$info = ldap_get_entries($ds, $sr);
echo "Data for ".$info["count"]." items returned:
";
for ($i=0; $i<$info["count"]; $i++) {
echo "dn is: ". $info[$i]["dn"] ."
";
echo "first cn entry is: ". $info[$i]["cn"][0] ."
";
echo "first email entry is: ". $info[$i]["mail"][0] ."
";
}
echo "Closing connection";
ldap_close($ds);
} else {
echo "
Unable to connect to LDAP server
";
}
?>
1539
LDAP functions
Using the PHP LDAP calls
Before you can use the LDAP calls you will need to know ..
•
The name or address of the directory server you will use
•
The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")
•
Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but
require a password for anything else)
The typical sequence of LDAP calls you will make in an application will follow this pattern:
ldap_connect()
//
ldap_bind()
do
//
something
and
establish
connection
anonymous
like
search
display
ldap_close()
or
authenticated
or
update
the
//
1540
to
the
server
|
"login"
|
directory
results
|
"logout"
ldap_8859_to_t61
(PHP 4 >= 4.0.2)
ldap_8859_to_t61 - Translate 8859 characters to t61 characters
Description
string ldap_8859_to_t61 (string value)
Warning
This function is currently not documented; only the argument list is available.
1541
ldap_add
(PHP 3, PHP 4 )
ldap_add - Add entries to LDAP directory
Description
bool ldap_add (resource link_identifier, string dn, array entry)
Returns TRUE on success or FALSE on failure.
The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn.
Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case
of multiple values for an attribute, they are indexed using integers starting with 0.
entry["attribute1"]
entry["attribute2"][0]
entry["attribute2"][1]
=
=
=
Example 418. Complete example with authenticated bind
1542
value
value1
value2
ldap_bind
(PHP 3, PHP 4 )
ldap_bind - Bind to LDAP directory
Description
bool ldap_bind (resource link_identifier [, string bind_rdn [, string bind_password]])
Binds to the LDAP directory with specified RDN and password. Returns TRUE on success or FALSE on failure.
ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous
bind is attempted.
Example 419. Using LDAP Bind
Example 420. Using LDAP Bind Anonymously
1544
ldap_close
(PHP 3, PHP 4 )
ldap_close - Close link to LDAP server
Description
bool ldap_close (resource link_identifier)
Returns TRUE on success or FALSE on failure.
ldap_close() closes the link to the LDAP server that's associated with the specified link_identifier.
This call is internally identical to ldap_unbind(). The LDAP API uses the call ldap_unbind(), so perhaps you should use
this in preference to ldap_close().
Note: This function is an alias of ldap_unbind().
1545
ldap_compare
(PHP 4 >= 4.0.2)
ldap_compare - Compare value of attribute found in entry specified with DN
Description
bool ldap_compare (resource link_identifier, string dn, string attribute, string value)
Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.
ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.
The following example demonstrates how to check whether or not given password matches the one defined in DN specified
entry.
Example 421. Complete example of password check
Warning
ldap_compare() can NOT be used to compare BINARY values!
Note: This function was added in 4.0.2.
1546
ldap_connect
(PHP 3, PHP 4 )
ldap_connect - Connect to an LDAP server
Description
resource ldap_connect ([string hostname [, int port]])
Returns a positive LDAP link identifier on success, or FALSE on error.
ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is
specified, then the port defaults to 389.
If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and use ldaps://hostname/ as host parameter. The port parameter is
not used when using URLs.
Note: URL and SSL support were added in 4.0.4.
Example 422. Example of connecting to LDAP server.
Example 423. Example of connecting securely to LDAP server.
1547
ldap_count_entries
(PHP 3, PHP 4 )
ldap_count_entries - Count the number of entries in a search
Description
int ldap_count_entries (resource link_identifier, resource result_identifier)
Returns number of entries in the result or FALSE on error.
ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.
1548
ldap_delete
(PHP 3, PHP 4 )
ldap_delete - Delete an entry from a directory
Description
bool ldap_delete (resource link_identifier, string dn)
Returns TRUE on success or FALSE on failure.
ldap_delete() function delete a particular entry in LDAP directory specified by dn.
1549
ldap_dn2ufn
(PHP 3, PHP 4 )
ldap_dn2ufn - Convert DN to User Friendly Naming format
Description
string ldap_dn2ufn (string dn)
ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.
1550
ldap_err2str
(PHP 3>= 3.0.13, PHP 4 )
ldap_err2str - Convert LDAP error number into string error message
Description
string ldap_err2str (int errno)
Returns string error message.
This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message
text, but always use an error number to check.
See also ldap_errno() and ldap_error().
Example 424. Enumerating all LDAP error messages
\n", ldap_err2str($i));
}
?>
1551
ldap_errno
(PHP 3>= 3.0.12, PHP 4 )
ldap_errno - Return the LDAP error number of the last LDAP command
Description
int ldap_errno (resource link_identifier)
Return the LDAP error number of the last LDAP command for this link.
This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This
number can be converted into a textual error message using ldap_err2str().
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters
to suppress warning output, the errors generated will also show up in your HTML output.
Example 425. Generating and catching an error
\n", ldap_errno($ld));
printf("LDAP-Error: %s
\n", ldap_error($ld));
die("Argh!
\n");
}
$info = ldap_get_entries($ld, $res);
printf("%d matching entries.
\n", $info["count"]);
?>
See also ldap_err2str() and ldap_error().
1552
ldap_error
(PHP 3>= 3.0.12, PHP 4 )
ldap_error - Return the LDAP error message of the last LDAP command
Description
string ldap_error (resource link_identifier)
Returns string error message.
This function returns the string error message explaining the error generated by the last LDAP command for the given
link_identifier While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to
suppress warning output, the errors generated will also show up in your HTML output.
See also ldap_err2str() and ldap_errno().
1553
ldap_explode_dn
(PHP 3, PHP 4 )
ldap_explode_dn - Splits DN into its component parts
Description
array ldap_explode_dn (string dn, int with_attrib)
ldap_explode_dn() function is used to split the DN returned by ldap_get_dn() and breaks it up into its component parts.
Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components.
with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.
1554
ldap_first_attribute
(PHP 3, PHP 4 )
ldap_first_attribute - Return first attribute
Description
string ldap_first_attribute (resource link_identifier, resource result_entry_identifier, int ber_identifier)
Returns the first attribute in the entry on success and FALSE on error.
Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first
attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling
ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.
See also ldap_get_attributes()
1555
ldap_first_entry
(PHP 3, PHP 4 )
ldap_first_entry - Return first result id
Description
resource ldap_first_entry (resource link_identifier, resource result_identifier)
Returns the result entry identifier for the first entry on success and FALSE on error.
Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions.
ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to
ldap_next_entry() routine to get successive entries from the result.
See also ldap_get_entries().
1556
ldap_first_reference
(PHP 4 >= 4.0.5)
ldap_first_reference - Return first reference
Description
resource ldap_first_reference (resource link, resource result)
Warning
This function is currently not documented; only the argument list is available.
1557
ldap_free_result
(PHP 3, PHP 4 )
ldap_free_result - Free result memory
Description
bool ldap_free_result (resource result_identifier)
Returns TRUE on success or FALSE on failure.
ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result
memory will be automatically freed when the script terminates.
Typically all the memory allocated for the ldap result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the
script low.
1558
ldap_get_attributes
(PHP 3, PHP 4 )
ldap_get_attributes - Get attributes from a search result entry
Description
array ldap_get_attributes (resource link_identifier, resource result_entry_identifier)
Returns a complete entry information in a multi-dimensional array on success and FALSE on error.
ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The
return value is a multi-dimensional array of attributes and values.
Having located a specific entry in the directory, you can find out what information is held for that entry by using this call.
You would use this call for an application which "browses" directory entries and/or where you do not know the structure of
the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.
return_value["count"]
return_value[0]
return_value[n]
=
return_value["attribute"]["count"]
return_value["attribute"][0]
return_value["attribute"][i]
number
=
=
=
=
=
of
number
first
(i+1)th
attributes
first
nth
of
value
value
in
values
of
of
Example 426. Show the list of attributes held for a particular directory entry
// $ds is the link identifier for the directory
// $sr is a valid search result from a prior call to
// one of the ldap directory search calls
$entry = ldap_first_entry($ds, $sr);
$attrs = ldap_get_attributes($ds, $entry);
echo $attrs["count"]." attributes held for this entry:";
for ($i=0; $i<$attrs["count"]; $i++)
echo $attrs[$i]."
";
See also ldap_first_attribute() and ldap_next_attribute()
1559
the
for
the
the
entry
attribute
attribute
attribute
attribute
attribute
ldap_get_dn
(PHP 3, PHP 4 )
ldap_get_dn - Get the DN of a result entry
Description
string ldap_get_dn (resource link_identifier, resource result_entry_identifier)
Returns the DN of the result entry and FALSE on error.
ldap_get_dn() function is used to find out the DN of an entry in the result.
1560
ldap_get_entries
(PHP 3, PHP 4 )
ldap_get_entries - Get all result entries
Description
array ldap_get_entries (resource link_identifier, resource result_identifier)
Returns a complete result information in a multi-dimenasional array on success and FALSE on error.
ldap_get_entries() function is used to simplify reading multiple entries from the result, specified with result_identifier, and
then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.
The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)
return_value["count"]
return_value[0]
=
:
return_value[i]["dn"]
return_value[i]["count"]
return_value[i][j]
=
number
to
refers
=
DN
of
=
jth
number
attribute
return_value[i]["attribute"]["count"]
=
attribute
jth
return_value[i]["attribute"][j]
=
of
the
entries
details
the
ith
of
in
number
of
in
See also ldap_first_entry() and ldap_next_entry()
1561
entry
attributes
ith
the
value
in
of
of
the
first
in
in
entry
in
values
ith
attribute
in
result
entry
the
result
ith
the
entry
result
for
ith
entry
entry
ldap_get_option
(PHP 4 >= 4.0.4)
ldap_get_option - Get the current value for given option
Description
bool ldap_get_option (resource link_identifier, int option, mixed retval)
Sets retval to the value of the specified option. Returns TRUE on success or FALSE on failure.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT,
LDAP_OPT_PROTOCOL_VERSION,
LDAP_OPT_ERROR_NUMBER,
LDAP_OPT_REFERRALS,
LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN.
These are described in draft-ietf-ldapext-ldap-c-api-xx.txt [http:/ / www.openldap.org/ devel/ cvsweb.cgi/ ~checkout~/ doc/
drafts/draft-ietf-ldapext-ldap-c-api-xx.txt]
Note: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4
Example 427. Check protocol version
// $ds is a valid link identifier for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version))
echo "Using protocol version $version";
else
echo "Unable to determine protocol version";
See also ldap_set_option().
1562
ldap_get_values_len
(PHP 3>= 3.0.13, PHP 4 )
ldap_get_values_len - Get all binary values from a result entry
Description
array ldap_get_values_len (resource link_identifier, resource result_entry_identifier, string attribute)
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by
the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values
are accessed by integer index in the array. The first index is 0.
This function is used exactly like ldap_get_values() except that it handles binary data and not string data.
Note: This function was added in 4.0.
1563
ldap_get_values
(PHP 3, PHP 4 )
ldap_get_values - Get all values from a result entry
Description
array ldap_get_values (resource link_identifier, resource result_entry_identifier, string attribute)
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the
result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are
accessed by integer index in the array. The first index is 0.
This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get
an individual entry.
You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use
the ldap_get_attributes() call to work out what attributes exist for a given entry.
LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's
directory entry all labeled with the attribute "mail"
return_value["count"]
return_value[0]
return_value[i]
=
=
=
number
first
ith
of
values
value
value
Example 428. List all values of the "mail" attribute for a directory entry
// $ds is a valid link identifier for a directory server
// $sr is a valid search result from a prior call to
//
one of the ldap directory search calls
// $entry is a valid entry identifier from a prior call to
//
one of the calls that returns a directory entry
$values = ldap_get_values($ds, $entry,"mail");
echo $values["count"]." email addresses for this entry.
";
for ($i=0; $i < $values["count"]; $i++)
echo $values[$i]."
";
1564
for
of
of
attribute
attribute
attribute
ldap_list
(PHP 3, PHP 4 )
ldap_list - Single-level search
Description
resource ldap_list (resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int
sizelimit [, int timelimit [, int deref]]]]])
Returns a search result identifier or FALSE on error.
ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.
LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below
the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)
This call takes 5 optional parameters. See ldap_search() notes.
Note: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
Example 429. Produce a list of all organizational units of an organization
// $ds is a valid link identifier for a directory server
$basedn = "o=My Company, c=US";
$justthese = array("ou");
$sr=ldap_list($ds, $basedn, "ou=*", $justthese);
$info = ldap_get_entries($ds, $sr);
for ($i=0; $i<$info["count"]; $i++)
echo $info[$i]["ou"][0] ;
Note: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
1565
ldap_mod_add
(PHP 3>= 3.0.8, PHP 4 )
ldap_mod_add - Add attribute values to current attributes
Description
bool ldap_mod_add (resource link_identifier, string dn, array entry)
Returns TRUE on success or FALSE on failure.
This function adds attribute(s) to the specified dn. It performs the modification at the attribute level as opposed to the object
level. Object-level additions are done by the ldap_add() function.
1566
ldap_mod_del
(PHP 3>= 3.0.8, PHP 4 )
ldap_mod_del - Delete attribute values from current attributes
Description
bool ldap_mod_del (resource link_identifier, string dn, array entry)
Returns TRUE on success or FALSE on failure.
This function removes attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the
object level. Object-level deletions are done by the ldap_delete() function.
1567
ldap_mod_replace
(PHP 3>= 3.0.8, PHP 4 )
ldap_mod_replace - Replace attribute values with new ones
Description
bool ldap_mod_replace (resoure link_identifier, string dn, array entry)
Returns TRUE on success or FALSE on failure.
This function replaces attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the
object level. Object-level modifications are done by the ldap_modify() function.
1568
ldap_modify
(PHP 3, PHP 4 )
ldap_modify - Modify an LDAP entry
Description
bool ldap_modify (resource link_identifier, string dn, array entry)
Returns TRUE on success or FALSE on failure.
ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in
ldap_add().
1569
ldap_next_attribute
(PHP 3, PHP 4 )
ldap_next_attribute - Get the next attribute in result
Description
string ldap_next_attribute (resource link_identifier, resource result_entry_identifier, resource ber_identifier)
Returns the next attribute in an entry on success and FALSE on error.
ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the
ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().
See also ldap_get_attributes()
1570
ldap_next_entry
(PHP 3, PHP 4 )
ldap_next_entry - Get next result entry
Description
resource ldap_next_entry (resource link_identifier, resource result_entry_identifier)
Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there
are no more entries in the result then it returns FALSE.
ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to
ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().
See also ldap_get_entries()
1571
ldap_next_reference
(PHP 4 >= 4.0.5)
ldap_next_reference - Get next reference
Description
resource ldap_next_reference (resource link, resource entry)
Warning
This function is currently not documented; only the argument list is available.
1572
ldap_parse_reference
(PHP 4 >= 4.0.5)
ldap_parse_reference - Extract information from reference entry
Description
bool ldap_parse_reference (resource link, resource entry, array referrals)
Warning
This function is currently not documented; only the argument list is available.
1573
ldap_parse_result
(PHP 4 >= 4.0.5)
ldap_parse_result - Extract information from result
Description
bool ldap_parse_result (resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals)
Warning
This function is currently not documented; only the argument list is available.
1574
ldap_read
(PHP 3, PHP 4 )
ldap_read - Read an entry
Description
resource ldap_read (resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int
sizelimit [, int timelimit [, int deref]]]]])
Returns a search result identifier or FALSE on error.
ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.
An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".
This call takes 5 optional parameters. See ldap_search() notes.
Note: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
1575
ldap_rename
(PHP 4 >= 4.0.5)
ldap_rename - Modify the name of an entry
Description
bool ldap_rename (resource link_identifier, string dn, string newrdn, string newparent, bool deleteoldrdn)
The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is
specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s)
is retained as non-distinguished values of the entry. Returns TRUE on success or FALSE on failure.
Note: This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding
to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x,
and was added in PHP 4.0.5.
1576
ldap_search
(PHP 3, PHP 4 )
ldap_search - Search LDAP tree
Description
resource ldap_search (resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int
sizelimit [, int timelimit [, int deref]]]]])
Returns a search result identifier or FALSE on error.
ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This
is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.
There is a optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just
those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.
The fourth parameter is a standard PHP string array of the required attributes, eg array("mail","sn","cn") Note that the "dn"
is always returned irrespective of which attributes types are requested.
Note too that some directory server hosts will be configured to return no more than a preset number of entries. If this occurs,
the server will indicate that it has only returned a partial results set. This occurs also if the sixth parameter sizelimit has been
used to limit the count of fetched entries.
The fifth parameter attrsonly should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.
With the sixth parameter sizelimit it is possible to limit the count of entries fetched. Setting this to 0 means no limit. NOTE:
This parameter can NOT override server-side preset sizelimit. You can set it lower though.
The seventh parameter timelimit sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset timelimit. You can set it lower though.
The eigth parameter deref specifies how aliases should be handled during the search. It can be one of the following:
•
LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
•
LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object
of the search.
•
LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
•
LDAP_DEREF_ALWAYS - aliases should be dereferenced always.
Note: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
The search filter can be simple or advanced, using boolean operators in the format described in the LDAP doumentation
(see the Netscape Directory SDK [http://developer.netscape.com/docs/manuals/directory/41/ag/find.htm] for full information on filters).
The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server
1577
ldap_search
to look for information in more than one attribute.
Example 430. LDAP search
// $ds is a valid link identifier for a directory server
// $person is all or part of a person's name, eg "Jo"
$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array( "ou", "sn", "givenname", "mail");
$sr=ldap_search($ds, $dn, $filter, $justthese);
$info = ldap_get_entries($ds, $sr);
print $info["count"]." entries returned
";
From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single
identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use
an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the
first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel
searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search
will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a
search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an
identifier.
1578
ldap_set_option
(PHP 4 >= 4.0.4)
ldap_set_option - Set the value of the given option
Description
bool ldap_set_option (resource link_identifier, int option, mixed newval)
Sets the value of the specified option to be newval. Returns TRUE on success or FALSE on failure. on error.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT,
LDAP_OPT_PROTOCOL_VERSION,
LDAP_OPT_ERROR_NUMBER,
LDAP_OPT_REFERRALS,
LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN,
LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS. Here's a brief description, see draftietf-ldapext-ldap-c-api-xx.txt [http:/ / www.openldap.org/ devel/ cvsweb.cgi/ ~checkout~/ doc/ drafts/ draftietf-ldapext-ldap-c-api-xx.txt] for details.
The
options
LDAP_OPT_DEREF,
LDAP_OPT_SIZELIMIT,
LDAP_OPT_TIMELIMIT,
LDAP_OPT_PROTOCOL_VERSION
and
LDAP_OPT_ERROR_NUMBER
have
integer
value,
LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have boolean value, and the options LDAP_OPT_HOST_NAME,
LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN have string value. The first example illustrates their
use. The options LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls,
this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value,
and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string
value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean
value. iscritical defaults to FALSE if not supplied. See also the second example below.
Note: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4.
Example 431. Set protocol version
// $ds is a valid link identifier for a directory server
if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
echo "Using LDAPv3";
else
echo "Failed to set protocol version to 3";
Example 432. Set server controls
// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => TRUE);
// iscritical defaults to FALSE
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2)))
echo "Failed to set server controls";
See also ldap_get_option().
1579
ldap_set_rebind_proc
(PHP 4 >= 4.2.0)
ldap_set_rebind_proc - Set a callback function to do re-binds on referral chasing.
Description
bool ldap_set_rebind_proc (resource link, string callback)
Warning
This function is currently not documented; only the argument list is available.
1580
ldap_sort
(PHP 4 >= 4.2.0)
ldap_sort - Sort LDAP result entries
Description
bool ldap_sort (resource link, resource result, string sortfilter)
Warning
This function is currently not documented; only the argument list is available.
1581
ldap_start_tls
(PHP 4 >= 4.2.0)
ldap_start_tls - Start TLS
Description
bool ldap_start_tls (resource link)
Warning
This function is currently not documented; only the argument list is available.
1582
ldap_t61_to_8859
(PHP 4 >= 4.0.2)
ldap_t61_to_8859 - Translate t61 characters to 8859 characters
Description
string ldap_t61_to_8859 (string value)
Warning
This function is currently not documented; only the argument list is available.
1583
ldap_unbind
(PHP 3, PHP 4 )
ldap_unbind - Unbind from LDAP directory
Description
bool ldap_unbind (resource link_identifier)
Returns TRUE on success or FALSE on failure.
ldap_unbind() function unbinds from the LDAP directory.
1584
Mail functions
Table of Contents
ezmlm_hash .................................................................................................................................... 1588
mail ............................................................................................................................................... 1589
1585
Introduction
The mail() function allows you to send mail.
Requirements
No external libraries are needed to build this extension.
Installation
There is no installation needed to use these functions; they are part of the PHP core.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 83. Mail configuration options
Name
Default
Changeable
SMTP
"localhost"
PHP_INI_ALL
smtp_port
"25"
PHP_INI_ALL
sendmail_from
NULL
PHP_INI_ALL
sendmail_path
DEFAULT_SENDMAIL_PATH
PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().
Here's a short explanation of the configuration directives.
SMTP string
Used under Windows only: DNS name or IP address of the SMTP server PHP should use for mail sent with the mail()
function.
smtp_port int
Used under Windows only: Number of the port to connect to the server specified with the SMTP setting when sending
mail with mail(); defaults to 25. Only available since PHP 4.3.0.
sendmail_from string
Which "From:" mail address should be used in mail sent from PHP under Windows.
sendmail_path string
Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail. configure does
an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.
Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if
any. For example, Qmail [http:/ / www.qmail.org/ ] users can normally set it to /var/qmail/bin/sendmail or /
var/qmail/bin/qmail-inject.
qmail-inject does not require any option to process mail correctly.
1586
Mail functions
Resource Types
This extension has no resource types defined.
Predefined Constants
This extension has no constants defined.
1587
ezmlm_hash
(PHP 3>= 3.0.17, PHP 4 >= 4.0.2)
ezmlm_hash - Calculate the hash value needed by EZMLM
Description
int ezmlm_hash (string addr)
ezmlm_hash() calculates the hash value needed when keeping EZMLM mailing lists in a MySQL database.
Example 433. Calculating the hash and subscribing a user
$user = "joecool@example.com";
$hash = ezmlm_hash ($user);
$query = sprintf ("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // using PHPLIB db interface
1588
mail
(PHP 3, PHP 4 )
mail - send mail
Description
bool mail (string to, string subject, string message [, string additional_headers [, string additional_parameters]])
mail() automatically mails the message specified in message to the receiver specified in to. Multiple recipients can be specified by putting a comma between each address in to. Email with attachments and special types of content can be sent using
this function. This is accomplished via MIME-encoding - for more information, see this Zend article [http://www.zend.com/
zend/spotlight/sendmimeemailpart1.php] or the PEAR Mime Classes [http://pear.php.net/Mail_Mime].
The following RFC's may also be useful: RFC 1896 [http://www.faqs.org/rfcs/rfc1896], RFC 2045 [http://www.faqs.org/
rfcs/ rfc2045], RFC 2046 [http:/ / www.faqs.org/ rfcs/ rfc2046], RFC 2047 [http:/ / www.faqs.org/ rfcs/ rfc2047], RFC 2048
[http://www.faqs.org/rfcs/rfc2048], and RFC 2049 [http://www.faqs.org/rfcs/rfc2049].
mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
Warning
The Windows implementation of mail() differs in many ways from the Unix implementation. First, it doesn't use a
local binary for composing messages but only operates on direct sockets which means a MTA is needed listening on
a network socket (which can either on the localhost or a remote machine). Second, the custom headers like From:,
Cc:, Bcc: and Date: are not interpreted by the MTA in the first place, but are parsed by PHP. PHP < 4.3 only supported the Cc: header element (and was case-sensitive). PHP >= 4.3 supports all the mentioned header elements
and is no longer case-sensitive.
Example 434. Sending mail.
If a fourth string argument is passed, this string is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a carriage return and newline.
Note: You must use \r\n to separate headers, although some Unix mail transfer agents may work with just a
single newline (\n).
Example 435. Sending mail with extra headers.
The additional_parameters parameter can be used to pass an additional parameter to the program configured to use when
1589
mail
sending mail using the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option. You may need to add the user that your web server runs as to your
sendmail configuration to prevent a 'X-Warning' header from being added to the message when you set the envelope sender
using this method.
Example 436. Sending mail with extra headers and setting an additional command line parameter.
Note: This fifth parameter was added in PHP 4.0.5. Since PHP 4.2.3 this parameter is disabled in safe_mode and
the mail() function will expose a warning message and return FALSE if you're trying to use it.
You can also use simple string building techniques to build complex email messages.
Example 437. Sending complex email.
" . ", " ; // note the comma
$to .= "Kelly ";
/* subject */
$subject = "Birthday Reminders for August";
/* message */
$message = '
Birthday Reminders for August
Here are the birthdays upcoming in August!
Person | Day | Month | Year |
Joe | 3rd | August | 1970 |
Sally | 17th | August | 1973 |
';
/* To send HTML mail, you can set the Content-type header. */
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
/* additional headers */
$headers .= "From: Birthday Reminder \r\n";
$headers .= "Cc: birthdayarchive@example.com\r\n";
$headers .= "Bcc: birthdaycheck@example.com\r\n";
/* and now mail it */
mail($to, $subject, $message, $headers);
?>
1590
mail
Note: Make sure you do not have any newline characters in the to or subject, or the mail may not be sent properly.
Note: The to parameter cannot be an address in the form of "Something ". The mail
command will not parse this properly while talking with the MTA.
See also imap_mail().
1591
mailparse functions
Table of Contents
mailparse_determine_best_xfer_encoding ............................................................................................. 1594
mailparse_msg_create ....................................................................................................................... 1595
mailparse_msg_extract_part_file ......................................................................................................... 1596
mailparse_msg_extract_part ............................................................................................................... 1597
mailparse_msg_free .......................................................................................................................... 1598
mailparse_msg_get_part_data ............................................................................................................. 1599
mailparse_msg_get_part .................................................................................................................... 1600
mailparse_msg_get_structure ............................................................................................................. 1601
mailparse_msg_parse_file .................................................................................................................. 1602
mailparse_msg_parse ........................................................................................................................ 1603
mailparse_rfc822_parse_addresses ...................................................................................................... 1604
mailparse_stream_encode .................................................................................................................. 1605
mailparse_uudecode_all .................................................................................................................... 1606
1592
Introduction
Warning
This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and
anything else documented about this extension -- may change without notice in a future release of PHP. Use this
extension at your own risk.
This extension has been moved from PHP as of PHP 4.2.0 and now mailparse lives in PECL [http://pear.php.net/mailparse].
Installation
These functions are only available if PHP was configured with --with-aspell[=DIR].
1593
mailparse_determine_best_xfer_encoding
(4.1.0 - 4.1.2 only)
mailparse_determine_best_xfer_encoding - Figures out the best way of encoding the content read from
the file pointer fp, which must be seek-able
Description
int mailparse_determine_best_xfer_encoding (resource fp)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1594
mailparse_msg_create
(4.1.0 - 4.1.2 only)
mailparse_msg_create - Returns a handle that can be used to parse a message
Description
int mailparse_msg_create (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1595
mailparse_msg_extract_part_file
(4.1.0 - 4.1.2 only)
mailparse_msg_extract_part_file - Extracts/decodes a message section, decoding the transfer encoding
Description
string mailparse_msg_extract_part_file (resource rfc2045, string filename [, string callbackfunc])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1596
mailparse_msg_extract_part
(4.1.0 - 4.1.2 only)
mailparse_msg_extract_part - Extracts/decodes a message section. If callbackfunc is not specified, the
contents will be sent to "stdout"
Description
void mailparse_msg_extract_part (resource rfc2045, string msgbody [, string callbackfunc])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1597
mailparse_msg_free
(4.1.0 - 4.1.2 only)
mailparse_msg_free - Frees a handle allocated by mailparse_msg_crea
Description
void mailparse_msg_free (resource rfc2045buf)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1598
mailparse_msg_get_part_data
(4.1.0 - 4.1.2 only)
mailparse_msg_get_part_data - Returns an associative array of info about the message
Description
array mailparse_msg_get_part_data (resource rfc2045)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1599
mailparse_msg_get_part
(4.1.0 - 4.1.2 only)
mailparse_msg_get_part - Returns a handle on a given section in a mimemessage
Description
int mailparse_msg_get_part (resource rfc2045, string mimesection)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1600
mailparse_msg_get_structure
(4.1.0 - 4.1.2 only)
mailparse_msg_get_structure - Returns an array of mime section names in the supplied message
Description
array mailparse_msg_get_structure (resource rfc2045)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1601
mailparse_msg_parse_file
(4.1.0 - 4.1.2 only)
mailparse_msg_parse_file - Parse file and return a resource representing the structure
Description
resource mailparse_msg_parse_file (string filename)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1602
mailparse_msg_parse
(4.1.0 - 4.1.2 only)
mailparse_msg_parse - Incrementally parse data into buffer
Description
void mailparse_msg_parse (resource rfc2045buf, string data)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1603
mailparse_rfc822_parse_addresses
(4.1.0 - 4.1.2 only)
mailparse_rfc822_parse_addresses - Parse addresses and returns a hash containing that data
Description
array mailparse_rfc822_parse_addresses (string addresses)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1604
mailparse_stream_encode
(4.1.0 - 4.1.2 only)
mailparse_stream_encode - Streams data from source file pointer, apply encoding and write to destfp
Description
bool mailparse_stream_encode (resource sourcefp, resource destfp, string encoding)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1605
mailparse_uudecode_all
()
mailparse_uudecode_all - Scans the data from fp and extract each embedded uuencoded file. Returns
an array listing filename information
Description
array mailparse_uudecode_all (resource fp)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1606
Mathematical Functions
Table of Contents
abs ................................................................................................................................................ 1610
acos ............................................................................................................................................... 1611
acosh ............................................................................................................................................. 1612
asin ............................................................................................................................................... 1613
asinh .............................................................................................................................................. 1614
atan2 ............................................................................................................................................. 1615
atan ............................................................................................................................................... 1616
atanh ............................................................................................................................................. 1617
base_convert ................................................................................................................................... 1618
bindec ............................................................................................................................................ 1619
ceil ................................................................................................................................................ 1620
cos ................................................................................................................................................ 1621
cosh ............................................................................................................................................... 1622
decbin ............................................................................................................................................ 1623
dechex ........................................................................................................................................... 1624
decoct ............................................................................................................................................ 1625
deg2rad .......................................................................................................................................... 1626
exp ................................................................................................................................................ 1627
expm1 ............................................................................................................................................ 1628
floor .............................................................................................................................................. 1629
fmod .............................................................................................................................................. 1630
getrandmax ..................................................................................................................................... 1631
hexdec ........................................................................................................................................... 1632
hypot ............................................................................................................................................. 1633
is_finite .......................................................................................................................................... 1634
is_infinite ....................................................................................................................................... 1635
is_nan ............................................................................................................................................ 1636
lcg_value ........................................................................................................................................ 1637
log10 ............................................................................................................................................. 1638
log1p ............................................................................................................................................. 1639
log ................................................................................................................................................ 1640
max ............................................................................................................................................... 1641
min ............................................................................................................................................... 1642
mt_getrandmax ................................................................................................................................ 1643
mt_rand .......................................................................................................................................... 1644
mt_srand ........................................................................................................................................ 1645
octdec ............................................................................................................................................ 1646
pi .................................................................................................................................................. 1647
pow ............................................................................................................................................... 1648
rad2deg .......................................................................................................................................... 1649
rand ............................................................................................................................................... 1650
round ............................................................................................................................................. 1651
sin ................................................................................................................................................. 1652
sinh ............................................................................................................................................... 1653
sqrt ................................................................................................................................................ 1654
srand ............................................................................................................................................. 1655
tan ................................................................................................................................................. 1656
tanh ............................................................................................................................................... 1657
1607
Introduction
These math functions will only handle values within the range of the integer and float types on your computer (this corresponds currently to the C types long resp. double). If you need to handle bigger numbers, take a look at the arbitrary precision math functions.
See also the manual page on arithmetic operators.
Requirements
No external libraries are needed to build this extension.
Installation
There is no installation needed to use these functions; they are part of the PHP core.
Runtime Configuration
This extension has no configuration directives defined in php.ini.
Resource Types
This extension has no resource types defined.
Predefined Constants
The constants below are always available as part of the PHP core.
Table 84. Math constants
Constant
Value
Description
M_PI
3.14159265358979323846
Pi
M_E
2.7182818284590452354
e
M_LOG2E
1.4426950408889634074
log_2 e
M_LOG10E
0.43429448190325182765
log_10 e
M_LN2
0.69314718055994530942
log_e 2
M_LN10
2.30258509299404568402
log_e 10
M_PI_2
1.57079632679489661923
pi/2
M_PI_4
0.78539816339744830962
pi/4
M_1_PI
0.31830988618379067154
1/pi
M_2_PI
0.63661977236758134308
2/pi
M_SQRTPI
1.77245385090551602729
sqrt(pi) [4.0.2]
M_2_SQRTPI
1.12837916709551257390
2/sqrt(pi)
M_SQRT2
1.41421356237309504880
sqrt(2)
M_SQRT3
1.73205080756887729352
sqrt(3) [4.0.2]
M_SQRT1_2
0.70710678118654752440
1/sqrt(2)
1608
Mathematical Functions
Constant
Value
Description
M_LNPI
1.14472988584940017414
log_e(pi) [4.0.2]
M_EULER
0.57721566490153286061
Euler constant [4.0.2]
Only M_PI is available in PHP versions up to and including PHP 4.0.0. All other constants are available starting with PHP
4.0.0. Constants labeled [4.0.2] were added in PHP 4.0.2.
1609
abs
(PHP 3, PHP 4 )
abs - Absolute value
Description
mixed abs (mixed number)
Returns the absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).
Example 438. abs() example
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);
// $abs2 = 5; (integer)
$abs3 = abs(-5); // $abs3 = 5; (integer)
1610
acos
(PHP 3, PHP 4 )
acos - Arc cosine
Description
float acos (float arg)
Returns the arc cosine of arg in radians. acos() is the complementary function of cos(), which means that
a==cos(acos(a)) for every value of a that is within acos()' range.
See also acosh(), asin() and atan().
1611
acosh
(PHP 4 >= 4.1.0)
acosh - Inverse hyperbolic cosine
Description
float acosh (float arg)
Returns the inverse hyperbolic cosine of arg, i.e. the value whose hyperbolic cosine is arg.
Note: This function is not implemented on Windows platforms.
See also acos(), asinh() and atanh().
1612
asin
(PHP 3, PHP 4 )
asin - Arc sine
Description
float asin (float arg)
Returns the arc sine of arg in radians. asin() is the complementary function of sin(), which means that a==sin(asin(a))
for every value of a that is within asin()'s range.
See also asinh(), acos() and atan().
1613
asinh
(PHP 4 >= 4.1.0)
asinh - Inverse hyperbolic sine
Description
float asinh (float arg)
Returns the inverse hyperbolic sine of arg, i.e. the value whose hyperbolic sine is arg.
Note: This function is not implemented on Windows platforms.
See also asin(), acosh() and atanh().
1614
atan2
(PHP 3>= 3.0.5, PHP 4 )
atan2 - arc tangent of two variables
Description
float atan2 (float y, float x)
This function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.
The function returns the result in radians, which is between -PI and PI (inclusive).
See also acos() and atan().
1615
atan
(PHP 3, PHP 4 )
atan - Arc tangent
Description
float atan (float arg)
Returns the arc tangent of arg in radians. atan() is the complementary function of tan(), which means that
a==tan(atan(a)) for every value of a that is within atan()'s range.
See also atanh(), asin() and acos().
1616
atanh
(PHP 4 >= 4.1.0)
atanh - Inverse hyperbolic tangent
Description
float atanh (float arg)
Returns the inverse hyperbolic tangent of arg, i.e. the value whose hyperbolic tangent is arg.
Note: This function is not implemented on Windows platforms.
See also atan(), asinh() and acosh().
1617
base_convert
(PHP 3>= 3.0.6, PHP 4 )
base_convert - Convert a number between arbitrary bases
Description
string base_convert (string number, int frombase, int tobase)
Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase.
Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.
Example 439. base_convert()
$binary = base_convert ($hexadecimal, 16, 2);
1618
bindec
(PHP 3, PHP 4 )
bindec - Binary to decimal
Description
int bindec (string binary_string)
Returns the decimal equivalent of the binary number represented by the binary_string argument.
bindec() converts a binary number to an integer. The largest number that can be converted is 31 bits of 1's or 2147483647 in
decimal.
See also: decbin().
1619
ceil
(PHP 3, PHP 4 )
ceil - Round fractions up
Description
float ceil (float value)
Returns the next highest integer value by rounding up value if necessary. The return value of ceil() is still of type float as the
value range of float is usually bigger than that of integer.
Example 440. ceil() example
echo ceil(4.3);
echo ceil(9.999);
// 5
// 10
See also floor() and round().
1620
cos
(PHP 3, PHP 4 )
cos - Cosine
Description
float cos (float arg)
cos() returns the cosine of the arg parameter. The arg parameter is in radians.
See also acos(), sin() tan() and deg2rad().
1621
cosh
(PHP 4 >= 4.1.0)
cosh - Hyperbolic cosine
Description
float cosh (float arg)
Returns the hyperbolic cosine of arg, defined as (exp(arg) + exp(-arg))/2.
See also cos(), acosh(), sin() and tan().
1622
decbin
(PHP 3, PHP 4 )
decbin - Decimal to binary
Description
string decbin (int number)
Returns a string containing a binary representation of the given number argument. The largest number that can be converted
is 4294967295 in decimal resulting to a string of 32 1's.
See also: bindec().
1623
dechex
(PHP 3, PHP 4 )
dechex - Decimal to hexadecimal
Description
string dechex (int number)
Returns a string containing a hexadecimal representation of the given number argument. The largest number that can be
converted is 2147483647 in decimal resulting to "7fffffff".
See also hexdec().
1624
decoct
(PHP 3, PHP 4 )
decoct - Decimal to octal
Description
string decoct (int number)
Returns a string containing an octal representation of the given number argument. The largest number that can be converted
is 2147483647 in decimal resulting to "17777777777".
See also octdec().
1625
deg2rad
(PHP 3>= 3.0.4, PHP 4 )
deg2rad - Converts the number in degrees to the radian equivalent
Description
float deg2rad (float number)
This function converts number from degrees to the radian equivalent.
See also rad2deg().
1626
exp
(PHP 3, PHP 4 )
exp - Calculates the exponent of e (the Neperian or Natural logarithm base)
Description
float exp (float arg)
Returns e raised to the power of arg.
See also log() and pow().
1627
expm1
(PHP 4 >= 4.1.0)
expm1 - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is
close to zero
Description
float expm1 (float number)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1628
floor
(PHP 3, PHP 4 )
floor - Round fractions down
Description
float floor (float value)
Returns the next lowest integer value by rounding down value if necessary. The return value of floor() is still of type float
because the value range of float is usually bigger than that of integer.
Example 441. floor() example
echo floor(4.3);
// 4
echo floor(9.999); // 9
See also ceil() and round().
1629
fmod
(PHP 4 >= 4.2.0)
fmod - Returns the floating point remainder (modulo) of the division of the arguments
Description
float fmod (float x, float y)
Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y
+ r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.
Example 442. Using fmod()
$x
$y
$r
//
= 5.7;
= 1.3;
= fmod($x, $y);
$r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
1630
getrandmax
(PHP 3, PHP 4 )
getrandmax - Show largest possible random value
Description
int getrandmax (void)
Returns the maximum value that can be returned by a call to rand().
See also rand(), srand() and mt_getrandmax().
1631
hexdec
(PHP 3, PHP 4 )
hexdec - Hexadecimal to decimal
Description
int hexdec (string hex_string)
Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. hexdec() converts a
hexadecimal string to a decimal number. The largest number that can be converted is 7fffffff or 2147483647 in decimal.
hexdec() will replace of any non-hexadecimal characters it encounters by 0. This way, all left zeros are ignored, but right
zeros will be valued.
Example 443. hexdec() example
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both prints "int(238)"
var_dump(hexdec("that"));
var_dump(hexdec("a0"));
// both prints int(160)
See also dechex().
1632
hypot
(PHP 4 >= 4.1.0)
hypot - Returns sqrt( num1*num1 + num2*num2)
Description
float hypot (float num1, float num2)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1633
is_finite
(PHP 4 >= 4.2.0)
is_finite -
Description
bool is_finite (float val)
Returns TRUE if val is a legal finite number within the allowed range for a PHP float on this platform.
1634
is_infinite
(PHP 4 >= 4.2.0)
is_infinite -
Description
bool is_infinite (float val)
Returns TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this
platform.
1635
is_nan
(PHP 4 >= 4.2.0)
is_nan -
Description
bool is_nan (float val)
Returns TRUE if val is 'not a number', like the result of acos(1.01).
1636
lcg_value
(PHP 4 )
lcg_value - Combined linear congruential generator
Description
float lcg_value (void)
lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 85 and 2^31 - 249. The period of this function is equal to the product of both primes.
1637
log10
(PHP 3, PHP 4 )
log10 - Base-10 logarithm
Description
float log10 (float arg)
Returns the base-10 logarithm of arg.
1638
log1p
(PHP 4 >= 4.1.0)
log1p - Returns log(1 + number), computed in a way that accurate even when the val ue of number is
close to zero
Description
float log1p (float number)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
Warning
This function is currently not documented; only the argument list is available.
1639
log
(PHP 3, PHP 4 )
log - Natural logarithm
Description
float log (float arg [, float base])
If the optional base parameter is specified, log() returns logbase arg, otherwise log() returns the natural logarithm of arg.
Note: The base parameter became available with PHP version 4.3.0.
As always you can calculate the logarithm in base b of a number n, but using the mathematical identity: logb(n) =
log(n)/log(b), where log is the neperian (or natural) logarithm.
See also exp().
1640
max
(PHP 3, PHP 4 )
max - Find highest value
Description
number max (mixed arg1, mixed arg2, mixed argn)
max() returns the numerically highest of the parameter values.
If the first parameter is an array, max() returns the highest value in that array. If the first parameter is an integer, string or
float, you need at least two parameters and max() returns the biggest of these values. You can compare an unlimited number
of values.
If one or more of the values is a float, all the values will be treated as floats, and a float is returned. If none of the values is a
float, all of them will be treated as integers, and an integer is returned.
See also min().
1641
min
(PHP 3, PHP 4 )
min - Find lowest value
Description
number min (number arg1, number arg2 [, ...])
number min (array numbers)
min() returns the numerically lowest of the parameter values.
In the first variant, you need at least two parameters and min() returns the lowest of these values. You can compare an unlimited number of values. If one of the variables is undefined, min() will fail.
In the second variant, min() returns the lowest value in numbers.
If one or more of the values is a float, all the values will be treated as floats, and a float is returned. If none of the values is a
float, all of them will be treated as integers, and an integer is returned. Upon failure, min() returns NULL and an error of
level E_WARNING is generated.
See also max().
1642
mt_getrandmax
(PHP 3>= 3.0.6, PHP 4 )
mt_getrandmax - Show largest possible random value
Description
int mt_getrandmax (void)
Returns the maximum value that can be returned by a call to mt_rand().
See also mt_rand(), mt_srand() and getrandmax().
1643
mt_rand
(PHP 3>= 3.0.6, PHP 4 )
mt_rand - Generate a better random value
Description
int mt_rand ([int min, int max])
Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses
the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. It
uses a random number generator with known characteristics using the Mersenne Twister [http:/ / www.math.keio.ac.jp/
~matumoto/emt.html], which will produce random numbers that should be suitable for seeding some kinds of cryptography
(see the home page for details) and is four times faster than what the average libc provides.
If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and RAND_MAX. If
you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5, 15).
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is
now done automatically.
Note: In versions before 3.0.7 the meaning of max was range. To get the same results in these versions the short
example should be mt_rand (5, 11) to get a random number between 5 and 15.
See also mt_srand(), mt_getrandmax() and rand().
1644
mt_srand
(PHP 3>= 3.0.6, PHP 4 )
mt_srand - Seed the better random number generator
Description
void mt_srand (int seed)
Seeds the random number generator with seed.
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is
now done automatically.
See also mt_rand(), mt_getrandmax() and srand().
1645
octdec
(PHP 3, PHP 4 )
octdec - Octal to decimal
Description
int octdec (string octal_string)
Returns the decimal equivalent of the octal number represented by the octal_string argument. The largest number that can
be converted is 17777777777 or 2147483647 in decimal.
See also decoct().
1646
pi
(PHP 3, PHP 4 )
pi - Get value of pi
Description
float pi (void)
Returns an approximation of pi. The returned float has a precision based on the precision directive in php.ini, which defaults to 14. Also, you can use the M_PI constant which yields identical results to pi().
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
1647
pow
(PHP 3, PHP 4 )
pow - Exponential expression
Description
number pow (number base, number exp)
Returns base raised to the power of exp. If possible, this function will return an integer.
If the power cannot be computed, a warning will be issued, and pow() will return FALSE.
Example 444. Some examples of pow()
Warning
In PHP 4.0.6 and earlier pow() always returned a float, and did not issue warnings.
See also exp() and sqrt().
1648
rad2deg
(PHP 3>= 3.0.4, PHP 4 )
rad2deg - Converts the radian number to the equivalent number in degrees
Description
float rad2deg (float number)
This function converts number from radian to degrees.
See also deg2rad().
1649
rand
(PHP 3, PHP 4 )
rand - Generate a random value
Description
int rand ([int min, int max])
If called without the optional min, max arguments rand() returns a pseudo-random value between 0 and RAND_MAX. If you
want a random number between 5 and 15 (inclusive), for example, use rand (5, 15).
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is
now done automatically.
Note: In versions before 3.0.7 the meaning of max was range. To get the same results in these versions the short
example should be rand (5, 11) to get a random number between 5 and 15.
See also srand(), getrandmax(), and mt_rand().
1650
round
(PHP 3, PHP 4 )
round - Rounds a float
Description
float round (float val [, int precision])
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Caution
PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.
echo
echo
echo
echo
echo
echo
round(3.4);
round(3.5);
round(3.6);
round(3.6, 0);
round(1.95583, 2);
round(1241757, -3);
//
//
//
//
//
//
3
4
4
4
1.96
1242000
Note: The precision parameter is only available in PHP 4.
See also ceil() and floor().
1651
sin
(PHP 3, PHP 4 )
sin - Sine
Description
float sin (float arg)
sin() returns the sine of the arg parameter. The arg parameter is in radians.
See also asin(), cos(), tan() and deg2rad().
1652
sinh
(PHP 4 >= 4.1.0)
sinh - Hyperbolic sine
Description
float sinh (float arg)
Returns the hyperbolic sine of arg, defined as (exp(arg) - exp(-arg))/2.
See also sin(), asinh(), cos() and tan().
1653
sqrt
(PHP 3, PHP 4 )
sqrt - Square root
Description
float sqrt (float arg)
Returns the square root of arg.
See also pow().
1654
srand
(PHP 3, PHP 4 )
srand - Seed the random number generator
Description
void srand (int seed)
Seeds the random number generator with seed.
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is
now done automatically.
See also rand(), getrandmax() and mt_srand().
1655
tan
(PHP 3, PHP 4 )
tan - Tangent
Description
float tan (float arg)
tan() returns the tangent of the arg parameter. The arg parameter is in radians.
See also atan(), sin(), cos() and deg2rad().
1656
tanh
(PHP 4 >= 4.1.0)
tanh - Hyperbolic tangent
Description
float tanh (float arg)
Returns the hyperbolic tangent of arg, defined as sinh(arg)/cosh(arg).
See also tan(), atanh(), sin() and cos().
1657
Multi-Byte String Functions
Table of Contents
mb_convert_case ............................................................................................................................. 1667
mb_convert_encoding ....................................................................................................................... 1668
mb_convert_kana ............................................................................................................................. 1669
mb_convert_variables ....................................................................................................................... 1670
mb_decode_mimeheader ................................................................................................................... 1671
mb_decode_numericentity ................................................................................................................. 1672
mb_detect_encoding ......................................................................................................................... 1673
mb_detect_order .............................................................................................................................. 1674
mb_encode_mimeheader ................................................................................................................... 1675
mb_encode_numericentity ................................................................................................................. 1676
mb_ereg_match ............................................................................................................................... 1677
mb_ereg_replace .............................................................................................................................. 1678
mb_ereg_search_getpos .................................................................................................................... 1679
mb_ereg_search_getregs .................................................................................................................... 1680
mb_ereg_search_init ......................................................................................................................... 1681
mb_ereg_search_pos ......................................................................................................................... 1682
mb_ereg_search_regs ........................................................................................................................ 1683
mb_ereg_search_setpos ..................................................................................................................... 1684
mb_ereg_search ............................................................................................................................... 1685
mb_ereg ......................................................................................................................................... 1686
mb_eregi_replace ............................................................................................................................. 1687
mb_eregi ........................................................................................................................................ 1688
mb_get_info .................................................................................................................................... 1689
mb_http_input ................................................................................................................................. 1690
mb_http_output ............................................................................................................................... 1691
mb_internal_encoding ....................................................................................................................... 1692
mb_language ................................................................................................................................... 1693
mb_output_handler ........................................................................................................................... 1694
mb_parse_str ................................................................................................................................... 1695
mb_preferred_mime_name ................................................................................................................ 1696
mb_regex_encoding ......................................................................................................................... 1697
mb_regex_set_options ...................................................................................................................... 1698
mb_send_mail ................................................................................................................................. 1699
mb_split ......................................................................................................................................... 1700
mb_strcut ....................................................................................................................................... 1701
mb_strimwidth ................................................................................................................................ 1702
mb_strlen ....................................................................................................................................... 1703
mb_strpos ....................................................................................................................................... 1704
mb_strrpos ...................................................................................................................................... 1705
mb_strtolower ................................................................................................................................. 1706
mb_strtoupper ................................................................................................................................. 1707
mb_strwidth .................................................................................................................................... 1708
mb_substitute_character .................................................................................................................... 1709
mb_substr_count .............................................................................................................................. 1710
mb_substr ....................................................................................................................................... 1711
1658
Introduction
There are many languages in which all characters can be expressed by single byte. Multi-byte character codes are used to
express many characters for many languages. mbstring is developed to handle Japanese characters. However, many mbstring functions are able to handle character encoding other than Japanese.
A multi-byte character encoding represents single character with consecutive bytes. Some character encoding has
shift(escape) sequences to start/end multi-byte character strings. Therefore, a multi-byte character string may be destroyed
when it is divided and/or counted unless multi-byte character encoding safe method is used. This module provides multibyte character safe string functions and other utility functions such as conversion functions.
Since PHP is basically designed for ISO-8859-1, some multi-byte character encoding does not work well with PHP. Therefore, it is important to set mbstring.internal_encoding to a character encoding that works with PHP.
PHP4 Character Encoding Requirements
•
Per byte encoding
•
Single byte characters in range of 00h-7fh which is compatible with ASCII
•
Multi-byte characters without 00h-7fh
These are examples of internal character encoding that works with PHP and does NOT work with PHP.
Character encodings work with PHP:
ISO-8859-*, EUC-JP, UTF-8
Character encodings do NOT work with PHP:
JIS, SJIS
Character encoding, that does not work with PHP, may be converted with mbstring's HTTP input/output conversion feature/function.
Note: SJIS should not be used for internal encoding unless the reader is familiar with parser/compiler, character
encoding and character encoding issues.
Note: If you use databases with PHP, it is recommended that you use the same character encoding for both database and internal encoding for ease of use and better performance.
If you are using PostgreSQL, it supports character encoding that is different from backend character encoding. See
the PostgreSQL manual for details.
Installation
mbstring is an extended module. You must enable the module with the configure script. Refer to the Install section for
details.
The following configure options are related to the mbstring module.
•
--enable-mbstring=LANG: Enable mbstring functions. This option is required to use mbstring functions.
As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean,
and Russian in addition to Japanese. To enable that feature, you will have to supply either one of the following options
1659
Multi-Byte String Functions
to the LANG parameter; --enable-mbstring=cn for Simplified Chinese support, --enable-mbstring=tw for Traditional Chinese support, --enable-mbstring=kr for Korean support, --enable-mbstring=ru for Russian support,
and --enable-mbstring=ja for Japanese support.
Also --enable-mbstring=all is convenient for you to enable all the supported languages listed above.
Note: Japanese language support is also enabled by --enable-mbstring without any options for the sake of
backwards compatibility.
•
--enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding
automatically.
Note: As of PHP 4.3.0, the option --enable-mbstr-enc-trans will be eliminated and replaced with mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On
(the default is Off).
•
--enable-mbregex: Enable regular expression functions with multibyte character support.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 85. Multi-Byte String configuration options
Name
Default
Changeable
mbstring.language
NULL
PHP_INI_ALL
mbstring.detect_order
NULL
PHP_INI_ALL
mbstring.http_input
NULL
PHP_INI_ALL
mbstring.http_output
NULL
PHP_INI_ALL
mbstring.internal_encoding
NULL
PHP_INI_ALL
mbstring.script_encoding
NULL
PHP_INI_ALL
mbstring.substitute_character
NULL
PHP_INI_ALL
mbstring.func_overload
"0"
PHP_INI_SYSTEM
mbstring.encoding_translation
"0"
PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().
Here's a short explanation of the configuration directives.
•
mbstring.language defines default language used in mbstring. Note that this option defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language
in php.ini
•
mbstring.encoding_translation enables HTTP input character encoding detection and translation into internal
chatacter encoding.
•
mbstring.internal_encoding defines default internal character encoding.
•
mbstring.http_input defines default HTTP input character encoding.
1660
Multi-Byte String Functions
•
mbstring.http_output defines default HTTP output character encoding.
•
mbstring.detect_order defines default character code detection order. See also mb_detect_order().
•
mbstring.substitute_character defines character to substitute for invalid character encoding.
•
mbstring.func_overloadoverload(replace) single byte functions by mbstring functions. mail(), ereg(), etc. are over-
loaded by mb_send_mail(), mb_ereg(), etc. Possible values are 0, 1, 2, 4 or a combination of them. For example, 7 for
overload everything. 0: No overload, 1: Overload mail() function, 2: Overload str*() functions, 4: Overload ereg*()
functions.
Web Browsers are supposed to use the same character encoding when submitting form. However, browsers may not use the
same character encoding. See mb_http_input() to detect character encoding used by browsers.
If enctype is set to multipart/form-data in HTML forms, mbstring does not convert character encoding in POST
data. The user must convert them in the script, if conversion is needed.
Although, browsers are smart enough to detect character encoding in HTML. charset is better to be set in HTTP header.
Change default_charset according to character encoding.
Example 445. php.ini setting example
; Set default language
mbstring.language
mbstring.language
= English; Set default language to English (default)
= Japanese; Set default language to Japanese
;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding
= UTF-8 ; Set internal encoding to UTF-8
;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On
;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input
= pass
; No conversion.
mbstring.http_input
= auto
; Set HTTP input to auto
; "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
mbstring.http_input
= SJIS
; Set HTTP2 input to SJIS
mbstring.http_input
= UTF-8,SJIS,EUC-JP ; Specify order
;; Set default HTTP output character encoding
mbstring.http_output
= pass
; No conversion
mbstring.http_output
= UTF-8
; Set HTTP output encoding to UTF-8
;; Set default character encoding detection order
mbstring.detect_order
= auto
; Set detect order to auto
mbstring.detect_order
= ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order
;; Set default substitute character
mbstring.substitute_character = 12307
mbstring.substitute_character = none
mbstring.substitute_character = long
; Specify Unicode value
; Do not print character
; Long Example: U+3000,JIS+7E7E
Example 446. php.ini setting for EUC-JP users
;; Disable Output Buffering
output_buffering
= Off
;; Set HTTP header charset
1661
Multi-Byte String Functions
default_charset
= EUC-JP
;; Set default language to Japanese
mbstring.language = Japanese
;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On
;; Set HTTP input encoding conversion to auto
mbstring.http_input
= auto
;; Convert HTTP output to EUC-JP
mbstring.http_output = EUC-JP
;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP
;; Do not print invalid characters
mbstring.substitute_character = none
Example 447. php.ini setting for SJIS users
;; Enable Output Buffering
output_buffering
= On
;; Set mb_output_handler to enable output conversion
output_handler
= mb_output_handler
;; Set HTTP header charset
default_charset
= Shift_JIS
;; Set default language to Japanese
mbstring.language = Japanese
;; Set http input encoding conversion to auto
mbstring.http_input = auto
;; Convert to SJIS
mbstring.http_output = SJIS
;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP
;; Do not print invalid characters
mbstring.substitute_character = none
Resource Types
This extension has no resource types defined.
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
MB_OVERLOAD_MAIL (integer)
MB_OVERLOAD_STRING (integer)
1662
Multi-Byte String Functions
MB_OVERLOAD_REGEX (integer)
HTTP Input and Output
HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.
If enctype for HTML form is set to multipart/form-data, mbstring does not convert character encoding in POST
data. If it is the case, strings are needed to be converted to internal character encoding.
•
HTTP Input
There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini.
Example 448. Disable HTTP input conversion in php.ini
;; Disable HTTP Input conversion
mbstring.http_input = pass
;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
mbstring.encoding_translation = Off
When using PHP as an Apache module, it is possible to override PHP ini setting per Virtual Host in httpd.conf or per
directory with .htaccess. Refer to the Configuration section and Apache Manual for details.
•
HTTP Output
There are several ways to enable output character encoding conversion. One is using php.ini, another is using
ob_start() with mb_output_handler() as ob_start callback function.
Note: For PHP3-i18n users, mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.
Example 449. php.ini setting example
;; Enable output character encoding conversion for all PHP pages
;; Enable Output Buffering
output_buffering
= On
;; Set mb_output_handler to enable output conversion
output_handler
= mb_output_handler
Example 450. Script example
Supported Character Encodings
Currently, the following character encoding is supported by the mbstring module. Character encoding may be specified
for mbstring functions' encoding parameter.
The following character encoding is supported in this PHP extension:
UCS-4, UCS-4BE, UCS-4LE, UCS-2, UCS-2BE, UCS-2LE, UTF-32, UTF-32BE, UTF-32LE, UCS-2LE, UTF-16, UTF-16BE,
UTF-16LE, UTF-8, UTF-7, ASCII, EUC-JP, SJIS, eucJP-win, SJIS-win, ISO-2022-JP, JIS, ISO-8859-1, ISO8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO8859-10, ISO-8859-13, ISO-8859-14, ISO-8859-15, byte2be, byte2le, byte4be, byte4le, BASE64, 7bit, 8bit
and UTF7-IMAP.
As of PHP 4.3.0, the following character encoding support will be added experimentally : EUC-CN, CP936, HZ, EUC-TW,
CP950, BIG-5, EUC-KR, UHC (CP949), ISO-2022-KR, Windows-1251 (CP1251), Windows-1252 (CP1252), CP866,
KOI8-R.
php.ini entry, which accepts encoding name, accepts "auto" and "pass" also. mbstring functions, which accepts encoding name, and accepts "auto".
If "pass" is set, no character encoding conversion is performed.
If "auto" is set, it is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS".
See also mb_detect_order()
Note: "Supported character encoding" does not mean that it works as internal character code.
Overloading PHP string functions with multi byte
string functions
Because almost PHP application written for language using single-byte character encoding, there are some difficulties for
multibyte string handling including japanese. Almost PHP string functions such as substr() do not support multibyte string.
Multibyte extension (mbstring) has some PHP string functions with multibyte support (ex. substr() supports mb_substr()).
Multibyte extension (mbstring) also supports 'function overloading' to add multibyte string functionality without code modification. Using function overloading, some PHP string functions will be oveloaded multibyte string functions. For example,
mb_substr() is called instead of substr() if function overloading is enabled. Function overload makes easy to port application supporting only single-byte encoding for multibyte application.
mbstring.func_overload in php.ini should be set some positive value to use function overloading. The value should
specify the category of overloading functions, sbould be set 1 to enable mail function overloading. 2 to enable string functions, 4 to regular expression functions. For example, if is set for 7, mail, strings, regex functions should be overloaded. The
list of overloaded functions are shown in below.
Table 86. Functions to be overloaded
1664
Multi-Byte String Functions
value of mbstring.func_overload
original function
overloaded function
1
mail()
mb_send_mail()
2
strlen()
mb_strlen()
2
strpos()
mb_strpos()
2
strrpos()
mb_strrpos()
2
substr()
mb_substr()
2
strtolower()
mb_strtolower()
2
strtoupper()
mb_strtoupper()
2
substr_count()
mb_substr_count()
4
ereg()
mb_ereg()
4
eregi()
mb_eregi()
4
ereg_replace()
mb_ereg_replace()
4
eregi_replace()
mb_eregi_replace()
4
split()
mb_split()
Basics of Japanese multi-byte characters
Most Japanese characters need more than 1 byte per character. In addition, several character encoding schemas are used under a Japanese environment. There are EUC-JP, Shift_JIS(SJIS) and ISO-2022-JP(JIS) character encoding. As Unicode becomes popular, UTF-8 is used also. To develop Web applications for a Japanese environment, it is important to use the
character set for the task in hand, whether HTTP input/output, RDBMS and E-mail.
•
Storage for a character can be up to six bytes
•
A multi-byte character is usually twice of the width compared to single-byte characters. Wider characters are called "zenkaku" - meaning full width, narrower characters are called "han-kaku" - meaning half width. "zen-kaku" characters are
usually fixed width.
•
Some character encoding defines shift(escape) sequence for entering/exiting multi-byte character strings.
•
ISO-2022-JP must be used for SMTP/NNTP.
•
"i-mode" web site is supposed to use SJIS.
References
Multi-byte character encoding and its related issues are very complex. It is impossible to cover in sufficient detail here.
Please refer to the following URLs and other resources for further readings.
•
Unicode/UTF/UCS/etc
http://www.unicode.org/
•
Japanese/Korean/Chinese character information
ftp://ftp.ora.com/pub/examples/nutshell/ujip/doc/cjk.inf
1665
Multi-Byte String Functions
1666
mb_convert_case
(PHP 4 >= 4.3.0)
mb_convert_case - Perform case folding on a string
Description
string mb_convert_case (string str, int mode [, string encoding])
mb_convert_case() returns case folded version of string converted in the way specified by mode.
mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
The return value is str with the appropriate case folding applied.
By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the
basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can
convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
Example 451. mb_convert_case() example
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
print $str; # Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
print $str; # Prints Mary Had A Little Lamb And She Loved It So
See also mb_strtolower(), mb_strtoupper(), strtolower(), strtoupper().
1667
mb_convert_encoding
(PHP 4 >= 4.0.6)
mb_convert_encoding - Convert character encoding
Description
string mb_convert_encoding (string str, string to-encoding [, mixed from-encoding])
mb_convert_encoding() converts character encoding of string str from from-encoding to to-encoding.
str : String to be converted.
from-encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.
Example 452. mb_convert_encoding() example
/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");
/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");
/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");
/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
See also: mb_detect_order().
1668
mb_convert_kana
(PHP 4 >= 4.0.6)
mb_convert_kana - Convert "kana" one from another ("zen-kaku" ,"han-kaku" and more)
Description
string mb_convert_kana (string str, string option [, mixed encoding])
mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is
only useful for Japanese.
option is conversion option. Default value is "KV".
encoding is character encoding. If it is omitted, internal character encoding is used.
Applicable Conversion Options
option : Specify with conversion of following options. Default "KV"
"r" : Convert "zen-kaku" alphabets to "han-kaku"
"R" : Convert "han-kaku" alphabets to "zen-kaku"
"n" : Convert "zen-kaku" numbers to "han-kaku"
"N" : Convert "han-kaku" numbers to "zen-kaku"
"a" : Convert "zen-kaku" alphabets and numbers to "han-kaku"
"A" : Convert "han-kaku" alphabets and numbers to "zen-kaku"
(Characters included in "a", "A" options are
U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
"s" : Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
"S" : Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
"k" : Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
"K" : Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
"h" : Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
"H" : Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
"c" : Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
"C" : Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
"V" : Collapse voiced sound notation and convert them into a character. Use with "K","H"
Example 453. mb_convert_kana() example
/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");
/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
1669
mb_convert_variables
(PHP 4 >= 4.0.6)
mb_convert_variables - Convert character code in variable(s)
Description
string mb_convert_variables (string to-encoding, mixed from-encoding, mixed vars)
mb_convert_variables() convert character encoding of variables vars in encoding from-encoding to encoding to-encoding.
It returns character encoding before conversion for success, FALSE for failure.
mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short
strings. Therefore, it is impossible to mix encoding in single array or object.
It from-encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.
vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted.
mb_convert_variables() assumes all parameters have the same encoding.
Example 454. mb_convert_variables() example
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
1670
mb_decode_mimeheader
(PHP 4 >= 4.0.6)
mb_decode_mimeheader - Decode string in MIME header field
Description
string mb_decode_mimeheader (string str)
mb_decode_mimeheader() decodes encoded-word string str in MIME header.
It returns decoded string in internal character encoding.
See also mb_encode_mimeheader().
1671
mb_decode_numericentity
(PHP 4 >= 4.0.6)
mb_decode_numericentity - Decode HTML numeric string reference to character
Description
string mb_decode_numericentity (string str, array convmap [, string encoding])
Convert numeric string reference of string str in specified block to character. It returns converted string.
array is array to specifies code area to convert.
encoding is character encoding. If it is omitted, internal character encoding is used.
Example 455. convmap example
$convmap = array (
int start_code1, int end_code1, int offset1, int mask1,
int start_code2, int end_code2, int offset2, int mask2,
........
int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.
See also: mb_encode_numericentity().
1672
mb_detect_encoding
(PHP 4 >= 4.0.6)
mb_detect_encoding - Detect character encoding
Description
string mb_detect_encoding (string str [, mixed encoding-list])
mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.
encoding-list is list of character encoding. Encoding order may be specified by array or comma separated list string.
If encoding_list is omitted, detect_order is used.
Example 456. mb_detect_encoding() example
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);
/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
echo mb_detect_encoding($str, "auto");
/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");
/* Use array to specify encoding_list
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);
*/
See also: mb_detect_order().
1673
mb_detect_order
(PHP 4 >= 4.0.6)
mb_detect_order - Set/Get character encoding detection order
Description
array mb_detect_order ([mixed encoding-list])
mb_detect_order() sets automatic character encoding detection order to encoding-list. It returns TRUE for success, FALSE
for failure.
encoding-list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP,
SJIS")
If encoding-list is omitted, it returns current character encoding detection order as array.
This setting affects mb_detect_encoding() and mb_send_mail().
Note: mbstring currently implements following encoding detection filters. If there is a invalid byte sequence for
following encoding, encoding detection will fail.
UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP
For ISO-8859-*, mbstring always detects as ISO-8859-*.
For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.
Example 457. Useless detect order example
; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8
; Always detect as UTF-8, since ASCII/UTF-7 values are
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7
Example 458. mb_detect_order() examples
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");
/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);
/* Display current detection order */
echo implode(", ", mb_detect_order());
See also mb_internal_encoding(), mb_http_input(), mb_http_output() mb_send_mail().
1674
mb_encode_mimeheader
(PHP 4 >= 4.0.6)
mb_encode_mimeheader - Encode string for MIME header
Description
string mb_encode_mimeheader (string str [, string charset [, string transfer-encoding [, string linefeed]]])
mb_encode_mimeheader() converts string str to encoded-word for header field. It returns converted string in ASCII encoding.
charset is character encoding name. Default is ISO-2022-JP.
transfer-encoding is transfer encoding. It should be one of "B" (Base64) or "Q" (Quoted-Printable). Default is "B".
linefeed is end of line marker. Default is "\r\n" (CRLF).
Example 459. mb_convert_kana() example
$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;
See also mb_decode_mimeheader().
1675
mb_encode_numericentity
(PHP 4 >= 4.0.6)
mb_encode_numericentity - Encode character to HTML numeric string reference
Description
string mb_encode_numericentity (string str, array convmap [, string encoding])
mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to
character code. It returns converted string.
array is array specifies code area to convert.
encoding is character encoding.
Example 460. convmap example
$convmap = array (
int start_code1, int end_code1, int offset1, int mask1,
int start_code2, int end_code2, int offset2, int mask2,
........
int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.
Example 461. mb_encode_numericentity() example
/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");
/* Convert user defined SJIS-win code in block 95-104 to numeric
string reference */
$convmap = array(
0xe000, 0xe03e, 0x1040, 0xffff,
0xe03f, 0xe0bb, 0x1041, 0xffff,
0xe0bc, 0xe0fa, 0x1084, 0xffff,
0xe0fb, 0xe177, 0x1085, 0xffff,
0xe178, 0xe1b6, 0x10c8, 0xffff,
0xe1b7, 0xe233, 0x10c9, 0xffff,
0xe234, 0xe272, 0x110c, 0xffff,
0xe273, 0xe2ef, 0x110d, 0xffff,
0xe2f0, 0xe32e, 0x1150, 0xffff,
0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");
See also: mb_decode_numericentity().
1676
mb_ereg_match
(4.2.0 - 4.3.2 only)
mb_ereg_match - Regular expression match for multibyte string
Description
bool mb_ereg_match (string pattern, string string [, string option])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_match() returns TRUE if string matches regular expression pattern, FALSE if not.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg().
1677
mb_ereg_replace
(4.2.0 - 4.3.2 only)
mb_ereg_replace - Replace regular expression with multibyte support
Description
string mb_ereg_replace (string pattern, string replacement, string string [, array option])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern.
Matching condition can be set by option parameter. If i is specified for this parameter, the case will be ignored. If x is specified, white space will be ignored. If m is specified, match will be executed in multiline mode and line break will be included in '.'. If p is specified, match will be executed in POSIX mode, line break will be considered as normal character. If e
is specified, replacement string will be evaluated as PHP expression.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_eregi_replace().
1678
mb_ereg_search_getpos
(4.2.0 - 4.3.2 only)
mb_ereg_search_getpos - Returns start point for next regular expression match
Description
array mb_ereg_search_getpos (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_search_getpos() returns the point to start regular expression match for mb_ereg_search(),
mb_ereg_search_pos(), mb_ereg_search_regs(). The position is represented by bytes from the head of string.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_search_setpos().
1679
mb_ereg_search_getregs
(4.2.0 - 4.3.2 only)
mb_ereg_search_getregs - Retrive the result from the last multibyte regular expression match
Description
array mb_ereg_search_getregs (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_search_getregs() returns an array including the sub-string of matched part by last mb_ereg_search(),
mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some maches, the first element will have the matched substring, the second element will have the first part grouped with brackets, the third element will have the second part grouped
with brackets, and so on. It returns FALSE on error;
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_search_init().
1680
mb_ereg_search_init
(4.2.0 - 4.3.2 only)
mb_ereg_search_init - Setup string and regular expression for multibyte regular expression match
Description
array mb_ereg_search_init (string string [, string pattern [, string option]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_search_init() sets string and pattern for multibyte regular expression. These values are used for
mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). It returns TRUE for success, FALSE for error.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_search_regs().
1681
mb_ereg_search_pos
(4.2.0 - 4.3.2 only)
mb_ereg_search_pos - Return position and length of matched part of multibyte regular expression for
predefined multibyte string
Description
array mb_ereg_search_pos ([string pattern [, string option]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the beggining of matched part, the second element will be length (bytes) of matched part. It returns
FALSE on error.
The string for match is specified by mb_ereg_search_init(). It it is not specified, the previous one will be used.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_search_init().
1682
mb_ereg_search_regs
(4.2.0 - 4.3.2 only)
mb_ereg_search_regs - Returns the matched part of multibyte regular expression
Description
array mb_ereg_search_regs ([string pattern [, string option]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an
array including substring of matched part as first element, the first grouped part with brackets as second element, the second
grouped part as third element, and so on. It returns FALSE on error.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_search_init().
1683
mb_ereg_search_setpos
(4.2.0 - 4.3.2 only)
mb_ereg_search_setpos - Set start point of next regular expression match
Description
array mb_ereg_search_setpos (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_search_setpos() sets the starting point of match for mb_ereg_search().
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_search_init().
1684
mb_ereg_search
(4.2.0 - 4.3.2 only)
mb_ereg_search - Multibyte regular expression match for predefined multibyte string
Description
bool mb_ereg_search ([string pattern [, string option]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, FALSE for otherwise. The
string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_search_init().
1685
mb_ereg
(4.2.0 - 4.3.2 only)
mb_ereg - Regular expression match with multibyte support
Description
int mb_ereg (string pattern, string string [, array regs])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg() executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional
third parameter was specified, the function returns the byte length of matched part, and therarray regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. It no matche found or error happend,
FALSE will be returned.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_eregi()
1686
mb_eregi_replace
(4.2.0 - 4.3.2 only)
mb_eregi_replace - Replace regular expression with multibyte support ignoring case
Description
string mb_eregi_replace (string pattern, string replace, string string)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern. The case will be ignored.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg_replace().
1687
mb_eregi
(4.2.0 - 4.3.2 only)
mb_eregi - Regular expression match ignoring case with multibyte support
Description
int mb_eregi (string pattern, string string [, array regs])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_eregi() executes the regular expression match with multibyte support, and returns 1 if matches are found. This function
ignore case. If the optional third parameter was specified, the function returns the byte length of matched part, and therarray
regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. It no matche
found or error happend, FALSE will be returned.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg().
1688
mb_get_info
(PHP 4 >= 4.2.0)
mb_get_info - Get internal settings of mbstring
Description
string mb_get_info ([string type])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_get_info() returns internal setting parameter of mbstring.
If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input",
"func_overload" will be returned.
If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter
will be returned.
See also mb_internal_encoding(), mb_http_output().
1689
mb_http_input
(PHP 4 >= 4.0.6)
mb_http_input - Detect HTTP input character encoding
Description
string mb_http_input ([string type])
mb_http_input() returns result of HTTP input character encoding detection.
type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE. If type is omitted, it returns last input
type processed.
Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.
See also mb_internal_encoding(), mb_http_output(), mb_detect_order().
1690
mb_http_output
(PHP 4 >= 4.0.6)
mb_http_output - Set/Get HTTP output character encoding
Description
string mb_http_output ([string encoding])
If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.
If encoding is omitted, mb_http_output() returns current HTTP output character encoding.
See also mb_internal_encoding(), mb_http_input(), mb_detect_order().
1691
mb_internal_encoding
(PHP 4 >= 4.0.6)
mb_internal_encoding - Set/Get internal character encoding
Description
string mb_internal_encoding ([string encoding])
mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.
encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default
character encoding for string functions defined by mbstring module.
encoding: Character encoding name
Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is
omitted, it returns current character encoding name.
Example 462. mb_internal_encoding() example
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");
/* Display current internal character encoding */
echo mb_internal_encoding();
See also mb_http_input(), mb_http_output(), mb_detect_order().
1692
mb_language
(PHP 4 >= 4.0.6)
mb_language - Set/Get current language
Description
string mb_language ([string language])
mb_language() sets language. If language is omitted, it returns current language as string.
language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni"
(UTF-8). mb_send_mail() uses this setting to encode e-mail.
Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.
Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is
omitted, it returns language name as string. If no language is set previously, it returns FALSE.
See also mb_send_mail().
1693
mb_output_handler
(PHP 4 >= 4.0.6)
mb_output_handler - Callback function converts character encoding in output buffer
Description
string mb_output_handler (string contents, int status)
mb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in output buffer from internal character encoding to HTTP output character encoding.
4.1.0 or later version, this hanlder adds charset HTTP header when following conditions are met:
•
Does not set Content-Type by header()
•
Default MIME type begins with text/
•
http_output setting is other than pass
contents : Output buffer contents
status : Output buffer status
Return Value: String converted
Example 463. mb_output_handler() example
mb_http_output("UTF-8");
ob_start("mb_output_handler");
Note: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, ContentType: header must be send using header() before any binary data was send to client (e.g. header("Content-Type:
image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.
Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.
If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().
See also ob_start().
1694
mb_parse_str
(PHP 4 >= 4.0.6)
mb_parse_str - Parse GET/POST/COOKIE data and set global variable
Description
bool mb_parse_str (string encoded_string [, array result])
mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/
COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.
encoded_string: URL encoded data.
result: Array contains decoded and character encoding converted values.
Return Value: It returns TRUE for success or FALSE for failure.
See also mb_detect_order(), mb_internal_encoding().
1695
mb_preferred_mime_name
(PHP 4 >= 4.0.6)
mb_preferred_mime_name - Get MIME charset string
Description
string mb_preferred_mime_name (string encoding)
mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.
Example 464. mb_preferred_mime_string() example
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
1696
mb_regex_encoding
(4.2.0 - 4.3.2 only)
mb_regex_encoding - Returns current encoding for multibyte regex as string
Description
string mb_regex_encoding ([string encoding])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_regex_encoding() returns the character encoding used by multibyte regex functions.
If the optional parameter encoding is specified, it is set to the character encoding for multibyte regex. The default value is
the internal character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_internal_encoding(), mb_ereg()
1697
mb_regex_set_options
(4.3.0 - 4.3.2 only)
mb_regex_set_options - Set/Get the default options for mbregex functions
Description
string mb_regex_set_options ([string options])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_regex_set_options() sets the default options described by options for multibyte regex functions.
Returns the previous options. If options is omitted, it returns the string that describes the current options.
Note: This function is supported in PHP 4.3.0 or higher.
See also mb_split(), mb_ereg() and mb_eregi()
1698
mb_send_mail
(PHP 4 >= 4.0.6)
mb_send_mail - Send encoded mail.
Description
bool mb_send_mail (string to, string subject, string message [, string additional_headers [, string additional_parameter]])
mb_send_mail() sends email. Headers and message are converted and encoded according to mb_language() setting.
mb_send_mail() is wrapper function of mail(). See mail() for details.
to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.
subject is subject of mail.
message is mail message.
additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers
are separated with a newline ("\n").
additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.
Returns TRUE on success or FALSE on failure.
See also mail(), mb_encode_mimeheader(), and mb_language().
1699
mb_split
(4.2.0 - 4.3.2 only)
mb_split - Split multibyte string using regular expression
Description
array mb_split (string pattern, string string [, int limit])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
mb_split() split multibyte string using regular expression pattern and returns the result as an array.
If optional parameter limit is specified, it will be split in limit elements as maximum.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
Note: This function is supported in PHP 4.2.0 or higher.
See also: mb_regex_encoding(), mb_ereg().
1700
mb_strcut
(PHP 4 >= 4.0.6)
mb_strcut - Get part of string
Description
string mb_strcut (string str, int start [, int length [, string encoding]])
mb_strcut() returns the portion of str specified by the start and length parameters.
mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's
second byte or larger, it starts from first byte of multi-byte character.
It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle
of shift sequence.
encoding is character encoding. If it is not set, internal character encoding is used.
See also mb_substr(), mb_internal_encoding().
1701
mb_strimwidth
(PHP 4 >= 4.0.6)
mb_strimwidth - Get truncated string with specified width
Description
string mb_strimwidth (string str, int start, int width, string trimmarker [, string encoding])
mb_strimwidth() truncates string str to specified width. It returns truncated string.
If trimmarker is set, trimmarker is appended to return value.
start is start position offset. Number of characters from the beginning of string. (First character is 0)
trimmarker is string that is added to the end of string when string is truncated.
encoding is character encoding. If it is omitted, internal encoding is used.
Example 465. mb_strimwidth() example
$str = mb_strimwidth($str, 0, 40, "..>");
See also: mb_strwidth(), mb_internal_encoding().
1702
mb_strlen
(PHP 4 >= 4.0.6)
mb_strlen - Get string length
Description
string mb_strlen (string str [, string encoding])
mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.
encoding is character encoding for str. If encoding is omitted, internal character encoding is used.
See also mb_internal_encoding(), strlen().
1703
mb_strpos
(PHP 4 >= 4.0.6)
mb_strpos - Find position of first occurrence of string in a string
Description
int mb_strpos (string haystack, string needle [, int offset [, string encoding]])
mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it
returns FALSE.
mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from
the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.
offset is search offset. If it is not specified, 0 is used.
encoding is character encoding name. If it is omitted, internal character encoding is used.
See also mb_strpos(), mb_internal_encoding(), strpos()
1704
mb_strrpos
(PHP 4 >= 4.0.6)
mb_strrpos - Find position of last occurrence of a string in a string
Description
int mb_strrpos (string haystack, string needle [, string encoding])
mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it
returns FALSE.
mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from
the beginning of haystack. First character's position is 0. Second character position is 1.
If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only
character.
encoding is character encoding. If it is not specified, internal character encoding is used.
See also mb_strpos(), mb_internal_encoding(), strrpos().
1705
mb_strtolower
(PHP 4 >= 4.3.0)
mb_strtolower - Make a string lowercase
Description
string mb_strtolower (string str [, string encoding])
mb_strtolower() returns str with all alphabetic characters converted to lowercase.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).
Example 466. mb_strtolower() example
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
print $str; # Prints mary had a little lamb and she loved it so
See also strtolower(), mb_strtoupper(), mb_convert_case().
1706
mb_strtoupper
(PHP 4 >= 4.3.0)
mb_strtoupper - Make a string uppercase
Description
string mb_strtoupper (string str [, string encoding])
mb_strtoupper() returns str with all alphabetic characters converted to uppercase.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
Example 467. mb_strtoupper() example
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
print $str; # Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
See also strtoupper(), mb_strtolower(), mb_convert_case().
1707
mb_strwidth
(PHP 4 >= 4.0.6)
mb_strwidth - Return width of string
Description
int mb_strwidth (string str [, string encoding])
mb_strwidth() returns width of string str.
Multi-byte character usually twice of width compare to single byte character.
Character width
U+0000
U+0020
U+2000
U+FF61
U+FFA0
-
U+0019
U+1FFF
U+FF60
U+FF9F
0
1
2
1
2
encoding is character encoding. If it is omitted, internal encoding is used.
See also: mb_strimwidth(), mb_internal_encoding().
1708
mb_substitute_character
(PHP 4 >= 4.0.6)
mb_substitute_character - Set/Get substitution character
Description
mixed mb_substitute_character ([mixed substrchar])
mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is
not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value
(Unicode character code value).
This setting affects mb_detect_encoding() and mb_send_mail().
substchar : Specify Unicode value as integer or specify as string as follows
•
"none" : no output
•
"long" : Output character code value (Example: U+3000,JIS+7E7E)
Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".
Example 468. mb_substitute_character() example
/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);
/* Set hex format */
mb_substitute_character("long");
/* Display current setting */
echo mb_substitute_character();
1709
mb_substr_count
(PHP 4 >= 4.3.0)
mb_substr_count - Count the number of substring occurrences
Description
int mb_substr_count (string haystack, string needle [, string encoding])
mb_substr_count() returns the number of times the needle substring occurs in the haystack string.
encoding specifies the encoding for needle and haystack. If omitted, internal character encoding is used.
Example 469. mb_substr_count() example
See also substr_count(), mb_strpos(), mb_substr().
1710
mb_substr
(PHP 4 >= 4.0.6)
mb_substr - Get part of string
Description
string mb_substr (string str, int start [, int length [, string encoding]])
mb_substr() returns the portion of str specified by the start and length parameters.
mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal encoding is assumed.
encoding is character encoding. If it is omitted, internal character encoding is used.
See also mb_strcut(), mb_internal_encoding().
1711
MCAL functions
Table of Contents
mcal_append_event .......................................................................................................................... 1716
mcal_close ...................................................................................................................................... 1717
mcal_create_calendar ........................................................................................................................ 1718
mcal_date_compare .......................................................................................................................... 1719
mcal_date_valid ............................................................................................................................... 1720
mcal_day_of_week ........................................................................................................................... 1721
mcal_day_of_year ............................................................................................................................ 1722
mcal_days_in_month ........................................................................................................................ 1723
mcal_delete_calendar ........................................................................................................................ 1724
mcal_delete_event ............................................................................................................................ 1725
mcal_event_add_attribute .................................................................................................................. 1726
mcal_event_init ............................................................................................................................... 1727
mcal_event_set_alarm ....................................................................................................................... 1728
mcal_event_set_category ................................................................................................................... 1729
mcal_event_set_class ........................................................................................................................ 1730
mcal_event_set_description ............................................................................................................... 1731
mcal_event_set_end ......................................................................................................................... 1732
mcal_event_set_recur_daily ............................................................................................................... 1733
mcal_event_set_recur_monthly_mday .................................................................................................. 1734
mcal_event_set_recur_monthly_wday .................................................................................................. 1735
mcal_event_set_recur_none ............................................................................................................... 1736
mcal_event_set_recur_weekly ............................................................................................................ 1737
mcal_event_set_recur_yearly ............................................................................................................. 1738
mcal_event_set_start ......................................................................................................................... 1739
mcal_event_set_title ......................................................................................................................... 1740
mcal_expunge ................................................................................................................................. 1741
mcal_fetch_current_stream_event ....................................................................................................... 1742
mcal_fetch_event ............................................................................................................................. 1743
mcal_is_leap_year ............................................................................................................................ 1745
mcal_list_alarms .............................................................................................................................. 1746
mcal_list_events .............................................................................................................................. 1747
mcal_next_recurrence ....................................................................................................................... 1748
mcal_open ...................................................................................................................................... 1749
mcal_popen .................................................................................................................................... 1750
mcal_rename_calendar ...................................................................................................................... 1751
mcal_reopen ................................................................................................................................... 1752
mcal_snooze ................................................................................................................................... 1753
mcal_store_event ............................................................................................................................. 1754
mcal_time_valid .............................................................................................................................. 1755
mcal_week_of_year .......................................................................................................................... 1756
1712
Introduction
MCAL stands for Modular Calendar Access Library.
Libmcal is a C library for accessing calendars. It's written to be very modular, with pluggable drivers. MCAL is the calendar
equivalent of the IMAP module for mailboxes.
With mcal support, a calendar stream can be opened much like the mailbox stream with the IMAP support. Calendars can be
local file stores, remote ICAP servers, or other formats that are supported by the mcal library.
Calendar events can be pulled up, queried, and stored. There is also support for calendar triggers (alarms) and recurring
events.
With libmcal, central calendar servers can be accessed, removing the need for any specific database or local file programming.
Most of the functions use an internal event structure that is unique for each stream. This alleviates the need to pass around
large objects between functions. There are convenience functions for setting, initializing, and retrieving the event structure
values.
Note: PHP had an ICAP extension previously, but the original library and the PHP extension is not supported anymore. The suggested replacement is MCAL.
Note: This extension is not available on Windows platforms.
Requirements
This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/and compile and
install it.
Installation
After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].
Runtime Configuration
This extension has no configuration directives defined in php.ini.
Resource Types
This extension has no resource types defined.
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
MCAL_SUNDAY (integer)
MCAL_MONDAY (integer)
MCAL_TUESDAY (integer)
1713
MCAL functions
MCAL_WEDNESDAY (integer)
MCAL_THURSDAY (integer)
MCAL_FRIDAY (integer)
MCAL_SATURDAY (integer)
MCAL_JANUARY (integer)
MCAL_FEBRUARY (integer)
MCAL_MARCH (integer)
MCAL_APRIL (integer)
MCAL_MAY (integer)
MCAL_JUNE (integer)
MCAL_JULY (integer)
MCAL_AUGUST (integer)
MCAL_SEPTEMBER (integer)
MCAL_OCTOBER (integer)
MCAL_NOVEMBER (integer)
MCAL_DECEMBER (integer)
MCAL_RECUR_NONE (integer)
MCAL_RECUR_DAILY (integer)
MCAL_RECUR_WEEKLY (integer)
MCAL_RECUR_MONTHLY_MDAY (integer)
MCAL_RECUR_MONTHLY_WDAY (integer)
MCAL_RECUR_YEARLY (integer)
MCAL_M_SUNDAY (integer)
MCAL_M_MONDAY (integer)
MCAL_M_TUESDAY (integer)
MCAL_M_WEDNESDAY (integer)
MCAL_M_THURSDAY (integer)
MCAL_M_FRIDAY (integer)
MCAL_M_SATURDAY (integer)
MCAL_M_WEEKDAYS (integer)
1714
MCAL functions
MCAL_M_WEEKEND (integer)
MCAL_M_ALLDAYS (integer)
1715
mcal_append_event
(PHP 4 )
mcal_append_event - Store a new event into an MCAL calendar
Description
int mcal_append_event (int mcal_stream)
mcal_append_event() stores the global event into an MCAL calendar for the stream mcal_stream.
Returns the id of the newly inserted event.
1716
mcal_close
(PHP 3>= 3.0.13, PHP 4 )
mcal_close - Close an MCAL stream
Description
int mcal_close (int mcal_stream, int flags)
Closes the given mcal stream.
1717
mcal_create_calendar
(PHP 3>= 3.0.13, PHP 4 )
mcal_create_calendar - Create a new MCAL calendar
Description
string mcal_create_calendar (int stream, string calendar)
Creates a new calendar named calendar.
1718
mcal_date_compare
(PHP 3>= 3.0.13, PHP 4 )
mcal_date_compare - Compares two dates
Description
int mcal_date_compare (int a_year, int a_month, int a_day, int b_year, int b_month, int b_day)
mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if ab respectively.
1719
mcal_date_valid
(PHP 3>= 3.0.13, PHP 4 )
mcal_date_valid - Returns TRUE if the given year, month, day is a valid date
Description
int mcal_date_valid (int year, int month, int day)
mcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.
1720
mcal_day_of_week
(PHP 3>= 3.0.13, PHP 4 )
mcal_day_of_week - Returns the day of the week of the given date
Description
int mcal_day_of_week (int year, int month, int day)
mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through
6 for Saturday.
1721
mcal_day_of_year
(PHP 3>= 3.0.13, PHP 4 )
mcal_day_of_year - Returns the day of the year of the given date
Description
int mcal_day_of_year (int year, int month, int day)
mcal_day_of_year() returns the day of the year of the given date.
1722
mcal_days_in_month
(PHP 3>= 3.0.13, PHP 4 )
mcal_days_in_month - Returns the number of days in a month
Description
int mcal_days_in_month (int month, int leap_year)
mcal_days_in_month() returns the number of days in the month month, taking into account if the considered year is a leap
year or not.
1723
mcal_delete_calendar
(PHP 3>= 3.0.13, PHP 4 )
mcal_delete_calendar - Delete an MCAL calendar
Description
string mcal_delete_calendar (int stream, string calendar)
Deletes the calendar named calendar.
1724
mcal_delete_event
(PHP 3>= 3.0.13, PHP 4 )
mcal_delete_event - Delete an event from an MCAL calendar
Description
int mcal_delete_event (int mcal_stream [, int event_id])
mcal_delete_event() deletes the calendar event specified by the event_id.
Returns TRUE.
1725
mcal_event_add_attribute
(PHP 3>= 3.0.15, PHP 4 )
mcal_event_add_attribute - Adds an attribute and a value to the streams global event structure
Description
void mcal_event_add_attribute (int stream, string attribute, string value)
mcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".
1726
mcal_event_init
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_init - Initializes a streams global event structure
Description
int mcal_event_init (int stream)
mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the
default settings.
Returns TRUE.
1727
mcal_event_set_alarm
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_alarm - Sets the alarm of the streams global event structure
Description
int mcal_event_set_alarm (int stream, int alarm)
mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.
Returns TRUE.
1728
mcal_event_set_category
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_category - Sets the category of the streams global event structure
Description
int mcal_event_set_category (int stream, string category)
mcal_event_set_category() sets the streams global event structure's category to the given string.
Returns TRUE.
1729
mcal_event_set_class
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_class - Sets the class of the streams global event structure
Description
int mcal_event_set_class (int stream, int class)
mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or
0 for private.
Returns TRUE.
1730
mcal_event_set_description
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_description - Sets the description of the streams global event structure
Description
int mcal_event_set_description (int stream, string description)
mcal_event_set_description() sets the streams global event structure's description to the given string.
Returns TRUE.
1731
mcal_event_set_end
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_end - Sets the end date and time of the streams global event structure
Description
int mcal_event_set_end (int stream, int year, int month [, int day [, int hour [, int min [, int sec ]]]])
mcal_event_set_end() sets the streams global event structure's end date and time to the given values.
Returns TRUE.
1732
mcal_event_set_recur_daily
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_daily - Sets the recurrence of the streams global event structure
Description
int mcal_event_set_recur_daily (int stream, int year, int month, int day, int interval)
mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccuring on a
daily basis, ending at the given date.
1733
mcal_event_set_recur_monthly_mday
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_mday - Sets the recurrence of the streams global event structure
Description
int mcal_event_set_recur_monthly_mday (int stream, int year, int month, int day, int interval)
mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by month day basis, ending at the given date.
1734
mcal_event_set_recur_monthly_wday
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_wday - Sets the recurrence of the streams global event structure
Description
int mcal_event_set_recur_monthly_wday (int stream, int year, int month, int day, int interval)
mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by week basis, ending at the given date.
1735
mcal_event_set_recur_none
(PHP 3>= 3.0.15, PHP 4 )
mcal_event_set_recur_none - Sets the recurrence of the streams global event structure
Description
int mcal_event_set_recur_none (int stream)
mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).
1736
mcal_event_set_recur_weekly
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_weekly - Sets the recurrence of the streams global event structure
Description
int mcal_event_set_recur_weekly (int stream, int year, int month, int day, int interval, int weekdays)
mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccuring on
a weekly basis, ending at the given date.
1737
mcal_event_set_recur_yearly
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_yearly - Sets the recurrence of the streams global event structure
Description
int mcal_event_set_recur_yearly (int stream, int year, int month, int day, int interval)
mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccuring on a
yearly basis,ending at the given date.
1738
mcal_event_set_start
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_start - Sets the start date and time of the streams global event structure
Description
int mcal_event_set_start (int stream, int year, int month [, int day [, int hour [, int min [, int sec ]]]])
mcal_event_set_start() sets the streams global event structure's start date and time to the given values.
Returns TRUE.
1739
mcal_event_set_title
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_title - Sets the title of the streams global event structure
Description
int mcal_event_set_title (int stream, string title)
mcal_event_set_title() sets the streams global event structure's title to the given string.
Returns TRUE.
1740
mcal_expunge
()
mcal_expunge - Deletes all events marked for being expunged.
Description
int mcal_expunge (int stream)
mcal_expunge() deletes all events which have been previously marked for deletion.
1741
mcal_fetch_current_stream_event
(PHP 3>= 3.0.13, PHP 4 )
mcal_fetch_current_stream_event - Returns an object containing the current streams event structure
Description
object mcal_fetch_current_stream_event (int stream)
mcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:
•
int id - ID of that event.
•
int public - TRUE if the event if public, FALSE if it is private.
•
string category - Category string of the event.
•
string title - Title string of the event.
•
string description - Description string of the event.
•
int alarm - number of minutes before the event to send an alarm/reminder.
•
object start - Object containing a datetime entry.
•
object end - Object containing a datetime entry.
•
int recur_type - recurrence type
•
int recur_interval - recurrence interval
•
datetime recur_enddate - recurrence end date
•
int recur_data - recurrence data
All datetime entries consist of an object that contains:
•
int year - year
•
int month - month
•
int mday - day of month
•
int hour - hour
•
int min - minutes
•
int sec - seconds
•
int alarm - minutes before event to send an alarm
1742
mcal_fetch_event
(PHP 3>= 3.0.13, PHP 4 )
mcal_fetch_event - Fetches an event from the calendar stream
Description
object mcal_fetch_event (int mcal_stream, int event_id [, int options])
mcal_fetch_event() fetches an event from the calendar stream specified by id.
Returns an event object consisting of:
•
int id - ID of that event.
•
int public - TRUE if the event if public, FALSE if it is private.
•
string category - Category string of the event.
•
string title - Title string of the event.
•
string description - Description string of the event.
•
int alarm - number of minutes before the event to send an alarm/reminder.
•
object start - Object containing a datetime entry.
•
object end - Object containing a datetime entry.
•
int recur_type - recurrence type
•
int recur_interval - recurrence interval
•
datetime recur_enddate - recurrence end date
•
int recur_data - recurrence data
All datetime entries consist of an object that contains:
•
int year - year
•
int month - month
•
int mday - day of month
•
int hour - hour
•
int min - minutes
•
int sec - seconds
•
int alarm - minutes before event to send an alarm
The possible values for recur_type are:
1743
mcal_fetch_event
•
0 - Indicates that this event does not recur
•
1 - This event recurs daily
•
2 - This event recurs on a weekly basis
•
3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)
•
4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)
•
5 - This event recurs on an annual basis
1744
mcal_is_leap_year
(PHP 3>= 3.0.13, PHP 4 )
mcal_is_leap_year - Returns if the given year is a leap year or not
Description
int mcal_is_leap_year (int year)
mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.
1745
mcal_list_alarms
(PHP 3>= 3.0.13, PHP 4 )
mcal_list_alarms - Return a list of events that has an alarm triggered at the given datetime
Description
array mcal_list_alarms (int mcal_stream [, int begin_year [, int begin_month [, int begin_day [, int end_year [,
int end_month [, int end_day]]]]]])
Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses
the start and end dates in the global event structure.
mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's
that are between the given dates or the internal event dates are returned.
1746
mcal_list_events
(PHP 3>= 3.0.13, PHP 4 )
mcal_list_events - Return a list of IDs for a date or a range of dates
Description
array mcal_list_events (int mcal_stream, object begin_date [, object end_date])
Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in
the global event structure.
mcal_list_events() takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are
between the given dates or the internal event dates are returned.
1747
mcal_next_recurrence
(PHP 3>= 3.0.13, PHP 4 )
mcal_next_recurrence - Returns the next recurrence of the event
Description
int mcal_next_recurrence (int stream, int weekstart, array next)
mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns
empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.
1748
mcal_open
(PHP 3>= 3.0.13, PHP 4 )
mcal_open - Opens up an MCAL connection
Description
int mcal_open (string calendar, string username, string password [, int options])
Returns an MCAL stream on success, FALSE on error.
mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the
options to that mailbox also. The streams internal event structure is also initialized upon connection.
1749
mcal_popen
(PHP 3>= 3.0.13, PHP 4 )
mcal_popen - Opens up a persistent MCAL connection
Description
int mcal_popen (string calendar, string username, string password [, int options])
Returns an MCAL stream on success, FALSE on error.
mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the
options to that mailbox also. The streams internal event structure is also initialized upon connection.
1750
mcal_rename_calendar
(PHP 3>= 3.0.13, PHP 4 )
mcal_rename_calendar - Rename an MCAL calendar
Description
string mcal_rename_calendar (int stream, string old_name, string new_name)
Renames the calendar old_name to new_name.
1751
mcal_reopen
(PHP 3>= 3.0.13, PHP 4 )
mcal_reopen - Reopens an MCAL connection
Description
int mcal_reopen (string calendar [, int options])
Reopens an MCAL stream to a new calendar.
mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the
options to that mailbox also.
1752
mcal_snooze
(PHP 3>= 3.0.13, PHP 4 )
mcal_snooze - Turn off an alarm for an event
Description
int mcal_snooze (int id)
mcal_snooze() turns off an alarm for a calendar event specified by the id.
Returns TRUE.
1753
mcal_store_event
(PHP 3>= 3.0.13, PHP 4 )
mcal_store_event - Modify an existing event in an MCAL calendar
Description
int mcal_store_event (int mcal_stream)
mcal_store_event() stores the modifications to the current global event for the given stream.
Returns the event id of the modified event on success and FALSE on error.
1754
mcal_time_valid
(PHP 3>= 3.0.13, PHP 4 )
mcal_time_valid - Returns TRUE if the given year, month, day is a valid time
Description
int mcal_time_valid (int hour, int minutes, int seconds)
mcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.
1755
mcal_week_of_year
(PHP 4 )
mcal_week_of_year - Returns the week number of the given date
Description
int mcal_week_of_year (int day, int month, int year)
1756
Mcrypt Encryption Functions
Table of Contents
mcrypt_cbc ..................................................................................................................................... 1762
mcrypt_cfb ..................................................................................................................................... 1763
mcrypt_create_iv ............................................................................................................................. 1764
mcrypt_decrypt ................................................................................................................................ 1765
mcrypt_ecb ..................................................................................................................................... 1766
mcrypt_enc_get_algorithms_name ...................................................................................................... 1767
mcrypt_enc_get_block_size ............................................................................................................... 1768
mcrypt_enc_get_iv_size .................................................................................................................... 1769
mcrypt_enc_get_key_size .................................................................................................................. 1770
mcrypt_enc_get_modes_name ............................................................................................................ 1771
mcrypt_enc_get_supported_key_sizes .................................................................................................. 1772
mcrypt_enc_is_block_algorithm_mode ................................................................................................ 1773
mcrypt_enc_is_block_algorithm ......................................................................................................... 1774
mcrypt_enc_is_block_mode ............................................................................................................... 1775
mcrypt_enc_self_test ........................................................................................................................ 1776
mcrypt_encrypt ................................................................................................................................ 1777
mcrypt_generic_deinit ...................................................................................................................... 1778
mcrypt_generic_end ......................................................................................................................... 1779
mcrypt_generic_init .......................................................................................................................... 1780
mcrypt_generic ................................................................................................................................ 1781
mcrypt_get_block_size ...................................................................................................................... 1782
mcrypt_get_cipher_name ................................................................................................................... 1783
mcrypt_get_iv_size .......................................................................................................................... 1784
mcrypt_get_key_size ........................................................................................................................ 1785
mcrypt_list_algorithms ...................................................................................................................... 1786
mcrypt_list_modes ........................................................................................................................... 1787
mcrypt_module_close ....................................................................................................................... 1788
mcrypt_module_get_algo_block_size .................................................................................................. 1789
mcrypt_module_get_algo_key_size ..................................................................................................... 1790
mcrypt_module_get_supported_key_sizes ............................................................................................ 1791
mcrypt_module_is_block_algorithm_mode ........................................................................................... 1792
mcrypt_module_is_block_algorithm .................................................................................................... 1793
mcrypt_module_is_block_mode .......................................................................................................... 1794
mcrypt_module_open ....................................................................................................................... 1795
mcrypt_module_self_test ................................................................................................................... 1797
mcrypt_ofb ..................................................................................................................................... 1798
mdecrypt_generic ............................................................................................................................. 1799
1757
Introduction
This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB
cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".
Requirements
These functions work using mcrypt [http://mcrypt.hellug.gr/]. To use it, download libmcrypt-x.x.tar.gz from here [http://
mcrypt.hellug.gr/] and follow the included installation instructions. Windows users will find all the needed compiled mcrypt
binaries here [http://ftp.proventum.net/pub/php/win32/misc/mcrypt/].
If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97,
RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE.
With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.
Installation
You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install
directory. Make sure you compile libmcrypt with the option --disable-posix-threads.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 87. Mcrypt configuration options
Name
Default
Changeable
mcrypt.algorithms_dir
NULL
PHP_INI_ALL
mcrypt.modes_dir
NULL
PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().
Resource Types
This extension has no resource types defined.
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the
functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported
encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and
discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).
•
MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data
there is short and random, the disadvantages of ECB have a favorable negative effect.
1758
Mcrypt Encryption Functions
•
MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
•
MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
•
MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error
propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
•
MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the
block size of the algorithm.
•
MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.
Some other mode and random device constants:
MCRYPT_ENCRYPT (integer)
MCRYPT_DECRYPT (integer)
MCRYPT_DEV_RANDOM (integer)
MCRYPT_DEV_URANDOM (integer)
MCRYPT_RAND (integer)
Mcrypt ciphers
Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see
the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP
with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible
to specify the name of the cipher as a string with a call to mcrypt_module_open().
•
MCRYPT_3DES
•
MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)
•
MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)
•
MCRYPT_BLOWFISH
•
MCRYPT_CAST_128
•
MCRYPT_CAST_256
•
MCRYPT_CRYPT
•
MCRYPT_DES
•
MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
•
MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)
•
MCRYPT_GOST
1759
Mcrypt Encryption Functions
•
MCRYPT_IDEA (non-free)
•
MCRYPT_LOKI97 (libmcrypt > 2.4.x only)
•
MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)
•
MCRYPT_PANAMA (libmcrypt > 2.4.x only)
•
MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)
•
MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)
•
MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)
•
MCRYPT_RC2
•
MCRYPT_RC4 (libmcrypt 2.2.x only)
•
MCRYPT_RC6 (libmcrypt > 2.4.x only)
•
MCRYPT_RC6_128 (libmcrypt 2.2.x only)
•
MCRYPT_RC6_192 (libmcrypt 2.2.x only)
•
MCRYPT_RC6_256 (libmcrypt 2.2.x only)
•
MCRYPT_SAFER64
•
MCRYPT_SAFER128
•
MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)
•
MCRYPT_SERPENT(libmcrypt > 2.4.x only)
•
MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
•
MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
•
MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
•
MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)
•
MCRYPT_TEAN (libmcrypt 2.2.x only)
•
MCRYPT_THREEWAY
•
MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)
•
MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )
•
MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)
•
MCRYPT_TWOFISH192
•
MCRYPT_TWOFISH256
•
MCRYPT_WAKE (libmcrypt > 2.4.x only)
•
MCRYPT_XTEA (libmcrypt > 2.4.x only)
1760
Mcrypt Encryption Functions
You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you
can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN
0-471-11709-9) for a discussion of this topic).
Examples
Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the
four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both
modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.
Example 470. Encrypt an input value with TripleDES under 2.2.x in ECB mode
This example will give you the encrypted data as a string in $encrypted_data.
If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.
Example 471. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode
This example will give you the encrypted data as a string in $encrypted_data. For a full example see
mcrypt_module_open().
1761
mcrypt_cbc
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_cbc - Encrypt/decrypt data in CBC mode
Description
string mcrypt_cbc (int cipher, string key, string data, int mode [, string iv])
string mcrypt_cbc (string cipher, string key, string data, int mode [, string iv])
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The
mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
1762
mcrypt_cfb
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_cfb - Encrypt/decrypt data in CFB mode
Description
string mcrypt_cfb (int cipher, string key, string data, int mode, string iv)
string mcrypt_cfb (string cipher, string key, string data, int mode [, string iv])
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The
mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
1763
mcrypt_create_iv
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_create_iv - Create an initialization vector (IV) from a random source
Description
string mcrypt_create_iv (int size, int source)
mcrypt_create_iv() is used to create an IV.
mcrypt_create_iv() takes two arguments, size determines the size of the IV, source specifies the source of the IV.
The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /
dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). If you use MCRYPT_RAND, make sure to
call srand() before to initialize the random number generator.
Example 472. mcrypt_create_iv() example
The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though
it can be desirable. You even can send it along with your ciphertext without loosing security.
More information can be found at http:/ / www.ciphersbyritter.com/ GLOSSARY.HTM#IV, http:/ /
fn2.freenet.edmonton.ab.ca/ ~jsavard/ crypto/ co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN
0-471-11709-9) for a discussion of this topic.
1764
mcrypt_decrypt
(PHP 4 >= 4.0.2)
mcrypt_decrypt - Decrypts crypttext with given parameters
Description
string mcrypt_decrypt (string cipher, string key, string data, string mode [, string iv])
mcrypt_decrypt() decrypts the data and returns the unencrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.
Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data
will be padded with '\0'.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you
do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to
'\0'.
1765
mcrypt_ecb
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_ecb - Encrypt/decrypt data in ECB mode
Description
string mcrypt_ecb (int cipher, string key, string data, int mode)
string mcrypt_ecb (string cipher, string key, string data, int mode [, string iv])
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The
mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
1766
mcrypt_enc_get_algorithms_name
(PHP 4 >= 4.0.2)
mcrypt_enc_get_algorithms_name - Returns the name of the opened algorithm
Description
string mcrypt_enc_get_algorithms_name (resource td)
This function returns the name of the algorithm.
Example 473. mcrypt_enc_get_algorithms_name() example
Prints:
CAST-256
CAST-256
1767
mcrypt_enc_get_block_size
(PHP 4 >= 4.0.2)
mcrypt_enc_get_block_size - Returns the blocksize of the opened algorithm
Description
int mcrypt_enc_get_block_size (resource td)
This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.
1768
mcrypt_enc_get_iv_size
(PHP 4 >= 4.0.2)
mcrypt_enc_get_iv_size - Returns the size of the IV of the opened algorithm
Description
int mcrypt_enc_get_iv_size (resource td)
This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then
the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.
1769
mcrypt_enc_get_key_size
(PHP 4 >= 4.0.2)
mcrypt_enc_get_key_size - Returns the maximum supported keysize of the opened mode
Description
int mcrypt_enc_get_key_size (resource td)
This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.
1770
mcrypt_enc_get_modes_name
(PHP 4 >= 4.0.2)
mcrypt_enc_get_modes_name - Returns the name of the opened mode
Description
string mcrypt_enc_get_modes_name (resource td)
This function returns the name of the mode.
Example 474. mcrypt_enc_get_modes_name() example
Prints:
CFB
ECB
1771
mcrypt_enc_get_supported_key_sizes
(PHP 4 >= 4.0.2)
mcrypt_enc_get_supported_key_sizes - Returns an array with the supported keysizes of the opened algorithm
Description
array mcrypt_enc_get_supported_key_sizes (resource td)
Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty
array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.
Example 475. mcrypt_enc_get_supported_key_sizes() example
This will print:
array(3) {
[0]=>
int(16)
[1]=>
int(24)
[2]=>
int(32)
}
?>
1772
mcrypt_enc_is_block_algorithm_mode
(PHP 4 >= 4.0.2)
mcrypt_enc_is_block_algorithm_mode - Checks whether the encryption of the opened mode works on
blocks
Description
bool mcrypt_enc_is_block_algorithm_mode (resource td)
This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (eg. FALSE for stream,
and TRUE for cbc, cfb, ofb).
1773
mcrypt_enc_is_block_algorithm
(PHP 4 >= 4.0.2)
mcrypt_enc_is_block_algorithm - Checks whether the algorithm of the opened mode is a block algorithm
Description
bool mcrypt_enc_is_block_algorithm (resource td)
This function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.
1774
mcrypt_enc_is_block_mode
(PHP 4 >= 4.0.2)
mcrypt_enc_is_block_mode - Checks whether the opened mode outputs blocks
Description
bool mcrypt_enc_is_block_mode (resource td)
This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (eg. TRUE for cbc and ecb, and
FALSE for cfb and stream).
1775
mcrypt_enc_self_test
(PHP 4 >= 4.0.2)
mcrypt_enc_self_test - This function runs a self test on the opened module
Description
bool mcrypt_enc_self_test (resource td)
This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In
case of an error, it returns TRUE.
1776
mcrypt_encrypt
(PHP 4 >= 4.0.2)
mcrypt_encrypt - Encrypts plaintext with given parameters
Description
string mcrypt_encrypt (string cipher, string key, string data, string mode [, string iv])
mcrypt_encrypt() encrypts the data and returns the encrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.
Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data
will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you
do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to
'\0'.
Example 476. mcrypt_encrypt() Example
The above example will print out:
42
64
See also mcrypt_module_open() for a more advanced API and an example.
1777
mcrypt_generic_deinit
(PHP 4 >= 4.1.1)
mcrypt_generic_deinit - This function deinitializes an encryption module
Description
bool mcrypt_generic_deinit (resource td)
This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the
module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.) Returns
FALSE on error, or TRUE on success.
See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().
1778
mcrypt_generic_end
(PHP 4 >= 4.0.2)
mcrypt_generic_end - This function terminates encryption
Description
bool mcrypt_generic_end (resource td)
Warning
This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with
mcrypt_module_close() due to multiple buffer frees.
This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all
the modules used. Returns FALSE on error, or TRUE on success.
1779
mcrypt_generic_init
(PHP 4 >= 4.0.2)
mcrypt_generic_init - This function initializes all buffers needed for encryption
Description
int mcrypt_generic_init (resource td, string key, string iv)
The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller
than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling
mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It
needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to
use it you should set it to zeros, but this is not recommended.
The function returns a negative value on error, -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly.
You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().
See for an example mcrypt_module_open() and the entry on mcrypt_generic_deinit().
1780
mcrypt_generic
(PHP 4 >= 4.0.2)
mcrypt_generic - This function encrypts data
Description
string mcrypt_generic (resource td, string data)
This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function
returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding
of the data.
If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or
the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use
mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field.
Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim()($str, "\0") to remove the padding.
If you are for example storing the data in a MySQL database remember tha varchar fields automatically have trailing spaces
removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store
data in a tinyblob/tinytext (or larger) field instead.
The encryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this
function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See
mcrypt_module_open() for an example.
See also mdecrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
1781
mcrypt_get_block_size
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_get_block_size - Get the block size of the specified cipher
Description
int mcrypt_get_block_size (int cipher)
int mcrypt_get_block_size (string cipher, string module)
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption
mode).
This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.
Example 477. mcrypt_get_block_size() example
Prints:
8
See also: mcrypt_get_key_size() and mcrypt_encrypt().
1782
mcrypt_get_cipher_name
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_get_cipher_name - Get the name of the specified cipher
Description
string mcrypt_get_cipher_name (int cipher)
string mcrypt_get_cipher_name (string cipher)
mcrypt_get_cipher_name() is used to get the name of the specified cipher.
mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.
Example 478. mcrypt_get_cipher_name() Example
The above example will produce:
3DES
1783
mcrypt_get_iv_size
(PHP 4 >= 4.0.2)
mcrypt_get_iv_size - Returns the size of the IV belonging to a specific cipher/mode combination
Description
int mcrypt_get_iv_size (resource td)
int mcrypt_get_iv_size (string cipher, string mode)
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.
mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the
IV is ignored in the specified cipher/mode combination zero is returned.
cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
mode is one of the MCRYPT_MODE_modename constants or one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV
is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at
encryption and decryption stages, otherwise your encryption will fail.
td is the resource that is returned by mcrypt_module_open().
Example 479. mcrypt_create_iv() example
See also mcrypt_get_block_size(), and mcrypt_create_iv().
1784
mcrypt_get_key_size
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_get_key_size - Get the key size of the specified cipher
Description
int mcrypt_get_key_size (int cipher)
int mcrypt_get_key_size (string cipher, string module)
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).
This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.
Example 480. mcrypt_get_block_size() example
Prints:
24
See also: mcrypt_get_block_size() and mcrypt_encrypt().
1785
mcrypt_list_algorithms
(PHP 4 >= 4.0.2)
mcrypt_list_algorithms - Get an array of all supported ciphers
Description
array mcrypt_list_algorithms ([string lib_dir])
mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.
mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.
Example 481. mcrypt_list_algorithms() Example
\n";
}
?>
The above example will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.
1786
mcrypt_list_modes
(PHP 4 >= 4.0.2)
mcrypt_list_modes - Get an array of all supported modes
Description
array mcrypt_list_modes ([string lib_dir])
mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.
mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If
not specifies, the value of the mcrypt.modes_dir php.ini directive is used.
Example 482. mcrypt_list_modes() Example
\n";
}
?>
The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini
directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).
1787
mcrypt_module_close
(PHP 4 >= 4.0.2)
mcrypt_module_close - Close the mcrypt module
Description
bool mcrypt_module_close (resource td)
This function closes the specified encryption handle.
See mcrypt_module_open() for an example.
1788
mcrypt_module_get_algo_block_size
(PHP 4 >= 4.0.2)
mcrypt_module_get_algo_block_size - Returns the blocksize of the specified algorithm
Description
int mcrypt_module_get_algo_block_size (string algorithm [, string lib_dir])
This function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.
1789
mcrypt_module_get_algo_key_size
(PHP 4 >= 4.0.2)
mcrypt_module_get_algo_key_size - Returns the maximum supported keysize of the opened mode
Description
int mcrypt_module_get_algo_key_size (string algorithm [, string lib_dir])
This function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter
can contain the location where the mode module is on the system.
1790
mcrypt_module_get_supported_key_sizes
(PHP 4 >= 4.0.2)
mcrypt_module_get_supported_key_sizes - Returns an array with the supported keysizes of the opened
algorithm
Description
array mcrypt_module_get_supported_key_sizes (string algorithm [, string lib_dir])
Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes
between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can
contain the location where the mode module is on the system.
See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.
1791
mcrypt_module_is_block_algorithm_mode
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_algorithm_mode - This function returns if the the specified module is a block
algorithm or not
Description
bool mcrypt_module_is_block_algorithm_mode (string mode [, string lib_dir])
This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (eg. FALSE for stream,
and TRUE for cbc, cfb, ofb). The optional lib_dir parameter can contain the location where the mode module is on the system.
1792
mcrypt_module_is_block_algorithm
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_algorithm - This function checks whether the specified algorithm is a block
algorithm
Description
bool mcrypt_module_is_block_algorithm (string algorithm [, string lib_dir])
This function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional
lib_dir parameter can contain the location where the algorithm module is on the system.
1793
mcrypt_module_is_block_mode
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_mode - This function returns if the the specified mode outputs blocks or not
Description
bool mcrypt_module_is_block_mode (string mode [, string lib_dir])
This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (eg. TRUE for cbc and ecb,
and FALSE for cfb and stream). The optional lib_dir parameter can contain the location where the mode module is on the
system.
1794
mcrypt_module_open
(PHP 4 >= 4.0.2)
mcrypt_module_open - Opens the module of the algorithm and the mode to be used
Description
resource mcrypt_module_open
mode_directory)
(string
algorithm,
string
algorithm_directory,
string
mode,
string
This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, eg. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling
mcrypt_module_close(). Normally it returns an encryption descriptor, or FALSE on error.
The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name,
it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or
mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were
compiled in into libmcrypt (usally /usr/local/lib/libmcrypt).
Example 483. mcrypt_module_open() examples
The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the
directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher an dmode, this only works
when the extension is linked against libmcrypt 2.4.x or 2.5.x.
Example 484. Using mcrypt_module_open() in encryption
The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the
directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works
when the extension is linked against libmcrypt 2.4.x or 2.5.x.
See
also
mcrypt_module_close(),
mcrypt_generic_deinit().
mcrypt_generic(),
1796
mdecrypt_generic(),
mcrypt_generic_init(),
and
mcrypt_module_self_test
(PHP 4 >= 4.0.2)
mcrypt_module_self_test - This function runs a self test on the specified module
Description
bool mcrypt_module_self_test (string algorithm [, string lib_dir])
This function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where
the algorithm module is on the system.
The function returns TRUE if the self test succeeds, or FALSE when if fails.
1797
mcrypt_ofb
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_ofb - Encrypt/decrypt data in OFB mode
Description
string mcrypt_ofb (int cipher, string key, string data, int mode, string iv)
string mcrypt_ofb (string cipher, string key, string data, int mode [, string iv])
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The
mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
1798
mdecrypt_generic
(PHP 4 >= 4.0.2)
mdecrypt_generic - Decrypt data
Description
string mdecrypt_generic (resource td, string data)
This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due
to the padding of the data.
Example 485. mdecrypt_generic() example
The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is
very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.
The decryption handle should alwayws be initialized with mcrypt_generic_init() with a key and an IV before calling this
function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See
mcrypt_module_open() for an example.
See also mcrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
1799
MCVE Payment Functions
Table of Contents
mcve_adduser ................................................................................................................................. 1803
mcve_adduserarg ............................................................................................................................. 1804
mcve_bt ......................................................................................................................................... 1805
mcve_checkstatus ............................................................................................................................ 1806
mcve_chkpwd ................................................................................................................................. 1807
mcve_chngpwd ................................................................................................................................ 1808
mcve_completeauthorizations ............................................................................................................. 1809
mcve_connect ................................................................................................................................. 1810
mcve_connectionerror ....................................................................................................................... 1811
mcve_deleteresponse ........................................................................................................................ 1812
mcve_deletetrans ............................................................................................................................. 1813
mcve_deleteusersetup ....................................................................................................................... 1814
mcve_deluser .................................................................................................................................. 1815
mcve_destroyconn ........................................................................................................................... 1816
mcve_destroyengine ......................................................................................................................... 1817
mcve_disableuser ............................................................................................................................. 1818
mcve_edituser ................................................................................................................................. 1819
mcve_enableuser .............................................................................................................................. 1820
mcve_force ..................................................................................................................................... 1821
mcve_getcell ................................................................................................................................... 1822
mcve_getcellbynum .......................................................................................................................... 1823
mcve_getcommadelimited ................................................................................................................. 1824
mcve_getheader ............................................................................................................................... 1825
mcve_getuserarg .............................................................................................................................. 1826
mcve_getuserparam .......................................................................................................................... 1827
mcve_gft ........................................................................................................................................ 1828
mcve_gl ......................................................................................................................................... 1829
mcve_gut ........................................................................................................................................ 1830
mcve_initconn ................................................................................................................................. 1831
mcve_initengine .............................................................................................................................. 1832
mcve_initusersetup ........................................................................................................................... 1833
mcve_iscommadelimited ................................................................................................................... 1834
mcve_liststats .................................................................................................................................. 1835
mcve_listusers ................................................................................................................................. 1836
mcve_maxconntimeout ..................................................................................................................... 1837
mcve_monitor ................................................................................................................................. 1838
mcve_numcolumns ........................................................................................................................... 1839
mcve_numrows ............................................................................................................................... 1840
mcve_override ................................................................................................................................. 1841
mcve_parsecommadelimited .............................................................................................................. 1842
mcve_ping ...................................................................................................................................... 1843
mcve_preauth .................................................................................................................................. 1844
mcve_preauthcompletion ................................................................................................................... 1845
mcve_qc ......................................................................................................................................... 1846
mcve_responseparam ........................................................................................................................ 1847
mcve_return .................................................................................................................................... 1848
mcve_returncode .............................................................................................................................. 1849
mcve_returnstatus ............................................................................................................................ 1850
1800
MCVE
mcve_sale ....................................................................................................................................... 1851
mcve_setblocking ............................................................................................................................ 1852
mcve_setdropfile .............................................................................................................................. 1853
mcve_setip ..................................................................................................................................... 1854
mcve_setssl ..................................................................................................................................... 1855
mcve_settimeout .............................................................................................................................. 1856
mcve_settle ..................................................................................................................................... 1857
mcve_text_avs ................................................................................................................................. 1858
mcve_text_code ............................................................................................................................... 1859
mcve_text_cv .................................................................................................................................. 1860
mcve_transactionauth ....................................................................................................................... 1861
mcve_transactionavs ......................................................................................................................... 1862
mcve_transactionbatch ...................................................................................................................... 1863
mcve_transactioncv .......................................................................................................................... 1864
mcve_transactionid ........................................................................................................................... 1865
mcve_transactionitem ....................................................................................................................... 1866
mcve_transactionssent ...................................................................................................................... 1867
mcve_transactiontext ........................................................................................................................ 1868
mcve_transinqueue ........................................................................................................................... 1869
mcve_transnew ................................................................................................................................ 1870
mcve_transparam ............................................................................................................................. 1871
mcve_transsend ............................................................................................................................... 1872
mcve_ub ........................................................................................................................................ 1873
mcve_uwait .................................................................................................................................... 1874
mcve_verifyconnection ..................................................................................................................... 1875
mcve_verifysslcert ........................................................................................................................... 1876
mcve_void ...................................................................................................................................... 1877
1801
Introduction
These functions interface the MCVE API (libmcve), allowing you to work directly with MCVE from your PHP scripts.
MCVE is Main Street Softworks' solution to direct credit card processing. It lets you directly address the credit card clearing
houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE module for PHP, you can process credit cards directly through MCVE via your
PHP scripts. The following references will outline the process.
Note: MCVE is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientelle to the MCVE platform.
Note: This extension is not available on Windows platforms.
Installation
To enable MCVE Support in PHP, first verify your LibMCVE installation directory. You will then need to configure PHP
with the --with-mcve option. If you use this option without specifying the path to your MCVE installation, PHP will attempt to look in the default LibMCVE Install location (/usr/local). If MCVE is in a non-standard location, run configure
with: --with-mcve=$mcve_path, where $mcve_path is the path to your MCVE installation. Please note that MCVE support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h under the include directory and libmcve.so and/or libmcve.a under the lib directory.
Since MCVE has true server/client separation, there are no additional requirements for running PHP with MCVE support.
To test your MCVE extension in PHP, you may connect to testbox.mcve.com on port 8333 for IP, or port 8444 for SSL using the MCVE PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at www.mcve.com [http://www.mcve.com/].
See Also
Additional documentation about MCVE's PHP API can be found at http://www.mcve.com/docs/phpapi.pdf. Main Street's
documentation is complete and should be the primary reference for functions.
1802
mcve_adduser
(PHP 4 >= 4.2.0)
mcve_adduser - Add an MCVE user using usersetup structure
Description
int mcve_adduser (resource conn, string admin_password, int usersetup)
Warning
This function is currently not documented; only the argument list is available.
1803
mcve_adduserarg
(PHP 4 >= 4.2.0)
mcve_adduserarg - Add a value to user configuration structure
Description
int mcve_adduserarg (resource usersetup, int argtype, string argval)
Warning
This function is currently not documented; only the argument list is available.
1804
mcve_bt
(PHP 4 >= 4.2.0)
mcve_bt - Get unsettled batch totals
Description
int mcve_bt (resource conn, string username, string password)
Warning
This function is currently not documented; only the argument list is available.
1805
mcve_checkstatus
(PHP 4 >= 4.2.0)
mcve_checkstatus - Check to see if a transaction has completed
Description
int mcve_checkstatus (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1806
mcve_chkpwd
(PHP 4 >= 4.2.0)
mcve_chkpwd - Verify Password
Description
int mcve_chkpwd (resource conn, string username, string password)
Warning
This function is currently not documented; only the argument list is available.
1807
mcve_chngpwd
(PHP 4 >= 4.2.0)
mcve_chngpwd - Change the system administrator's password
Description
int mcve_chngpwd (resource conn, string admin_password, string new_password)
Warning
This function is currently not documented; only the argument list is available.
1808
mcve_completeauthorizations
(PHP 4 >= 4.2.0)
mcve_completeauthorizations - Number of complete authorizations in queue, returning an array of their
identifiers
Description
int mcve_completeauthorizations (resource conn, int &array)
Warning
This function is currently not documented; only the argument list is available.
1809
mcve_connect
(PHP 4 >= 4.2.0)
mcve_connect - Establish the connection to MCVE
Description
int mcve_connect (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1810
mcve_connectionerror
(PHP 4 >= 4.3.0)
mcve_connectionerror - Get a textual representation of why a connection failed
Description
string mcve_connectionerror (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1811
mcve_deleteresponse
(PHP 4 >= 4.2.0)
mcve_deleteresponse - Delete specified transaction from MCVE_CONN structure
Description
bool mcve_deleteresponse (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1812
mcve_deletetrans
(PHP 4 >= 4.3.0)
mcve_deletetrans - Delete specified transaction from MCVE_CONN structure
Description
bool mcve_deletetrans (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1813
mcve_deleteusersetup
(PHP 4 >= 4.2.0)
mcve_deleteusersetup - Deallocate data associated with usersetup structure
Description
void mcve_deleteusersetup (resource usersetup)
Warning
This function is currently not documented; only the argument list is available.
1814
mcve_deluser
(PHP 4 >= 4.2.0)
mcve_deluser - Delete an MCVE user account
Description
int mcve_deluser (resource conn, string admin_password, string username)
Warning
This function is currently not documented; only the argument list is available.
1815
mcve_destroyconn
(PHP 4 >= 4.2.0)
mcve_destroyconn - Destroy the connection and MCVE_CONN structure
Description
void mcve_destroyconn (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1816
mcve_destroyengine
(PHP 4 >= 4.2.0)
mcve_destroyengine - Free memory associated with IP/SSL connectivity
Description
void mcve_destroyengine (void)
Warning
This function is currently not documented; only the argument list is available.
1817
mcve_disableuser
(PHP 4 >= 4.2.0)
mcve_disableuser - Disable an active MCVE user account
Description
int mcve_disableuser (resource conn, string admin_password, string username)
Warning
This function is currently not documented; only the argument list is available.
1818
mcve_edituser
(PHP 4 >= 4.2.0)
mcve_edituser - Edit MCVE user using usersetup structure
Description
int mcve_edituser (resource conn, string admin_password, int usersetup)
Warning
This function is currently not documented; only the argument list is available.
1819
mcve_enableuser
(PHP 4 >= 4.2.0)
mcve_enableuser - Enable an inactive MCVE user account
Description
int mcve_enableuser (resource conn, string admin_password, string username)
Warning
This function is currently not documented; only the argument list is available.
1820
mcve_force
(PHP 4 >= 4.2.0)
mcve_force - Send a FORCE to MCVE. (typically, a phone-authorization)
Description
int mcve_force (resiurce conn, string username, string password, string trackdata, string account, string expdate,
float amount, string authcode, string comments, string clerkid, string stationid, int ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1821
mcve_getcell
(PHP 4 >= 4.2.0)
mcve_getcell - Get a specific cell from a comma delimited response by column name
Description
string mcve_getcell (resource conn, int identifier, string column, int row)
Warning
This function is currently not documented; only the argument list is available.
1822
mcve_getcellbynum
(PHP 4 >= 4.2.0)
mcve_getcellbynum - Get a specific cell from a comma delimited response by column number
Description
string mcve_getcellbynum (resource conn, int identifier, int column, int row)
Warning
This function is currently not documented; only the argument list is available.
1823
mcve_getcommadelimited
(PHP 4 >= 4.2.0)
mcve_getcommadelimited - Get the RAW comma delimited data returned from MCVE
Description
string mcve_getcommadelimited (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1824
mcve_getheader
(PHP 4 >= 4.2.0)
mcve_getheader - Get the name of the column in a comma-delimited response
Description
string mcve_getheader (resource conn, int identifier, int column_num)
Warning
This function is currently not documented; only the argument list is available.
1825
mcve_getuserarg
(PHP 4 >= 4.2.0)
mcve_getuserarg - Grab a value from usersetup structure
Description
string mcve_getuserarg (resource usersetup, int argtype)
Warning
This function is currently not documented; only the argument list is available.
1826
mcve_getuserparam
(PHP 4 >= 4.3.0)
mcve_getuserparam - Get a user response parameter
Description
string mcve_getuserparam (resource conn, long identifier, int key)
Warning
This function is currently not documented; only the argument list is available.
1827
mcve_gft
(PHP 4 >= 4.2.0)
mcve_gft - Audit MCVE for Failed transactions
Description
int mcve_gft (resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)
Warning
This function is currently not documented; only the argument list is available.
1828
mcve_gl
(PHP 4 >= 4.2.0)
mcve_gl - Audit MCVE for settled transactions
Description
int mcve_gl (int conn, string username, string password, int type, string account, string batch, string clerkid,
string stationid, string comments, int ptrannum, string startdate, string enddate)
Warning
This function is currently not documented; only the argument list is available.
1829
mcve_gut
(PHP 4 >= 4.2.0)
mcve_gut - Audit MCVE for Unsettled Transactions
Description
int mcve_gut (resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)
Warning
This function is currently not documented; only the argument list is available.
1830
mcve_initconn
(PHP 4 >= 4.2.0)
mcve_initconn - Create and initialize an MCVE_CONN structure
Description
resource mcve_initconn (void)
Warning
This function is currently not documented; only the argument list is available.
1831
mcve_initengine
(PHP 4 >= 4.2.0)
mcve_initengine - Ready the client for IP/SSL Communication
Description
int mcve_initengine (string location)
Warning
This function is currently not documented; only the argument list is available.
1832
mcve_initusersetup
(PHP 4 >= 4.2.0)
mcve_initusersetup - Initialize structure to store user data
Description
resource mcve_initusersetup (void)
Warning
This function is currently not documented; only the argument list is available.
1833
mcve_iscommadelimited
(PHP 4 >= 4.2.0)
mcve_iscommadelimited - Checks to see if response is comma delimited
Description
int mcve_iscommadelimited (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1834
mcve_liststats
(PHP 4 >= 4.2.0)
mcve_liststats - List statistics for all users on MCVE system
Description
int mcve_liststats (resource conn, string admin_password)
Warning
This function is currently not documented; only the argument list is available.
1835
mcve_listusers
(PHP 4 >= 4.2.0)
mcve_listusers - List all users on MCVE system
Description
int mcve_listusers (resource conn, string admin_password)
Warning
This function is currently not documented; only the argument list is available.
1836
mcve_maxconntimeout
(PHP 4 >= 4.3.0)
mcve_maxconntimeout - The maximum amount of time the API will attempt a connection to MCVE
Description
bool mcve_maxconntimeout (resource conn, int secs)
Warning
This function is currently not documented; only the argument list is available.
1837
mcve_monitor
(PHP 4 >= 4.2.0)
mcve_monitor - Perform communication with MCVE (send/receive data) Non-blocking
Description
int mcve_monitor (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1838
mcve_numcolumns
(PHP 4 >= 4.2.0)
mcve_numcolumns - Number of columns returned in a comma delimited response
Description
int mcve_numcolumns (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1839
mcve_numrows
(PHP 4 >= 4.2.0)
mcve_numrows - Number of rows returned in a comma delimited response
Description
int mcve_numrows (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1840
mcve_override
(PHP 4 >= 4.2.0)
mcve_override - Send an OVERRIDE to MCVE
Description
int mcve_override (resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1841
mcve_parsecommadelimited
(PHP 4 >= 4.2.0)
mcve_parsecommadelimited - Parse the comma delimited response so mcve_getcell, etc will work
Description
int mcve_parsecommadelimited (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1842
mcve_ping
(PHP 4 >= 4.3.0)
mcve_ping - Send a ping request to MCVE
Description
int mcve_ping (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1843
mcve_preauth
(PHP 4 >= 4.2.0)
mcve_preauth - Send a PREAUTHORIZATION to MCVE
Description
int mcve_preauth (resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1844
mcve_preauthcompletion
(PHP 4 >= 4.2.0)
mcve_preauthcompletion - Complete a PREAUTHORIZATION... Ready it for settlement
Description
int mcve_preauthcompletion (resource conn, string username, string password, float finalamount, int sid, int
ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1845
mcve_qc
(PHP 4 >= 4.2.0)
mcve_qc - Audit MCVE for a list of transactions in the outgoing queue
Description
int mcve_qc (resource conn, string username, string password, string clerkid, string stationid, string comments,
int ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1846
mcve_responseparam
(PHP 4 >= 4.3.0)
mcve_responseparam - Get a custom response parameter
Description
string mcve_responseparam (resource conn, long identifier, string key)
Warning
This function is currently not documented; only the argument list is available.
1847
mcve_return
(PHP 4 >= 4.2.0)
mcve_return - Issue a RETURN or CREDIT to MCVE
Description
int mcve_return (int conn, string username, string password, string trackdata, string account, string expdate,
float amount, string comments, string clerkid, string stationid, int ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1848
mcve_returncode
(PHP 4 >= 4.2.0)
mcve_returncode - Grab the exact return code from the transaction
Description
int mcve_returncode (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1849
mcve_returnstatus
(PHP 4 >= 4.2.0)
mcve_returnstatus - Check to see if the transaction was successful
Description
int mcve_returnstatus (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1850
mcve_sale
(PHP 4 >= 4.2.0)
mcve_sale - Send a SALE to MCVE
Description
int mcve_sale (resource conn, string username, string password, string trackdata, string account, string expdate,
float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1851
mcve_setblocking
(PHP 4 >= 4.3.0)
mcve_setblocking - Set blocking/non-blocking mode for connection
Description
int mcve_setblocking (resource conn, int tf)
Warning
This function is currently not documented; only the argument list is available.
1852
mcve_setdropfile
(PHP 4 >= 4.2.0)
mcve_setdropfile - Set the connection method to Drop-File
Description
int mcve_setdropfile (resource conn, string directory)
Warning
This function is currently not documented; only the argument list is available.
1853
mcve_setip
(PHP 4 >= 4.2.0)
mcve_setip - Set the connection method to IP
Description
int mcve_setip (resource conn, string host, int port)
Warning
This function is currently not documented; only the argument list is available.
1854
mcve_setssl
(PHP 4 >= 4.2.0)
mcve_setssl - Set the connection method to SSL
Description
int mcve_setssl (resource conn, string host, int port)
Warning
This function is currently not documented; only the argument list is available.
1855
mcve_settimeout
(PHP 4 >= 4.2.0)
mcve_settimeout - Set maximum transaction time (per trans)
Description
int mcve_settimeout (resource conn, int seconds)
Warning
This function is currently not documented; only the argument list is available.
1856
mcve_settle
(PHP 4 >= 4.2.0)
mcve_settle - Issue a settlement command to do a batch deposit
Description
int mcve_settle (resource conn, string username, string password, string batch)
Warning
This function is currently not documented; only the argument list is available.
1857
mcve_text_avs
(PHP 4 >= 4.3.0)
mcve_text_avs - Get a textual representation of the return_avs
Description
string mcve_text_avs (string code)
Warning
This function is currently not documented; only the argument list is available.
1858
mcve_text_code
(PHP 4 >= 4.3.0)
mcve_text_code - Get a textual representation of the return_code
Description
string mcve_text_code (string code)
Warning
This function is currently not documented; only the argument list is available.
1859
mcve_text_cv
(PHP 4 >= 4.3.0)
mcve_text_cv - Get a textual representation of the return_cv
Description
string mcve_text_cv (int code)
Warning
This function is currently not documented; only the argument list is available.
1860
mcve_transactionauth
(PHP 4 >= 4.2.0)
mcve_transactionauth - Get the authorization number returned for the transaction (alpha-numeric)
Description
string mcve_transactionauth (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1861
mcve_transactionavs
(PHP 4 >= 4.2.0)
mcve_transactionavs - Get the Address Verification return status
Description
int mcve_transactionavs (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1862
mcve_transactionbatch
(PHP 4 >= 4.2.0)
mcve_transactionbatch - Get the batch number associated with the transaction
Description
int mcve_transactionbatch (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1863
mcve_transactioncv
(PHP 4 >= 4.2.0)
mcve_transactioncv - Get the CVC2/CVV2/CID return status
Description
int mcve_transactioncv (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1864
mcve_transactionid
(PHP 4 >= 4.2.0)
mcve_transactionid - Get the unique system id for the transaction
Description
int mcve_transactionid (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1865
mcve_transactionitem
(PHP 4 >= 4.2.0)
mcve_transactionitem - Get the ITEM number in the associated batch for this transaction
Description
int mcve_transactionitem (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1866
mcve_transactionssent
(PHP 4 >= 4.2.0)
mcve_transactionssent - Check to see if outgoing buffer is clear
Description
int mcve_transactionssent (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1867
mcve_transactiontext
(PHP 4 >= 4.2.0)
mcve_transactiontext - Get verbiage (text) return from MCVE or processing institution
Description
string mcve_transactiontext (resource conn, int identifier)
Warning
This function is currently not documented; only the argument list is available.
1868
mcve_transinqueue
(PHP 4 >= 4.2.0)
mcve_transinqueue - Number of transactions in client-queue
Description
int mcve_transinqueue (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1869
mcve_transnew
(PHP 4 >= 4.3.0)
mcve_transnew - Start a new transaction
Description
int mcve_transnew (resource conn)
Warning
This function is currently not documented; only the argument list is available.
1870
mcve_transparam
(PHP 4 >= 4.3.0)
mcve_transparam - Add a parameter to a transaction
Description
int mcve_transparam (resource conn, long identifier, int key)
Warning
This function is currently not documented; only the argument list is available.
1871
mcve_transsend
(PHP 4 >= 4.3.0)
mcve_transsend - Finalize and send the transaction
Description
int mcve_transsend (resource conn, long identifier)
Warning
This function is currently not documented; only the argument list is available.
1872
mcve_ub
(PHP 4 >= 4.2.0)
mcve_ub - Get a list of all Unsettled batches
Description
int mcve_ub (resource conn, string username, string password)
Warning
This function is currently not documented; only the argument list is available.
1873
mcve_uwait
(PHP 4 >= 4.3.0)
mcve_uwait - Wait x microsecs
Description
int mcve_uwait (long microsecs)
Warning
This function is currently not documented; only the argument list is available.
1874
mcve_verifyconnection
(PHP 4 >= 4.3.0)
mcve_verifyconnection - Set whether or not to PING upon connect to verify connection
Description
bool mcve_verifyconnection (resource conn, int tf)
Warning
This function is currently not documented; only the argument list is available.
1875
mcve_verifysslcert
(PHP 4 >= 4.3.0)
mcve_verifysslcert - Set whether or not to verify the server ssl certificate
Description
bool mcve_verifysslcert (resource conn, int tf)
Warning
This function is currently not documented; only the argument list is available.
1876
mcve_void
(PHP 4 >= 4.2.0)
mcve_void - VOID a transaction in the settlement queue
Description
int mcve_void (resource conn, string username, string password, int sid, int ptrannum)
Warning
This function is currently not documented; only the argument list is available.
1877
Mhash Functions
Table of Contents
mhash_count ................................................................................................................................... 1881
mhash_get_block_size ...................................................................................................................... 1882
mhash_get_hash_name ...................................................................................................................... 1883
mhash_keygen_s2k .......................................................................................................................... 1884
mhash ............................................................................................................................................ 1885
1878
Introduction
These functions are intended to work with mhash [http://mhash.sourceforge.net/]. Mhash can be used to create checksums,
message digests, message authentication codes, and more.
This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and
many others. For a complete list of supported hashes, refer to the documentation of mhash. The general rule is that you can
access the hash algorithm from PHP with MHASH_HASHNAME. For example, to access TIGER you use the PHP constant
MHASH_TIGER.
Requirements
To use it, download the mhash distribution from its web site [http://mhash.sourceforge.net/] and follow the included installation instructions.
Installation
You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.
Runtime Configuration
This extension has no configuration directives defined in php.ini.
Resource Types
This extension has no resource types defined.
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.
•
MHASH_MD5
•
MHASH_SHA1
•
MHASH_HAVAL256
•
MHASH_HAVAL192
•
MHASH_HAVAL160
•
MHASH_HAVAL128
•
MHASH_RIPEMD160
•
MHASH_GOST
1879
Mhash Functions
•
MHASH_TIGER
•
MHASH_CRC32
•
MHASH_CRC32B
Examples
Example 486. Compute the MD5 digest and hmac and print it out as hex
\n";
$hash = mhash (MHASH_MD5, $input, "Jefe");
print "The hmac is ".bin2hex ($hash)."
\n";
?>
This will produce:
The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738
1880
mhash_count
(PHP 3>= 3.0.9, PHP 4 )
mhash_count - Get the highest available hash id
Description
int mhash_count (void)
mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.
Example 487. Traversing all hashes
1881
mhash_get_block_size
(PHP 3>= 3.0.9, PHP 4 )
mhash_get_block_size - Get the block size of the specified hash
Description
int mhash_get_block_size (int hash)
mhash_get_block_size() is used to get the size of a block of the specified hash.
mhash_get_block_size() takes one argument, the hash and returns the size in bytes or FALSE, if the hash does not exist.
1882
mhash_get_hash_name
(PHP 3>= 3.0.9, PHP 4 )
mhash_get_hash_name - Get the name of the specified hash
Description
string mhash_get_hash_name (int hash)
mhash_get_hash_name() is used to get the name of the specified hash.
mhash_get_hash_name() takes the hash id as an argument and returns the name of the hash or FALSE, if the hash does not
exist.
Example 488. mhash_get_hash_name() example
The above example will print out:
MD5
1883
mhash_keygen_s2k
(PHP 4 >= 4.0.4)
mhash_keygen_s2k - Generates a key
Description
string mhash_keygen_s2k (int hash, string password, string salt, int bytes)
mhash_keygen_s2k() generates a key that is bytes long, from a user given password. This is the Salted S2K algorithm as
specified in the OpenPGP document (RFC 2440). That algorithm will use the specified hash algorithm to create the key.
The salt must be different and random enough for every key you generate in order to create different keys. That salt must be
known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be
padded with zeros if you supply less bytes.
Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users
normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly
recommended to use some kind of tranformation (like this function) to the user supplied key.
1884
mhash
(PHP 3>= 3.0.9, PHP 4 )
mhash - Compute hash
Description
string mhash (int hash, string data [, string key])
mhash() applies a hash function specified by hash to the data and returns the resulting hash (also called digest). If the key is
specified it will return the resulting HMAC. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode. In case of an error returns FALSE.
1885
Mimetype Functions
Table of Contents
mime_content_type .......................................................................................................................... 1888
1886
Introduction
The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences
at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.
This extension is derivated from Apache mod_mime_magic, which is itself based on the file command maintaind by Ian
F. Darwin. See the source code for further historic and copyright information.
Requirements
No external libraries are needed to build this extension.
Installation
You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.
Note: The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP
4.3.2
Note: This extension is not capable of handling the fully decorated magic file that generally comes with standard
Linux distro's and is supposed to be used with recent versions of file command.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 88. Mimetype configuration options
Name
Default
Changeable
mime_magic.magicfile
"/usr/share/misc/magic.mime"
PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().
Resource Types
This extension has no resource types defined.
Predefined Constants
This extension has no constants defined.
1887
mime_content_type
(PHP 4 >= 4.3.0)
mime_content_type - Detect MIME Content-type for a file
Description
string mime_content_type (string filename)
Returns the MIME content type for a file as determined by using information from the magic.mime file. Content types are
returned in MIME format, like text/plain or application/octet-stream.
1888
Microsoft SQL Server functions
Table of Contents
mssql_bind ..................................................................................................................................... 1892
mssql_close .................................................................................................................................... 1893
mssql_connect ................................................................................................................................. 1894
mssql_data_seek .............................................................................................................................. 1895
mssql_execute ................................................................................................................................. 1896
mssql_fetch_array ............................................................................................................................ 1897
mssql_fetch_assoc ............................................................................................................................ 1898
mssql_fetch_batch ............................................................................................................................ 1899
mssql_fetch_field ............................................................................................................................. 1900
mssql_fetch_object ........................................................................................................................... 1901
mssql_fetch_row .............................................................................................................................. 1902
mssql_field_length ........................................................................................................................... 1903
mssql_field_name ............................................................................................................................ 1904
mssql_field_seek .............................................................................................................................. 1905
mssql_field_type .............................................................................................................................. 1906
mssql_free_result ............................................................................................................................. 1907
mssql_free_statement ........................................................................................................................ 1908
mssql_get_last_message .................................................................................................................... 1909
mssql_guid_string ............................................................................................................................ 1910
mssql_init ....................................................................................................................................... 1911
mssql_min_error_severity .................................................................................................................. 1912
mssql_min_message_severity ............................................................................................................. 1913
mssql_next_result ............................................................................................................................ 1914
mssql_num_fields ............................................................................................................................ 1915
mssql_num_rows ............................................................................................................................. 1916
mssql_pconnect ............................................................................................................................... 1917
mssql_query .................................................................................................................................... 1918
mssql_result .................................................................................................................................... 1919
mssql_rows_affected ........................................................................................................................ 1920
mssql_select_db ............................................................................................................................... 1921
1889
Introduction
These functions allow you to access MS SQL Server database.
Requirements
Requirements for WIn32 platforms.
The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can
be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to
\winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access. Configuration of the client will require installation of all the tools.
Requirements for Unix/Linux platforms.
To use the MSSQL extension on Unix/Linux, you first need to build and install the FreeTDS library. Source code and installation instructions are available at the FreeTDS home page: http://www.freetds.org/
Installation
The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.
To get these functions to work, you have to compile PHP with --with-mssql[=DIR], where DIR is the FreeTDS install
prefix. And FreeTDS should be compiled using --enable-msdblib.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 89. MS SQL Server configuration options
Name
Default
Changeable
mssql.allow_persistent
"1"
PHP_INI_SYSTEM
mssql.max_persistent
"-1"
PHP_INI_SYSTEM
mssql.max_links
"-1"
PHP_INI_SYSTEM
mssql.min_error_severity
"10"
PHP_INI_ALL
mssql.min_message_severity
"10"
PHP_INI_ALL
mssql.compatability_mode
"0"
PHP_INI_ALL
mssql.connect_timeout
"5"
PHP_INI_ALL
mssql.timeout
"60"
PHP_INI_ALL
mssql.textsize
"-1"
PHP_INI_ALL
mssql.textlimit
"-1"
PHP_INI_ALL
mssql.batchsize
"0"
PHP_INI_ALL
mssql.datetimeconvert
"1"
PHP_INI_ALL
mssql.secure_connection
"0"
PHP_INI_SYSTEM
mssql.max_procs
"25"
PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().
1890
Microsoft SQL Server functions
Resource Types
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
MSSQL_ASSOC (integer)
MSSQL_NUM (integer)
MSSQL_BOTH (integer)
SQLTEXT (integer)
SQLVARCHAR (integer)
SQLCHAR (integer)
SQLINT1 (integer)
SQLINT2 (integer)
SQLINT4 (integer)
SQLBIT (integer)
SQLFLT8 (integer)
1891
mssql_bind
(PHP 4 >= 4.1.0)
mssql_bind - Adds a parameter to a stored procedure or a remote stored procedure
Description
int mssql_bind (int stmt, string param_name, mixed var, int type [, int is_output [, int is_null [, int maxlen]]])
Warning
This function is currently not documented; only the argument list is available.
See also mssql_execute(), mssql_free_statement(), and mssql_init()
1892
mssql_close
(PHP 3, PHP 4 )
mssql_close - Close MS SQL Server connection
Description
int mssql_close ([int link_identifier])
mssql_close() closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link
identifier isn't specified, the last opened link is assumed.
Returns TRUE on success or FALSE on failure.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
mssql_close() will not close persistent links generated by mssql_pconnect().
See also mssql_connect(), and mssql_pconnect().
1893
mssql_connect
(PHP 3, PHP 4 )
mssql_connect - Open MS SQL server connection
Description
int mssql_connect ([string servername [, string username [, string password]]])
Returns: A positive MS SQL link identifier on success, or FALSE on error.
mssql_connect() establishes a connection to a MS SQL server. The servername argument has to be a valid servername that
is defined in the 'interfaces' file.
In case a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the
link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling
mssql_close().
See also mssql_pconnect(), mssql_close().
1894
mssql_data_seek
(PHP 3, PHP 4 )
mssql_data_seek - Move internal row pointer
Description
int mssql_data_seek (int result_identifier, int row_number)
Returns: TRUE on success, FALSE on failure.
mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to
point to the specified row number. The next call to mssql_fetch_row() would return that row.
See also: mssql_data_seek().
1895
mssql_execute
(PHP 4 >= 4.1.0)
mssql_execute - Executes a stored procedure on a MS SQL server database
Description
int mssql_execute (int stmt)
Warning
This function is currently not documented; only the argument list is available.
Note: if the stored procedure returns parameters or a return value these will be available after the call to
mssql_execute() unless the stored procedure returns more than one result set. In that case use mssql_next_result()
to shift through the results. When the last result has been processed the output parameters and return values will be
available.
See also mssql_bind(), mssql_free_statement(), and mssql_init()
1896
mssql_fetch_array
(PHP 3, PHP 4 )
mssql_fetch_array - Fetch row as array
Description
array mssql_fetch_array (int result)
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of
the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(),
while it provides a significant added value.
For further details, also see mssql_fetch_row().
1897
mssql_fetch_assoc
(PHP 4 >= 4.2.0)
mssql_fetch_assoc - Returns an associative array of the current row in the result set specified by result_id
Description
array mssql_fetch_assoc (int result_id [, int result_type])
Warning
This function is currently not documented; only the argument list is available.
1898
mssql_fetch_batch
(PHP 4 >= 4.0.4)
mssql_fetch_batch - Returns the next batch of records
Description
int mssql_fetch_batch (string result_index)
Warning
This function is currently not documented; only the argument list is available.
1899
mssql_fetch_field
(PHP 3, PHP 4 )
mssql_fetch_field - Get field information
Description
object mssql_fetch_field (int result [, int field_offset])
Returns an object containing field information.
mssql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't
specified, the next field that wasn't yet retrieved by mssql_fetch_field() is retrieved.
The properties of the object are:
•
name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial
number.
•
column_source - the table from which the column was taken
•
max_length - maximum length of the column
•
numeric - 1 if the column is numeric
See also mssql_field_seek().
1900
mssql_fetch_object
(PHP 3)
mssql_fetch_object - Fetch row as object
Description
object mssql_fetch_object (int result)
Returns: An object with properties that correspond to the fetched row, or FALSE if there are no more rows.
mssql_fetch_object() is similar to mssql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is
insignificant).
See also mssql_fetch_array(), and mssql_fetch_row().
1901
mssql_fetch_row
(PHP 3, PHP 4 )
mssql_fetch_row - Get row as enumerated array
Description
array mssql_fetch_row (int result)
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
mssql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to mssql_fetch_rows() would return the next row in the result set, or FALSE if there are no more rows.
See also mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths(), and mssql_result().
1902
mssql_field_length
(PHP 3>= 3.0.3, PHP 4 )
mssql_field_length - Get the length of a field
Description
int mssql_field_length (int result [, int offset])
Warning
This function is currently not documented; only the argument list is available.
1903
mssql_field_name
(PHP 3>= 3.0.3, PHP 4 )
mssql_field_name - Get the name of a field
Description
int mssql_field_name (int result [, int offset])
1904
mssql_field_seek
(PHP 3, PHP 4 )
mssql_field_seek - Set field offset
Description
int mssql_field_seek (int result, int field_offset)
Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.
See also: mssql_fetch_field().
1905
mssql_field_type
(PHP 3>= 3.0.3, PHP 4 )
mssql_field_type - Get the type of a field
Description
string mssql_field_type (int result [, int offset])
1906
mssql_free_result
(PHP 3, PHP 4 )
mssql_free_result - Free result memory
Description
int mssql_free_result (int result)
mssql_free_result() only needs to be called if you are worried about using too much memory while your script is running.
All result memory will automatically be freed when the script ends. You may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.
1907
mssql_free_statement
(PHP 4 >= 4.3.2)
mssql_free_statement - Free statement memory
Description
int mssql_free_statement (int statement)
mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with
the statement identifier as an argument and the associated statement memory will be freed.
See also mssql_bind(), mssql_execute(), and mssql_init()
1908
mssql_get_last_message
(PHP 3, PHP 4 )
mssql_get_last_message - Returns the last message from server (over min_message_severity?)
Description
string mssql_get_last_message (void)
1909
mssql_guid_string
(PHP 4 >= 4.1.0)
mssql_guid_string - Converts a 16 byte binary GUID to a string
Description
string mssql_guid_string (string binary [, int short_format])
Warning
This function is currently not documented; only the argument list is available.
1910
mssql_init
(PHP 4 >= 4.1.0)
mssql_init - Initializes a stored procedure or a remote stored procedure
Description
int mssql_init (string sp_name [, int conn_id])
Warning
This function is currently not documented; only the argument list is available.
See also mssql_bind(), mssql_execute(), and mssql_free_statement()
1911
mssql_min_error_severity
(PHP 3, PHP 4 )
mssql_min_error_severity - Sets the lower error severity
Description
void mssql_min_error_severity (int severity)
1912
mssql_min_message_severity
(PHP 3, PHP 4 )
mssql_min_message_severity - Sets the lower message severity
Description
void mssql_min_message_severity (int severity)
1913
mssql_next_result
(PHP 4 >= 4.0.5)
mssql_next_result - Move the internal result pointer to the next result
Description
bool mssql_next_result (int result_id)
When sending more than one SQL statement to the server or executing a stored procedure with multiple results, it will cause
the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the rows from the new result set. The function will
return TRUE if an additional result set was available or FALSE otherwise.
Example 489. mssql_next_result() example
1914
mssql_num_fields
(PHP 3, PHP 4 )
mssql_num_fields - Get number of fields in result
Description
int mssql_num_fields (int result)
mssql_num_fields() returns the number of fields in a result set.
See also mssql_db_query(), mssql_query(), mssql_fetch_field(), and mssql_num_rows().
1915
mssql_num_rows
(PHP 3, PHP 4 )
mssql_num_rows - Get number of rows in result
Description
int mssql_num_rows (int result)
mssql_num_rows() returns the number of rows in a result set.
See also mssql_db_query(), mssql_query(), and mssql_fetch_row().
1916
mssql_pconnect
(PHP 3, PHP 4 )
mssql_pconnect - Open persistent MS SQL connection
Description
int mssql_pconnect ([string servername [, string username [, string password]]])
Returns: A positive MS SQL persistent link identifier on success, or FALSE on error.
mssql_pconnect() acts very much like mssql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mssql_close() will not close links established by mssql_pconnect()).
This type of links is therefore called 'persistent'.
1917
mssql_query
(PHP 3, PHP 4 )
mssql_query - Send MS SQL query
Description
int mssql_query (string query [, int link_identifier])
Returns: A positive MS SQL result identifier on success, or FALSE on error.
mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link
as if mssql_connect() was called, and use it.
See also mssql_db_query(), mssql_select_db(), and mssql_connect().
1918
mssql_result
(PHP 3, PHP 4 )
mssql_result - Get result data
Description
int mssql_result (int result, int i, mixed field)
mssql_result() returns the contents of one cell from a MS SQL result set. The field argument can be the field's offset, the
field's name or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as
bar from...'), it uses the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below).
As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mssql_result().
Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: mssql_fetch_row(), mssql_fetch_array(), and mssql_fetch_object().
1919
mssql_rows_affected
(PHP 4 >= 4.0.4)
mssql_rows_affected - Returns the number of records affected by the query
Description
int mssql_rows_affected (int conn_id)
Warning
This function is currently not documented; only the argument list is available.
1920
mssql_select_db
(PHP 3, PHP 4 )
mssql_select_db - Select MS SQL database
Description
int mssql_select_db (string database_name [, int link_identifier])
Returns: TRUE on success, FALSE on error
mssql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link
identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if
mssql_connect() was called, and use it.
Every subsequent call to mssql_query() will be made on the active database.
See also: mssql_connect(), mssql_pconnect(), and mssql_query()
1921
Ming functions for Flash
Table of Contents
ming_setcubicthreshold ..................................................................................................................... 1928
ming_setscale .................................................................................................................................. 1929
ming_useswfversion ......................................................................................................................... 1930
SWFAction ..................................................................................................................................... 1931
SWFBitmap->getHeight .................................................................................................................... 1940
SWFBitmap->getWidth ..................................................................................................................... 1941
SWFBitmap .................................................................................................................................... 1942
swfbutton_keypress .......................................................................................................................... 1944
SWFbutton->addAction .................................................................................................................... 1945
SWFbutton->addShape ..................................................................................................................... 1946
SWFbutton->setAction ...................................................................................................................... 1947
SWFbutton->setdown ....................................................................................................................... 1948
SWFbutton->setHit .......................................................................................................................... 1949
SWFbutton->setOver ........................................................................................................................ 1950
SWFbutton->setUp ........................................................................................................................... 1951
SWFbutton ..................................................................................................................................... 1952
SWFDisplayItem->addColor .............................................................................................................. 1955
SWFDisplayItem->move ................................................................................................................... 1956
SWFDisplayItem->moveTo ............................................................................................................... 1957
SWFDisplayItem->multColor ............................................................................................................. 1958
SWFDisplayItem->remove ................................................................................................................ 1959
SWFDisplayItem->Rotate .................................................................................................................. 1960
SWFDisplayItem->rotateTo ............................................................................................................... 1961
SWFDisplayItem->scale .................................................................................................................... 1963
SWFDisplayItem->scaleTo ................................................................................................................ 1964
SWFDisplayItem->setDepth .............................................................................................................. 1965
SWFDisplayItem->setName ............................................................................................................... 1966
SWFDisplayItem->setRatio ............................................................................................................... 1967
SWFDisplayItem->skewX ................................................................................................................. 1969
SWFDisplayItem->skewXTo ............................................................................................................. 1970
SWFDisplayItem->skewY ................................................................................................................. 1971
SWFDisplayItem->skewYTo ............................................................................................................. 1972
SWFDisplayItem ............................................................................................................................. 1973
SWFFill->moveTo ........................................................................................................................... 1974
SWFFill->rotateTo ........................................................................................................................... 1975
SWFFill->scaleTo ............................................................................................................................ 1976
SWFFill->skewXTo ......................................................................................................................... 1977
SWFFill->skewYTo ......................................................................................................................... 1978
SWFFill ......................................................................................................................................... 1979
swffont->getwidth ............................................................................................................................ 1980
SWFFont ........................................................................................................................................ 1981
SWFGradient->addEntry ................................................................................................................... 1982
SWFGradient .................................................................................................................................. 1983
SWFMorph->getshape1 .................................................................................................................... 1985
SWFMorph->getshape2 .................................................................................................................... 1986
SWFMorph ..................................................................................................................................... 1987
SWFMovie->add ............................................................................................................................. 1989
SWFMovie->nextframe ..................................................................................................................... 1990
1922
Ming (flash)
SWFMovie->output .......................................................................................................................... 1991
swfmovie->remove ........................................................................................................................... 1992
SWFMovie->save ............................................................................................................................ 1993
SWFMovie->setbackground ............................................................................................................... 1994
SWFMovie->setdimension ................................................................................................................. 1995
SWFMovie->setframes ..................................................................................................................... 1996
SWFMovie->setrate ......................................................................................................................... 1997
SWFMovie->streammp3 ................................................................................................................... 1998
SWFMovie ..................................................................................................................................... 1999
SWFShape->addFill ......................................................................................................................... 2000
SWFShape->drawCurve .................................................................................................................... 2002
SWFShape->drawCurveTo ................................................................................................................ 2003
SWFShape->drawLine ...................................................................................................................... 2004
SWFShape->drawLineTo .................................................................................................................. 2005
SWFShape->movePen ...................................................................................................................... 2006
SWFShape->movePenTo ................................................................................................................... 2007
SWFShape->setLeftFill ..................................................................................................................... 2008
SWFShape->setLine ......................................................................................................................... 2009
SWFShape->setRightFill ................................................................................................................... 2011
SWFShape ...................................................................................................................................... 2012
swfsprite->add ................................................................................................................................. 2013
SWFSprite->nextframe ..................................................................................................................... 2014
SWFSprite->remove ......................................................................................................................... 2015
SWFSprite->setframes ...................................................................................................................... 2016
SWFSprite ...................................................................................................................................... 2017
SWFText->addString ........................................................................................................................ 2019
SWFText->getWidth ........................................................................................................................ 2020
SWFText->moveTo .......................................................................................................................... 2021
SWFText->setColor ......................................................................................................................... 2022
SWFText->setFont ........................................................................................................................... 2023
SWFText->setHeight ........................................................................................................................ 2024
SWFText->setSpacing ...................................................................................................................... 2025
SWFText ........................................................................................................................................ 2026
SWFTextField->addstring ................................................................................................................. 2027
SWFTextField->align ....................................................................................................................... 2028
SWFTextField->setbounds ................................................................................................................. 2029
SWFTextField->setcolor ................................................................................................................... 2030
SWFTextField->setFont .................................................................................................................... 2031
SWFTextField->setHeight ................................................................................................................. 2032
SWFTextField->setindentation ........................................................................................................... 2033
SWFTextField->setLeftMargin ........................................................................................................... 2034
SWFTextField->setLineSpacing ......................................................................................................... 2035
SWFTextField->setMargins ............................................................................................................... 2036
SWFTextField->setname ................................................................................................................... 2037
SWFTextField->setrightMargin .......................................................................................................... 2038
SWFTextField ................................................................................................................................. 2039
1923
Warning
This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and
anything else documented about this extension -- may change without notice in a future release of PHP. Use this
extension at your own risk.
Introduction
First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash")
format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs),
morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only
thing that's missing is sound events.
Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary,
though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if
not embedded.
Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the
code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides
some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming
is still being maintained; if there's a feature that you want to see, just let us know ming@opaque.net
[mailto:ming@opaque.net].
Ming was added in PHP 4.0.5.
Requirements
To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are
available at the Ming home page: http://ming.sourceforge.net/along with examples, a small tutorial, and the latest news.
Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.
This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line
in the Makefile to change the installation directory.
Installation
Example 490. built into php (unix)
mkdir
cp
/ext/ming
/ext/ming
php_ext/*
cd
./buildconf
./configure
--with-ming
Build and install php as usual, restart web server if necessary.
Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of
your Ming scripts.
1924
Ming functions for Flash
Runtime Configuration
This extension has no configuration directives defined in php.ini.
Resource Types
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
SWFBUTTON_HIT (integer)
SWFBUTTON_DOWN (integer)
SWFBUTTON_OVER (integer)
SWFBUTTON_UP (integer)
SWFBUTTON_MOUSEUPOUTSIDE (integer)
SWFBUTTON_DRAGOVER (integer)
SWFBUTTON_DRAGOUT (integer)
SWFBUTTON_MOUSEUP (integer)
SWFBUTTON_MOUSEDOWN (integer)
SWFBUTTON_MOUSEOUT (integer)
SWFBUTTON_MOUSEOVER (integer)
SWFFILL_RADIAL_GRADIENT (integer)
SWFFILL_LINEAR_GRADIENT (integer)
SWFFILL_TILED_BITMAP (integer)
SWFFILL_CLIPPED_BITMAP (integer)
SWFTEXTFIELD_HASLENGTH (integer)
SWFTEXTFIELD_NOEDIT (integer)
SWFTEXTFIELD_PASSWORD (integer)
SWFTEXTFIELD_MULTILINE (integer)
SWFTEXTFIELD_WORDWRAP (integer)
SWFTEXTFIELD_DRAWBOX (integer)
SWFTEXTFIELD_NOSELECT (integer)
SWFTEXTFIELD_HTML (integer)
1925
Ming functions for Flash
SWFTEXTFIELD_ALIGN_LEFT (integer)
SWFTEXTFIELD_ALIGN_RIGHT (integer)
SWFTEXTFIELD_ALIGN_CENTER (integer)
SWFTEXTFIELD_ALIGN_JUSTIFY (integer)
SWFACTION_ONLOAD (integer)
SWFACTION_ENTERFRAME (integer)
SWFACTION_UNLOAD (integer)
SWFACTION_MOUSEMOVE (integer)
SWFACTION_MOUSEDOWN (integer)
SWFACTION_MOUSEUP (integer)
SWFACTION_KEYDOWN (integer)
SWFACTION_KEYUP (integer)
SWFACTION_DATA (integer)
Predefined Classes
The classes below are defined by this extension, and will only be available when the extension has either been compiled into
PHP or dynamically loaded at runtime.
Ming introduces 13 new objects in PHP, all with matching methods and attributes. To use them, you need to know about objects.
swfshape
swffill
swfgradient
swfbitmap
swftext
swftextfield
swffont
swfdisplayitem
swfmovie
swfbutton
swfaction
swfmorph
1926
Ming functions for Flash
swfsprite
1927
ming_setcubicthreshold
(PHP 4 >= 4.0.5)
ming_setcubicthreshold - Set cubic threshold (?)
Description
void ming_setcubicthreshold (int threshold)
Warning
This function is currently not documented; only the argument list is available.
1928
ming_setscale
(PHP 4 >= 4.0.5)
ming_setscale - Set scale (?)
Description
void ming_setscale (int scale)
Warning
This function is currently not documented; only the argument list is available.
1929
ming_useswfversion
(PHP 4 >= 4.2.0)
ming_useswfversion - Use SWF version (?)
Description
void ming_useswfversion (int version)
Warning
This function is currently not documented; only the argument list is available.
1930
SWFAction
()
SWFAction - Creates a new Action.
Description
new swfaction (string script)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfaction() creates a new Action, and compiles the given script into an SWFAction object.
The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded
to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery
because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every
function would have to know exactly where to return to.
So what's left? The compiler recognises the following tokens:
•
break
•
for
•
continue
•
if
•
else
•
do
•
while
There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in
expressions:
time()
Returns the number of milliseconds (?) elapsed since the movie started.
random(seed)
Returns a pseudo-random number in the range 0-seed.
length(expr)
Returns the length of the given expression.
int(number)
Returns the given number rounded down to the nearest integer.
1931
SWFAction
concat(expr, expr)
Returns the concatenation of the given expressions.
ord(expr)
Returns the ASCII code for the given character
chr(num)
Returns the character for the given ASCII code
substr(string, location, length)
Returns the substring of length length at location location of the given string string.
Additionally, the following commands may be used:
duplicateClip(clip, name, depth)
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.
removeClip(expr)
Removes the named movie clip.
trace(expr)
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
startDrag(target, lock, [left, top, right, bottom])
Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1
(TRUE). Optional parameters define a bounding area for the dragging.
stopDrag()
Stop dragging my heart around. And this movie clip, too.
callFrame(expr)
Call the named frame as a function.
getURL(url, target, [method])
Load the given URL into the named target. The target argument corresponds to HTML document targets (such as
"_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the
server.
loadMovie(url, target)
Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical
values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).
nextFrame()
Go to the next frame.
prevFrame()
Go to the last (or, rather, previous) frame.
play()
Start playing the movie.
stop()
Stop playing the movie.
toggleQuality()
Toggle between high and low quality.
1932
SWFAction
stopSounds()
Stop playing all sounds.
gotoFrame(num)
Go to frame number num. Frame numbers start at 0.
gotoFrame(name)
Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.
setTarget(expr)
Sets the context for action. Or so they say- I really have no idea what this does.
And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check
if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt
it actually works. You can just use /:framesLoaded instead.
Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of
them, and here they are:
•
x
•
y
•
xScale
•
yScale
•
currentFrame - (read-only)
•
totalFrames - (read-only)
•
alpha - transparency level
•
visible - 1=on, 0=off (?)
•
width - (read-only)
•
height - (read-only)
•
rotation
•
target - (read-only) (???)
•
framesLoaded - (read-only)
•
name
•
dropTarget - (read-only) (???)
•
url - (read-only) (???)
•
highQuality - 1=high, 0=low (?)
•
focusRect - (???)
•
soundBufTime - (???)
So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash
keeps track of the sprites in the movie, just like a unix filesystem- here it shows that box is at the top level. If the sprite
1933
SWFAction
named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.
This simple example will move the red square across the window.
Example 491. swfaction() example
addFill(0xff, 0, 0);
$s->setRightFill($f);
$s->movePenTo(-500,-500);
$s->drawLineTo(500,-500);
$s->drawLineTo(500,500);
$s->drawLineTo(-500,500);
$s->drawLineTo(-500,-500);
$p = new SWFSprite();
$i = $p->add($s);
$i->setDepth(1);
$p->nextFrame();
for($n=0; $n<5; ++$n)
{
$i->rotate(-15);
$p->nextFrame();
}
$m = new SWFMovie();
$m->setBackground(0xff, 0xff, 0xff);
$m->setDimension(6000,4000);
$i = $m->add($p);
$i->setDepth(1);
$i->moveTo(-500,2000);
$i->setName("box");
$m->add(new SWFAction("/box.x += 3;"));
$m->nextFrame();
$m->add(new SWFAction("gotoFrame(0); play();"));
$m->nextFrame();
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
This simple example tracks down your mouse on the screen.
Example 492. swfaction() example
setRate(36.0);
$m->setDimension(1200, 800);
$m->setBackground(0, 0, 0);
/* mouse tracking sprite - empty, but follows mouse so we can
get its x and y coordinates */
$i = $m->add(new SWFSprite());
$i->setName('mouse');
$m->add(new SWFAction("
startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
"));
1934
SWFAction
/* might as well turn off antialiasing, since these are just squares. */
$m->add(new SWFAction("
this.quality = 0;
"));
/* morphing box */
$r = new SWFMorph();
$s = $r->getShape1();
/* Note this is backwards from normal shapes. No idea why. */
$s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
$s->movePenTo(-40, -40);
$s->drawLine(80, 0);
$s->drawLine(0, 80);
$s->drawLine(-80, 0);
$s->drawLine(0, -80);
$s = $r->getShape2();
$s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
$s->movePenTo(-1, -1);
$s->drawLine(2, 0);
$s->drawLine(0, 2);
$s->drawLine(-2, 0);
$s->drawLine(0, -2);
/* sprite container for morphing box this is just a timeline w/ the box morphing */
$box = new SWFSprite();
$box->add(new SWFAction("
stop();
"));
$i = $box->add($r);
for($n=0; $n<=20; ++$n)
{
$i->setRatio($n/20);
$box->nextFrame();
}
/* this container sprite allows us to use the same action code many times */
$cell = new SWFSprite();
$i = $cell->add($box);
$i->setName('box');
$cell->add(new SWFAction("
setTarget('box');
/* ...x means the x coordinate of the parent, i.e. (..).x */
dx = (/mouse.x + random(6)-3 - ...x)/5;
dy = (/mouse.y + random(6)-3 - ...y)/5;
gotoFrame(int(dx*dx + dy*dy));
"));
$cell->nextFrame();
$cell->add(new SWFAction("
gotoFrame(0);
play();
"));
$cell->nextFrame();
/* finally, add a bunch of the cells to the movie */
1935
SWFAction
for($x=0; $x<12; ++$x)
{
for($y=0; $y<8; ++$y)
{
$i = $m->add($cell);
$i->moveTo(100*$x+50, 100*$y+50);
}
}
$m->nextFrame();
$m->add(new SWFAction("
gotoFrame(1);
play();
"));
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
Same as above, but with nice colored balls...
Example 493. swfaction() example
setDimension(11000, 8000);
$m->setBackground(0x00, 0x00, 0x00);
$m->add(new SWFAction("
this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);
"));
// mouse tracking sprite
$t = new SWFSprite();
$i = $m->add($t);
$i->setName('mouse');
$g = new SWFGradient();
$g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
$g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
$g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
$g->addEntry(1.0, 0xff, 0xff, 0xff, 0);
// gradient shape thing
$s = new SWFShape();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.03);
$s->setRightFill($f);
$s->movePenTo(-600, -600);
$s->drawLine(1200, 0);
$s->drawLine(0, 1200);
$s->drawLine(-1200, 0);
$s->drawLine(0, -1200);
// need to make this a sprite so we can multColor it
$p = new SWFSprite();
$p->add($s);
$p->nextFrame();
1936
SWFAction
// put the shape in here, each frame a different color
$q = new SWFSprite();
$q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
$i = $q->add($p);
$i->multColor(1.0,
$q->nextFrame();
$i->multColor(1.0,
$q->nextFrame();
$i->multColor(1.0,
$q->nextFrame();
$i->multColor(1.0,
$q->nextFrame();
$i->multColor(0.5,
$q->nextFrame();
$i->multColor(0.5,
$q->nextFrame();
$i->multColor(1.0,
$q->nextFrame();
1.0, 1.0);
0.5, 0.5);
0.75, 0.5);
1.0, 0.5);
1.0, 0.5);
0.5, 1.0);
0.5, 1.0);
// finally, this one contains the action code
$p = new SWFSprite();
$i = $p->add($q);
$i->setName('frames');
$p->add(new SWFAction("
dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;
"));
$p->nextFrame();
$p->add(new SWFAction("
this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;
"));
$p->nextFrame();
$p->add(new SWFAction("prevFrame(); play();"));
$p->nextFrame();
$i = $m->add($p);
$i->setName('frames');
$m->nextFrame();
$m->add(new SWFAction("
lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;
++num;
if(num == 11)
num = 1;
removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);
"));
1937
SWFAction
$m->nextFrame();
$m->add(new SWFAction("prevFrame(); play();"));
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
This simple example will handles keyboard actions. (You'll probably have to click in the window to give it focus. And you'll
probably have to leave your mouse in the frame, too. If you know how to give buttons focus programatically, feel free to
share, won't you?)
Example 494. swfaction() example
add(new SWFAction("stop();"));
$chars = "abcdefghijklmnopqrstuvwxyz".
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".
"1234567890!@#$%^&/*()_+-=/[]{}|;:,.<>?`~";
$f = new SWFFont("_sans");
for($n=0; $nremove($i);
$t = new SWFTextField();
$t->setFont($f);
$t->setHeight(240);
$t->setBounds(600,240);
$t->align(SWFTEXTFIELD_ALIGN_CENTER);
$t->addString($c);
$i = $p->add($t);
$p->labelFrame($c);
$p->nextFrame();
}
/* hit region for button - the entire frame */
$s = new SWFShape();
$s->setFillStyle0($s->addSolidFill(0, 0, 0, 0));
$s->drawLine(600, 0);
$s->drawLine(0, 400);
$s->drawLine(-600, 0);
$s->drawLine(0, -400);
/* button checks for pressed key, sends sprite to the right frame */
$b = new SWFButton();
$b->addShape($s, SWFBUTTON_HIT);
for($n=0; $naddAction(new SWFAction("
setTarget('/char');
gotoFrame('$c');
"), SWFBUTTON_KEYPRESS($c));
}
$m = new SWFMovie();
$m->setDimension(600,400);
$i = $m->add($p);
$i->setName('char');
$i->moveTo(0,80);
1938
SWFAction
$m->add($b);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1939
SWFBitmap->getHeight
()
SWFBitmap->getHeight - Returns the bitmap's height.
Description
int swfbitmap->getheight (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbitmap->getheight() returns the bitmap's height in pixels.
See also swfbitmap->getwidth().
1940
SWFBitmap->getWidth
()
SWFBitmap->getWidth - Returns the bitmap's width.
Description
int swfbitmap->getwidth (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbitmap->getwidth() returns the bitmap's width in pixels.
See also swfbitmap->getheight().
1941
SWFBitmap
()
SWFBitmap - Loads Bitmap object
Description
new swfbitmap (string filename [, int alphafilename])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file named filename. alphafilename indicates a MSK
file to be used as an alpha mask for a Jpeg image.
Note: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!
SWFBitmap has the following methods : swfbitmap->getwidth() and swfbitmap->getheight().
You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from
the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but
that's not set up yet.
Example 495. Import PNG files
addFill(new SWFBitmap("png.dbl"));
$s->setRightFill($f);
$s->drawLine(32, 0);
$s->drawLine(0, 32);
$s->drawLine(-32, 0);
$s->drawLine(0, -32);
$m = new SWFMovie();
$m->setDimension(32, 32);
$m->add($s);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
And you can put an alpha mask on a jpeg fill.
Example 496. swfbitmap() example
addFill(new SWFBitmap("alphafill.jpg", "alphafill.msk"));
$s->setRightFill($f);
1942
SWFBitmap
$s->drawLine(640, 0);
$s->drawLine(0, 480);
$s->drawLine(-640, 0);
$s->drawLine(0, -480);
$c = new SWFShape();
$c->setRightFill($c->addFill(0x99, 0x99, 0x99));
$c->drawLine(40, 0);
$c->drawLine(0, 40);
$c->drawLine(-40, 0);
$c->drawLine(0, -40);
$m = new SWFMovie();
$m->setDimension(640, 480);
$m->setBackground(0xcc, 0xcc, 0xcc);
// draw checkerboard background
for($y=0; $y<480; $y+=40)
{
for($x=0; $x<640; $x+=80)
{
$i = $m->add($c);
$i->moveTo($x, $y);
}
$y+=40;
for($x=40; $x<640; $x+=80)
{
$i = $m->add($c);
$i->moveTo($x, $y);
}
}
$m->add($s);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1943
swfbutton_keypress
(PHP 4 >= 4.0.5)
swfbutton_keypress - Returns the action flag for keyPress(char)
Description
int swfbutton_keypress (string str)
Warning
This function is currently not documented; only the argument list is available.
1944
SWFbutton->addAction
()
SWFbutton->addAction - Adds an action
Description
void swfbutton->addaction (ressource action, int flags)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton->addaction() adds the action action to this button for the given conditions. The following flags are valid: SWFBUTTON_MOUSEOVER,
SWFBUTTON_MOUSEOUT,
SWFBUTTON_MOUSEUP,
SWFBUTTON_MOUSEUPOUTSIDE,
SWFBUTTON_MOUSEDOWN,
SWFBUTTON_DRAGOUT
and
SWFBUTTON_DRAGOVER.
See also swfbutton->addshape() and swfaction().
1945
SWFbutton->addShape
()
SWFbutton->addShape - Adds a shape to a button
Description
void swfbutton->addshape (ressource shape, int flags)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton->addshape() adds the shape shape to this button. The following flags' values are valid: SWFBUTTON_UP,
SWFBUTTON_OVER, SWFBUTTON_DOWN or SWFBUTTON_HIT. SWFBUTTON_HIT isn't ever displayed, it
defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of
the button.
1946
SWFbutton->setAction
()
SWFbutton->setAction - Sets the action
Description
void swfbutton->setaction (ressource action)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton->setaction() sets the action to be performed when the button is clicked. Alias for addAction(shape, SWFBUTTON_MOUSEUP). action is a swfaction().
See also swfbutton->addshape() and swfaction().
1947
SWFbutton->setdown
()
SWFbutton->setdown - Alias for addShape(shape, SWFBUTTON_DOWN))
Description
void swfbutton->setdown (ressource shape)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).
See also swfbutton->addshape() and swfaction().
1948
SWFbutton->setHit
()
SWFbutton->setHit - Alias for addShape(shape, SWFBUTTON_HIT)
Description
void swfbutton->sethit (ressource shape)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).
See also swfbutton->addshape() and swfaction().
1949
SWFbutton->setOver
()
SWFbutton->setOver - Alias for addShape(shape, SWFBUTTON_OVER)
Description
void swfbutton->setover (ressource shape)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).
See also swfbutton->addshape() and swfaction().
1950
SWFbutton->setUp
()
SWFbutton->setUp - Alias for addShape(shape, SWFBUTTON_UP)
Description
void swfbutton->setup (ressource shape)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).
See also swfbutton->addshape() and swfaction().
1951
SWFbutton
()
SWFbutton - Creates a new Button.
Description
new swfbutton (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfbutton() creates a new Button. Roll over it, click it, see it call action code. Swank.
SWFButton has the following methods : swfbutton->addshape(), swfbutton->setup(), swfbutton->setover() swfbutton>setdown(), swfbutton->sethit() swfbutton->setaction() and swfbutton->addaction().
This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.
Example 497. swfbutton() example
setFont($f);
$t->addString($string);
$t->setHeight(200);
$t->setBounds(3200,200);
return $t;
}
function addLabel($string)
{
global $p;
$i = $p->add(label($string));
$p->nextFrame();
$p->remove($i);
}
$p->add(new SWFAction("stop();"));
addLabel("NO ACTION");
addLabel("SWFBUTTON_MOUSEUP");
addLabel("SWFBUTTON_MOUSEDOWN");
addLabel("SWFBUTTON_MOUSEOVER");
addLabel("SWFBUTTON_MOUSEOUT");
addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
addLabel("SWFBUTTON_DRAGOVER");
addLabel("SWFBUTTON_DRAGOUT");
function rect($r, $g, $b)
{
1952
SWFbutton
$s = new SWFShape();
$s->setRightFill($s->addFill($r, $g, $b));
$s->drawLine(600,0);
$s->drawLine(0,600);
$s->drawLine(-600,0);
$s->drawLine(0,-600);
return $s;
}
$b = new SWFButton();
$b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
$b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
$b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);
$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
SWFBUTTON_MOUSEUP);
$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
SWFBUTTON_MOUSEDOWN);
$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
SWFBUTTON_MOUSEOVER);
$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
SWFBUTTON_MOUSEOUT);
$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
SWFBUTTON_MOUSEUPOUTSIDE);
$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
SWFBUTTON_DRAGOVER);
$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
SWFBUTTON_DRAGOUT);
$m = new SWFMovie();
$m->setDimension(4000,3000);
$i = $m->add($p);
$i->setName("label");
$i->moveTo(400,1900);
$i = $m->add($b);
$i->moveTo(400,900);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.
Example 498. swfbutton->addaction() example
setRightFill($s->addFill(0xff, 0, 0));
$s->drawLine(1000,0);
$s->drawLine(0,1000);
$s->drawLine(-1000,0);
$s->drawLine(0,-1000);
$b = new SWFButton();
$b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);
$b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
SWFBUTTON_MOUSEDOWN);
1953
SWFbutton
$b->addAction(new SWFAction("stopDrag();"),
SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);
$p = new SWFSprite();
$p->add($b);
$p->nextFrame();
$m = new SWFMovie();
$i = $m->add($p);
$i->setName('test');
$i->moveTo(1000,1000);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1954
SWFDisplayItem->addColor
()
SWFDisplayItem->addColor - Adds the given color to this item's color transform.
Description
void swfdisplayitem->addcolor ([int red [, int green [, int blue [, int a]]]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
1955
SWFDisplayItem->move
()
SWFDisplayItem->move - Moves object in relative coordinates.
Description
void swfdisplayitem->move (int dx, int dy)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->move() moves the current object by (dx,dy) from its current position.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->moveto().
1956
SWFDisplayItem->moveTo
()
SWFDisplayItem->moveTo - Moves object in global coordinates.
Description
void swfdisplayitem->moveto (int x, int y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->moveto() moves the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->move().
1957
SWFDisplayItem->multColor
()
SWFDisplayItem->multColor - Multiplies the item's color transform.
Description
void swfdisplayitem->multcolor ([int red [, int green [, int blue [, int a]]]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->multcolor() multiplies the item's color transform by the given values.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This simple example will modify your picture's atmospher to Halloween (use a landscape or bright picture).
Example 499. swfdisplayitem->multcolor() example
setRightFill($s->addFill($b));
$s->drawLine($b->getWidth(), 0);
$s->drawLine(0, $b->getHeight());
$s->drawLine(-$b->getWidth(), 0);
$s->drawLine(0, -$b->getHeight());
$m = new SWFMovie();
$m->setDimension($b->getWidth(), $b->getHeight());
$i = $m->add($s);
for($n=0; $n<=20; ++$n)
{
$i->multColor(1.0-$n/10, 1.0, 1.0);
$i->addColor(0xff*$n/20, 0, 0);
$m->nextFrame();
}
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1958
SWFDisplayItem->remove
()
SWFDisplayItem->remove - Removes the object from the movie
Description
void swfdisplayitem->remove (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->remove() removes this object from the movie's display list.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfmovie->add().
1959
SWFDisplayItem->Rotate
()
SWFDisplayItem->Rotate - Rotates in relative coordinates.
Description
void swfdisplayitem->rotate (float ddegrees)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->rotate() rotates the current object by ddegrees degrees from its current rotation.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->rotateto().
1960
SWFDisplayItem->rotateTo
()
SWFDisplayItem->rotateTo - Rotates the object in global coordinates.
Description
void swfdisplayitem->rotateto (float degrees)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->rotateto() set the current object rotation to degrees degrees in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This example bring three rotating string from the background to the foreground. Pretty nice.
Example 500. swfdisplayitem->rotateto() example
setRate(24.0);
$m->setDimension(2400, 1600);
$m->setBackground(0xff, 0xff, 0xff);
// functions with huge numbers of arbitrary
// arguments are always a good idea! Really!
function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
{
global $f, $m;
$t = new SWFText();
$t->setFont($f);
$t->setColor($r, $g, $b, $a);
$t->setHeight(960);
$t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
$t->addString($string);
// we can add properties just like a normal php var,
// as long as the names aren't already used.
// e.g., we can't set $i->scale, because that's a function
$i = $m->add($t);
$i->x = $x;
$i->y = $y;
$i->rot = $rot;
$i->s = $scale;
$i->rotateTo($rot);
$i->scale($scale, $scale);
// but the changes are local to the function, so we have to
// return the changed object. kinda weird..
1961
SWFDisplayItem->rotateTo
return $i;
}
function step($i)
{
$oldrot = $i->rot;
$i->rot = 19*$i->rot/20;
$i->x = (19*$i->x + 1200)/20;
$i->y = (19*$i->y + 800)/20;
$i->s = (19*$i->s + 1.0)/20;
$i->rotateTo($i->rot);
$i->scaleTo($i->s, $i->s);
$i->moveTo($i->x, $i->y);
return $i;
}
// see?
it sure paid off in legibility:
$i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
$i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
$i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);
for($i=1; $i<=100; ++$i)
{
$i1 = step($i1);
$i2 = step($i2);
$i3 = step($i3);
$m->nextFrame();
}
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
See also swfdisplayitem->rotate().
1962
SWFDisplayItem->scale
()
SWFDisplayItem->scale - Scales the object in relative coordinates.
Description
void swfdisplayitem->scale (int dx, int dy)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->scale() scales the current object by (dx,dy) from its current size.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scaleto().
1963
SWFDisplayItem->scaleTo
()
SWFDisplayItem->scaleTo - Scales the object in global coordinates.
Description
void swfdisplayitem->scaleto (int x, int y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->scaleto() scales the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scale().
1964
SWFDisplayItem->setDepth
()
SWFDisplayItem->setDepth - Sets z-order
Description
void swfdisplayitem->setdepth (float depth)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->rotate() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by
add'ing a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the laterdefined one can be moved.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
1965
SWFDisplayItem->setName
()
SWFDisplayItem->setName - Sets the object's name
Description
void swfdisplayitem->setname (string name)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
1966
SWFDisplayItem->setRatio
()
SWFDisplayItem->setRatio - Sets the object's ratio.
Description
void swfdisplayitem->setratio (float ratio)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->setratio() sets the object's ratio to ratio. Obviously only useful for morphs.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This simple example will morph nicely three concentric circles.
Example 501. swfdisplayitem->setname() example
addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0xff, 0xff);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0xff, 0xff, 0xff);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0xff, 0xff, 0xff);
$g->addEntry(1.00, 0, 0, 0);
$s = $p->getShape1();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);
$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0, 0);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0, 0xff, 0);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0, 0, 0xff);
$g->addEntry(1.00, 0, 0, 0);
$s = $p->getShape2();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$f->skewXTo(1.0);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
1967
SWFDisplayItem->setRatio
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);
$m = new SWFMovie();
$m->setDimension(320, 240);
$i = $m->add($p);
$i->moveTo(160, 120);
for($n=0; $n<=1.001; $n+=0.01)
{
$i->setRatio($n);
$m->nextFrame();
}
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1968
SWFDisplayItem->skewX
()
SWFDisplayItem->skewX - Sets the X-skew.
Description
void swfdisplayitem->skewx (float ddegrees)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->skewx() adds ddegrees to current x-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
1969
SWFDisplayItem->skewXTo
()
SWFDisplayItem->skewXTo - Sets the X-skew.
Description
void swfdisplayitem->skewxto (float degrees)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is
more forward, less is more backward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
1970
SWFDisplayItem->skewY
()
SWFDisplayItem->skewY - Sets the Y-skew.
Description
void swfdisplayitem->skewy (float ddegrees)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->skewy() adds ddegrees to current y-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewyto(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
1971
SWFDisplayItem->skewYTo
()
SWFDisplayItem->skewYTo - Sets the Y-skew.
Description
void swfdisplayitem->skewyto (float degrees)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is
more upward, less is more downward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewy(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
1972
SWFDisplayItem
()
SWFDisplayItem - Creates a new displayitem object.
Description
new swfdisplayitem (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfdisplayitem() creates a new swfdisplayitem object.
Here's where all the animation takes place. After you define a shape, a text object, a sprite, or a button, you add it to the
movie, then use the returned handle to move, rotate, scale, or skew the thing.
SWFDisplayItem has the following methods : swfdisplayitem->move(), swfdisplayitem->moveto(), swfdisplayitem>scaleto(), swfdisplayitem->scale(), swfdisplayitem->rotate(), swfdisplayitem->rotateto(), swfdisplayitem->skewxto(),
swfdisplayitem->skewx(), swfdisplayitem->skewyto() swfdisplayitem->skewyto(), swfdisplayitem->setdepth() swfdisplayitem->remove(), swfdisplayitem->setname() swfdisplayitem->setratio(), swfdisplayitem->addcolor() and swfdisplayitem->multcolor().
1973
SWFFill->moveTo
()
SWFFill->moveTo - Moves fill origin
Description
void swffill->moveto (int x, int y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swffill->moveto() moves fill's origin to (x,y) in global coordinates.
1974
SWFFill->rotateTo
()
SWFFill->rotateTo - Sets fill's rotation
Description
void swffill->rotateto (float degrees)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swffill->rotateto() sets fill's rotation to degrees degrees.
1975
SWFFill->scaleTo
()
SWFFill->scaleTo - Sets fill's scale
Description
void swffill->scaleto (int x, int y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.
1976
SWFFill->skewXTo
()
SWFFill->skewXTo - Sets fill x-skew
Description
void swffill->skewxto (float x)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a is a 45-degree forward slant. More is more forward, less is more
backward.
1977
SWFFill->skewYTo
()
SWFFill->skewYTo - Sets fill y-skew
Description
void swffill->skewyto (float y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is a is a 45-degree upward slant. More is more upward, less is more
downward.
1978
SWFFill
()
SWFFill - Loads SWFFill object
Description
new SWFFill (void)
The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by
the swfshape->addfill() methods.
SWFFill has the following methods : swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and
swffill->skewyto().
1979
swffont->getwidth
()
swffont->getwidth - Returns the string's width
Description
int swffont->getwidth (string string)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swffont->getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the swftext()
version of this method which uses the text object's scale.
1980
SWFFont
()
SWFFont - Loads a font definition
Description
new swffont (string filename)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a
browser-defined font reference.
FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of
a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.
Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition
will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:
will give you the standard sans-serif font, probably the same as what you'd get with in
HTML.
swffont() returns a reference to the font definition, for use in the swftext->setfont() and the swftextfield->setfont() methods.
SWFFont has the following methods : swffont->getwidth().
1981
SWFGradient->addEntry
()
SWFGradient->addEntry - Adds an entry to the gradient list.
Description
void swfgradient->addentry (float ratio, int red, int green, int blue [, int a])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.
red, green, blue is a color (RGB mode). Last parameter a is optional.
1982
SWFGradient
()
SWFGradient - Creates a gradient object
Description
new swfgradient (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfgradient() creates a new SWFGradient object.
After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.
SWFGradient has the following methods : swfgradient->addentry().
This simple example will draw a big black-to-white gradient as background, and a redish disc in its center.
Example 502. swfgradient() example
setDimension(320, 240);
$s = new SWFShape();
// first gradient- black to white
$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(1.0, 0xff, 0xff, 0xff);
$f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
$f->scaleTo(0.01);
$f->moveTo(160, 120);
$s->setRightFill($f);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);
$m->add($s);
$s = new SWFShape();
// second gradient- radial gradient from red to transparent
$g = new SWFGradient();
$g->addEntry(0.0, 0xff, 0, 0, 0xff);
$g->addEntry(1.0, 0xff, 0, 0, 0);
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.005);
$f->moveTo(160, 120);
$s->setRightFill($f);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
1983
SWFGradient
$s->drawLine(-320, 0);
$s->drawLine(0, -240);
$m->add($s);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1984
SWFMorph->getshape1
()
SWFMorph->getshape1 - Gets a handle to the starting shape
Description
mixed swfmorph->getshape1 (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmorph->getshape1() gets a handle to the morph's starting shape. swfmorph->getshape1() returns an swfshape() object.
1985
SWFMorph->getshape2
()
SWFMorph->getshape2 - Gets a handle to the ending shape
Description
mixed swfmorph->getshape2 (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.
1986
SWFMorph
()
SWFMorph - Creates a new SWFMorph object.
Description
new swfmorph (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmorph() creates a new SWFMorph object.
Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!
The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things
are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it
gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things
would be much easier.)
SWFMorph has the following methods : swfmorph->getshape1() and swfmorph->getshape1().
This simple example will morph a big red square into a smaller blue black-bordered square.
Example 503. swfmorph() example
getShape1();
$s->setLine(0,0,0,0);
/* Note that this is backwards from normal shapes (left instead of right).
I have no idea why, but this seems to work.. */
$s->setLeftFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-1000,-1000);
$s->drawLine(2000,0);
$s->drawLine(0,2000);
$s->drawLine(-2000,0);
$s->drawLine(0,-2000);
$s = $p->getShape2();
$s->setLine(60,0,0,0);
$s->setLeftFill($s->addFill(0, 0, 0xff));
$s->movePenTo(0,-1000);
$s->drawLine(1000,1000);
$s->drawLine(-1000,1000);
$s->drawLine(-1000,-1000);
$s->drawLine(1000,-1000);
$m = new SWFMovie();
$m->setDimension(3000,2000);
$m->setBackground(0xff, 0xff, 0xff);
$i = $m->add($p);
$i->moveTo(1500,1000);
1987
SWFMorph
for($r=0.0; $r<=1.0; $r+=0.1)
{
$i->setRatio($r);
$m->nextFrame();
}
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1988
SWFMovie->add
()
SWFMovie->add - Adds any type of data to a movie.
Description
void swfmovie->add (ressource instance)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->add() adds instance to the current movie. instance is any type of data : Shapes, text, fonts, etc. must all be
add'ed to the movie to make this work.
For displayable types (shape, text, button, sprite), this returns an swfdisplayitem(), a handle to the object in a display list.
Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.
See also all other objects (adding this later), and swfmovie->remove()
See examples in : swfdisplayitem->rotateto() and swfshape->addfill().
1989
SWFMovie->nextframe
()
SWFMovie->nextframe - Moves to the next frame of the animation.
Description
void swfmovie->nextframe (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->nextframe() moves to the next frame of the animation.
1990
SWFMovie->output
()
SWFMovie->output - Dumps your lovingly prepared movie out.
Description
void swfmovie->output (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->output() dumps your lovingly prepared movie out. In PHP, preceding this with the command
convinces the browser to display this as a flash movie.
See also swfmovie->save().
See examples in : swfmovie->streammp3(), swfdisplayitem->rotateto(), swfaction()... Any example will use this method.
1991
swfmovie->remove
()
swfmovie->remove - Removes the object instance from the display list.
Description
void swfmovie->remove (resource instance)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->remove() removes the object instance instance from the display list.
See also swfmovie->add().
1992
SWFMovie->save
()
SWFMovie->save - Saves your movie in a file.
Description
void swfmovie->save (string filename)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->save() saves your movie to the file named filename.
See also output().
1993
SWFMovie->setbackground
()
SWFMovie->setbackground - Sets the background color.
Description
void swfmovie->setbackground (int red, int green, int blue)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->setbackground() sets the background color. Why is there no rgba version? Think about it. (Actually, that's not
such a dumb question after all- you might want to let the html background show through. There's a way to do that, but it
only works on IE4. Search the http://www.macromedia.com/site for details.)
1994
SWFMovie->setdimension
()
SWFMovie->setdimension - Sets the movie's width and height.
Description
void swfmovie->setdimension (int width, int height)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->setdimension() sets the movie's width to width and height to height.
1995
SWFMovie->setframes
()
SWFMovie->setframes - Sets the total number of frames in the animation.
Description
void swfmovie->setframes (string numberofframes)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->setframes() sets the total number of frames in the animation to numberofframes.
1996
SWFMovie->setrate
()
SWFMovie->setrate - Sets the animation's frame rate.
Description
void swfmovie->setrate (int rate)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->setrate() sets the frame rate to rate, in frame per seconds. Animation will slow down if the player can't render
frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.
1997
SWFMovie->streammp3
()
SWFMovie->streammp3 - Streams a MP3 file.
Description
void swfmovie->streammp3 (string mp3FileName)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie->streammp3() streams the mp3 file mp3FileName. Not very robust in dealing with oddities (can skip over an
initial ID3 tag, but that's about it). Like swfshape->addjpegfill(), this isn't a stable function- we'll probably need to make a
separate SWFSound object to contain sound types.
Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length
of song * frames per second) frames to get the entire stream in.
Yes, now you can use ming to put that rock and roll devil worship music into your SWF files. Just don't tell the RIAA.
Example 504. swfmovie->streammp3() example
setRate(12.0);
$m->streamMp3("distortobass.mp3");
// use your own MP3
// 11.85 seconds at 12.0 fps = 142 frames
$m->setFrames(142);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
1998
SWFMovie
()
SWFMovie - Creates a new movie object, representing an SWF version 4 movie.
Description
new swfmovie (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfmovie() creates a new movie object, representing an SWF version 4 movie.
SWFMovie has the following methods : swfmovie->output(),swfmovie->save(), swfmovie->add(), swfmovie->remove(),
swfmovie->nextframe(), swfmovie->setbackground(), swfmovie->setrate(), swfmovie->setdimension(), swfmovie>setframes() and swfmovie->streammp3().
See examples in : swfdisplayitem->rotateto(), swfshape->setline(), swfshape->addfill()... Any example will use this object.
1999
SWFShape->addFill
()
SWFShape->addFill - Adds a solid fill to the shape.
Description
void swfshape->addfill (int red, int green, int blue [, int a])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
void swfshape->addfill (SWFbitmap bitmap [, int flags])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
void swfshape->addfill (SWFGradient gradient [, int flags])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->addfill() adds a solid fill to the shape's list of fill styles. swfshape->addfill() accepts three different types of arguments.
red, green, blue is a color (RGB mode). Last parameter a is optional.
The bitmap argument is an swfbitmap() object. The flags argument can be one of the following values : SWFFILL_CLIPPED_BITMAP or SWFFILL_TILED_BITMAP. Default is SWFFILL_TILED_BITMAP. I think.
The gradient argument is an swfgradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure
about this one. Really.
swfshape->addfill() returns an swffill() object for use with the swfshape->setleftfill() and swfshape->setrightfill() functions described below.
See also swfshape->setleftfill() and swfshape->setrightfill().
This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care
about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the
shape in this example..
Example 505. swfshape->addfill() example
addFill
$b = new SWFBitmap("alphafill.jpg");
// use your own bitmap
$width = $b->getWidth();
$height = $b->getHeight();
$s = $p->getShape1();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);
$f->moveTo(-$width/2, -$height/4);
$f->scaleTo(1.0, 0.5);
$s->setLeftFill($f);
$s->movePenTo(-$width/2, -$height/4);
$s->drawLine($width, 0);
$s->drawLine(0, $height/2);
$s->drawLine(-$width, 0);
$s->drawLine(0, -$height/2);
$s = $p->getShape2();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);
// these two have no effect!
$f->moveTo(-$width/4, -$height/2);
$f->scaleTo(0.5, 1.0);
$s->setLeftFill($f);
$s->movePenTo(-$width/4, -$height/2);
$s->drawLine($width/2, 0);
$s->drawLine(0, $height);
$s->drawLine(-$width/2, 0);
$s->drawLine(0, -$height);
$m = new SWFMovie();
$m->setDimension($width, $height);
$i = $m->add($p);
$i->moveTo($width/2, $height/2);
for($n=0; $n<1.001; $n+=0.03)
{
$i->setRatio($n);
$m->nextFrame();
}
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
2001
SWFShape->drawCurve
()
SWFShape->drawCurve - Draws a curve (relative).
Description
void swfshape->drawcurve (int controldx, int controldy, int anchordx, int anchordy)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->drawcurve() draws a quadratic curve (using the current line style,set by swfshape->setline()) from the current
pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards
the control point, then smoothly turn to the anchor point.
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
2002
SWFShape->drawCurveTo
()
SWFShape->drawCurveTo - Draws a curve.
Description
void swfshape->drawcurveto (int controlx, int controly, int anchorx, int anchory)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->drawcurveto() draws a quadratic curve (using the current line style, set by swfshape->setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point,
then smoothly turn to the anchor point.
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
2003
SWFShape->drawLine
()
SWFShape->drawLine - Draws a line (relative).
Description
void swfshape->drawline (int dx, int dy)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to
displacement (dx,dy).
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawlineto().
2004
SWFShape->drawLineTo
()
SWFShape->drawLineTo - Draws a line.
Description
void swfshape->drawlineto (int x, int y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position
to point (x,y) in the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawline().
2005
SWFShape->movePen
()
SWFShape->movePen - Moves the shape's pen (relative).
Description
void swfshape->movepen (int dx, int dy)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in
the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
2006
SWFShape->movePenTo
()
SWFShape->movePenTo - Moves the shape's pen.
Description
void swfshape->movepento (int x, int y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.
See also swfshape->movepen(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
2007
SWFShape->setLeftFill
()
SWFShape->setLeftFill - Sets left rasterizing color.
Description
void swfshape->setleftfill (swfgradient fill)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
void swfshape->setleftfill (int red, int green, int blue [, int a])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy
to know what those fills are ahead of time, so the swf format requires these to be specified.
swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the
shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.
This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill
on the other side.
Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.
See also swfshape->setrightfill().
2008
SWFShape->setLine
()
SWFShape->setLine - Sets the shape's line style.
Description
void swfshape->setline (int width [, int red [, int green [, int blue [, int a]]]])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape->setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all
other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.
swfshape->setline() accepts 1, 4 or 5 arguments (not 3 or 2).
You must declare all line styles before you use them (see example).
This simple example will draw a big "!#%*@", in funny colors and gracious style.
Example 506. swfshape->setline() example
addFill(0xff, 0, 0);
$f2 = $s->addFill(0xff, 0x7f, 0);
$f3 = $s->addFill(0xff, 0xff, 0);
$f4 = $s->addFill(0, 0xff, 0);
$f5 = $s->addFill(0, 0, 0xff);
// bug: have to
$s->setLine(40,
$s->setLine(40,
$s->setLine(40,
$s->setLine(40,
$s->setLine(40,
declare all line styles before you use them
0x7f, 0, 0);
0x7f, 0x3f, 0);
0x7f, 0x7f, 0);
0, 0x7f, 0);
0, 0, 0x7f);
$f = new SWFFont('Techno.fdb');
$s->setRightFill($f1);
$s->setLine(40, 0x7f, 0, 0);
$s->drawGlyph($f, '!');
$s->movePen($f->getWidth('!'), 0);
$s->setRightFill($f2);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->drawGlyph($f, '#');
$s->movePen($f->getWidth('#'), 0);
$s->setRightFill($f3);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->drawGlyph($f, '%');
$s->movePen($f->getWidth('%'), 0);
$s->setRightFill($f4);
$s->setLine(40, 0, 0x7f, 0);
$s->drawGlyph($f, '*');
$s->movePen($f->getWidth('*'), 0);
2009
SWFShape->setLine
$s->setRightFill($f5);
$s->setLine(40, 0, 0, 0x7f);
$s->drawGlyph($f, '@');
$m = new SWFMovie();
$m->setDimension(3000,2000);
$m->setRate(12.0);
$i = $m->add($s);
$i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
2010
SWFShape->setRightFill
()
SWFShape->setRightFill - Sets right rasterizing color.
Description
void swfshape->setrightfill (swfgradient fill)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
void swfshape->setrightfill (int red, int green, int blue [, int a])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
See also swfshape->setleftfill().
Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.
2011
SWFShape
()
SWFShape - Creates a new shape object.
Description
new swfshape (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfshape() creates a new shape object.
SWFShape has the following methods : swfshape->setline(), swfshape->addfill(), swfshape->setleftfill(), swfshape>setrightfill(), swfshape->movepento(), swfshape->movepen(), swfshape->drawlineto(), swfshape->drawline(), swfshape->drawcurveto() and swfshape->drawcurve().
This simple example will draw a big red elliptic quadrant.
Example 507. swfshape() example
setLine(40, 0x7f, 0, 0);
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(200, 200);
$s->drawLineTo(6200, 200);
$s->drawLineTo(6200, 4600);
$s->drawCurveTo(200, 4600, 200, 200);
$m = new SWFMovie();
$m->setDimension(6400, 4800);
$m->setRate(12.0);
$m->add($s);
$m->nextFrame();
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
2012
swfsprite->add
()
swfsprite->add - Adds an object to a sprite
Description
void swfsprite->add (resource object)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfsprite->add() adds a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object.
For displayable types (swfshape(), swfbutton(), swftext(), swfaction() or swfsprite()), this returns a handle to the object in
a display list.
2013
SWFSprite->nextframe
()
SWFSprite->nextframe - Moves to the next frame of the animation.
Description
void swfsprite->nextframe (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfsprite->setframes() moves to the next frame of the animation.
2014
SWFSprite->remove
()
SWFSprite->remove - Removes an object to a sprite
Description
void swfsprite->remove (ressource object)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfsprite->remove() remove a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object from the
sprite.
2015
SWFSprite->setframes
()
SWFSprite->setframes - Sets the total number of frames in the animation.
Description
void swfsprite->setframes (int numberofframes)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfsprite->setframes() sets the total number of frames in the animation to numberofframes.
2016
SWFSprite
()
SWFSprite - Creates a movie clip (a sprite)
Description
new swfsprite (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swfsprite() are also known as a "movie clip", this allows one to create objects which are animated in their own timelines.
Hence, the sprite has most of the same methods as the movie.
swfsprite() has the following methods : swfsprite->add(), swfsprite->remove(), swfsprite->nextframe() and swfsprite>setframes().
This simple example will spin gracefully a big red square.
Example 508. swfsprite() example
setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-500,-500);
$s->drawLineTo(500,-500);
$s->drawLineTo(500,500);
$s->drawLineTo(-500,500);
$s->drawLineTo(-500,-500);
$p = new SWFSprite();
$i = $p->add($s);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$m = new SWFMovie();
$i = $m->add($p);
$i->moveTo(1500,1000);
$i->setName("blah");
$m->setBackground(0xff, 0xff, 0xff);
$m->setDimension(3000,2000);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
2017
SWFSprite
2018
SWFText->addString
()
SWFText->addString - Draws a string
Description
void swftext->addstring (string string)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.
2019
SWFText->getWidth
()
SWFText->getWidth - Computes string's width
Description
void swftext->getwidth (string string)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.
2020
SWFText->moveTo
()
SWFText->moveTo - Moves the pen
Description
void swftext->moveto (int x, int y)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is
zero, though, value in that dimension stays the same. Annoying, should be fixed.
2021
SWFText->setColor
()
SWFText->setColor - Sets the current font color
Description
void swftext->setcolor (int red, int green, int blue [, int a])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.
2022
SWFText->setFont
()
SWFText->setFont - Sets the current font
Description
void swftext->setfont (string font)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext->setfont() sets the current font to font.
2023
SWFText->setHeight
()
SWFText->setHeight - Sets the current font height
Description
void swftext->setheight (int height)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext->setheight() sets the current font height to height. Default is 240.
2024
SWFText->setSpacing
()
SWFText->setSpacing - Sets the current font spacing
Description
void swftext->setspacing (float spacing)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext->setspacing() sets the current font spacing to spacingspacing. Default is 1.0. 0 is all of the letters written at the
same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount
of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing.
This was really just a way to figure out how letter advances work, anyway.. So nyah.
2025
SWFText
()
SWFText - Creates a new SWFText object.
Description
new swftext (void)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftext() creates a new SWFText object, fresh for manipulating.
SWFText has the following methods : swftext->setfont(), swftext->setheight(), swftext->setspacing(), swftext>setcolor(), swftext->moveto(), swftext->addstring() and swftext->getwidth().
This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.
Example 509. swftext() example
setFont($f);
$t->moveTo(200, 2400);
$t->setColor(0xff, 0xff, 0);
$t->setHeight(1200);
$t->addString("PHP generates Flash with Ming!!");
$m = new SWFMovie();
$m->setDimension(5400, 3600);
$m->add($t);
header('Content-type: application/x-shockwave-flash');
$m->output();
?>
2026
SWFTextField->addstring
()
SWFTextField->addstring - Concatenates the given string to the text field
Description
void swftextfield->addstring (string string)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setname() concatenates the string string to the text field.
2027
SWFTextField->align
()
SWFTextField->align - Sets the text field alignment
Description
void swftextfield->align (int alignement)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.
2028
SWFTextField->setbounds
()
SWFTextField->setbounds - Sets the text field width and height
Description
void swftextfield->setbounds (int width, int height)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming
makes a poor guess at what the bounds are.
2029
SWFTextField->setcolor
()
SWFTextField->setcolor - Sets the color of the text field.
Description
void swftextfield->setcolor (int red, int green, int blue [, int a])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.
2030
SWFTextField->setFont
()
SWFTextField->setFont - Sets the text field font
Description
void swftextfield->setfont (string font)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setfont() sets the text field font to the [browser-defined?] font font.
2031
SWFTextField->setHeight
()
SWFTextField->setHeight - Sets the font height of this text field font.
Description
void swftextfield->setheight (int height)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setheight() sets the font height of this text field font to the given height height. Default is 240.
2032
SWFTextField->setindentation
()
SWFTextField->setindentation - Sets the indentation of the first line.
Description
void swftextfield->setindentation (int width)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setindentation() sets the indentation of the first line in the text field, to width.
2033
SWFTextField->setLeftMargin
()
SWFTextField->setLeftMargin - Sets the left margin width of the text field.
Description
void swftextfield->setleftmargin (int width)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.
2034
SWFTextField->setLineSpacing
()
SWFTextField->setLineSpacing - Sets the line spacing of the text field.
Description
void swftextfield->setlinespacing (int height)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.
2035
SWFTextField->setMargins
()
SWFTextField->setMargins - Sets the margins width of the text field.
Description
void swftextfield->setmargins (int left, int right)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setmargins() set both margins at once, for the man on the go.
2036
SWFTextField->setname
()
SWFTextField->setname - Sets the variable name
Description
void swftextfield->setname (string name)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.
2037
SWFTextField->setrightMargin
()
SWFTextField->setrightMargin - Sets the right margin width of the text field.
Description
void swftextfield->setrightmargin (int width)
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.
2038
SWFTextField
()
SWFTextField - Creates a text field object
Description
new swftextfield ([int flags])
Warning
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else
documented about this function may change without notice in a future release of PHP. Use this function at your
own risk.
swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated,
scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.
The optional flags change the text field's behavior. It has the following possibles values :
•
SWFTEXTFIELD_DRAWBOX draws the outline of the textfield
•
SWFTEXTFIELD_HASLENGTH
•
SWFTEXTFIELD_HTML allows text markup using HTML-tags
•
SWFTEXTFIELD_MULTILINE allows multiple lines
•
SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable
•
SWFTEXTFIELD_NOSELECT makes the field non-selectable
•
SWFTEXTFIELD_PASSWORD obscures the data entry
•
SWFTEXTFIELD_WORDWRAP allows text to wrap
Flags are combined with the bitwise OR operation. For example,
creates a totally useless non-editable password field.
SWFTextField has the following methods : swftextfield->setfont(), swftextfield->setbounds(), swftextfield->align(), swftextfield->setheight(), swftextfield->setleftmargin(), swftextfield->setrightmargin(), swftextfield->setmargins(), swftextfield->setindentation(), swftextfield->setlinespacing(), swftextfield->setcolor(), swftextfield->setname() and swftextfield->addstring().
2039
Miscellaneous functions
Table of Contents
connection_aborted .......................................................................................................................... 2043
connection_status ............................................................................................................................. 2044
connection_timeout .......................................................................................................................... 2045
constant .......................................................................................................................................... 2046
define ............................................................................................................................................ 2047
defined ........................................................................................................................................... 2048
die ................................................................................................................................................. 2049
eval ............................................................................................................................................... 2050
exit ................................................................................................................................................ 2051
get_browser .................................................................................................................................... 2052
highlight_file ................................................................................................................................... 2054
highlight_string ............................................................................................................................... 2056
ignore_user_abort ............................................................................................................................ 2057
pack .............................................................................................................................................. 2058
show_source ................................................................................................................................... 2060
sleep .............................................................................................................................................. 2061
uniqid ............................................................................................................................................ 2062
unpack ........................................................................................................................................... 2063
usleep ............................................................................................................................................ 2064
2040
Introduction
These functions were placed here because none of the other categories seemed to fit.
Requirements
No external libraries are needed to build this extension.
Installation
There is no installation needed to use these functions; they are part of the PHP core.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 90. Misc. Configuration Options
Name
Default
Changeable
ignore_user_abort
"0"
PHP_INI_ALL
highlight.string
#CC0000
PHP_INI_ALL
highlight.comment
#FF9900
PHP_INI_ALL
highlight.keyword
#006600
PHP_INI_ALL
highlight.bg
#FFFFFF
PHP_INI_ALL
highlight.default
#0000CC
PHP_INI_ALL
highlight.html
#000000
PHP_INI_ALL
browscap
NULL
PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().
Here's a short explanation of the configuration directives.
ignore_user_abort boolean
TRUE by default. If changed to FALSE scripts will be terminated as soon as they try to output something after a client
has aborted their connection.
See also ignore_user_abort().
highlight.xxx string
Colors for Syntax Highlighting mode. Anything that's acceptable in would work.
browscap string
Name (e.g.: browscap.ini)and location of browser capabilities file. See also get_browser().
Resource Types
This extension has no resource types defined.
2041
Miscellaneous functions
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
CONNECTION_ABORTED (integer)
CONNECTION_NORMAL (integer)
CONNECTION_TIMEOUT (integer)
2042
connection_aborted
(PHP 3>= 3.0.7, PHP 4 )
connection_aborted - Returns TRUE if client disconnected
Description
int connection_aborted (void)
Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.
2043
connection_status
(PHP 3>= 3.0.7, PHP 4 )
connection_status - Returns connection status bitfield
Description
int connection_status (void)
Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.
2044
connection_timeout
(PHP 3>= 3.0.7, PHP 4 <= 4.0.4)
connection_timeout - Return TRUE if script timed out
Description
bool connection_timeout (void)
Returns TRUE if script timed out.
Deprecated
This function is deprecated, and doesn't even exist anymore as of 4.0.5.
See the Connection Handling description in the Features chapter for a complete explanation.
2045
constant
(PHP 4 >= 4.0.4)
constant - Returns the value of a constant
Description
mixed constant (string name)
constant() will return the value of the constant indicated by name.
constant() is useful if you need to retrieve the value of a constant, but do not know it's name. i.e. It is stored in a variable or
returned by a function.
Example 510. constant() example
See also define(), defined() and the section on Constants.
2046
define
(PHP 3, PHP 4 )
define - Defines a named constant.
Description
bool define (string name, mixed value [, bool case_insensitive])
Defines a named constant. See the section on constants for more details.
The name of the constant is given by name; the value is given by value.
The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined
case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.
Example 511. Defining Constants
Returns TRUE on success or FALSE on failure.
See also defined(), constant() and the section on Constants.
2047
defined
(PHP 3, PHP 4 )
defined - Checks whether a given named constant exists
Description
bool defined (string name)
Returns TRUE if the named constant given by name has been defined, FALSE otherwise.
Example 512. Checking Constants
See also define(), constant(), get_defined_constants() and the section on Constants.
2048
die
()
die - Alias of exit()
Description
This function is an alias of exit().
2049
eval
(PHP 3, PHP 4 )
eval - Evaluate a string as PHP code
Description
mixed eval (string code_str)
eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.
Also remember that variables given values under eval() will retain these values in the main script afterwards.
A return statement will terminate the evaluation of the string immediately. In PHP 4, eval() returns NULL unless return()
is called in the evaluated code, in which case the value passed to return() is returned. In PHP 3, eval() does not return a
value.
Example 513. eval() example - simple text merge
';
echo $str;
eval ("\$str = \"$str\";");
echo $str;
?>
The above example will show:
This is a $string with my $name in it.
This is a cup with my coffee in it.
Tip
As with anything that outputs its result directly to the browser, you can use the output-control functions to capture
the output of this function, and save it in a string (for example).
2050
exit
(PHP 3, PHP 4 )
exit - Output a message and terminate the current script
Description
void exit ([string status])
void exit (int status)
Note: This is not a real function, but a language construct.
The exit() function terminates execution of the script. It prints status just before exiting.
If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 1 to 254, the exit
status 255 is reserved by PHP and shall not be used.
Note: PHP version >= 4.2.0 does NOT print the status if it is an integer.
Note: The die() function is an alias for exit().
Example 514. exit() example
See also: register_shutdown_function().
2051
get_browser
(PHP 3, PHP 4 )
get_browser - Tells what the user's browser is capable of
Description
object get_browser ([string user_agent])
get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. By default, the value of HTTP_USER_AGENT is used; however, you can alter this (i.e., look
up another browser's info) by passing the optional user_agent parameter to get_browser().
The information is returned in an object, which will contain various data elements representing, for instance, the browser's
major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies;
and so forth.
While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The
format of the file is fairly self-explanatory.
The following example shows how one might list all available information retrieved about the user's browser.
Example 515. get_browser() example
\n";
$browser = get_browser();
foreach ($browser as $name => $value) {
print "$name $value
\n";
}
?>
The output of the above script would look something like this:
Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)
browser_name_pattern: Mozilla/4\.5.*
parent: Netscape 4.0
platform: Linux
majorver: 4
minorver: 5
browser: Netscape
version: 4
frames: 1
tables: 1
cookies: 1
backgroundsounds:
vbscript:
javascript: 1
javaapplets: 1
activexcontrols:
beta:
crawler:
authenticodeupdate:
msn:
In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the
2052
get_browser
browscap.ini file on your system. browscap.ini is not bundled with PHP but you may find an up-to-date browscap.ini
file here [http://www.garykeith.com/browsers/downloads.asp]. By default, the browscap directive is commented out.
Note: The cookies value simply means that the browser itself is capable of accepting cookies and does not mean
the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one
with setcookie(), reload, and check for the value.
Note: On versions older than PHP 4.0.6, you will have to pass the user agent in via the optional user_agent parameter if the PHP directive register_globals is off. In this case, you will pass in
$HTTP_SERVER_VARS['HTTP_USER_AGENT'].
2053
highlight_file
(PHP 4 )
highlight_file - Syntax highlighting of a file
Description
mixed highlight_file (string filename [, bool return])
The highlight_file() function prints out a syntax higlighted version of the code contained in filename using the colors
defined in the built-in syntax highlighter for PHP.
If the second parameter return is set to TRUE then highlight_file() will return the highlighted code as a string instead of
printing it out. If the second parameter is not set to TRUE then highlight_file() will return TRUE on success, FALSE on failure.
Note: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is
FALSE
Note: Care should be taken when using the show_source() and highlight_file() functions to make sure that you do
not inadvertently reveal sensitive information such as passwords or any other type of information that might create
a potential security risk.
Note: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.
Example 516. Creating a source highlighting URL
To setup a URL that can code hightlight any script that you pass to it, we will make use of the "ForceType" directive in
Apache to generate a nice URL pattern, and use the function highlight_file() to show a nice looking code list.
In your httpd.conf you can add the following:
ForceType application/x-httpd-php
And then make a file named "source" and put it in your web root directory.
Source Display
ERROR: Script Name needed
";
} else {
if (ereg("(\.php|\.inc)$",$script)) {
echo "Source of: $PATH_INFO
\n
\n";
highlight_file($script);
} else {
echo "ERROR: Only PHP or include script names are allowed
";
}
}
echo "
Processed: ".date("Y/M/d H:i:s",time());
2054
highlight_file
?>
Then you can use an URL like the one below to display a colorized version of a script located in "/path/to/script.php" in
your web site.
http://your.server.com/source/path/to/script.php
See also highlight_string(), show_source().
2055
highlight_string
(PHP 4 )
highlight_string - Syntax highlighting of a string
Description
mixed highlight_string (string str [, bool return])
The highlight_string() function outputs a syntax highlighted version of str using the colors defined in the built-in syntax
highlighter for PHP.
If the second parameter return is set to TRUE then highlight_string() will return the highlighted code as a string instead of
printing it out. If the second parameter is not set to TRUE then highlight_string() will return TRUE on success, FALSE on
failure.
Note: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is
FALSE
See also highlight_file(), and show_source().
2056
ignore_user_abort
(PHP 3>= 3.0.7, PHP 4 )
ignore_user_abort - Set whether a client disconnect should abort script execution
Description
int ignore_user_abort ([int setting])
This function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can
be called without an argument to not change the current setting and only return the current setting. See the Connection
Handling section in the Features chapter for a complete description of connection handling in PHP.
2057
pack
(PHP 3, PHP 4 )
pack - Pack data into binary string.
Description
string pack (string format [, mixed args])
Pack given arguments into binary string according to format. Returns binary string containing data.
The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some
formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an
optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input
data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute
position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed
and packed into the resulting binary string. Currently implemented are
•
a NUL-padded string
•
A SPACE-padded string
•
h Hex string, low nibble first
•
H Hex string, high nibble first
•
c signed char
•
C unsigned char
•
s signed short (always 16 bit, machine byte order)
•
S unsigned short (always 16 bit, machine byte order)
•
n unsigned short (always 16 bit, big endian byte order)
•
v unsigned short (always 16 bit, little endian byte order)
•
i signed integer (machine dependent size and byte order)
•
I unsigned integer (machine dependent size and byte order)
•
l signed long (always 32 bit, machine byte order)
•
L unsigned long (always 32 bit, machine byte order)
•
N unsigned long (always 32 bit, big endian byte order)
•
V unsigned long (always 32 bit, little endian byte order)
•
f float (machine dependent size and representation)
•
d double (machine dependent size and representation)
•
x NUL byte
2058
pack
•
X Back up one byte
•
@ NUL-fill to absolute position
Example 517. pack() format string
$binarydata = pack ("nvc*", 0x1234, 0x5678, 65, 66);
The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.
Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack()
gives the same result for signed and unsigned format codes.
Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned
integer value too large to be stored that way it is converted to a float which often yields an undesired result.
2059
show_source
(PHP 4 )
show_source - Alias of highlight_file()
Description
This function is an alias of highlight_file().
2060
sleep
(PHP 3, PHP 4 )
sleep - Delay execution
Description
void sleep (int seconds)
The sleep() function delays program execution for the given number of seconds.
See also usleep() and set_time_limit()
2061
uniqid
(PHP 3, PHP 4 )
uniqid - Generate a unique ID
Description
string uniqid (string prefix [, bool lcg])
uniqid() returns a prefixed unique identifier based on the current time in microseconds. The prefix can be useful for instance if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same
microsecond. Prefix can be up to 114 characters long.
If the optional lcg parameter is TRUE, uniqid() will add additional "combined LCG" entropy at the end of the return value,
which should make the results more unique.
With an empty prefix, the returned string will be 13 characters long. If lcg is TRUE, it will be 23 characters.
Note: The lcg parameter is only available in PHP 4 and PHP 3.0.13 and later.
If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along the lines of
$token = md5(uniqid("")); // no prefix
$better_token = md5(uniqid(rand(),1)); // better, difficult to guess
This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.
2062
unpack
(PHP 3, PHP 4 )
unpack - Unpack data from binary string
Description
array unpack (string format, string data)
unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.
unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you
have to name the different format codes and separate them by a slash /.
Example 518. unpack() format string
$array = unpack ("c2chars/nint", $binarydata);
The resulting array will contain the entries "chars1", "chars2" and "int".
For an explanation of the format codes see also: pack()
Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as
PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.
2063
usleep
(PHP 3, PHP 4 )
usleep - Delay execution in microseconds
Description
void usleep (int micro_seconds)
The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of
a second.
See also sleep() and set_time_limit().
Note: This function does not work on Windows systems.
2064
mnoGoSearch Functions
Table of Contents
udm_add_search_limit ...................................................................................................................... 2070
udm_alloc_agent .............................................................................................................................. 2071
udm_api_version .............................................................................................................................. 2072
udm_cat_list ................................................................................................................................... 2073
udm_cat_path .................................................................................................................................. 2074
udm_check_charset .......................................................................................................................... 2075
udm_check_stored ........................................................................................................................... 2076
udm_clear_search_limits ................................................................................................................... 2077
udm_close_stored ............................................................................................................................ 2078
udm_crc32 ...................................................................................................................................... 2079
udm_errno ...................................................................................................................................... 2080
udm_error ....................................................................................................................................... 2081
udm_find ........................................................................................................................................ 2082
udm_free_agent ............................................................................................................................... 2083
udm_free_ispell_data ........................................................................................................................ 2084
udm_free_res .................................................................................................................................. 2085
udm_get_doc_count ......................................................................................................................... 2086
udm_get_res_field ............................................................................................................................ 2087
udm_get_res_param ......................................................................................................................... 2088
udm_load_ispell_data ....................................................................................................................... 2089
udm_open_stored ............................................................................................................................. 2091
udm_set_agent_param ...................................................................................................................... 2092
2065
Introduction
These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a fullfeatured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a
number of unique features, which makes it appropriate for a wide range of applications from search within your site to a
specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is
an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files,
recursively grabbing all the documents and storing meta-data about that documents in a SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later
use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.
More information about mnoGoSearch can be found at http://www.mnogosearch.ru/.
Note: This extension is not available on Windows platforms.
Requirements
Download mnoGosearch from http://www.mnogosearch.ru/and install it on your system. You need at least version 3.1.10 of
mnoGoSearch installed to use these functions.
Installation
In order to have these functions available, you must compile PHP with mnoGosearch support by using the -with-mnogosearchoption. If you use this option without specifying the path to mnoGosearch, PHP will look for mnoGosearch under /usr/local/mnogosearch path by default. If you installed mnoGosearch at a different location you
should specify it: --with-mnogosearch=DIR.
Note: PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you
use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch -with-mysql=/usr.
Runtime Configuration
This extension has no configuration directives defined in php.ini.
Resource Types
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
UDM_FIELD_URLID (integer)
UDM_FIELD_URL (integer)
UDM_FIELD_CONTENT (integer)
2066
mnoGoSearch Functions
UDM_FIELD_TITLE (integer)
UDM_FIELD_KEYWORDS (integer)
UDM_FIELD_DESC (integer)
UDM_FIELD_DESCRIPTION (integer)
UDM_FIELD_TEXT (integer)
UDM_FIELD_SIZE (integer)
UDM_FIELD_RATING (integer)
UDM_FIELD_SCORE (integer)
UDM_FIELD_MODIFIED (integer)
UDM_FIELD_ORDER (integer)
UDM_FIELD_CRC (integer)
UDM_FIELD_CATEGORY (integer)
UDM_FIELD_LANG (integer)
UDM_FIELD_CHARSET (integer)
UDM_PARAM_PAGE_SIZE (integer)
UDM_PARAM_PAGE_NUM (integer)
UDM_PARAM_SEARCH_MODE (integer)
UDM_PARAM_CACHE_MODE (integer)
UDM_PARAM_TRACK_MODE (integer)
UDM_PARAM_PHRASE_MODE (integer)
UDM_PARAM_CHARSET (integer)
UDM_PARAM_LOCAL_CHARSET (integer)
UDM_PARAM_BROWSER_CHARSET (integer)
UDM_PARAM_STOPTABLE (integer)
UDM_PARAM_STOP_TABLE (integer)
UDM_PARAM_STOPFILE (integer)
UDM_PARAM_STOP_FILE (integer)
UDM_PARAM_WEIGHT_FACTOR (integer)
UDM_PARAM_WORD_MATCH (integer)
UDM_PARAM_MAX_WORD_LEN (integer)
2067
mnoGoSearch Functions
UDM_PARAM_MAX_WORDLEN (integer)
UDM_PARAM_MIN_WORD_LEN (integer)
UDM_PARAM_MIN_WORDLEN (integer)
UDM_PARAM_ISPELL_PREFIXES (integer)
UDM_PARAM_ISPELL_PREFIX (integer)
UDM_PARAM_PREFIXES (integer)
UDM_PARAM_PREFIX (integer)
UDM_PARAM_CROSS_WORDS (integer)
UDM_PARAM_CROSSWORDS (integer)
UDM_PARAM_VARDIR (integer)
UDM_PARAM_DATADIR (integer)
UDM_PARAM_HLBEG (integer)
UDM_PARAM_HLEND (integer)
UDM_PARAM_SYNONYM (integer)
UDM_PARAM_SEARCHD (integer)
UDM_PARAM_QSTRING (integer)
UDM_PARAM_REMOTE_ADDR (integer)
UDM_LIMIT_CAT (integer)
UDM_LIMIT_URL (integer)
UDM_LIMIT_TAG (integer)
UDM_LIMIT_LANG (integer)
UDM_LIMIT_DATE (integer)
UDM_PARAM_FOUND (integer)
UDM_PARAM_NUM_ROWS (integer)
UDM_PARAM_WORDINFO (integer)
UDM_PARAM_WORD_INFO (integer)
UDM_PARAM_SEARCHTIME (integer)
UDM_PARAM_SEARCH_TIME (integer)
UDM_PARAM_FIRST_DOC (integer)
UDM_PARAM_LAST_DOC (integer)
2068
mnoGoSearch Functions
UDM_MODE_ALL (integer)
UDM_MODE_ANY (integer)
UDM_MODE_BOOL (integer)
UDM_MODE_PHRASE (integer)
UDM_CACHE_ENABLED (integer)
UDM_CACHE_DISABLED (integer)
UDM_TRACK_ENABLED (integer)
UDM_TRACK_DISABLED (integer)
UDM_PHRASE_ENABLED (integer)
UDM_PHRASE_DISABLED (integer)
UDM_CROSS_WORDS_ENABLED (integer)
UDM_CROSSWORDS_ENABLED (integer)
UDM_CROSS_WORDS_DISABLED (integer)
UDM_CROSSWORDS_DISABLED (integer)
UDM_PREFIXES_ENABLED (integer)
UDM_PREFIX_ENABLED (integer)
UDM_ISPELL_PREFIXES_ENABLED (integer)
UDM_ISPELL_PREFIX_ENABLED (integer)
UDM_PREFIXES_DISABLED (integer)
UDM_PREFIX_DISABLED (integer)
UDM_ISPELL_PREFIXES_DISABLED (integer)
UDM_ISPELL_PREFIX_DISABLED (integer)
UDM_ISPELL_TYPE_AFFIX (integer)
UDM_ISPELL_TYPE_SPELL (integer)
UDM_ISPELL_TYPE_DB (integer)
UDM_ISPELL_TYPE_SERVER (integer)
UDM_MATCH_WORD (integer)
UDM_MATCH_BEGIN (integer)
UDM_MATCH_SUBSTR (integer)
UDM_MATCH_END (integer)
2069
udm_add_search_limit
(PHP 4 >= 4.0.5)
udm_add_search_limit - Add various search limits
Description
int udm_add_search_limit (int agent, int var, string val)
udm_add_search_limit() returns TRUE on success, FALSE on error. Adds search restrictions.
agent - a link to Agent, received after call to udm_alloc_agent().
var - defines parameter, indicating limit.
val - defines value of the current parameter.
Possible var values:
•
UDM_LIMIT_URL - defines document URL limitations to limit search through subsection of database. It supports SQL
% and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one
character. E.g. http://my.domain.__/catalog may stand for http://my.domain.ru/catalog and http://my.domain.ua/catalog.
•
UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and
parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the
search will be made among both of the tags.
•
UDM_LIMIT_LANG - defines document language limitations.
•
UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you
can have one category inside another and so on. You have to use two characters for each level. Use a hex number going
from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and
you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then
it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to
search for sites under that category then you pass it cat=010201 in the url.
•
UDM_LIMIT_DATE - defines limitation by date document was modified.
Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:
Udm_Add_Search_Limit($udm,UDM_LIMIT_DATE,"<908012006");
If > character is used, then search will be restricted to those documents having modification date greater than entered. If
<, then smaller.
2070
udm_alloc_agent
(PHP 4 >= 4.0.5)
udm_alloc_agent - Allocate mnoGoSearch session
Description
int udm_alloc_agent (string dbaddr [, string dbmode])
udm_alloc_agent() returns mnogosearch agent identifier on success, FALSE on error. This function creates a session with
database parameters.
dbaddr - URL-style database description. Options (type, host, database name, port, user and password) to connect to SQL
database.
Do
not
matter
for
built-in
text
files
support.
Format:
DBAddr
DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/ Currently supported DBType values are: mysql, pgsql, msql,
solid, mssql, oracle, ibase. Actually, it does not matter for native libraries support. But ODBC users should specify one of
supported values. If your database type is not supported, you may use "unknown" instead.
dbmode - You may select SQL database mode of words storage. When "single" is specified, all words are stored in the same
table. If "multi" is selected, words will be located in different tables depending of their lengths. "multi" mode is usually
faster but requires more tables in database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorythm instead of words. This mode requres less disk space and it is faster comparing with "single" and
"multi" modes. "crc-multi" uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like "multi" mode. Format: DBMode single/multi/crc/crc-multi
Note: dbaddr and dbmode must match those used during indexing.
Note: In fact this function does not open connection to database and thus does not check entered login and password. Actual connection to database and login/password verification is done by udm_find().
2071
udm_api_version
(PHP 4 >= 4.0.5)
udm_api_version - Get mnoGoSearch API version.
Description
int udm_api_version (void)
udm_api_version() returns mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will
return 30110.
This function allows user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.
Example:
if (udm_api_version() >= 30111) {
print "Total number of urls in database: ".udm_get_doc_count($udm)."
\n";
}
2072
udm_cat_list
(PHP 4 >= 4.0.6)
udm_cat_list - Get all the categories on the same level with the current one.
Description
array udm_cat_list (int agent, string category)
udm_cat_list() returns array listing all categories of the same level as current category in the categories tree.
The function can be useful for developing categories tree browser.
Returns array with the following format:
The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding
category names.
$array[0]
$array[1]
$array[2]
$array[3]
$array[4]
$array[5]
Following
is
an
example
will
will
will
will
will
will
of
displaying
contain
contain
contain
contain
contain
contain
links
of
the
$name
";
}
?>
2073
current
'020300'
'Audi'
'020301'
'BMW'
'020302'
'Opel'
...
etc.
level
in
format:
Audi
BMW
Opel
...
udm_cat_path
(PHP 4 >= 4.0.6)
udm_cat_path - Get the path to the current category.
Description
array udm_cat_path (int agent, string category)
udm_cat_path() returns array describing path in the categories tree from the tree root to the current category.
agent - agent link identifier.
category - current category - the one to get path to.
Returns array with the following format:
The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding
category names.
For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:
$array[0]
$array[1]
$array[2]
$array[3]
$array[4]
$array[5]
$array[4]
$array[5]
will
will
will
will
will
will
will
will
contain
contain
contain
contain
contain
contain
contain
contain
''
'Root'
'02'
'Sport'
'0203'
'Auto'
'02031D'
'Ferrari'
Example 519. Specifying path to the current category in the following format: '> Root > Sport > Auto >
Ferrari'
$name ";
}
?>
2074
udm_check_charset
(PHP 4 >= 4.2.0)
udm_check_charset - Check if the given charset is known to mnogosearch
Description
int udm_check_charset (int agent, string charset)
Warning
This function is currently not documented; only the argument list is available.
2075
udm_check_stored
(PHP 4 >= 4.2.0)
udm_check_stored - Check connection to stored
Description
int udm_check_stored (int agent, int link, string doc_id)
Warning
This function is currently not documented; only the argument list is available.
2076
udm_clear_search_limits
(PHP 4 >= 4.0.5)
udm_clear_search_limits - Clear all mnoGoSearch search restrictions
Description
int udm_clear_search_limits (int agent)
udm_clear_search_limits() resets defined search limitations and returns TRUE.
2077
udm_close_stored
(PHP 4 >= 4.2.0)
udm_close_stored - Close connection to stored
Description
int udm_close_stored (int agent, int link)
Warning
This function is currently not documented; only the argument list is available.
2078
udm_crc32
(PHP 4 >= 4.2.0)
udm_crc32 - Return CRC32 checksum of gived string
Description
int udm_crc32 (int agent, string str)
Warning
This function is currently not documented; only the argument list is available.
2079
udm_errno
(PHP 4 >= 4.0.5)
udm_errno - Get mnoGoSearch error number
Description
int udm_errno (int agent)
udm_errno() returns mnoGoSearch error number, zero if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving numeric agent error code.
2080
udm_error
(PHP 4 >= 4.0.5)
udm_error - Get mnoGoSearch error message
Description
string udm_error (int agent)
udm_error() returns mnoGoSearch error message, empty string if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving agent error message.
2081
udm_find
(PHP 4 >= 4.0.5)
udm_find - Perform search
Description
int udm_find (int agent, string query)
udm_find() returns result link identifier on success, FALSE on error.
The search itself. The first argument - session, the next one - query itself. To find something just type words you want to
find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here
only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc".
Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents
that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select
"bool" match mode in the search from.
mnoGoSearch understands the following boolean operators:
& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".
| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".
~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!
() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is
simple and powerful at the same time. Just consider query as usual boolean expression.
2082
udm_free_agent
(PHP 4 >= 4.0.5)
udm_free_agent - Free mnoGoSearch session
Description
int udm_free_agent (int agent)
udm_free_agent() returns TRUE on success, FALSE on error.
agent - link to agent identifier, received ` after call to udm_alloc_agent().
Freeing up memory allocated for agent session.
2083
udm_free_ispell_data
(PHP 4 >= 4.0.5)
udm_free_ispell_data - Free memory allocated for ispell data
Description
int udm_free_ispell_data (int agent)
udm_free_ispell_data() always returns TRUE.
agent - agent link identifier, received after call to udm_alloc_agent().
Note: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in
previous versions.
2084
udm_free_res
(PHP 4 >= 4.0.5)
udm_free_res - Free mnoGoSearch result
Description
int udm_free_res (int res)
udm_free_res() returns TRUE on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
Freeing up memory allocated for results.
2085
udm_get_doc_count
(PHP 4 >= 4.0.5)
udm_get_doc_count - Get total number of documents in database.
Description
int udm_get_doc_count (int agent)
udm_get_doc_count() returns number of documents in database.
agent - link to agent identifier, received after call to udm_alloc_agent().
Note: This function is supported only in mnoGoSearch 3.1.11 or later.
2086
udm_get_res_field
(PHP 4 >= 4.0.5)
udm_get_res_field - Fetch mnoGoSearch result field
Description
string udm_get_res_field (int res, int row, int field)
udm_get_res_field() returns result field value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.
field - field identifier, may have the following values:
•
UDM_FIELD_URL - document URL field
•
UDM_FIELD_CONTENT - document Content-type field (for example, text/html).
•
UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from
the categories tree root. (This parameter is available only in PHP 4.0.6 or later).
•
UDM_FIELD_TITLE - document title field.
•
UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).
•
UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).
•
UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).
•
UDM_FIELD_SIZE - document size.
•
UDM_FIELD_URLID - unique URL ID of the link.
•
UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).
•
UDM_FIELD_MODIFIED - last-modified field in unixtime format.
•
UDM_FIELD_ORDER - the number of the current document in set of found documents.
•
UDM_FIELD_CRC - document CRC.
2087
udm_get_res_param
(PHP 4 >= 4.0.5)
udm_get_res_param - Get mnoGoSearch result parameters
Description
string udm_get_res_param (int res, int param)
udm_get_res_param() returns result parameter value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
param - parameter identifier, may have the following values:
•
UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to
UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.
•
UDM_PARAM_FOUND - total number of results matching the query.
•
UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword,
good:5637, book: 120"
•
UDM_PARAM_SEARCHTIME - search time in seconds.
•
UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.
•
UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.
2088
udm_load_ispell_data
(PHP 4 >= 4.0.5)
udm_load_ispell_data - Load ispell data
Description
int udm_load_ispell_data (int agent, int var, string val1, string val2, int flag)
udm_load_ispell_data() loads ispell data. Returns TRUE on success, FALSE on error.
agent - agent link identifier, received after call to udm_alloc_agent().
var - parameter, indicating the source for ispell data. May have the following values:
After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use
UDM_ISPELL_TYPE_SERVER mode.
The
fastest
mode
is
UDM_ISPELL_TYPE_SERVER.
UDM_ISPELL_TYPE_TEXT
is
slower
and
UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to
speed up DB mode in future versions and it is going to be faster than TEXT mode.
•
UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2
are ignored and should be left blank. flag should be equal to 1.
Note: flag indicates that after loading ispell data from defined source it sould be sorted (it is necessary for correct
functioning of ispell). In case of loading ispell data from files there may be several calls to
udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db
mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if
ispell tables are absent, the function will return FALSE and code and error message will be accessible through
udm_error() and udm_errno().
Example:
if (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_DB,'','',1)) {
printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
exit;
}
•
UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In
this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a
relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the
path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and
an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(),
since those functions can only return messages associated with SQL. Please, see flag parameter description in
UDM_ISPELL_TYPE_DB.
Example:
if ((! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) ||
(! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) ||
(! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) ||
(! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) {
exit;
}
2089
udm_load_ispell_data
Note: flag is equal to 1 only in the last call.
•
UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please
note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current
path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and
udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.
if ((! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) ||
(! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) ||
(! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) ||
(! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) {
exit;
}
Note: flag is equal to 1 only in the last call.
•
UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running
spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag
parameter in this case is not needed since ispell data is stored on spellserver already sorted.
Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default),
sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so
that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi)
list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by
omitting loading and sorting all the spell data).
udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only
defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of
errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion
does not work.
Note: This function is available in mnoGoSearch 3.1.12 or later.
Example:
if (!udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SERVER,'','',1)) {
printf("Error loading ispell data from server
\n");
exit;
}
2090
udm_open_stored
(PHP 4 >= 4.2.0)
udm_open_stored - Open connection to stored
Description
int udm_open_stored (int agent, string storedaddr)
Warning
This function is currently not documented; only the argument list is available.
2091
udm_set_agent_param
(PHP 4 >= 4.0.5)
udm_set_agent_param - Set mnoGoSearch agent session parameters
Description
int udm_set_agent_param (int agent, int var, string val)
udm_set_agent_param() returns TRUE on success, FALSE on error. Defines mnoGoSearch session parameters.
The following parameters and their values are available:
•
UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning
from 0, with UDM_PARAM_PAGE_SIZE results per page).
•
UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.
•
UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all
words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL boolean search. See udm_find() for details on boolean search.
•
UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store
search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster
performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.
•
UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query
tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use
tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search,
front-end uses those tables to store query words, a number of found documents and current UNIX timestamp in seconds.
Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.
•
UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf).
Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is
enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE).
In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning
with 3.1.11 phrases are supported in cachemode as well.
Examples of phrase search:
"Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you
need to put double quotes around the phrase
•
UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g.
koi8-r, cp1251, ...
•
UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch
- while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the
module looks for the file in relation to current path, i.e. to the path where the php script is executed.)
•
UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.
•
UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title,
keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the
2092
udm_set_agent_param
indexer.conf. Let's imagine that we have these weights:
URLWeight
BodyWeight
TitleWeight
KeywordWeight
DescWeight
1
2
4
8
16
As far as indexer uses bit OR operation for word weights when some word presents several time in the same document,
it is possible at search time to detect word appearance in different document parts. Word which appears only in the body
will have 00000010 argegate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight.
This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For
the given above weights configuration:
E
D
C
B
A
is
is
is
is
is
a
a
a
a
a
factor
factor
factor
factor
factor
for
for
for
for
for
weight
1
(URL
Weight
weight
2
(BodyWeight
weight
4
(TitleWeight
weight
8
(KeywordWeight
weight
16
(DescWeight
bit)
bit)
bit)
bit)
bit)
Examples:
UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only.
UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only.
UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and
Body.
UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:
Description
Keywords
Title
Body
URL
with
factor
with
with
with
with
15
(F
factor
factor
factor
factor
hex)
9
4
2
1
If UDM_PARAM_WEIGHT_FACTOR variable is ommited, original weight value is taken to sort results. For a given
above weight configuration it means that document description has a most big weight 16.
•
UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature
works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and
other modes since they use word CRC and do not support substring search. Available values:
UDM_MATCH_BEGIN - word beginning match;
UDM_MATCH_END - word ending match;
2093
udm_set_agent_param
UDM_MATCH_WORD - whole word match;
UDM_MATCH_SUBSTR - word substring match.
•
UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a
stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3
characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.
•
UDM_PARAM_ISPELL_PREFIXES
Possible
values:
UDM_PREFIXES_ENABLED
and
UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search
query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data
with udm_load_ispell_data().
•
UDM_PARAM_CROSS_WORDS
enables
or
disables
crosswords
UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED.
support.
Possible
values:
The corsswords feature allows to assign words between and also to a document this link leads to. It
works in SQL database mode and is not supported in built-in database and Cachemode.
Note: Crosswords are supported only in mnoGoSearch 3.1.11 or later.
•
UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database
and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The
parameter is available in PHP 4.1.0 or later.
•
UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database
and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The
parameter is available in PHP 4.1.0 or later.
2094
mSQL functions
Table of Contents
msql_affected_rows .......................................................................................................................... 2097
msql_close ...................................................................................................................................... 2098
msql_connect .................................................................................................................................. 2099
msql_create_db ................................................................................................................................ 2100
msql_createdb ................................................................................................................................. 2101
msql_data_seek ............................................................................................................................... 2102
msql_dbname .................................................................................................................................. 2103
msql_drop_db ................................................................................................................................. 2104
msql_dropdb ................................................................................................................................... 2105
msql_error ...................................................................................................................................... 2106
msql_fetch_array ............................................................................................................................. 2107
msql_fetch_field .............................................................................................................................. 2108
msql_fetch_object ............................................................................................................................ 2109
msql_fetch_row ............................................................................................................................... 2110
msql_field_seek ............................................................................................................................... 2111
msql_fieldflags ................................................................................................................................ 2112
msql_fieldlen .................................................................................................................................. 2113
msql_fieldname ............................................................................................................................... 2114
msql_fieldtable ................................................................................................................................ 2115
msql_fieldtype ................................................................................................................................. 2116
msql_free_result .............................................................................................................................. 2117
msql_freeresult ................................................................................................................................ 2118
msql_list_dbs .................................................................................................................................. 2119
msql_list_fields ............................................................................................................................... 2120
msql_list_tables ............................................................................................................................... 2121
msql_listdbs .................................................................................................................................... 2122
msql_listfields ................................................................................................................................. 2123
msql_listtables ................................................................................................................................. 2124
msql_num_fields .............................................................................................................................. 2125
msql_num_rows .............................................................................................................................. 2126
msql_numfields ............................................................................................................................... 2127
msql_numrows ................................................................................................................................ 2128
msql_pconnect ................................................................................................................................ 2129
msql_query ..................................................................................................................................... 2130
msql_regcase ................................................................................................................................... 2131
msql_result ..................................................................................................................................... 2132
msql_select_db ................................................................................................................................ 2133
msql_selectdb .................................................................................................................................. 2134
msql_tablename ............................................................................................................................... 2135
msql .............................................................................................................................................. 2136
2095
Introduction
These functions allow you to access mSQL database servers. More information about mSQL can be found at http:/ /
www.hughes.com.au/.
Requirements
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 91. mSQL configuration options
Name
Default
Changeable
msql.allow_persistent
"On"
PHP_INI_SYSTEM
msql.max_persistent
"-1"
PHP_INI_SYSTEM
msql.max_links
"-1"
PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().
Here's a short explanation of the configuration directives.
msql.allow_persistent boolean
Whether to allow persistent mSQL connections.
msql.max_persistent integer
The maximum number of persistent mSQL connections per process.
msql.max_links integer
The maximum number of mSQL connections per process, including persistent connections.
Resource Types
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
MSQL_ASSOC (integer)
MSQL_NUM (integer)
MSQL_BOTH (integer)
2096
msql_affected_rows
(PHP 3>= 3.0.6, PHP 4 )
msql_affected_rows - Returns number of affected rows
Description
int msql_affected_rows (int query_identifier)
Returns number of affected ("touched") rows by a specific query (i.e. the number of rows returned by a SELECT, the number of rows modified by an update, or the number of rows removed by a delete).
See also: msql_query().
2097
msql_close
(PHP 3, PHP 4 )
msql_close - Close mSQL connection
Description
int msql_close (int link_identifier)
Returns TRUE on success, FALSE on error.
msql_close() closes the link to a mSQL database that's associated with the specified link identifier. If the link identifier isn't
specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
msql_close() will not close persistent links generated by msql_pconnect().
See also: msql_connect() and msql_pconnect().
2098
msql_connect
(PHP 3, PHP 4 )
msql_connect - Open mSQL connection
Description
int msql_connect ([string hostname [, string server [, string username [, string password ]]]])
msql_connect() establishes a connection to a mSQL server. The server parameter can also include a port number. eg. "hostname:port". It defaults to 'localhost'.
Returns a positive mSQL link identifier on success, or FALSE on error.
In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the
link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling
msql_close().
See also msql_pconnect() et msql_close().
2099
msql_create_db
(PHP 3, PHP 4 )
msql_create_db - Create mSQL database
Description
int msql_create_db (string database_name [, int link_identifier])
msql_create_db() attempts to create a new database on the server associated with the specified link identifier.
See also msql_drop_db().
2100
msql_createdb
(PHP 3, PHP 4 )
msql_createdb - Create mSQL database
Description
int msql_createdb (string database_name [, int link_identifier])
Identical to msql_create_db().
2101
msql_data_seek
(PHP 3, PHP 4 )
msql_data_seek - Move internal row pointer
Description
int msql_data_seek (int query_identifier, int row_number)
msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point
to the specifyed row number. The next call to msql_fetch_row() would return that row.
Returns TRUE on success or FALSE on failure.
See also msql_fetch_row().
2102
msql_dbname
(PHP 3, PHP 4 )
msql_dbname - Get current mSQL database name
Description
string msql_dbname (int query_identifier, int i)
msql_dbname() returns the database name stored in position i of the result pointer returned from the msql_listdbs() function. The msql_numrows() function can be used to determine how many database names are available.
2103
msql_drop_db
(PHP 3, PHP 4 )
msql_drop_db - Drop (delete) mSQL database
Description
int msql_drop_db (string database_name, int link_identifier)
Returns TRUE on success or FALSE on failure.
msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.
See also: msql_create_db().
2104
msql_dropdb
(PHP 3, PHP 4 )
msql_dropdb - Drop (delete) mSQL database
Description
See msql_drop_db().
2105
msql_error
(PHP 3, PHP 4 )
msql_error - Returns error message of last msql call
Description
string msql_error ([int link_identifier])
Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the
error string.
2106
msql_fetch_array
(PHP 3, PHP 4 )
msql_fetch_array - Fetch row as array
Description
int msql_fetch_array (int query_identifier [, int result_type])
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of
the result array, it also stores the data in associative indices, using the field names as keys.
The second optional argument result_type in msql_fetch_array() is a constant and can take the following values:
MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.
Be careful if you are retrieving results from a query that may return a record that contains only one field that has a value of
0 (or an empty string, or NULL).
An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(),
while it provides a significant added value.
See also msql_fetch_row().
2107
msql_fetch_field
(PHP 3, PHP 4 )
msql_fetch_field - Get field information
Description
object msql_fetch_field (int query_identifier, int field_offset)
Returns an object containing field information
msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't
specified, the next field that wasn't yet retreived by msql_fetch_field() is retreived.
The properties of the object are:
•
name - column name
•
table - name of the table the column belongs to
•
not_null - 1 if the column cannot be NULL
•
primary_key - 1 if the column is a primary key
•
unique - 1 if the column is a unique key
•
type - the type of the column
See also msql_field_seek().
2108
msql_fetch_object
(PHP 3, PHP 4 )
msql_fetch_object - Fetch row as object
Description
int msql_fetch_object (int query_identifier [, int result_type])
Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.
msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property
names).
The optional second argument result_type in msql_fetch_array() is a constant and can take the following values:
MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.
Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).
See also: msql_fetch_array() and msql_fetch_row().
2109
msql_fetch_row
(PHP 3, PHP 4 )
msql_fetch_row - Get row as enumerated array
Description
array msql_fetch_row (int query_identifier)
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned
as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
See also: msql_fetch_array(), msql_fetch_object(), msql_data_seek(), and msql_result().
2110
msql_field_seek
(PHP 3, PHP 4 )
msql_field_seek - Set field offset
Description
int msql_field_seek (int query_identifier, int field_offset)
Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.
See also: msql_fetch_field().
2111
msql_fieldflags
(PHP 3, PHP 4 )
msql_fieldflags - Get field flags
Description
string msql_fieldflags (int query_identifier, int i)
msql_fieldflags() returns the field flags of the specified field. Currently this is either, "not NULL", "primary key", a combination of the two or "" (an empty string).
2112
msql_fieldlen
(PHP 3, PHP 4 )
msql_fieldlen - Get field length
Description
int msql_fieldlen (int query_identifier, int i)
msql_fieldlen() returns the length of the specified field.
2113
msql_fieldname
(PHP 3, PHP 4 )
msql_fieldname - Get field name
Description
string msql_fieldname (int query_identifier, int field)
msql_fieldname() returns the name of the specified field. query_identifier is the query identifier, and field is the field index.
msql_fieldname($result, 2); will return the name of the second field in the result associated with the result identifier.
2114
msql_fieldtable
(PHP 3, PHP 4 )
msql_fieldtable - Get table name for field
Description
int msql_fieldtable (int query_identifier, int field)
Returns the name of the table field was fetched from.
2115
msql_fieldtype
(PHP 3, PHP 4 )
msql_fieldtype - Get field type
Description
string msql_fieldtype (int query_identifier, int i)
msql_fieldtype() is similar to the msql_fieldname() function. The arguments are identical, but the field type is returned.
This will be one of "int", "char" or "real".
2116
msql_free_result
(PHP 3, PHP 4 )
msql_free_result - Free result memory
Description
int msql_free_result (int query_identifier)
msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is
freed automatically, so you only need to call this function when you want to make sure you don't use too much memory
while the script is running.
2117
msql_freeresult
(PHP 3, PHP 4 )
msql_freeresult - Free result memory
Description
See msql_free_result()
2118
msql_list_dbs
(PHP 3, PHP 4 )
msql_list_dbs - List mSQL databases on server
Description
int msql_list_dbs (void)
msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the
msql_dbname() function to traverse this result pointer.
2119
msql_list_fields
(PHP 3, PHP 4 )
msql_list_fields - List result fields
Description
int msql_list_fields (string database, string tablename)
msql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A
result pointer is returned which can be used with msql_fieldflags(), msql_fieldlen(), msql_fieldname(), and
msql_fieldtype(). A query identifier is a positive integer. The function returns -1 if a error occurs. A string describing the
error will be placed in $phperrmsg, and unless the function was called as @msql_list_fields() then this error string
will also be printed out.
See also msql_error().
2120
msql_list_tables
(PHP 3, PHP 4 )
msql_list_tables - List tables in an mSQL database
Description
int msql_list_tables (string database)
msql_list_tables() takes a database name and result pointer much like the msql() function. The msql_tablename() function
should be used to extract the actual table names from the result pointer.
2121
msql_listdbs
(PHP 3, PHP 4 )
msql_listdbs - List mSQL databases on server
Description
See msql_list_dbs().
2122
msql_listfields
(PHP 3, PHP 4 )
msql_listfields - List result fields
Description
See msql_list_fields().
2123
msql_listtables
(PHP 3, PHP 4 )
msql_listtables - List tables in an mSQL database
Description
See msql_list_tables().
2124
msql_num_fields
(PHP 3, PHP 4 )
msql_num_fields - Get number of fields in result
Description
int msql_num_fields (int query_identifier)
msql_num_fields() returns the number of fields in a result set.
See also: msql(), msql_query(), msql_fetch_field(), and msql_num_rows().
2125
msql_num_rows
(PHP 3, PHP 4 )
msql_num_rows - Get number of rows in result
Description
int msql_num_rows (int query_identifier)
msql_num_rows() returns the number of rows in a result set.
See also: msql(), msql_query(), and msql_fetch_row().
2126
msql_numfields
(PHP 3, PHP 4 )
msql_numfields - Get number of fields in result
Description
int msql_numfields (int query_identifier)
Identical to msql_num_fields().
2127
msql_numrows
(PHP 3, PHP 4 )
msql_numrows - Get number of rows in result
Description
int msql_numrows (void)
Identical to msql_num_rows().
2128
msql_pconnect
(PHP 3, PHP 4 )
msql_pconnect - Open persistent mSQL connection
Description
int msql_pconnect ([string server [, string username [, string password ]]])
msql_pconnect() acts very much like msql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is
found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by msql_pconnect()).
Returns a positive mSQL persistent link identifier on success, or FALSE on error.
This type of links is therefore called 'persistent'.
2129
msql_query
(PHP 3, PHP 4 )
msql_query - Send mSQL query
Description
int msql_query (string query, int link_identifier)
msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.
If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as
if msql_connect() was called, and use it.
Returns a positive mSQL query identifier on success, or FALSE on error.
Example 520. msql_query() example
See also msql(), msql_select_db(), and msql_connect().
2130
msql_regcase
(PHP 3, PHP 4 )
msql_regcase - Make regular expression for case insensitive match
Description
See sql_regcase().
2131
msql_result
(PHP 3, PHP 4 )
msql_result - Get result data
Description
int msql_result (int query_identifier, int i, mixed field)
Returns the contents of the cell at the row and offset in the specified mSQL result set.
msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the
field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as
bar from ...'), use the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below).
As these functions return the contents of multiple cells in one function call, they're MUCH quicker than msql_result().
Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().
2132
msql_select_db
(PHP 3, PHP 4 )
msql_select_db - Select mSQL database
Description
int msql_select_db (string database_name, int link_identifier)
Returns TRUE on success, FALSE on error.
msql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link
identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if
msql_connect() was called, and use it.
Every subsequent call to msql_query() will be made on the active database.
See also msql_connect(), msql_pconnect(), and msql_query().
2133
msql_selectdb
(PHP 3, PHP 4 )
msql_selectdb - Select mSQL database
Description
See msql_select_db().
2134
msql_tablename
(PHP 3, PHP 4 )
msql_tablename - Get table name of field
Description
string msql_tablename (int query_identifier, int field)
msql_tablename() takes a result pointer returned by the msql_list_tables() function as well as an integer index and returns
the name of a table. The msql_numrows() function may be used to determine the number of tables in the result pointer.
Example 521. msql_tablename() example
";
$i++;
}
?>
2135
msql
(PHP 3, PHP 4 )
msql - Send mSQL query
Description
int msql (string database, string query, int link_identifier)
Returns a positive mSQL query identifier to the query result, or FALSE on error.
msql() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find
an open link to the mSQL server and if no such link is found it'll try to create one as if msql_connect() was called with no
arguments (see msql_connect()).
2136
MySQL Functions
Table of Contents
mysql_affected_rows ........................................................................................................................ 2141
mysql_change_user .......................................................................................................................... 2143
mysql_client_encoding ...................................................................................................................... 2144
mysql_close .................................................................................................................................... 2145
mysql_connect ................................................................................................................................ 2146
mysql_create_db .............................................................................................................................. 2147
mysql_data_seek .............................................................................................................................. 2148
mysql_db_name ............................................................................................................................... 2149
mysql_db_query .............................................................................................................................. 2150
mysql_drop_db ................................................................................................................................ 2151
mysql_errno .................................................................................................................................... 2152
mysql_error .................................................................................................................................... 2153
mysql_escape_string ......................................................................................................................... 2154
mysql_fetch_array ............................................................................................................................ 2155
mysql_fetch_assoc ........................................................................................................................... 2157
mysql_fetch_field ............................................................................................................................ 2159
mysql_fetch_lengths ......................................................................................................................... 2161
mysql_fetch_object .......................................................................................................................... 2162
mysql_fetch_row ............................................................................................................................. 2163
mysql_field_flags ............................................................................................................................. 2164
mysql_field_len ............................................................................................................................... 2165
mysql_field_name ............................................................................................................................ 2166
mysql_field_seek ............................................................................................................................. 2167
mysql_field_table ............................................................................................................................. 2168
mysql_field_type ............................................................................................................................. 2169
mysql_free_result ............................................................................................................................. 2170
mysql_get_client_info ....................................................................................................................... 2171
mysql_get_host_info ......................................................................................................................... 2172
mysql_get_proto_info ....................................................................................................................... 2173
mysql_get_server_info ...................................................................................................................... 2174
mysql_info ..................................................................................................................................... 2175
mysql_insert_id ............................................................................................................................... 2176
mysql_list_dbs ................................................................................................................................ 2177
mysql_list_fields .............................................................................................................................. 2178
mysql_list_processes ........................................................................................................................ 2179
mysql_list_tables ............................................................................................................................. 2180
mysql_num_fields ............................................................................................................................ 2181
mysql_num_rows ............................................................................................................................. 2182
mysql_pconnect ............................................................................................................................... 2183
mysql_ping ..................................................................................................................................... 2184
mysql_query ................................................................................................................................... 2185
mysql_real_escape_string .................................................................................................................. 2187
mysql_result ................................................................................................................................... 2188
mysql_select_db .............................................................................................................................. 2189
mysql_stat ...................................................................................................................................... 2190
mysql_tablename ............................................................................................................................. 2191
mysql_thread_id .............................................................................................................................. 2192
mysql_unbuffered_query ................................................................................................................... 2193
2137
Introduction
These functions allow you to access MySQL database servers. More information about MySQL can be found at http:/ /
www.mysql.com/.
Documentation for MySQL can be found at http://www.mysql.com/documentation/.
Requirements
In order to have these functions available, you must compile PHP with MySQL support.
Installation
By using the --with-mysql[=DIR] configuration option you enable PHP to access MySQL databases. If you use this option without specifying the path to MySQL, PHP will use the bundled MySQL client libraries. As of PHP 4, --with-mysql
is enabled by default so to disable MySQL support you must use --without-mysql. Users who run other applications that
use MySQL (for example, running PHP 3 and PHP 4 as concurrent apache modules, or auth-mysql) should always specify
the path to the MySQL DIR: --with-mysql=/path/to/mysql. This will force PHP to use the client libraries installed by
MySQL, avoiding any conflicts.
The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.
Warning
Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension. See the recode extension for more information.
Runtime Configuration
The behaviour of these functions is affected by settings in php.ini.
Table 92. MySQL Configuration Options
Name
Default
Changeable
mysql.allow_persistent
"On"
PHP_INI_SYSTEM
mysql.max_persistent
"-1"
PHP_INI_SYSTEM
mysql.max_links
"-1"
PHP_INI_SYSTEM
mysql.default_port
NULL
PHP_INI_ALL
mysql.default_socket
NULL
PHP_INI_ALL
mysql.default_host
NULL
PHP_INI_ALL
mysql.default_user
NULL
PHP_INI_ALL
mysql.default_password
NULL
PHP_INI_ALL
mysql.connect_timeout
"0"
PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().
Here's a short explanation of the configuration directives.
2138
MySQL Functions
mysql.allow_persistent boolean
Whether to allow persistent connections to MySQL.
mysql.max_persistent integer
The maximum number of persistent MySQL connections per process.
mysql.max_links integer
The maximum number of MySQL connections per process, including persistent connections.
mysql.default_port string
The default TCP port number to use when connecting to the database server if no other port is specified. If no default is
specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /
etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.
mysql.default_socket string
The default socket name to use when connecting to a local database server if no other socket name is specified.
mysql.default_host string
The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe
mode.
mysql.default_user string
The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe
mode.
mysql.default_password string
The default password to use when connecting to the database server if no other password is specified. Doesn't apply in
safe mode.
mysql.connect_timeout integer
Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server.
Resource Types
There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the
second a resource which holds the result of a query.
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled
into PHP or dynamically loaded at runtime.
Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect() and mysql_pconnect() functions.
The following constants are defined:
Table 93. MySQL client constants
constant
description
MYSQL_CLIENT_COMPRESS
use compression protocol
MYSQL_CLIENT_IGNORE_SPACE
Allow space after function names
MYSQL_CLIENT_INTERACTIVE
Allow interactive_timeout seconds (instead of wait_timeout)
of inactivity before closing the connection.
2139
MySQL Functions
The function mysql_fetch_array() uses a constant for the different types of result arrays. The following constants are
defined:
Table 94. MySQL fetch constants
constant
description
MYSQL_ASSOC
Columns are returned into the array having the fieldname as
the array index.
MYSQL_BOTH
Columns are returned into the array having both a numerical
index and the fieldname as the array index.
MYSQL_NUM
Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the
result.
Examples
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.
Example 522. MySQL extension overview example
\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
print "\t\n";
foreach ($line as $col_value) {
print "\t\t$col_value | \n";
}
print "\t
\n";
}
print "