005.13 M319 OpenSSL Functions
005.13 M319 OpenSSL Functions
<?php
print "<HTML><PRE>";
$conn = OCILogon("scott","tiger");
$sql = "delete from emp where deptno = 10";
$stmt = OCIParse($conn,$sql);
if ( OCIStatementType($stmt) == "DELETE" ) {
die "You are not allowed to delete from this table<BR>";
}
OCILogoff($conn);
print "</PRE></HTML>";
?>
OCIWriteLobToFile (PHP 4 )
Coming soon
void OCIWriteLobToFile ( object lob [, string filename [, int start [, int lenght]]]) \linebreak
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1075
LXXI. OpenSSL functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Introduction
This module uses the functions of OpenSSL (http://www.openssl.org/) for generation and verification of
signatures and for sealing (encrypting) and opening (decrypting) data. PHP-4.0.4pl1 requires OpenSSL
>= 0.9.6, but PHP-4.0.5 and greater with also work with OpenSSL >= 0.9.5.
Nota: Please keep in mind that this extension is still considered experimental!
OpenSSL offers many features that this module currently doesn’t support. Some of these may be added
in the future.
Key/Certificate parameters
Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have
to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may
use one of the following methods:
• Certificates
• Public/Private Keys
1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
2. For public keys only: an X.509 resource
3. A string having the format file://path/to/file.pem - the named file must contain a PEM
1076
OpenSSL
Certificate Verification
When calling a function that will verify a signature/certificate, the cainfo parameter is an array
containing file and directory names the specify the locations of trusted CA files. If a directory is
specified, then it must be a correctly formed hashed directory as the openssl command would use.
PKCS7 Flags/Constants
The S/MIME functions make use of flags which are specified using a bitfield which can include one or
more of the following values:
Constant Description
PKCS7_TEXT adds text/plain content type headers to
encrypted/signed message. If decrypting or
verifying, it strips those headers from the output - if
the decrypted or verified message is not of MIME
type text/plain then an error will occur.
PKCS7_BINARY normally the input message is converted to
"canonical" format which is effectively using CR
and LF as end of line: as required by the S/MIME
specification. When this options is present, no
translation occurs. This is useful when handling
binary data which may not be in MIME format.
PKCS7_NOINTERN when verifying a message, certificates (if any)
included in the message are normally searched for
the signing certificate. With this option only the
certificates specified in the extracerts
parameter of openssl_pkcs7_verify() are used. The
supplied certificates can still be used as untrusted
CAs however.
PKCS7_NOVERIFY do not verify the signers certificate of a signed
message.
1077
OpenSSL
Constant Description
PKCS7_NOCHAIN do not chain verification of signers certificates: that
is don’t use the certificates in the signed message as
untrusted CAs.
PKCS7_NOCERTS when signing a message the signer’s certificate is
normally included - with this option it is excluded.
This will reduce the size of the signed message but
the verifier must have a copy of the signers
certificate available locally (passed using the
extracerts to openssl_pkcs7_verify() for
example.
PKCS7_NOATTR normally when a message is signed, a set of
attributes are included which include the signing
time and the supported symmetric algorithms. With
this option they are not included.
PKCS7_DETACHED When signing a message, use cleartext signing with
the MIME type multipart/signed. This is the default
if the flags parameter to openssl_pkcs7_sign() if
you do not specify any flags. If you turn this option
off, the message will be signed using opaque
signing, which is more resistant to translation by
mail relays but cannot be read by mail agents that do
not support S/MIME.
PKCS7_NOSIGS Don’t try and verify the signatures on a message
1078
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1079
OpenSSL
bool openssl_csr_new ( array dn, resource privkey [, array extraattribs [, array configargs]]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
resource openssl_csr_sign ( mixed csr, mixed x509, mixed priv_key, long days) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1080
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Returns an error message string, or FALSE if there are no more error messages to return.
openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so
this function should be called multiple times to collect all of the information.
The parameters/return type of this function may change before it appears in a release version of PHP
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1081
OpenSSL
openssl_free_key() frees the key associated with the specified key_identifier from memory.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
bool openssl_open ( string sealed_data, string open_data, string env_key, mixed priv_key_id) \linebreak
1082
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. If successful the opened data is returned in
open_data.
openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier
priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The
envelope key is generated when the data are sealed and can only be used by one specific private key. See
openssl_seal() for more information.
bool openssl_pkcs7_decrypt ( string infilename, string outfilename, mixed recipcert, mixed recipkey) \linebreak
1083
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Decrypts the S/MIME encrypted message contained in the file specified by infilename using the
certificate and it’s associated private key specified by recipcert and recipkey.
The decrypted message is output to the file specified by outfilename
// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg"; // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file
bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, long flags]) \line-
break
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1084
OpenSSL
openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2
40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which
is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that
will be prepended to the data after it has been encrypted. flags can be used to specify options that
affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed
by header name, or an indexed array, where each element contains a single header line.
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk. You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,
HQ
EOD;
// load key
$key = implode("", file("nighthawk.pem"));
// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
array("To" => "[email protected]", // keyed
syntax
"From: HQ <[email protected]>", // indexed syntax
"Subject" => "Eyes only")))
{
// message encrypted - send it!
exec(ini_get("sendmail_path") . " < enc.txt");
}
1085
OpenSSL
bool openssl_pkcs7_sign ( string infilename, string outfilename, mixed signcert, mixed privkey, array headers [,
long flags [, string extracertsfilename]]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the
certificate and it’s matching private key specified by signcert and privkey parameters.
headers is an array of headers that will be prepended to the data after it has been signed (see
openssl_pkcs7_encrypt() for more information about the format of this parameter.
flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to
PKCS7_DETACHED.
extracerts specifies the name of a file containing a bunch of extra certificates to include in the
signature which can for example be used to help the recipient to verify the certificate that you used.
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD
The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
array("mycert.pem", "mypassphrase"),
array("To" => "[email protected]", // keyed syntax
"From: HQ <[email protected]>", // indexed syntax
"Subject" => "Eyes only"))
{
// message signed - send it!
exec(ini_get("sendmail_path") . " < signed.txt");
}
1086
OpenSSL
bool openssl_pkcs7_verify ( string filename, int flags [, string outfilename [, array cainfo [, string extracerts]]])
\linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename
and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct
(the message has been tampered with, or the signing certificate is invalid), or -1 on error.
flags can be used to affect how the signature is verified - see PKCS7 constants for more information.
If the outfilename is specified, it should be a string holding the name of a file into which the
certificates of the persons that signed the messages will be stored in PEM format.
If the cainfo is specified, it should hold information about the trusted CA certificates to use in the
verification process - see certificate verification for more information about this parameter.
If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as
untrusted CAs.
bool openssl_pkey_export_to_file ( mixed key, string outfilename [, string passphrase [, array config_args]])
\linebreak
1087
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool openssl_pkey_export ( mixed key, mixed out [, string passphrase [, array config_args]]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1088
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool openssl_private_decrypt ( string data, string crypted, mixed key [, int padding]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool openssl_private_encrypt ( string data, string crypted, mixed key [, int padding]) \linebreak
1089
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool openssl_public_decrypt ( string data, string crypted, resource key [, int padding]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool openssl_public_encrypt ( string data, string crypted, mixed key [, int padding]) \linebreak
1090
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
int openssl_seal ( string data, string sealed_data, array env_keys, array pub_key_ids) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is
returned in sealed_data, and the envelope keys in env_keys.
openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is
encrypted with each of the public keys associated with the identifiers in pub_key_ids and each
encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients
(provided one has obtained their public keys). Each recipient must receive both the sealed data and the
envelope key that was encrypted with the recipient’s public key.
1091
OpenSSL
// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1,$pk2));
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. If successful the signature is returned in
signature.
openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by
encryption using the private key associated with priv_key_id. Note that the data itself is not
encrypted.
1092
OpenSSL
$pkeyid = openssl_get_privatekey($priv_key);
// compute signature
openssl_sign($data, $signature, $pkeyid);
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
// $data and $signature are assumed to contain the data and the signature
1093
OpenSSL
echo "bad";
else
echo "ugly, error checking signature";
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool openssl_x509_checkpurpose ( mixed x509cert, int purpose, array cainfo [, string untrustedfile]) \linebreak
1094
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.
openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used
for the purpose specified by purpose.
cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.
untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used
to help verify the certificate, although no trust in placed in the certificates that come from that file.
Constant Description
X509_PURPOSE_SSL_CLIENT Can the certificate be used for the client side of an
SSL connection?
X509_PURPOSE_SSL_SERVER Can the certificate be used for the server side of an
SSL connection?
X509_PURPOSE_NS_SSL_SERVER Can the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGN Can the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPT Can the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGN Can the cert be used to sign a certificate revocation
list (CRL)?
X509_PURPOSE_ANY Can the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!
1095
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1096
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
openssl_x509_free() frees the certificate associated with the specified x509cert resource from
memory.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
openssl_x509_parse() returns information about the supplied x509cert, including fields such as
subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the
data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the
short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of
commonName.
The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.
1097
OpenSSL
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1098
LXXII. Funciones Oracle
1099
Oracle
int ora_bind ( int cursor, string nombre de variable PHP, string nombre de parámetro SQL, int longitud [, int
tipo]) \linebreak
Devuelve verdadero si el vínculo se realiza con éxito, y sino devuelve falso. Los detalles de los errores
pueden examinarse usando la funciones ora_error() y ora_errorcode().
Esta función liga la variable PHP nombrada con el parámetro SQL. El parámtro SQL debe estar en la
forma ":name". Con el parámetro optativo tipo, se define si el parámetro SQL se trata de un parámetro de
entrada/salida (0 y por defecto), entrada (1) o salida (2). Como en PHP 3.0.1, se puede usar las
constantes ORA_BIND_INOUT, ORA_BIND_IN y ORA_BIND_OUT en lugar de los números.
ora_bind debe ser llamada después de ora_parse() y antes de ora_exec(). Los valores de entrada pueden
pasarse por asignación a las variables PHP vinculadas, despues de la llamada a ora_exec() dichas
variables contendrán los valores de salida, si éstos estuvieran disponibles.
<?php
ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;");
ora_bind($curs, "result", ":x", $len, 2);
ora_bind($curs, "input", ":in", 5, 1);
ora_bind($curs, "output", ":out", 5, 2);
$input = 765;
ora_exec($curs);
echo "Result: $result<BR>Out: $output<BR>In: $input";
?>
1100
Oracle
1101
Oracle
Nota: El soporte para las identificaciones de conexión fue agregado en la versión 3.0.4.
1102
Oracle
En las versiones UNIX de Oracle, pueden encontrarse detalles acerca de un mensaje de error como este:
$ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" //
*Cause: An update or insert statement attempted to insert a duplicate key //
For Trusted ORACLE configured in DBMS MAC mode, you may see // this message
if a duplicate entry exists at a different level. // *Action: Either remove
the unique restriction or do not insert the key
Nota: El soporte para las identificaciones de conexión fue agregado en la versión 3.0.4.
1103
Oracle
Ejemplo 1. ora_fetch_into()()
<?php
$results = array();
ora_fetch_into($cursor, $results);
echo $results[0];
echo $results[1];
$results = array();
ora_fetch_into($cursor, $results, ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
echo $results[’MyColumn’];
?>
1104
Oracle
Si hubiesen datos con caracteres no-ASCII, habría que asegurarse de que esté presente la variable de
entorno NLS_LANG en el sistema. Para los modulos de servidor, deberían definirse en el entorno del
servidor antes de iniciarlo.
Devuelve el índice de la conexión si aquella tuvo éxito, de lo cantrario devuelve falso. Los detalles del
error pueden verse invocando las funciones ora_error() y ora_errorcode().
1105
Oracle
1106
LXXIII. Ovrimos SQL functions
Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast
transactions.
Ovrimos SQL Server is available at www.ovrimos.com (http://www.ovrimos.com/). To enable ovrimos
support in PHP just compile php with the ’--with-ovrimos’ parameter to configure script. You’ll need to
install the sqlcli library available in the Ovrimos SQL Server distribution.
Ejemplo 1. Connect to Ovrimos SQL Server and select from a system table
<?php
$conn = ovrimos_connect ("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
echo ("Connection ok!");
$res = ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
if ($res != 0) {
echo "Statement ok!";
ovrimos_result_all ($res);
ovrimos_free_result ($res);
}
ovrimos_close($conn);
}
?>
1107
OvrimosSQL
int ovrimos_connect ( string host, string db, string user, string password) \linebreak
ovrimos_connect() is used to connect to the specified database.
ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of ’host’ and
’port’ are those used everywhere in Ovrimos APIs. ’Host’ is a host name or IP address and ’db’ is either
a database name, or a string containing the port number.
<?php
$conn = ovrimos_connect ("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
echo "Connection ok!";
$res=ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
if ($res != 0) {
echo "Statement ok!";
ovrimos_result_all ($res);
ovrimos_free_result ($res);
}
ovrimos_close ($conn);
}
?>
1108
OvrimosSQL
The above example will connect to the database and print out the specified table.
1109
OvrimosSQL
int ovrimos_fetch_into ( int result_id, array result_array [, string how [, int rownumber]]) \linebreak
ovrimos_fetch_into() is used to fetch a row from the result set.
ovrimos_fetch_into() fetches a row from the result set into ’result_array’, which should be passed by
reference. Which row is fetched is determined by the two last parameters. ’how’ is one of ’Next’
(default), ’Prev’, ’First’, ’Last’, ’Absolute’, corresponding to forward direction from current position,
backward direction from current position, forward direction from the start, backward direction from the
end and absolute position from the start (essentially equivalent to ’first’ but needs ’rownumber’). Case is
not significant. ’Rownumber’ is optional except for absolute positioning. Returns TRUE or FALSE.
<?php
$conn=ovrimos_connect ("neptune", "8001", "admin", "password");
if ($conn!=0) {
echo "Connection ok!";
$res=ovrimos_exec ($conn,"select table_id, table_name from sys.tables");
if ($res != 0) {
echo "Statement ok!";
if (ovrimos_fetch_into ($res, &$row)) {
list ($table_id, $table_name) = $row;
echo "table_id=".$table_id.", table_name=".$table_name."\n";
if (ovrimos_fetch_into ($res, &$row)) {
list ($table_id, $table_name) = $row;
echo "table_id=".$table_id.", table_name=".$table_name."\n";
} else {
echo "Next: error\n";
}
} else {
echo "First: error\n";
}
ovrimos_free_result ($res);
}
ovrimos_close ($conn);
}
?>
1110
OvrimosSQL
<?php
$conn = ovrimos_connect ("remote.host", "8001", "admin", "password");
if ($conn != 0) {
echo "Connection ok!";
$res=ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
if ($res != 0) {
echo "Statement ok!";
if (ovrimos_fetch_row ($res, "First")) {
$table_id = ovrimos_result ($res, 1);
$table_name = ovrimos_result ($res, 2);
echo "table_id=".$table_id.", table_name=".$table_name."\n";
if (ovrimos_fetch_row ($res, "Next")) {
$table_id = ovrimos_result ($res, "table_id");
$table_name = ovrimos_result ($res, "table_name");
echo "table_id=".$table_id.", table_name=".$table_name."\n";
} else {
echo "Next: error\n";
}
} else {
echo "First: error\n";
}
ovrimos_free_result ($res);
}
ovrimos_close ($conn);
}
?>
1111
OvrimosSQL
ovrimos_field_name() returns the output column name at the (1-based) index specified.
1112
OvrimosSQL
<?php
$conn=ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn!=0) {
echo "Connection ok!";
$res=ovrimos_prepare ($conn, "select table_id, table_name
from sys.tables where table_id=1");
if ($res != 0) {
echo "Prepare ok!";
if (ovrimos_execute ($res)) {
echo "Execute ok!\n";
ovrimos_result_all ($res);
} else {
echo "Execute not ok!";
}
ovrimos_free_result ($res);
} else {
1113
OvrimosSQL
This will connect to Ovrimos SQL Server, prepare a statement and the execute it.
<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
echo "Connection ok!";
$res = ovrimos_prepare ($conn, "select table_id, table_name
from sys.tables where table_id = 7");
if ($res != 0) {
echo "Prepare ok!";
if (ovrimos_execute ($res, array(3))) {
echo "Execute ok!\n";
ovrimos_result_all ($res);
} else {
echo "Execute not ok!";
}
ovrimos_free_result ($res);
} else {
echo "Prepare not ok!\n";
}
ovrimos_close ($conn);
}
?>
This will execute an SQL statement and print the result in an HTML table.
1114
OvrimosSQL
<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
echo "Connection ok!";
$res = ovrimos_exec ($conn, "select table_id, table_name
from sys.tables where table_id = 1")
if ($res != 0) {
echo "Statement ok! cursor=".ovrimos_cursor ($res)."\n";
$colnb = ovrimos_num_fields ($res);
echo "Output columns=".$colnb."\n";
for ($i=1; $i<=$colnb; $i++) {
$name = ovrimos_field_name ($res, $i);
$type = ovrimos_field_type ($res, $i);
$len = ovrimos_field_len ($res, $i);
echo "Column ".$i." name=".$name." type=".$type." len=".$len."\n";
}
ovrimos_result_all ($res);
ovrimos_free_result ($res);
}
ovrimos_close ($conn);
}
?>
<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
echo "Connection ok!";
$res = ovrimos_exec ($conn, "update test set i=5");
if ($res != 0) {
echo "Statement ok!";
echo ovrimos_num_rows ($res)." rows affected\n";
ovrimos_free_result ($res);
}
ovrimos_close ($conn);
}
?>
1115
OvrimosSQL
1116
LXXIV. Output Control Functions
The Output Control functions allow you to control when output is sent from the script. This can be useful
in several different situations, especially if you need to send headers to the browser after your script has
began outputing data. The Output Control functions do not affect headers sent using header() or
setcookie(), only functions such as echo() and data between blocks of PHP code.
<?php
ob_start();
echo "Hello\n";
ob_end_flush();
?>
In the above example, the output from echo() would be stored in the output buffer until ob_end_flush()
was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an
error. (You can not normally send headers to the browser after data has already been sent.)
See also header() and setcookie().
1117
Output Control
ob_end_clean (PHP 4 )
Clean (erase) the output buffer and turn off output buffering
ob_end_flush (PHP 4 )
Flush (send) the output buffer and turn off output buffering
1118
Output Control
ob_get_contents (PHP 4 )
Return the contents of the output buffer
1119
Output Control
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
This will return the current status of output buffers. It returns array contains buffer status or FALSE for
error.
See also ob_get_level().
ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending
gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually
sends compressed data, it determines what type of content encoding the browser will accept ("gzip",
"deflate" or none at all) and will return it’s output accordingly. All browsers are supported since it’s up to
the browser to send the correct header saying that it accepts compressed web pages.
<?php
ob_start("ob_gzhandler");
?>
<html>
<body>
<p>This should be a compressed page.
</html>
<body>
1120
Output Control
ob_implicit_flush (PHP 4 )
Turn implicit flush on/off
ob_start (PHP 4 )
Turn on output buffering
1121
LXXV. Object property and method call
overloading
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
The purpose of this extension is to allow overloading of object property access and method calls. Only
one function is defined in this extension, overload() which takes the name of the class that should have
this functionality enabled. The class named has to define appropriate methods if it wants to have this
functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a
method. This way overloading can be selective. Inside these handler functions the overloading is
disabled so you can access object properties normally.
Some simple examples on using the overload() function:
<?php
class OO
{
var $a = 111;
var $elem = array(’b’ => 9, ’c’ => 42);
1122
Object overloading
overload(’OO’);
$o = new OO;
print "\$o->a: $o->a\n"; // print: $o->a:
print "\$o->b: $o->b\n"; // print: $o->b: 9
print "\$o->c: $o->c\n"; // print: $o->c: 42
print "\$o->d: $o->d\n"; // print: $o->d:
?>
Aviso
As this is an experimental extension, not all things work. There is no __call()
support currently, you can only overload the get and set operations for properties.
You cannot invoke the original overloading handlers of the class, and __set() only
works to one level of property access.
1123
Object overloading
1124
LXXVI. PDF functions
You can use the PDF functions in PHP to create PDF files if you have the PDF library by Thomas Merz
(available at http://www.pdflib.com/pdflib/index.html; you will also need the JPEG library
(ftp://ftp.uu.net/graphics/jpeg/) and the TIFF library (http://www.libtiff.org/) to compile this. These two
libs also quite often make problems when configuring php. Follow the messages of configure to fix
possible problems. If you use pdflib 2.01 check how the lib was installed. There should be file or link
libpdf.so. Version 2.01 just creates a lib with the name libpdf2.01.so which cannot be found when linking
the test programm in configure. You will have to create a symbolic link from libpdf.so to libpdf2.01.so.).
Version 2.20 of pdflib has introduced more changes to its API and support for chinese and japanese
fonts. This unfortunately causes some changes of the pdf module of php4 (not php3). If you use pdflib
2.20 handle the in memory generation of PDF documents with care. Until pdflib 3.0 is released it might
be unstable. The encoding parameter of pdf_set_font() has changed to a string. This means that instead
of e.g. 4 you have to use ’winansi’.
If you use pdflib 2.30 the pdf_set_text_matrix() will have gone. It is not supported any more. In general it
is a good advise to consult the release notes of the used version of pdflib for possible changes.
Since version 3.0 of pdflib you should configure pdflib with the option --enable-shared-pdflib.
Any version of PHP4 after March, 9th 2000 do not support versions of pdflib older than 3.0. PHP3 on the
other hand should not be used with version newer than 2.01.
Please consult the excellent documentation for pdflib shipped with the source distribution of pdflib. It
provides a very good overview of what pdflib capable of doing. Most of the functions in pdflib and the
PHP module have the same name. The parameters are also identical. You should also understand some of
the concepts of PDF or Postscript to efficiently use this module. All lengths and coordinates are
measured in Postscript points. There are generally 72 PostScript points to an inch, but this depends on
the output resolution.
There is another PHP module for pdf document creation based on FastIO’s (http://www.fastio.com/).
ClibPDF. It has a slightly different API. Check the ClibPDF functions section for details.
Currently all versions of pdflib are supported. It is recommended that you use the newest version since it
has more features and fixes some problems which required a patch for the old version. Unfortunately, the
changes of the pdflib API in 2.x compared to 0.6 have been so severe that even some PHP functions had
to be altered. Here is a list of changes:
• The Info structure does not exist anymore. Therefore the function pdf_get_info() is obsolete and the
functions pdf_set_info_creator(), pdf_set_info_title(), pdf_set_info_author(), pdf_set_info_subject()
and pdf_set_info_keywords() do not take the info structure as the first parameter but the pdf document.
This also means that the pdf document must be opened before these functions can be called. The
above functions can and should also be replaced by pdf_set_info()
• The way a new document is opened has changed. The function pdf_open() takes only one parameter
which is the file handle of a file opened with fopen().
There were some more changes with the release 2.01 of pdflib which should be covered by PHP. Some
functions are not required anymore (e.g. pdf_put_image()). You will get a warning so don’t be shocked.
The pdf module introduces two new types of variables (if pdflib 2.x is used it is only one new type). They
are called pdfdoc and pdfinfo (pdfinfo is not existent if pdflib 2.x is used. pdfdoc is a pointer
1125
PDF
to a pdf document and almost all functions need it as its first parameter. pdfinfo contains meta data
about the PDF document. It has to be set before pdf_open() is called.
Nota: The following is only TRUE for pdflib 0.6. Read the pdflib manual for newer version
In order to output text into a PDF document you will need to provide the afm file for each font. Afm files
contain font metrics for a Postscript font. By default these afm files are searched for in a directory named
’fonts’ relative to the directory where the PHP script is located. (Again, this was TRUE for pdflib 0.6,
newer versions do not not neccessarily need the afm files.)
Most of the functions are fairly easy to use. The most difficult part is probably to create a very simple pdf
document at all. The following example should help to get started. It uses the PHP functions for pdflib
0.6. It creates the file test.pdf with one page. The page contains the text "Times-Roman" in an outlined
30pt font. The text is also underlined.
<?php
$fp = fopen("test.pdf", "w");
$info = PDF_get_info();
pdf_set_info_author($info, "Uwe Steinmann");
PDF_set_info_title($info, "Test for PHP wrapper of PDFlib 0.6");
PDF_set_info_author($info, "Name of Author");
pdf_set_info_creator($info, "See Author");
pdf_set_info_subject($info, "Testing");
$pdf = PDF_open($fp, $info);
PDF_begin_page($pdf, 595, 842);
PDF_add_outline($pdf, "Page 1");
pdf_set_font($pdf, "Times-Roman", 30, 4);
pdf_set_text_rendering($pdf, 1);
PDF_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
PDF_end_page($pdf);
PDF_close($pdf);
fclose($fp);
echo "<A HREF=getpdf.php3>finished</A>";
?>
<?php
$fp = fopen("test.pdf", "r");
header("Content-type: application/pdf");
fpassthru($fp);
fclose($fp);
?>
1126
PDF
Doing the same with pdflib 2.x looks like the following:
<?php
$fp = fopen("test.pdf", "w");
$pdf = PDF_open($fp);
pdf_set_info_author($pdf, "Uwe Steinmann");
PDF_set_info_title($pdf, "Test for PHP wrapper of PDFlib 2.0");
PDF_set_info_author($pdf, "Name of Author");
pdf_set_info_creator($pdf, "See Author");
pdf_set_info_subject($pdf, "Testing");
PDF_begin_page($pdf, 595, 842);
PDF_add_outline($pdf, "Page 1");
pdf_set_font($pdf, "Times-Roman", 30, 4);
pdf_set_text_rendering($pdf, 1);
PDF_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
PDF_end_page($pdf);
PDF_close($pdf);
fclose($fp);
echo "<A HREF=getpdf.php3>finished</A>";
?>
The pdflib distribution contains a more complex example which creates a serious of pages with an analog
clock. This example converted into PHP using pdflib 2.x looks as the following (you can see the same
example in the documentation for the clibpdf module):
<?php
$pdffilename = "clock.pdf";
$radius = 200;
$margin = 20;
$pagecount = 40;
while($pagecount-- > 0) {
1127
PDF
/* minute strokes */
pdf_setlinewidth($pdf, 2.0);
for ($alpha = 0; $alpha < 360; $alpha += 6) {
pdf_rotate($pdf, 6.0);
pdf_moveto($pdf, $radius, 0.0);
pdf_lineto($pdf, $radius-$margin/3, 0.0);
pdf_stroke($pdf);
}
pdf_restore($pdf);
pdf_save($pdf);
/* 5 minute strokes */
pdf_setlinewidth($pdf, 3.0);
for ($alpha = 0; $alpha < 360; $alpha += 30) {
pdf_rotate($pdf, 30.0);
pdf_moveto($pdf, $radius, 0.0);
pdf_lineto($pdf, $radius-$margin, 0.0);
pdf_stroke($pdf);
}
$ltime = getdate();
1128
PDF
pdf_restore($pdf);
pdf_end_page($pdf);
}
$pdf = pdf_close($pdf);
fclose($fp);
echo "<A HREF=getpdf.php3?filename=".$pdffilename.">finished</A>";
?>
1129
PDF
void pdf_add_annotation ( int pdf document, double llx, double lly, double urx, double ury, string title, string
content) \linebreak
The pdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right
corner at (urx, ury).
int pdf_add_bookmark ( int pdf object, string text [, int parent [, int open]]) \linebreak
Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a
bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child
bookmarks will be folded out, and invisible if open = 0.
int pdf_add_launchlink ( int pdf object, float llx, float lly, float urx, float ury, string filename) \linebreak
Add a launch annotation (to a target of arbitrary file type).
int pdf_add_locallink ( int pdf object, float llx, float lly, float urx, float ury, int page, string dest) \linebreak
Add a link annotation to a target within the current PDF file.
1130
PDF
int pdf_add_note ( int pdf object, float llx, float lly, float urx, float ury, string contents, string title, string icon,
int open) \linebreak
Add a note annotation. icon is one of of "comment, "insert", "note", "paragraph", "newparagraph", "key",
or "help".
int pdf_add_outline ( int pdf document, string text [, int parent [, int open]]) \linebreak
The PDF_add_outline() function adds a bookmark with text text that points to the current page. The
bookmark is inserted as a child of parent and is by default open if open is not 0. The return value is
an identifier for the bookmark which can be used as a parent for other bookmarks. Therefore you can
build up hierarchies of bookmarks.
Unfortunately pdflib does not make a copy of the string, which forces PHP to allocate the memory.
Currently this piece of memory is not been freed by any PDF function but it will be taken care of by the
PHP memory manager.
int pdf_add_pdflink ( int pdf object, float llx, float lly, float urx, float ury, string filename, int page, string dest)
\linebreak
Add a file link annotation (to a PDF target).
1131
PDF
int pdf_add_weblink ( int pdf object, float llx, float lly, float urx, float ury, string url) \linebreak
Add a weblink annotation to a target URL on the Web.
void pdf_arc ( int pdf document, double x-coor, double y-coor, double radius, double start, double end) \line-
break
The PDF_arc() function draws an arc with center at point (x-coor, y-coor) and radius radius,
starting at angle start and ending at angle end.
See also PDF_circle(), PDF_stroke().
void pdf_arc ( resource pdf object, float x, float y, float r, float alpha, float beta) \linebreak
Draw a clockwise circular arc from alpha to beta degrees
See also: pdf_arc()
int pdf_attach_file ( int pdf object, float llx, float lly, float urx, float ury, string filename, string description, string
author, string mimetype, string icon) \linebreak
Add a file attachment annotation. icon is one of "graph, "paperclip", "pushpin", or "tag".
void pdf_begin_page ( int pdf document, double width, double height) \linebreak
The PDF_begin_page() function starts a new page with height height and width width. In order to
create a valid document you must call this function and PDF_end_page().
1132
PDF
int pdf_begin_pattern ( int pdf object, float width, float height, float xstep, float ystep, int painttype) \linebreak
Starts a new pattern definition and returns a pattern handle. width, and height define the bounding
box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the
pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the
pattern is applied.
void pdf_begin_template ( int pdf object, float width, float height) \linebreak
Start a new template definition.
void pdf_circle ( int pdf document, double x-coor, double y-coor, double radius) \linebreak
The PDF_circle() function draws a circle with center at point (x-coor, y-coor) and radius radius.
See also PDF_arc(), PDF_stroke().
1133
PDF
Nota: Due to an unclean implementation of the pdflib 0.6 the internal closing of the document also
closes the file. This should not be done because pdflib did not open the file, but expects an already
open file when PDF_open() is called. Consequently it shouldn’t close the file. In order to fix this just
take out line 190 of the file p_basic.c in the pdflib 0.6 source distribution until the next release of
pdflib will fix this.
Nota: This function works properly without any patches to pdflib if pdflib 2.0 support is activated.
1134
PDF
1135
PDF
void pdf_concat ( int pdf object, float a, float b, float c, float d, float e, float f) \linebreak
Concatenate a matrix to the CTM.
void pdf_curveto ( int pdf document, double x1, double y1, double x2, double y2, double x3, double y3) \line-
break
The PDF_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using
(x1, y1) and (x2, y2) as control points.
See also PDF_moveto(), PDF_lineto(), PDF_stroke().
1136
PDF
1137
PDF
The PDF_fill() function fills the interior of the current path with the current fill color.
See also PDF_closepath(), PDF_stroke(), PDF_setgray_fill(), PDF_setgray(),
PDF_setrgbcolor_fill(), PDF_setrgbcolor().
int pdf_findfont ( int pdf object, string fontname, string encoding, int embed) \linebreak
Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the
font file will be checked, but not yet used. encoding is one of "builtin", "macroman", "winansi",
"host", or a user-defined encoding name, or the name of a CMap.
pdf_findfont() returns a font handle or FALSE on error.
<?php
?>
pdf_get_font (PHP 4 )
Deprecated: font handling
1138
PDF
Deprecated.
See pdf_get_value().
pdf_get_fontname (PHP 4 )
Deprecated: font handling
Deprecated.
See pdf_get_parameter().
pdf_get_fontsize (PHP 4 )
Deprecated: font handling
Deprecated.
See pdf_get_value().
1139
PDF
string pdf_get_parameter ( int pdf document, string name, double modifier) \linebreak
The PDF_get_parameter() function gets several parameters of pdflib which are of the type string. The
function parameter modifier characterizes the parameter to get. If the modifier is not needed it has to
be 0.
See also PDF_get_value(), PDF_set_value(), PDF_set_parameter().
string pdf_get_pdi_parameter ( int pdf object, string key, int doc, int page, int index) \linebreak
Get the contents of some PDI document parameter with string type.
string pdf_get_pdi_value ( int pdf object, string key, int doc, int page, int index) \linebreak
Get the contents of some PDI document parameter with numerical type.
1140
PDF
double pdf_get_value ( int pdf document, string name, double modifier) \linebreak
The PDF_get_value() function gets several numerical parameters of pdflib. The function parameter
modifier characterizes the parameter to get. If the modifier is not needed it has to be 0.
See also PDF_set_value(), PDF_get_parameter(), PDF_set_parameter().
void pdf_lineto ( int pdf document, double x-coor, double y-coor) \linebreak
The PDF_lineto() function draws a line from the current point to the point with coordinates (x-coor,
y-coor).
See also PDF_moveto(), PDF_curveto(), PDF_stroke().
void pdf_moveto ( int pdf document, double x-coor, double y-coor) \linebreak
1141
PDF
The PDF_moveto() function sets the current point to the coordinates x-coor and y-coor.
int pdf_open_CCITT ( int pdf object, string filename, int width, int height, int BitReverse, int k, int Blackls1)
\linebreak
Open a raw CCITT image.
<?php
$pdf = pdf_new();
pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "A PDF document created in memory!", 50, 750);
pdf_end_page($pdf);
pdf_close($pdf);
1142
PDF
$data = pdf_get_buffer($pdf);
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=test.pdf");
header("Content-length: " . strlen($data));
echo $data;
?>
<?php
$im = PDF_open_gif($pdf, "test.gif");
pdf_place_image($pdf, $im, 100, 100, 1);
pdf_close_image($pdf, $im);
?>
int pdf_open_image_file ( int PDF-document, string imagetype, string filename [, string stringparam [, string
intparam]]) \linebreak
Open an image file. Supported types are "jpeg", "tiff", "gif", and "png". stringparam is either "",
"mask", "masked", or "page". intparamis either 0, the image id of the applied mask, or the page.
1143
PDF
int pdf_open_image ( int PDF-document, string imagetype, string source, string data, long length, int width, int
height, int components, int bpc, string params) \linebreak
Use image data from a variety of data sources. Supported types are "jpeg", "ccitt", "raw". Supported
sources are "memory", "fileref", "url". len is only used for type="raw", params is only used for
type="ccitt".
<?php
$im = ImageCreate(100, 100);
$col = ImageColorAllocate($im, 80, 45, 190);
ImageFill($im, 10, 10, $col);
$pim = PDF_open_memory_image($pdf, $im);
ImageDestroy($im);
pdf_place_image($pdf, $pim, 100, 100, 1);
pdf_close_image($pdf, $pim);
?>
1144
PDF
int pdf_open_pdi_page ( int pdf object, int dochandle, int pagenumber, string pagelabel) \linebreak
Prepare a page for later use with pdf_place_image()
int pdf_open_pdi ( int pdf object, string filename, string stringparam, int intparam) \linebreak
Open an existing PDF document for later use.
PDF_open_png (PHP 4 )
Opens a PNG image
<?php
$im = PDF_open_png ($pdf, "test.png");
pdf_place_image ($pdf, $im, 100, 100, 1);
pdf_close_image ($pdf, $im);
?>
1145
PDF
pdf_open_tiff (PHP 4 )
Deprecated: Opens a TIFF image
Nota: The return value is needed as the first parameter in all other functions writing to the pdf
document.
Nota: This function does not allow the second parameter if pdflib 2.0 support is activated.
void pdf_place_image ( int pdf document, int image, double x-coor, double y-coor, double scale) \linebreak
The PDF_place_image() function places an image on the page at postion (x-coor, x-coor). The
image can be scaled at the same time.
See also PDF_put_image().
1146
PDF
void pdf_place_pdi_page ( int pdf object, int page, float x, float y, float sx, float sy) \linebreak
Place a PDF page with the lower left corner at (x, y), and scale it.
void pdf_rect ( int pdf document, double x-coor, double y-coor, double width, double height) \linebreak
The PDF_rect() function draws a rectangle with its lower left corner at point (x-coor, y-coor). This
width is set to widgth. This height is set to height.
See also PDF_stroke().
<?php PDF_save($pdf);
// do all kinds of rotations, transformations, ...
PDF_restore($pdf) ?>
1147
PDF
void pdf_scale ( int pdf document, double x-scale, double y-scale) \linebreak
The PDF_scale() function sets the scaling factor in both directions. The following example scales x and
y direction by 72. The following line will therefore be drawn one inch in both directions.
Ejemplo 1. Scaling
void pdf_set_border_color ( int pdf document, double red, double green, double blue) \linebreak
The PDF_set_border_color() function sets the color of the suroundig box of links and annotations. The
three color components have to have a value between 0.0 and 1.0.
See also PDF_set_border_style(), PDF_set_border_dash().
1148
PDF
void pdf_set_border_dash ( int pdf document, double black, double white) \linebreak
The PDF_set_border_dash() function sets the lenght of black and white areas of a dashed line of the
suroundig box of links and annotations.
See also PDF_set_border_style(), PDF_set_border_color().
void pdf_set_border_style ( int pdf document, string style, double width) \linebreak
The PDF_set_border_style() function sets the style and width of the suroundig box of links and
annotations. The parameter style can be ’solid’ or ’dashed’.
See also PDF_set_border_color(), PDF_set_border_dash().
void pdf_set_font ( int pdf document, string font name, double size, string encoding [, int embed]) \linebreak
1149
PDF
The PDF_set_font() function sets the current font face, font size and encoding. If you use pdflib 0.6 you
will need to provide the Adobe Font Metrics (afm-files) for the font in the font path (default is ./fonts). If
you use php3 or a version of pdflib older than 2.20 the fourth parameter encoding can take the
following values: 0 = builtin, 1 = pdfdoc, 2 = macroman, 3 = macexpert, 4 = winansi. An encoding
greater than 4 and less than 0 will default to winansi. winansi is often a good choice. If you use php4 and
a version of pdflib >= 2.20 the encoding parameter has changed to a string. Use ’winansi’, ’builtin’,
’host’, ’macroman’ etc. instead. If the last parameter is set to 1 the font is embedded into the pdf
document otherwise it is not. To embed a font is usually a good idea if the font is not widely spread and
you cannot ensure that the person watching your document has access on fonts in the document. I font is
only embedded once even if you call PDF_set_font() several times.
Nota: This function has to be called after PDF_begin_page() in order to create a valid pdf document.
Nota: If you reference a font in a .upr file make sure the name in the afm file and the font name are
the same. Otherwise, the font will be embedded several times (Thanks to Paul Haddon for finding
this.)
1150
PDF
void pdf_set_info ( int pdf document, string fieldname, string value) \linebreak
The PDF_set_info() function sets an information field of a pdf document. Possible values for the
fieldname are ’Subject’, ’Title’, ’Creator’, ’Author’, ’Keywords’ and one user-defined name. It can be
called before beginning a page.
<?php
$fd = fopen("test.pdf", "w");
$pdfdoc = pdf_open($fd);
pdf_set_info($pdfdoc, "Author", "Uwe Steinmann");
pdf_set_info($pdfdoc, "Creator", "Uwe Steinmann");
pdf_set_info($pdfdoc, "Title", "Testing Info Fields");
pdf_set_info($pdfdoc, "Subject", "Test");
pdf_set_info($pdfdoc, "Keywords", "Test, Fields");
pdf_set_info($pdfdoc, "CustomField", "What ever makes sense");
1151
PDF
PDF_set_parameter (PHP 4 )
Sets certain parameters
void pdf_set_parameter ( int pdf document, string name, string value) \linebreak
The PDF_set_parameter() function sets several parameters of pdflib which are of the type string.
See also PDF_get_value(), PDF_set_value(), PDF_get_parameter().
1152
PDF
void pdf_set_text_pos ( int pdf document, double x-coor, double y-coor) \linebreak
The PDF_set_text_pos() function sets the position of text for the next pdf_show() function call.
See also PDF_show(), PDF_show_xy().
void pdf_set_value ( int pdf document, string name, double value) \linebreak
The PDF_set_value() function sets several numerical parameters of pdflib.
See also PDF_get_value(), PDF_get_parameter(), PDF_set_parameter().
1153
PDF
void pdf_setcolor ( int pdf object, string type, string colorspace, float c1 [, float c2 [, float c3 [, float c4]]])
\linebreak
Set the current color space and color. The parameter type can be "fill", "stroke", or "both" to specify
that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be
gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color
components for the color space specified by colorspace. Except as otherwise noted, the color
components are floating-point values that range from 0 to 1.
For gray only c1 is used.
For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.
For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.
For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value
between 0 and 1.
For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().
1154
PDF
void pdf_setdash ( int pdf document, double white, double black) \linebreak
The PDF_setdash() function sets the dash pattern white white points and black black points. If both
are 0 a solid line is set.
void pdf_setfont ( int pdf object, int font, float size) \linebreak
Set the current font in the given size, using a font handle returned by pdf_findfont()
See Also: pdf_findfont().
1155
PDF
void pdf_setmatrix ( int pdf object, float a, float b, float c, float d, float e, float f) \linebreak
Explicitly set the current transformation matrix.
1156
PDF
void pdf_setrgbcolor_fill ( int pdf document, double red value, double green value, double blue value) \linebreak
The PDF_setrgbcolor_fill() function sets the current rgb color value to fill a path.
See also PDF_setrgbcolor_fill().
void pdf_setrgbcolor_stroke ( int pdf document, double red value, double green value, double blue value)
\linebreak
The PDF_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.
See also PDF_setrgbcolor_stroke().
void pdf_setrgbcolor ( int pdf document, double red value, double green value, double blue value) \linebreak
1157
PDF
The PDF_setrgbcolor_stroke() function sets the current drawing and filling color to the given rgb color
value.
See also PDF_setrgbcolor_stroke(), PDF_setrgbcolor_fill().
PDF_show_boxed (PHP 4 )
Output text in a box
int pdf_show_boxed ( int pdf document, string text, double x-coor, double y-coor, double width, double height,
string mode) \linebreak
The PDF_show_boxed() function outputs the string text in a box with its lower left position at
(x-coor, y-coor). The boxes dimension is height by width. The parameter mode determines
how the text is type set. If width and height are zero, the mode can be "left", "right" or "center". If
width or height is unequal zero it can also be "justify" and "fulljustify".
Returns the number of characters that could not be processed because they did not fit into the box.
See also PDF_show(), PDF_show_xy().
void pdf_show_xy ( int pdf document, string text, double x-coor, double y-coor) \linebreak
The PDF_show_xy() function outputs the string text at position (x-coor, y-coor).
See also PDF_show().
PDF_skew (PHP 4 )
Skews the coordinate system
1158
PDF
void pdf_skew ( int pdf document, double alpha, double beta) \linebreak
The PDF_skew() function skew the coordinate system by alpha (x) and beta (y) degrees. alpha and
beta may not be 90 or 270 degrees.
void pdf_translate ( int pdf document, double x-coor, double y-coor) \linebreak
The PDF_translate() function sets the origin of coordinate system to the point (x-coor, y-coor)
relativ the current origin. The following example draws a line from (0, 0) to (200, 200) relative to the
initial coordinate system. You have to set the current point after PDF_translate() and before you start
drawing more objects.
Ejemplo 1. Translation
1159
PDF
PDF_stroke($pdf);
?>
1160
LXXVII. Verisign Payflow Pro functions
This extension allows you to process credit cards and other financial transactions using Verisign Payment
Services, formerly known as Signio (http://www.verisign.com/products/payflow/pro/index.html).
These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.
You will require the appropriate SDK for your platform, which may be downloaded from within the
manager interface (https://manager.verisign.com/) once you have registered.
Once you have downloaded the SDK you should copy the files from the lib directory of the distribution.
Copy the header file pfpro.h to /usr/local/include and the library file libpfpro.so to
/usr/local/lib.
When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension
will do so automatically if required. However the functions are still available in case you are processing a
number of transactions and require fine control over the library. You may perform any number of
transactions using pfpro_process() between the two.
These functions have been added in PHP 4.0.2.
Nota: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow
Pro Developers Guide for full details of the required parameters.
1161
Verisign Payflow Pro
string pfpro_process_raw ( string parameters [, string address [, int port [, int timeout [, string proxy address [,
int proxy port [, string proxy logon [, string proxy password]]]]]]]) \linebreak
Returns: A string containing the response.
pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use
pfpro_process() instead, as the encoding rules of these transactions are non-standard.
The first parameter in this case is a string containing the raw transaction request. All other parameters are
the same as with pfpro_process(). The return value is a string containing the raw response.
Nota: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters
and encoding rules. You would be well advised to use pfpro_process() instead.
<?php
pfpro_init();
1162
Verisign Payflow Pro
$response = pfpro_process("USER=mylogin&PWD[5]=m&ndy&TRXTYPE=S&TENDER=C&AMT=1.50&ACCT=411111
if (!$response) {
die("Couldn’t establish link to Verisign.\n");
}
pfpro_cleanup();
?>
array pfpro_process ( array parameters [, string address [, int port [, int timeout [, string proxy address [, int
proxy port [, string proxy logon [, string proxy password]]]]]]]) \linebreak
Returns: An associative array containing the response
pfpro_process() processes a transaction with Payflow Pro. The first parameter is an associative array
containing keys and values that will be encoded and passed to the processor.
The second parameter is optional and specifies the host to connect to. By default this is "test.signio.com",
so you will certainly want to change this to "connect.signio.com" in order to process live transactions.
The third parameter specifies the port to connect on. It defaults to 443, the standard SSL port.
The fourth parameter specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that
this timeout appears to only begin once a link to the processor has been established and so your script
could potentially continue for a very long time in the event of DNS or network problems.
The fifth parameter, if required, specifies the hostname of your SSL proxy. The sixth parameter specifies
the port to use.
The seventh and eighth parameters specify the logon identity and password to use on the proxy.
The function returns an associative array of the keys and values in the response.
Nota: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.
<?php
pfpro_init();
1163
Verisign Payflow Pro
$response = pfpro_process($transaction);
if (!$response) {
die("Couldn’t establish link to Verisign.\n");
}
pfpro_cleanup();
?>
1164
LXXVIII. opciones e información de PHP
1165
opciones/información PHP
assert_options (PHP 4 )
Set/get the various assert flags
assert_options() will return the original setting of any option or FALSE on errors.
assert (PHP 4 )
Checks if assertion is FALSE
1166
opciones/información PHP
assert() callbacks are particularly useful for building automated test suites because they allow you to
easily capture the code passed to the assertion, along with information on where the assertion was made.
While this information can be captured via other methods, using assertions makes it much faster and
easier!
The callback function should accept three arguments. The first argument will contain the file the
assertion failed in. The second argument will contain the line the assertion failed on and the third
argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be
passed via this argument)
<?php
// Active assert and make it quiet
assert_options (ASSERT_ACTIVE, 1);
assert_options (ASSERT_WARNING, 0);
assert_options (ASSERT_QUIET_EVAL, 1);
dl (PHP 3, PHP 4 )
Loads a PHP extension at runtime
1167
opciones/información PHP
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. If the functionality of loading modules is not
available (see Note) or has been disabled (either by turning it off enable_dl or by enabling safe_mode
in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library
couldn’t be loaded, in addition to FALSE an E_WARNING message is emitted.
Use extension_loaded() to test whether a given extension is already available or not. This works on both
built-in extensions and dynamically loaded ones (either through php.ini or dl()).
Example:
if (!extension_loaded(’gd’)) {
if (!dl(’gd.so’)) {
exit;
}
}
The directory where the extension is loaded from depends on your platform:
Windows - If not explicitly set in the php.ini, the extension is loaded from c:\php4\extensions\
by default.
Unix - If not explicitly set in the php.ini, the default extension directory depends on
Nota: dl() is not supported in multithreaded Web servers. Use the extensions statement in your
php.ini when operating under such an environment. However, the CGI and CLI build are not
affected !
1168
opciones/información PHP
1169
opciones/información PHP
print_r (get_defined_constants());
Array
(
[E_ERROR] => 1
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_ALL] => 2047
[TRUE] => 1
)
get_extension_funcs (PHP 4 )
Returns an array with the names of the functions of a module
will print a list of the functions in the modules xml and gd respectively.
See also: get_loaded_extensions()
1170
opciones/información PHP
get_included_files (PHP 4 )
Returns an array with the names of included or required files
Nota: Files included using the auto_prepend_file configuration directive are not included in the
returned array.
<?php
include("test1.php");
include_once("test2.php");
require("test3.php");
require_once("test4.php");
$included_files = get_included_files();
foreach($included_files as $filename) {
echo "$filename\n";
}
?>
test1.php
test2.php
test3.php
test4.php
Nota: In PHP 4.0.1pl2 and previous versions get_included_files() assumed that the required files
ended in the extension .php; other extensions would not be returned. The array returned by
1171
opciones/información PHP
get_included_files() was an associative array and only listed files included by include() and
include_once().
get_loaded_extensions (PHP 4 )
Returns an array with the names of all modules compiled and loaded
print_r (get_loaded_extensions());
Array
(
[0] => xml
[1] => wddx
[2] => standard
[3] => session
[4] => posix
[5] => pgsql
[6] => pcre
[7] => gd
[8] => ftp
[9] => db
[10] => calendar
[11] => bcmath
)
1172
opciones/información PHP
get_required_files (PHP 4 )
Returns an array with the names of included or required files
1173
opciones/información PHP
Puede ver una lista de todas las variables de entorno utilizando phpinfo(). Puede encontrar el significado
de la mayoría echando un vistazo en CGI specification (especificación CGI)
(http://hoohoo.ncsa.uiuc.edu/cgi/), especialmente en page on environmental variables (página de
variables de entorno) (http://hoohoo.ncsa.uiuc.edu/cgi/env.html).
1174
opciones/información PHP
$dat = getrusage();
echo $dat["ru_nswap"]; # number of swaps
echo $dat["ru_majflt"]; # number of page faults
echo $dat["ru_utime.tv_sec"]; # user time used (seconds)
echo $dat["ru_utime.tv_usec"]; # user time used (microseconds)
ini_alter (PHP 4 )
Changes the value of a configuration option
1175
opciones/información PHP
ini_get (PHP 4 )
Gets the value of a configuration option
ini_restore (PHP 4 )
Restores the value of a configuration option
1176
opciones/información PHP
ini_set (PHP 4 )
Sets the value of a configuration option
1177
opciones/información PHP
1178
opciones/información PHP
1179
opciones/información PHP
1180
opciones/información PHP
safe_mode_allowed_env_vars SAFE_MODE_ALLOWED_ENV_VARS
PHP_INI_SYSTEM
1181
opciones/información PHP
1182
opciones/información PHP
1183
opciones/información PHP
php_logo_guid (PHP 4 )
Obtiene el guid logo
$sapi_type = php_sapi_name();
if ($sapi_type == "cgi")
print "You are using CGI PHP\n";
else
print "You are not using CGI PHP\n";
1184
opciones/información PHP
php_uname() returns a string with a description of the operating system PHP is built on.
if (substr(php_uname(), 0, 7) == "Windows") {
die ("Sorry, this script doesn’t run on Windows.\n");
}
phpcredits (PHP 4 )
Prints out the credits for PHP
...
phpcredits(CREDITS_GENERAL);
...
And if you want to print the core developers and the documentation group, in a page of its own, you will
use:
<?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?>
And if you feel like embedding all the credits in your page, then code like the one below will do it:
<html>
<head>
<title>My credits page</title>
</head>
1185
opciones/información PHP
<body>
<?php
// some code of your own
phpcredits(CREDITS_ALL);
// some more code
?>
</body>
</html>
name description
CREDITS_ALL All the credits, equivalent to using:
CREDITS_DOCS + CREDITS_GENERAL +
CREDITS_GROUP + CREDITS_MODULES +
CREDITS_FULLPAGE. It generates a complete
stand-alone HTML page with the appropriate tags.
CREDITS_DOCS The credits for the documentation team
CREDITS_FULLPAGE Usually used in combination with the other flags.
Indicates that the a complete stand-alone HTML
page needs to be printed including the information
indicated by the other flags.
CREDITS_GENERAL General credits: Language design and concept, PHP
4.0 authors and SAPI module.
CREDITS_GROUP A list of the core developers
CREDITS_MODULES A list of the extension modules for PHP, and their
authors
CREDITS_SAPI A list of the server API modules for PHP, and their
authors
1186
opciones/información PHP
está compilado como un módulo), el entorno PHP, información sobre la versión del SO, rutas, opciones
de configuración maestras y locales, cabeceras HTTP, y la Licencia Pública GNU.
Véase también phpversion().
putenv("UNIQID=$uniqid");
1187
opciones/información PHP
// prints -1
echo version_compare("4.0.4", "4.0.6");
1188
opciones/información PHP
zend_logo_guid (PHP 4 )
Obtiene el guid zend
zend_version (PHP 4 )
Gets the version of the current Zend engine
1189
LXXIX. Funciones POSIX
Este módulo contiene una interfaz a aquellas funciones definidas en el documento estandar IEEE 1003.1
(POSIX.1) que no son accesibles de otra manera. POSIX.1 por ejemplo definió las funciones
open(),read(), write() y close(), las cuales han sido parte de PHP durante mucho tiempo.Algunas
funciones específicas del sistema no habian estado disponibles antes, aunque con este módulo se intenta
remediar esto ofreciendo un acceso fácil a esas funciones.
1190
POSIX
1191
POSIX
1192
POSIX
Esta no es una función POSIX, pero es normal en sistemas BSD y System V. Si su sistema no soporta
esta función a nivel de sistema, esta función PHP devolverá siempre FALSE.
1193
POSIX
Elemento Descripción
Elemento Descripción
name El elemento name contiene el nombre de usuario
del usuario. Este es un nombre, normalmente menor
de 16 caracteres, que no es su nombre completo,
pero identifica al usario. Este debe ser el mismo que
el parámetro username usado en la llamada a la
función y por lo tanto es redundante.
passwd El elemento passwd contiene la contraseña del
usuario en un formato encriptado. Normalmente,
por ejemplo en un sistema que este utilizando
contraseñas "shadow", devolverá un asterisco.
uid El ID de usuario del usuario en formato numérico.
gid El ID de grupo del usuario. Utiliza la función
posix_getgrgid() para resolver el nombre del grupo
y una lista de sus miembros.
gecos GECOS es un término obsoleto que se refiere al
campo apuntado de información en un sistema de
procesamiento batch Honeywell. El campo y sus
contenidos han sido formalizado por POSIX y
contiene una lista separada por comas con el
nombre completo del usuario, teléfono del trabajo,
número de oficina y télefono de casa. En muchos
sistemas solo está disponible el nombre completo
del usuario.
dir Este elemento contiene la ruta absoluta al directorio
del usuario (directorio home).
shell El elemento shell contiene la ruta absoluta al
ejecutable del shell por defecto del usuario.
1194
POSIX
Elemento Descripción
name El elemento name contiene el nombre de usuario
del usuario. Este es un nombre, normalmente menor
de 16 caracteres, que no es su verdadero nombre.
passwd El elemento passwd contiene la contraseña del
usuario en un formato encriptado. Normalmente,
por ejemplo en un sistema con contraseñas
"shadow", devolverá un asterisco.
uid ID del usuario, debe ser el mismo que el parametro
uid usado en la llamada a la función, y por lo tanto
redundante.
gid El ID del grupo del usuario. Utiliza la función
posix_getgrgid() para resolver el nombre del grupo
y una lista de sus miembros.
gecos GECOS es un término obsoleto que se refiere al
campo apuntado de de información en un sistema de
procesamiento batch Honeywell. El campo y sus
contenidos han sido formalizados por POSIX y
contiene una lista separada por comas con el
nombre completo del usuario, teléfono del trabajo,
número de oficina y teléfono de casa. En muchos
sistemas solo está disponible el nombre completo
del usuario.
dir Este elemento contiene la ruta absoluta al directorio
del usuario (directorio home).
shell El elemento shell contiene la ruta absoluta al
ejecutable del shell por defecto del usuario.
1195
POSIX
1196
POSIX
1197
POSIX
1198
POSIX
Posix requiere que usted no debe hacer ninguna suposición sobre el formato de los valores, por ejemplo
usted no puede confiar en los tres dígitos de la version o cualquier cosa devuelta por esta función.
1199
LXXX. Funciones de PostgreSQL
Postgres, desarrollado originalmente en el UC Berkeley Computer Science Department, ha sido pionero
en muchos de los conceptos relacionales/orientados a objeto que ahora están empezando a estar
disponibles en algunas bases de datos comperciales. Tiene soporte de lenguaje SQL92/SQL3, integridad
transaccional, y extensibilidad de tipos. PostgreSQL es un descendiente de dominio público, más
concretamente open source, del código original de Berkeley.
PostgreSQL se encuentra disponible sin coste alguno. La versión actual la tienes a tu disposición en
www.PostgreSQL.org (http://www.postgresql.org/).
Desde la versión 6.3 (02/03/1998) PostgreSQL usa sockets tipo Unix. Abajo se da una tabla con las
diferentes posibilidades. El socket se encuentra en el ficheero /tmp/.s.PGSQL.5432. Esta opción se
controla mediante el flag ’-i’ del postmaster y cuando se incluye significa "escuchar sockets TCP/IP
además de los de dominio Unix" ya que si no se le dice nada solo escucha sockets tipo Unix.
1200
PostgreSQL
commit y end. Si la transacción falla debe ser cerrada con abort y rollback.
<?php
$database = pg_Connect ("", "", "", "", "jacarta");
pg_exec ($database, "begin");
$oid = pg_locreate ($database);
echo ("$oid\n");
$handle = pg_loopen ($database, $oid, "w");
echo ("$handle\n");
pg_lowrite ($handle, "gaga");
pg_loclose ($handle);
pg_exec ($database, "commit")
pg_exec ($database, "end")
?>
1201
PostgreSQL
Ejemplo 1. pg_affected_rows()
<?php
$result = pg_query ($conn, "INSERT INTO publisher VALUES (’Author’)");
$cmdtuples = pg_affected_rows ($result);
echo $cmdtuples . " tuples are affected.";
?>
1202
PostgreSQL
pg_client_encoding() returns the client encoding as the string. The returned string should be either :
SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX
(X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250.
Nota: This function requires PHP-4.0.3 or higher and PostgreSQL-7.0 or higher. If libpq is compiled
without multibyte encoding support, pg_set_client_encoding() always return "SQL_ASCII".
Supported encoding depends on PostgreSQL version. Refer to PostgreSQL manual for details to
enable multibyte support and encoding supported.
The function used to be called pg_clientencoding().
int pg_connect ( string host, string port, string options, string tty, string dbname) \linebreak
Devuelve un índice de conexión en caso de éxito, o falso si la conexión no se puede realizar. Esta función
abre una conexión a una base de datos PostgreSQL. Cada uno de los argumentos debe ser una cadena
entrecomillada, incluyendo el número de puerto. Los parámetros options y tty son opcionales y pueden
ser omitidos. Esta función devuelve un índice de conexión que se necesitará para otras funciones
PostgreSQL. Puedes tener multiples conexiones abiertas al mismo tiempo.
Una conexión también se puede establecer con el siguiente comando: $conn =
pg_connect("dbname=marliese port=5432"); Otros parámetros aparte de dbname y port son host,
tty, options, user y password.
Ver también pg_pConnect().
1203
PostgreSQL
array pg_convert ( resource connection, string table_name, array assoc_array [, int options]) \linebreak
pg_convert() check and convert assoc_array suitable for SQL statement.
1204
PostgreSQL
int pg_copy_from ( int connection, string table_name, array rows [, string delimiter [, string null_as]]) \linebreak
pg_copy_from() insert records into a table from rows. It issues COPY command internally to insert
records. Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
See also pg_copy_to()
int pg_copy_to ( int connection, string table_name [, string delimiter [, string null_as]]) \linebreak
pg_copy_to() copies a table to an array. The resulting array is returned. It returns FALSE on failure.
See also pg_copy_from()
long pg_delete ( resource connection, string table_name, array assoc_array [, int options]) \linebreak
pg_delete() deletes record condition specified by assoc_array which has field=>value. If option
is specified, pg_convert() is applied to assoc_array with specified option.
Ejemplo 1. pg_delete
<?php
$db = pg_connect (’dbname=foo’);
// This is safe, since $_POST is converted automatically
1205
PostgreSQL
Nota: When you SELECT bytea type, PostgreSQL returns octal byte value prefixed by \ (e.g. \032).
Users are supposed to convert back to binary format by yourself.
This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea type must be
casted when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES
(’$image_escaped’::bytea); PostgreSQL 7.2.2 or later does not need cast. Exception is when
client and backend character encoding does not match, there may be multi-byte stream error. User
must cast to bytea to avoid this error.
Newer PostgreSQL will support unescape function. Support for built-in unescape function will be
added when it’s available.
1206
PostgreSQL
Una cosa importante a tener en cuenta es que usar pg_fetch_array() NO es significativamente más lento
que usar pg_fetch_row(), y sin embargo el valor añadido que aporta sí lo es.
Para más detalles, ver pg_fetch_row()
1207
PostgreSQL
<?php
$conn = pg_pconnect("","","","","publisher");
if (!$conn) {
echo "An error occured.\n";
exit;
}
1208
PostgreSQL
<?php
$database = "verlag";
$db_conn = pg_connect ("localhost", "5432", "", "", $database);
if (!$db_conn): ?>
<H1>Failed connecting to postgres database <? echo $database ?></H1> <?
exit;
endif;
<PRE><?php
$fields[] = Array ("autor", "Author");
$fields[] = Array ("jahr", " Year");
$fields[] = Array ("titel", " Title");
1209
PostgreSQL
of results to return. Row numbering starts from 0. Instead of naming the field, you may use the field
index as an unquoted number. Field indices start from 0.
PostgreSQL has many built in types and only the basic ones are directly supported here. All forms of
integer, boolean and void types are returned as integer values. All forms of float, and real types are
returned as float values. All other types, including arrays are returned as strings formatted in the same
default PostgreSQL manner that you would see in the psql program.
<?php
$conn = pg_pconnect("","","","","publisher");
if (!$conn) {
echo "An error occured.\n";
exit;
}
1210
PostgreSQL
1211
PostgreSQL
1212
PostgreSQL
1213
PostgreSQL
bool pg_insert ( resource connection, string table_name, array assoc_array [, int options]) \linebreak
pg_insert() inserts assoc_array which has field=>value into table specified as table_name. If
options is specified, pg_convert() is applied to assoc_array with specified option.
Ejemplo 1. pg_insert
<?php
$db = pg_connect (’dbname=foo’);
// This is safe, since $_POST is converted autotmatically
$res = pg_insert($db, ’post_log’, $_POST);
if ($res) {
echo "POST data is succesfully logged\n";
}
else {
echo "User must have sent wrong inputs\n";
}
?>
1214
PostgreSQL
Aviso
This function is EXPERIMENTAL and it is not fully implemented yet.
pg_last_notice() was added in PHP 4.0.6. However, PHP 4.0.6 has problem with
notice message handling. Use of the PostgreSQL module with PHP 4.0.6 is not
recommended even if you are not using pg_last_notice().
This function is fully implemented in PHP 4.3.0. PHP earlier than PHP 4.3.0
ignores database connection parameter.
Notice message tracking can be set to optional by setting 1 for pgsql.ignore_notice ini from PHP
4.3.0.
Notice message logging can be set to optional by setting 0 for pgsql.log_notice ini from PHP 4.3.0.
Unless pgsql.ignore_notice is set to 0, notice message cannot be logged.
See also pg_query() and pg_last_error().
1215
PostgreSQL
1216
PostgreSQL
Aviso
Do not close the database connection before closing the large object resource.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
1217
PostgreSQL
1218
PostgreSQL
1219
PostgreSQL
Nota: Use pg_affected_rows() to get number of rows affected by INSERT, UPDATE and DELETE
query.
1220
PostgreSQL
int pg_pconnect ( string host, string port, string options, string tty, string dbname) \linebreak
Devuelve un índice de conexión en caso de éxito, o FALSE si no es posible realizar la conexión. Abre una
conexión persistente hacia una base de datos de PostgreSQL. Cada uno de los parámetros puede ser una
cadena entrecomillada (quoted), incluyendo el número de puerto. Los parámetros options y tty son
opcionales y pueden omitirse. Esta función devuelve un índice de conexión que luego será empleado al
llamar a otras funciones PostgreSQL. Puedes tener multiples conexiones persistentes abiertas al mismo
tiempo. Ver también pg_Connect().
Una conexión también se puede establecer con el comando siguiente: $conn =
pg_pconnect("dbname=marliese port=5432"); Otros parámetros además de dbname y port son
host, tty, options, user y password.
1221
PostgreSQL
copy-operation. That final NULL-character is added automatically. Devuelve TRUE si todo fue bien,
FALSE en caso de fallo.
Nota: The application must explicitly send the two characters "\." on the last line to indicate to the
backend that it has finished sending its data.
<?php
$conn = pg_pconnect ("dbname=foo");
pg_query($conn, "create table bar (a int4, b char(16), d float8)");
pg_query($conn, "copy bar from stdin");
pg_put_line($conn, "3\thello world\t4.5\n");
pg_put_line($conn, "4\tgoodbye world\t7.11\n");
pg_put_line($conn, "\\.\n");
pg_end_copy($conn);
?>
Nota: connection is a optional parameter for pg_query(). If connection is not set, default
connection is used. Default connection is the last connection made by pg_connect() or
pg_pconnect().
Although connection can be omitted, it is not recommended, since it could be a cause of hard to
find bug in script.
1222
PostgreSQL
Nota: This function used to be called pg_exec(). pg_exec() is still available for compatibility
reasons but users are encouraged to use the newer name.
array pg_select ( resource connection, string table_name, array assoc_array [, int options]) \linebreak
pg_select() selects records specified by assoc_array which has field=>value. For successful query,
it returns array contains all records and fields that match the condition specified by assoc_array. If
options is specified, pg_convert() s applied to assoc_array with specified option.
Ejemplo 1. pg_select
<?php
$db = pg_connect (’dbname=foo’);
1223
PostgreSQL
bool pg_send_query ( resource connection, string query) \linebreak bool pg_send_query ( string query) \line-
break
pg_send_query() send asynchronous query to the connection. Unlike pg_query(), it can send
multiple query to PostgreSQL and get the result one by one using pg_get_result(). Script execution is not
block while query is executing. Use pg_connection_busy() to check connection is busy (i.e. query is
executing) Query may be canceled by calling pg_cancel_query().
Although, user can send multiple query at once. User cannot send multiple query over busy connection.
If query is sent while connection is busy, it waits until last query is finished and discards all result.
See also pg_query(), pg_cancel_query(), pg_get_result() and pg_connection_busy()
1224
PostgreSQL
Nota: This function requires PHP-4.0.3 or higher and PostgreSQL-7.0 or higher. Supported encoding
depends on PostgreSQL version. Refer to PostgreSQL manual for details.
The function used to be called pg_setclientencoding().
1225
PostgreSQL
long pg_update ( resource connection, string table_name, array condition, array data [, int options]) \linebreak
pg_update() updates records that matches condition with data If options is specified, pg_convert()
is applied to assoc_array with specified options.
Ejemplo 1. pg_update
<?php
$db = pg_connect (’dbname=foo’);
$data = array(’field1’=>’AA’, ’field2’=>’BB’);
// This is safe, since $_POST is converted automatically
$res = pg_update($db, ’post_log’, $_POST, $data);
if ($res) {
echo "Data is updated: $res\n";
}
else {
echo "User must have sent wrong inputs\n";
}
?>
1226
LXXXI. Process Control Functions
Process Control support in PHP implements the Unix style of process creation, program execution,
signal handling and process termination. Process Control should not be enabled within a webserver
environment and unexpected results may happen if any Process Control functions are used within a
webserver environment.
This documentation is intended to explain the general usage of each of the Process Control functions. For
detailed information about Unix process control you are encouraged to consult your systems
documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as
Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).
Process Control support in PHP is not enabled by default. You will need to use the --enable-pcntl
configuration option when compiling PHP to enable Process Control support.
Nota: Currently, this module will not function on non-Unix platforms (Windows).
The following list of signals are supported by the Process Control functions. Please see your systems
signal(7) man page for details of the default behavior of these signals.
1227
PCNTL
<?php
$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
exit(); // we are the parent
} else {
// we are the child
}
function sig_handler($signo) {
switch($signo) {
case SIGTERM:
// handle shutdown tasks
exit;
break;
case SIGHUP:
// handle restart tasks
break;
default:
// handle all other signals
}
?>
1228
PCNTL
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
<?php
$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
// we are the parent
} else {
// we are the child
}
?>
1229
PCNTL
<?php
switch($signo) {
case SIGTERM:
// handle shutdown tasks
exit;
break;
case SIGHUP:
// handle restart tasks
break;
case SIGUSR1:
print "Caught SIGUSR1...\n";
break;
default:
// handle all other signals
}
print "Done\n"
?>
1230
PCNTL
pcntl_waitpid() will store status information in the status parameter which can be evaluated using the
following functions: pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(),
pcntl_wtermsig() and pcntl_wstopsig().
The value of options is the value of zero or more of the following two global constants OR’ed
together:
1231
PCNTL
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifexited().
1232
PCNTL
1233
LXXXII. Funciones de ejecución de programas
1234
Ejecución de programas
system("ls ".escapeshellarg($dir));
system(EscapeShellCmd($cmd))
1235
Ejecución de programas
exec() ejecuta la orden indicada en command, sin embargo no produce ninguna salida. Simplemente
devuelve la última línea de la salida resultado de la orden. Si necesita ejecutar una orden y obtener
directamente todos los datos devueltos por la orden sin ninguna interferencia, use la función PassThru().
Si el parámetro array existe, entonces el array especificado se rellenará con cada una de las líneas de la
salida producida por la orden. Notar que si el array ya contiene algunos elementos, exec() los añadirá al
final del array. Si no quiere que la función añada dichos elementos, haga un unset() sobre el array antes
de pasárselo a exec().
Si el parámetro return_var existe a la vez que el parámetro array, entonces el valor de retorno de
la orden ejecutada se guardará en dicha variable.
Destacar que si usted va a permitir que se pasen datos provenientes de usuarios a esta función, entonces
debería usar EscapeShellCmd() para asegurarse de que los usuarios no pueden engañar al sistema para
ejecutar instrucciones arbitrarias.
Véase también system(), PassThru(), popen(), EscapeShellCmd(), y el operador ‘ (apóstrofe invertido).
1236
Ejecución de programas
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/error-output.txt", "a"), // stderr is a file to write to
);
$process = proc_open("php", $descriptorspec, $pipes);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt
while(!feof($pipes[1])) {
echo fgets($pipes[1], 1024);
}
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
The file descriptor numbers in descriptorspec are not limited to 0, 1 and 2 - you may specify any
valid file descriptor number and it will be passed to the child process. This allows your script to
interoperate with other scripts that run as "co-processes". In particular, this is useful for passing
passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for
reading status information provided by those programs on auxillary file descriptors.
1237
Ejecución de programas
Nota: Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process
as inheritable handles, but since the Windows architecture does not associate file descriptor
numbers with low-level handles, the child process does not (yet) have a means of accessing those
handles. Stdin, stdout and stderr work as expected.
Nota: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much
easier to use.
See also exec(), system(), passthru(), popen(), escapeshellcmd(), and the backtick operator.
shell_exec (PHP 4 )
Execute command via shell and return complete output as string
1238
LXXXIII. Printer functions
These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in
PHP 4 (4.0.4).
1239
Printer
printer_abort (unknown)
Deletes the printer’s spool file
$handle = printer_open();
printer_abort($handle);
printer_close($handle);
printer_close (unknown)
Close an open printer connection
$handle = printer_open();
printer_close($handle);
printer_create_brush (unknown)
Create a new brush
1240
Printer
printer_create_dc (unknown)
Create a new device context
$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);
printer_create_dc($handle);
/* do some stuff with the dc */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);
/* create another dc */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* do some stuff with the dc */
printer_delete_dc($handle);
printer_endpage($handle);
printer_end_doc($handle);
printer_close($handle);
1241
Printer
printer_create_font (unknown)
Create a new font
mixed printer_create_font ( string face, int height, int width, int font_weight, bool italic, bool underline, bool
strikeout, int orientaton) \linebreak
The function creates a new font and returns a handle to it. A font is used to draw text. For an example see
printer_select_font(). face must be a string specifying the font face. height specifies the font height,
and width the font width. The font_weight specifies the font weight (400 is normal), and can be
one of the following predefined constants.
• PRINTER_FW_THIN : sets the font weight to thin (100).
• PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).
• PRINTER_FW_LIGHT: sets the font weight to light (300).
• PRINTER_FW_NORMAL: sets the font weight to normal (400).
• PRINTER_FW_MEDIUM : sets the font weight to medium (500).
• PRINTER_FW_BOLD: sets the font weight to bold (700).
• PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).
• PRINTER_FW_HEAVY: sets the font weight to heavy (900).
italic can be TRUE or FALSE, and sets whether the font should be italic.
underline can be TRUE or FALSE, and sets whether the font should be underlined.
strikeout can be TRUE or FALSE, and sets whether the font should be striked out.
orientation specifies a rotation. For an example see printer_select_font().
printer_create_pen (unknown)
Create a new pen
1242
Printer
printer_delete_brush (unknown)
Delete a brush
printer_delete_dc (unknown)
Delete a device context
printer_delete_font (unknown)
Delete a font
printer_delete_pen (unknown)
Delete a pen
1243
Printer
printer_draw_bmp (unknown)
Draw a bmp
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_draw_chord (unknown)
Draw a chord
void printer_draw_chord ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad_x, int rad_y, int
rad_x1, int rad_y1) \linebreak
The function simply draws an chord. handle must be a valid handle to a printer.
rec_x is the upper left x coordinate of the bounding rectangle.
rec_y is the upper left y coordinate of the bounding rectangle.
rec_x1 is the lower right x coordinate of the bounding rectangle.
rec_y1 is the lower right y coordinate of the bounding rectangle.
rad_x is x coordinate of the radial defining the beginning of the chord.
rad_y is y coordinate of the radial defining the beginning of the chord.
rad_x1 is x coordinate of the radial defining the end of the chord.
rad_y1 is y coordinate of the radial defining the end of the chord.
1244
Printer
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_delete_brush($brush);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_draw_elipse (unknown)
Draw an ellipse
void printer_draw_elipse ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y) \linebreak
The function simply draws an ellipse. handle must be a valid handle to a printer.
ul_x is the upper left x coordinate of the ellipse.
ul_y is the upper left y coordinate of the ellipse.
lr_x is the lower right x coordinate of the ellipse.
lr_y is the lower right y coordinate of the ellipse.
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
1245
Printer
printer_delete_brush($brush);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_draw_line (unknown)
Draw a line
void printer_draw_line ( resource printer_handle, int from_x, int from_y, int to_x, int to_y) \linebreak
The function simply draws a line from position from_x, from_y to position to_x, to_y using the
selected pen. printer_handle must be a valid handle to a printer.
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_draw_pie (unknown)
Draw a pie
1246
Printer
void printer_draw_pie ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad1_x, int rad1_y, int
rad2_x, int rad2_y) \linebreak
The function simply draws an pie. handle must be a valid handle to a printer.
rec_x is the upper left x coordinate of the bounding rectangle.
rec_y is the upper left y coordinate of the bounding rectangle.
rec_x1 is the lower right x coordinate of the bounding rectangle.
rec_y1 is the lower right y coordinate of the bounding rectangle.
rad1_x is x coordinate of the first radial’s ending.
rad1_y is y coordinate of the first radial’s ending.
rad2_x is x coordinate of the second radial’s ending.
rad2_y is y coordinate of the second radial’s ending.
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_delete_brush($brush);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_draw_rectangle (unknown)
Draw a rectangle
void printer_draw_rectangle ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y) \linebreak
The function simply draws a rectangle.
handle must be a valid handle to a printer.
1247
Printer
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_delete_brush($brush);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_draw_roundrect (unknown)
Draw a rectangle with rounded corners
void printer_draw_roundrect ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y, int width, int height) \line-
break
The function simply draws a rectangle with rounded corners.
handle must be a valid handle to a printer.
ul_x is the upper left x coordinate of the rectangle.
ul_y is the upper left y coordinate of the rectangle.
lr_x is the lower right x coordinate of the rectangle.
lr_y is the lower right y coordinate of the rectangle.
width is the width of the ellipse.
height is the height of the ellipse.
1248
Printer
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_delete_brush($brush);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_draw_text (unknown)
Draw text
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
$font = printer_create_font("Arial",72,48,400,false,false,false,0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
1249
Printer
printer_end_doc (unknown)
Close document
printer_end_page (unknown)
Close active page
printer_get_option (unknown)
Retrieve printer configuration data
$handle = printer_open();
print printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);
1250
Printer
printer_list (unknown)
Return an array of printers attached to the server
printer_logical_fontheight (unknown)
Get logical font height
$handle = printer_open();
print printer_logical_fontheight($handle, 72);
printer_close($handle);
1251
Printer
printer_open (unknown)
Open connection to a printer
If no parameter was given it tries to open a connection to the default printer (if not specified in php.ini
as printer.default_printer, php tries to detect it).
printer_open() also starts a device context.
printer_select_brush (unknown)
Select a brush
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
1252
Printer
printer_draw_rectangle($handle, 1,1,500,500);
printer_delete_brush($brush);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_select_font (unknown)
Select a font
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
1253
Printer
printer_select_pen (unknown)
Select a pen
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_set_option (unknown)
Configure the printer connection
1254
Printer
1255
Printer
$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);
printer_start_doc (unknown)
Start a new document
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
printer_start_page (unknown)
Start a new page
1256
Printer
printer_write (unknown)
Write data to the printer
$handle = printer_open();
printer_write($handle, "Text to print");
printer_close($handle);
1257
LXXXIV. Pspell Functions
The pspell() functions allow you to check the spelling of a word and offer suggestions.
You need the aspell and pspell libraries, available from http://aspell.sourceforge.net/ and http://aspell.net/
respectively, and add the --with-pspell[=dir] option when compiling php.
1258
Pspell
Ejemplo 1. pspell_add_to_personal()
1259
Pspell
Ejemplo 1. pspell_check()
Ejemplo 1. pspell_add_to_personal()
int pspell_config_create ( string language [, string spelling [, string jargon [, string encoding]]]) \linebreak
pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create()
immediatelly followed by pspell_new_config() will produce the exact same result. However, after
1260
Pspell
creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config()
to take advantage of some advanced functionality.
The language parameter is the language code which consists of the two letter ISO 639 language code and
an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as
English. Known values are ’american’, ’british’, and ’canadian’.
The jargon parameter contains extra information to distinguish two different words lists that have the
same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are ’utf-8’,
’iso8859-*’, ’koi8-r’, ’viscii’, ’cp1252’, ’machine unsigned 16’, ’machine unsigned 32’. This parameter
is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
For more information and examples, check out inline manual pspell website:http://aspell.net/.
Ejemplo 1. pspell_config_create()
1261
Pspell
Ejemplo 1. pspell_config_ignore()
Ejemplo 1. pspell_config_mode()
1262
Pspell
Ejemplo 1. pspell_config_personal()
Ejemplo 1. pspell_config_repl()
1263
Pspell
Ejemplo 1. pspell_config_runtogether()
1264
Pspell
Ejemplo 1. pspell_new_config()
int pspell_new_personal ( string personal, string language [, string spelling [, string jargon [, string encoding [,
int mode]]]]) \linebreak
pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary
link identifier for use in other pspell functions. The wordlist can be modified and saved with
pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save
replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file
with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a
new dictionary with pspell_new_config().
The personal parameter specifies the file where words added to the personal list will be stored. It should
be an absolute filename beginning with ’/’ because otherwise it will be relative to $HOME, which is
"/root" for most systems, and is probably not what you want.
The language parameter is the language code which consists of the two letter ISO 639 language code and
an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as
English. Known values are ’american’, ’british’, and ’canadian’.
The jargon parameter contains extra information to distinguish two different words lists that have the
same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are ’utf-8’,
’iso8859-*’, ’koi8-r’, ’viscii’, ’cp1252’, ’machine unsigned 16’, ’machine unsigned 32’. This parameter
is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
1265
Pspell
• PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be
a legal compound, athough there should be a space between the two words. Changing this setting only
affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST,
PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of
them.
For more information and examples, check out inline manual pspell website:http://aspell.net/.
Ejemplo 1. pspell_new_personal()
int pspell_new ( string language [, string spelling [, string jargon [, string encoding [, int mode]]]]) \linebreak
pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell
functions.
The language parameter is the language code which consists of the two letter ISO 639 language code and
an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as
English. Known values are ’american’, ’british’, and ’canadian’.
The jargon parameter contains extra information to distinguish two different words lists that have the
same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are ’utf-8’,
’iso8859-*’, ’koi8-r’, ’viscii’, ’cp1252’, ’machine unsigned 16’, ’machine unsigned 32’. This parameter
is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
• PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be
a legal compound, athough there should be a space between the two words. Changing this setting only
affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
1266
Pspell
Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST,
PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of
them.
For more information and examples, check out inline manual pspell website:http://aspell.net/.
Ejemplo 1. pspell_new()
Ejemplo 1. pspell_add_to_personal()
1267
Pspell
pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by
pspell_suggest() later. In order to be able to take advantage of this function, you have to use
pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you
have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom
wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this
function will not work unless you have pspell .11.2 and aspell .32.5 or later.
Ejemplo 1. pspell_store_replacement()
Ejemplo 1. pspell_suggest()
1268
LXXXV. GNU Readline
Las funciones readline() implementan una interfaz con la librería GNU Readline. Un ejemplo de la
manera de funcionar podría ser la forma en que el Bash permite usar las flechas de dirección para insertar
carácteres o desplazarse a través del historial de comandos. Debido a la naturaleza interactiva de esta
libreria, tendrá un uso muy reducido en la escritura de aplicaciones Web, aunque puede ser útil para
scripts que han de ser ejecutados desde la consola.
La página principal del proyecto GNU Readline es
http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. Está actualizada por Chet Ramey, quien además
es el autor de Bash.
1269
Readline
readline_add_history (PHP 4 )
Añade una línea al historial
readline_clear_history (PHP 4 )
Borra el historial
readline_completion_function (PHP 4 )
Registra una función de completitud
readline_info (PHP 4 )
Establece/Obtiene diversas variables internas de readline
readline_list_history (PHP 4 )
Lista el historial
1270
Readline
readline_read_history (PHP 4 )
Lee un historial
readline_write_history (PHP 4 )
Escribe el historial
readline (PHP 4 )
Lee una línea
Ejemplo 1. readline()
//Vuelca el historial
print_r (readline_list_history());
1271
LXXXVI. Funciones GNU Recode
Este modulo contiene un interfaz para la biblioteca GNU Recode version 3.5. Para poder usar las
funciones definidas en este modulo, debereis de compilar el interprete PHP con la opcion --with-recode.
Para poder hacer esto debereis tener instalado en vuestro sistema GNU Recode 3.5 o superior.
La biblioteca GNU Recode convierte entre ficheros con diferentes codigos de caracteres y codificacion.
Cuando esto no puede realizarse exactamente, puede desahacerse de los caracteres problematicos o crear
una aproximacion. La biblioteca reconoce o produce alrededor de 150 codigos de caracteres y puede
convertir ficheros entre casi todos los pares posibles. La gran mayoria de de codigos de caracteres RFC
1345 estan soportados.
1272
Recode
recode (PHP 4 )
Recode a string according to a recode request
1273
LXXXVII. Funciones de expresiones regulares
compatibles con Perl
La sintaxis, para los patrones usados en estas funciones, es muy semejante al Perl. Las expresiones
estarán encerradas por delimitadores, por ejemplo una barra de dividir (/). Cualquier carácter puede ser
usado para delimitar incluso los que no son caracteres alfanuméricos o la barra invertida (\). Si el carácter
delimitador ha sido usado en la propia expresión, es necesario que sea precedido por una barra inversa.
El delimitador de fin puede ser seguido por varios modificadores que afectarán al resultado. Examina
Modificadores de Patrones.
• /<\/\w+>/
• |(\d{3})-\d+|Sm
• /^(?i)php[34]/
Nota: Para las funciones de expresiones compatibles con Perl se necesita PHP 4 o PHP 3.0.9 o
superior.
1274
PCRE
Los posibles modificadores PRCE (Funciones de Expresiones Compatibles con Perl), en este momento,
son mostrados a continuación. Los nombres entre paréntesis se refieren a nombres internos PCRE para
dichos modificadores.
i (PCRE_CASELESS)
Si es usado, no se distinguirá entre mayúsculas y minúsculas.
m (PCRE_MULTILINE)
Por defecto, PCRE trata la cadena de entrada como si fuera una sola línea de caracteres (aun cuando
tenga varias). El carácter especial de "inicio de línea" (^) empareja sólo al principio de la cadena,
mientras el carácter especial de "fin de línea" ($) casa sólo el fin de la entrada, o antes un carácter de
nueva línea (a menos que el modificador E sea definido). Esto es lo mismo que en Perl.
Cuando este modificador es utilizado, los constructores de "inicio de línea" y "fin de línea" son
emparejados con el carácter de nueva línea. Esto es equivalente al modificador /m del Perl. Si no hay
caracteres "\n" en la cadena de entrada, o no existen ^ o $ en el patrón, entonces este modificador no
alterará el resultado.
s (PCRE_DOTALL)
Si se usa, el carácter especial de un punto en el patrón emparejará todos los caracteres, incluyendo el de
nueva línea. Sin él, el carácter de nueva línea es excluido. Este modificador equivale a /s en Perl. Una
cláusula como [^a] siempre casa con un carácter de nueva línea, independientemente de la utilización de
este modificador.
x (PCRE_EXTENDED)
Si es definido, los caracteres de información con espacios en blanco en el patrón son ignorados excepto
cuando son precedidos por una barra invertida o dentro de una clase carácter, y los caracteres entre un #
fuera de una clase carácter y los siguientes caracteres de nueva línea, incluidos, son ignorados también.
Esto es equivalente al /x en Perl y hace posible incluir comentarios dentro de patrones complejos. Sin
embargo, esto es sólo aplicable a caracteres de información. Los caracteres de espacio en blanco nunca
pueden aparecer en la secuencia de caracteres especiales de un patrón, por ejemplo en la secuencia (?( la
cual introduce un subpatrón condicional.
e
Si es usado, preg_replace() hace las sustituciones \\ de forma habitual, evalúa el código PHP y usa el
resultado para realizar una sustitución en la cadena de búsqueda.
Sólo preg_replace() hace uso de este modificador y es ignorado por las otras funciones PCRE.
1275
PCRE
A (PCRE_ANCHORED)
Si es definido, el patrón es forzado a ser "anclado", esto es, es obligado a emparejar sólo desde el inicio
de la cadena (el "subject string"). Esta característica también puede realizarse con el apropiado patrón, y
esta es la única manera de hacerlo en Perl.
E (PCRE_DOLLAR_ENDONLY)
Si es usado, el carácter del dólar en el patrón casará sólo con fin de la cadena de entrada (subject).Sin
este modificador, un dólar es también emparejado con el carácter inmediatamente antes del de una nueva
línea (pero no antes de cualquier otra nueva línea). Este modificador es ignorado si m es definido. No hay
equivalente en Perl para este modificador.
S
Cuando un patrón va a ser usado varias veces, es mejor dedicar más tiempo a analizarlo para acelerar el
proceso de casamientos. Si es definido entonces se realizar un análisis adicional. Estudiar a un patrón es
sólo útil para los no anclados, esto es, no tienen un carácter de inicio fijado.
U (PCRE_UNGREEDY)
Este modificador invierte la "codicia" de los cuantificadores aunque no son ansiosos por defecto, se
vuelven codiciosos si son seguidos por un "?". No es compatible con Perl. también puede usarse dentro
del patrón.
X (PCRE_EXTRA)
Este modificador activa características adicionales del PCRE que no son compatible con Perl. Cualquier
barra invertida en el patrón que sea seguida por una letra que no tenga una interpretación especial
provocará un error, estas combinaciones están reservado para futuras ampliaciones. Por defecto, como en
Perl, una barra invertida seguida por una letra sin un significado especial es tratada literalmente. No hay
otras características controladas por este modificador a la fecha de hoy.
1276
PCRE
isspace() casa con el espacio, salto de pagina, nueva línea, retorno de carro,
tabulador horizontal y vertical. Perl 5 ya no incluye el tabulador vertical
en su conjunto de caracteres de espacio en blanco. La secuencia de
escape \n que estuvo durante mucho tiempo en la documentación de Perl nunca
fue reconocida. Sin embargo, el carácter fue tratado como espacio en blanco
hasta la 5.002. En 5.004 y 5.005 no casa \s.
1277
PCRE
(a) Aunque las sentencias de más adelante deben emparejar cadenas de longitud fija,
cada opción de una sentencia de punto actual puede casar con una cadena de
longitud diferente. Perl 5.005 requiere que todas ellas tengan la misma
longitud.
(c) Si se define PCRE_EXTRA, una barra invertida seguida de una letra sin
un significado especial provoca un error.
casa una parte de una cadena de entrada que es idéntica a ella. El poder
de las expresiones proviene de la posibilidad de incluir alternativas y
repeticiones en el patrón. Éstos son codificados en el patrón usando
meta-characters (caracteres
especiales también llamados meta caracteres), los cuales no se representan
a ellos mismos, en vez de eso, son interpretados de una manera especial.
1278
PCRE
BARRA INVERTIDA
Por ejemplo, si quieres casar un carácter "*", debes escribir "\*" en el patrón.
Esto es aplicable ya sea o no el carácter siguiente interpretado como un
carácter especial, por eso siempre es aconsejable preceder un carácter
no alfanumérico con "\" para especificar que se representa a él mismo. En
particular, si quieres casar una barra invertida, escribe "\\".
1279
PCRE
Después de "\x", hasta dos dígitos hexadecimales son leídos (las letras
pueden ser mayúsculas o minúsculas).
Después de "\0" son leídos dos dígitos octales más. En ambos casos, si hay
menos de dos dígitos, se usrará lo que haya. Esto es, la secuencia "\0\x\07"
indica dos ceros binarios seguidos por un carácter BEL. Asegúrate dar dos
dígitos después del inicial cero si el carácter que sigue es un dígito octal.
El uso de una barra invertida seguido por otro dígito que no sea el cero
es complejo. Fuera de una clase carácter, PCRE interpreta cualquier dígito
como un número decimal. Si el número es menor que diez, o si ha habido
al menos tantos paréntesis capturados a la izquierda en la expresión,
entonces la secuencia entera es tomada como una back
reference (referencia atrás). Una descripción
de como trabaja esto es dada después, siguiendo la discusión de subpatrones
con paréntesis.
1280
PCRE
Ten en cuenta que el valor octal de un número mayor o igual a cien no debe
ser precedido por un cero ya que no son leídos más de tres dígitos octales.
Todas las secuencias que definen el valor de un byte pueden ser usadas
tanto dentro como fuera de la clase carácter. Además, la secuencia
"\b" es interpretada como el carácter backspace (hex 08) dentro. Fuera es
definido de otra manera (ver más adelante).
\b limites de palabra
\B no sean limites de palabra
\A inicio de la cadena de entrada (independiente del modo multilínea)
1281
PCRE
Estas sentencias no pueden aparecer dentro de una clase carácter (pero ten
en cuenta que "\b" tiene un significado diferente, quiere decir el carácter
backspace dentro de una clase carácter)
CIRCUNFLEJO Y DOLAR
El significado del dólar puede ser cambiado para que sólo empareje el
final de la cadena de entrada definiendo la opción PCRE_DOLLAR_ENDONLY a la
hora de compilar o tiempo de ejecución. Esto no afecta a la sentencia \Z.
1282
PCRE
Ten en cuenta que las secuencias \A, \Z y \z pueden ser usadas para casar
el inicio y el final de la cadena en ambos modos, y si todas las opciones
de un patrón empiezan con \A siempre es anclado, independientemente de si
PCRE_MULTILINE es definido o no.
FINAL (PUNTO)
Fuera de una clase carácter, un punto en el patrón casa con un carácter
cualquiera en la cadena de entrada, incluyendo un carácter no imprimible,
exceptuando el de nueva línea (por defecto). Si la opción PCRE_DOTALL es
definida, entonces los puntos casan con los de nueva línea también. El
manejo de puntos es completamente independiente del uso del circunflejo y el
dólar, la única relación entre ellos son los caracteres de nueva línea. Los
puntos no tienen un significado especial dentro de una clase carácter.
CORCHETES
Un corchete de apertura crea una clase carácter, terminada por uno de cierre.
Un corchete de cierre no tiene un significado especial. Si un corchete de
cierre es necesitado como un miembro de la clase, será el primer carácter
de datos en la clase (después de un circunflejo inicial, si está presente)
o con una barra invertida antes.
1283
PCRE
Los tipos de caracteres \d, \D, \s, \S, \w, y \W también pueden aparecer
en una clase carácter y añaden los caracteres que ellos casen para la clase.
Por ejemplo, [\dABCDEF] casa cualquier dígito hexadecimal. Un circunflejo
puede ser usado convenientemente con el tipo de carácter mayúsculo para
especificar un conjunto más restrictivo de caracteres que el de un casamiento
con tipo de carácter minúsculo. Por ejemplo, la clase [^\W_] empareja
cualquier letra o digito pero no el subrayado.
BARRA VERTICAL
1284
PCRE
gilbert|sullivan
i para PCRE_CASELESS
m para PCRE_MULTILINE
s para PCRE_DOTALL
x para PCRE_EXTENDED
Por ejemplo, (?im) define sin tener en cuenta mayúsculas y minúsculas y modo
multilínea. También es posible eliminar estas opciones precediendo las
letras con un menos y una combinación de definiciones y eliminaciones tal
como (?im-sx), la cual define PCRE_CASELESS y PCRE_MULTILINE mientras
elimina PCRE_DOTALL y PCRE_EXTENDED, también se permite. Si una letra
aparece antes y después del menos, la opción es eliminada.
(?i)abc
a(?i)bc
ab(?i)c
abc(?i)
el cual tiene el mismo efecto que compilar el patrón abc con la opción
PCRE_CASELESS. En otras palabras, tales definiciones de "nivel superior"
se aplican a todo el patrón (a menos que haya otro cambio dentro del
subpatrón). Si hay más de una definición de la misma opción en el mismo
nivel superior, la definición más a la derecha se usa.
1285
PCRE
por eso
(a(?i)b)c
(a(?i)b|c)
empareja "ab", "aB", "c", y "C", siempre y cuando case "C" la primera
opción es abandonada antes de definir la opción. Esto es porque los efectos
de definiciones de opción ocurren en tiempo de compilación. De otro modo,
éstos sería una conducta muy rara.
SUBPATRONES
cat(aract|erpillar|)
las subcadenas capturadas son "red king", "red", y "king" y los números
son 1,2 y 3
1286
PCRE
las subcadenas capturadas son "white queen" y "queen" y son numeradas como
1 y 2. El número máximo de subcadenas es de 99 y el número máximo de
subpatrones, capturados o no, es de 200.
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
REPETICION
z{2,4}
casa con "zz", "zzz", o "zzzz". Una llave de cierre por si misma no es un
carácter especial. Si el segundo número es omitido, pero aparece la coma,
entonces no hay límite superior; si el segundo número y la coma son
omitidos, el cuantificador indica el número exacto de repeticiones. Así
1287
PCRE
[aeiou]{3,}
empareja al menos tres vocales seguidas, pero pueden ser muchas más, mientras
\d{8}
casa exactamente ocho dígitos. Una llave abierta en una posición donde un
cuantificador no es permitido o una que no empareje con la sintaxis de un
cuantificador es tomada como un carácter literal. Por ejemplo, {,6} no es
un cuantificador, pero sí una cadena literal de cuatro caracteres.
* es equivalente a {0,}
+ es equivalente a {1,}
? es equivalente a {0,1}
(a?)*
Por defecto, los cuantificadores son "codiciosos", esto es, casan tantas
veces como les es posible (hasta el número máximo de veces permitido), sin
provocar que el resto del patrón falle. El ejemplo clásico de donde viene
este problema es en intentar casar comentarios en los programas en C.
Estos aparecen entre las secuencias /* y */ y dentro de la secuencia los
caracteres * y / pueden aparecer individualmente. Un modo de casar
comentarios en C es aplicando el patrón
/\*.*\*/
para la cadena
1288
PCRE
/\*.*?\*/
\d??\d
(tweedle[dume]{3}\s*)+
/(a|(b))+/
1289
PCRE
REFERENCIAS ATRAS
Fuera de una clase carácter, una barra invertida seguida por un digito
mayor que cero (y posiblemente más dígitos) es una referencia atrás a un
subpatrón capturado antes (a su izquierda) en el patrón, siempre que haya
habido tantos paréntesis a la izquierda capturados.
casa con "sense and sensibility" y "response and responsi bility", pero
no "sense and responsibility". Si el casamiento con la distinción entre
minúsculas y mayúsculas está activado en el momento de la referencia atrás,
entonces la distinción de las letras es relevante. Por ejemplo,
((?i)rah)\s+\1
casa con "rah rah" y "RAH RAH", pero no "RAH rah", pero el subpatrón
capturado originalmente es emparejado sin la distinción.
(a|(bc))\2
fallará siempre si inicia a casar con "a" mejor que con "bc". Ya que puede
haber hasta 99 referencias atrás, todos los dígitos seguidos por una barra
invertida son tomados como parte de número potencial de referencias atrás.
Si el patrón continua con un carácter de dígito, entonces algún delimitador
debe ser usado para terminar la referencia atrás. Si la opción PCRE_EXTENDED
es definida, este puede ser el espacio en blanco. De otro modo un comentario
vació puede ser usado.
1290
PCRE
Una referencia atrás ocurre dentro del paréntesis al cual refiere, falla
cuando el subpatrón es usado por primera vez, así por ejemplo, (a\1) nunca
emparejará. Sin embargo, tal referencia puede ser útil dentro de los
subpatrones repetidos. Por ejemplo, el patrón
(a|b\1)+
casa con cualquier número de "a"s y también con "aba", "ababaa" etc. Para
cada iteración del subpatrón, la referencia atrás casa la cadena de
caracteres correspondiente a la iteración anterior. Para que esto trabaje,
el patrón debe ser tal que la primera iteración no necesite casar la referencia
atrás. Esto puede hacerse usando alternativas, como en el ejemplo anterior,
o por medio de cuantificadores con un número mínimo de cero.
SENTENCIAS
\w+(?=;)
foo(?!bar)
casa cualquier ocurrencia de "foo" que no es seguida por "bar". Ten en cuenta
que el patrón similar
(?!foo)bar
no encuentra una ocurrencia de "bar" que es precedida por algo que no sea "foo";
encuentra cualquier ocurrencia de "bar", ya que la sentencia (?!foo) es siempre
verdadera cuando los tres primeros caracteres son "bar". Una sentencia en el
punto actual es necesaria para realizar este efecto. Las sentencias de punto
actual empiezan con (?<= para sentencias afirmativas y (?<! para las
negativas. Por ejemplo,
(?<!foo)bar
1291
PCRE
(?<=bullock|donkey)
es permitido, pero
(?<!dogs?|cats?)
(?<=ab(c|de))
(?<=abc|abde)
(?<=\d{3})(?<!999)foo
(?<=(?<!foo)bar)baz
empareja una ocurrencia de "baz" que es precedida por "bar" la cual no sea
precedida por "foo".
1292
PCRE
123456bar
(?>\d+)bar
Esta clase de paréntesis "bloquean" la parte del patrón que tiene que
ser emparejada una vez y un fallo impide que la re-evalue.
Subpatrones de una sola vez no son subpatrones capturados. Estos casos tal
como el ejemplo anterior pueden ser interpretado como de una repetición
maximizada que debe tragar todo lo que pueda.
Por esto, mientras ambos \d+ y \d? están preparados para ajustar el número
de dígitos que emparejan para hacer que el resto del patrón case, (?>\d+)
sólo puede emparejar un secuencia de dígitos entera.
1293
PCRE
Subpatrones de una sola vez pueden usarse con sentencias de punto actual
para especificar eficientes emparejamientos al final de la cadena de entrada.
Consideremos un patrón sencillo como este
abcd$
^.*abcd$
^(?>.*)(?<=abcd)
entonces no hay vuelta atrás para el elemento .*; sólo puede casar la cadena
entera. La sentencia de punto actual subsiguiente hace un test sencillo
sobre los últimos cuatro caracteres. Si falla, el casamiento inmediatamente
da un resultado negativo. Para cadena largas, este acercamiento da una
diferencia significativa en tiempo de ejecución.
SUBPATRONES CONDICIONALES
(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
1294
PCRE
( \( )? [^()]+ (?(1) \) )
(?(?=[^a-z]*[a-z])
\d{2}[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
COMENTARIOS
RENDIMIENTO
Ciertos elementos que pueden aparecer en los patrones son más eficientes
que otros. Es más eficiente usar una clase carácter como [aeiou] que un
conjunto de alternativas tal como (a|e|i|o|u). En general, los constructores
más sencillos que dan la conducta requerida son, normalmente, más eficientes.
El libro de Jeffrey Friedl contiene un montón de discusiones sobre la
1295
PCRE
(.*) second
preg_grep (PHP 4 )
Devuelve un array con los elementos que casen con el patrón
1296
PCRE
int preg_match_all ( string pattern, string subject, array matches [, int order]) \linebreak
Busca en subject todos los emparejamientos de la expresión pattern y los pone en matches de la
forma indicada por order.
Después de encontrar el primer emparejamiento, las subsiguientes búsquedas empiezan desde el punto
del último casamiento.
order puede tener los siguientes valores:
PREG_PATTERN_ORDER
Los resultados serán devueltos de manera que $matches[0] es un array con el patrón de búsqueda
completo, $matches[1] es una array de las cadenas casadas por el primer subpatrón que esté entre
paréntesis y así sucesivamente.
Así, $out[0] contiene el array con las cadena que casan completamente con el patrón y $out[1] con
las cadenas que se encuentran entre los tags.
PREG_SET_ORDER
Los resultados son dados de manera que $matches[0] es una array del primer conjunto de
emparejamientos, $matches[1] es un array de los segundos conjuntos de casamientos y así
sucesivamente.
1297
PCRE
1298
PCRE
. \\ + * ? [ ^ ] $ ( ) { } = ! < > | :
mixed preg_replace_callback ( mixed pattern, mixed callback, mixed subject [, int limit]) \linebreak
The behavior of this function is almost identical to preg_replace(), except for the fact that instead of
replacement parameter, one should specify a callback that will be called and passed an array of
matched elements in the subject string. The callback should return the replacement string. This function
was added in PHP 4.0.5.
See also preg_replace().
1299
PCRE
Si pattern y replacement son arrays, entonces preg_replace() toma un valor desde cada array y
los usas para buscar y sustituir sobre subject. Si replacement tiene menos valores que pattern,
entonces la cadena vacía es usada como valor para el resto de sustituciones. Si pattern es una array y
replacement es una cadena, entonces esta cadena de sustitución es usada para todos los valores de
pattern. Sin embargo, lo contrario no tiene sentido.
El modificador /e hace que la función preg_replace() trate el parámetro replacement como código
PHP después de que la apropiada sustitución sea hecha. Atención, asegúrate que replacement es un
código PHP correcto, de otro modo PHP dará un error de parse en la línea que contenga preg_replace().
$startDate = 5/27/1999
array preg_split ( string pattern, string subject [, int limit [, int flags]]) \linebreak
1300
PCRE
Devuelve un array conteniendo las subcadenas de subject divididas mediante los emparejamientos
limitados por pattern.
Si limit es proporcionado, entonces sólo limit subcadenas son devueltas.
Si el flags es PREG_SPLIT_NO_EMPTY entonces las cadenas vacías no serán devueltas por
preg_split().
1301
LXXXVIII. qtdom functions
1302
qtdom functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1303
LXXXIX. Funciones para expresiones regulares
Las expresiones regulares se usan en PHP para manipular cadenas complejas. Las funciones que
soportan expresiones regulares son:
• ereg()
• ereg_replace()
• eregi()
• eregi_replace()
• split()
En todas estas funciones, el primer argumento es una expresión regular. PHP utiliza las expresiones
regulares extendidas de POSIX, definidas en POSIX 1003.2. Para una descripción completa de las
expresiones regulares POSIX, ver las páginas de manual de regex incluidas en el directorio regex de la
distribución de PHP. Están en formato de página de manual, por lo que se deben leer con una orden como
man /usr/local/src/regex/regex.7.
ereg("abc",$string);
/* Devuelve true si "abc"
se encuentra en $string. */
ereg("^abc",$string);
/* Devuelve true si "abc"
se encuentra al comienzo de $string. */
ereg("abc$",$string);
/* Devuelve true si "abc"
se encuentra al final de $string. */
eregi("(ozilla.[23]|MSIE.3)",$HTTP_USER_AGENT);
/* Devuelve true si el navegador cliente
es Netscape 2, 3 o MSIE 3. */
$string = ereg_replace("^","<BR>",$string);
/* Coloca la etiqueta <BR> al comienzo de $string. */
$string = ereg_replace("$","<BR>",$string);
/* Coloca la etiqueta <BR> al final de $string. */
$string = ereg_replace("\n","",$string);
/* Elimina los caracteres fin-de-línea de $string. */
1304
Regexps
1305
Regexps
1306
Regexps
1307
Regexps
Para examinar una fecha que puede estar delimitada por barras, puntos o guiones:
1308
Regexps
imprime
[Ff][Oo][Oo][ ][Bb][Aa][Rr]
.
Se puede utilizar para lograr coincidencias que no diferencien mayúsculas de minúsculas en productos
que sólo soportan expresiones regulares que sí distinguen.
1309
XC. Funciones Semáforo y de memoria
compartida
Este módulo provee funciones semáforo utilizando los semaforos de System V. Los semáforos pueden
usarse para obtener acceso exclusivo a algun recurso del ordenador en cuestión, o para limitar el número
de procesos que pueden usar un recurso simultaneamente.
Este módulo provee tambien funciones de memoria compartida, usando el compartimiento de memoria
de System V. La memoria compartida puede usarse para proveer acceso a variables globales. Los
diferentes demonios http e incluso otros programas, (como Perl, C, ...) son capaces de utilizar estos
datos, para intercambiarlos de modo global. Recuerde que, la memoria compartida NO es segura para los
accesos simultáneos. Use los semáforos para obtener sincronismo.
1310
Semaphore
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool msg_receive ( int queue, int desiredmsgtype, int msgtype, int maxsize, mixed message [, bool unserialize [,
int flags [, int errorcode]]]) \linebreak
msg_receive() will receive the first message from the specified queue of the type specified by
desiredmsgtype. The type of the message that was received will be stored in msgtype. The
maximum size of message to be accepted is specified by the maxsize; if the message in the queue is
larger than this size the function will fail (unless you set flags as described below). The received
message will be stored in message, unless there were errors receiving the message, in which case the
optional errorcode will be set to the value of the system errno variable to help you identify the cause.
If desiredmsgtype is 0, the message from the front of the queue is returned. If desiredmsgtype
is greater than 0, then the first message of that type is returned. If desiredmsgtype is less than 0, the
first message on the queue with the lowest type less than or equal to the absolute value of
1311
Semaphore
desiredmsgtype will be read. If no messages match the criteria, your script will wait until a suitable
message arrives on the queue. You can prevent the script from blocking by specifying
MSG_IPC_NOWAIT in the flags parameter.
unserialize defaults to TRUE; if it is set to TRUE, the message is treated as though it was serialized
using the same mechanism as the session module. The message will be unserialized and then returned to
your script. This allows you to easily receive arrays or complex object structures from other PHP scripts,
or if you are using the WDDX serializer, from any WDDX compatible source. If unserialize is
FALSE, the message will be returned as a binary-safe string.
The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but
you may specify one or more of the following values (by adding or ORing them together).
Upon successful completion the message queue data structure is updated as follows: msg_lrpid is set
to the process-ID of the calling process, msg_qnum is decremented by 1 and msg_rtime is set to the
current time.
msg_receive() returns TRUE on success or FALSE on failure. If the function fails, the optional
errorcode will be set to the value of the system errno variable.
See also: msg_remove_queue(), msg_send(), msg_stat_queue() and msg_set_queue().
This function was introduced in PHP 4.3.0 (not yet released).
1312
Semaphore
bool msg_send ( int queue, int msgtype, mixed message [, bool serialize [, bool blocking [, int errorcode]]])
\linebreak
msg_send() sends a message of type msgtype (which MUST be greater than 0) to a the message
queue specified by queue.
If the message is too large to fit in the queue, your script will wait until another process reads messages
from the queue and frees enough space for your message to be sent. This is called blocking; you can
prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will
immediately return FALSE if the message is too big for the queue, and set the optional errorcode to
EAGAIN, indicating that you should try to send your message again a little later on.
The optional serialize controls how the message is sent. serialize defaults to TRUE which
means that the message is serialized using the same mechanism as the session module before being
sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are
using the WDDX serializer, to any WDDX compatible client.
Upon successful completion the message queue data structure is updated as follows: msg_lspid is set
to the process-ID of the calling process, msg_qnum is incremented by 1 and msg_stime is set to the
current time.
See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().
This function was introduced in PHP 4.3.0 (not yet released).
1313
Semaphore
1314
Semaphore
1315
Semaphore
Nota: This function does not work on Windows systems. It was added on PHP 4.1.0.
1316
Semaphore
1317
XCI. SESAM database functions
SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers,
Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.
In numerous productive BS2000 installations, SESAM/SQL-Server has proven ...
Now there is a PHP3 SESAM interface available which allows database operations via PHP-scripts.
Configuration notes: There is no standalone support for the PHP SESAM interface, it works only as
an integrated Apache module. In the Apache PHP module, this SESAM interface is configured using
Apache directives.
Directive Meaning
php3_sesam_oml Name of BS2000 PLAM library containing the load-
able SESAM driver modules. Required for using SESAM
functions. Example:
php3_sesam_oml $.SYSLNK.SESAM-SQL.030
In addition to the configuration of the PHP/SESAM interface, you have to configure the
1318
SESAM
To get a connection between a PHP script and the database handler, the CNF and NAM parameters of
the selected SESAM configuration file must match the id of the started database handler.
In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution
table including the host and database names.
The communication between PHP (running in the POSIX subsystem) and the database handler
(running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and
SESAM connection modules using common memory. Because of the common memory access, and
because PHP is a static part of the web server, database accesses are very fast, as they do not
require remote accesses via ODBC, JDBC or UTM.
Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are
pulled in from SESAM’s OML PLAM library. In the configuration, you must tell PHP the name of this
PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is
available in the SESAM Tool Library, which is part of the standard distribution).
Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to
a single quote preceded by a backslash, used in some other databases), it is advisable to set the
PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all
PHP scripts using the SESAM interface.
Runtime considerations: Because of limitations of the BS2000 process model, the driver can be
loaded only after the Apache server has forked off its server child processes. This will slightly slow
down the initial SESAM request of each child, but subsequent accesses will respond at full speed.
When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the
driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message
after successful load of the message catalog, which will be sent to Apache’s error_log file. BS2000
currently does not allow suppression of this message, it will slowly fill up the log.
Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the
user id running the web server. Otherwise, the server will be unable to load the driver, and will not
allow to call any SESAM functions. Also, access to the database must be granted to the user id under
which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.
Cursor Types: The result cursors which are allocated for SQL "select type" queries can be either
"sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors,
the default is "sequential".
When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each
"scrollable" query, there are global default values for the scrolling type (initialized to:
SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or
each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable"
1319
SESAM
cursor, the following post-processing is done for the global default values for the scrolling type and
scrolling offset:
Porting note: Because in the PHP world it is natural to start indexes at zero (rather than 1), some
adaptions have been made to the SESAM interface: whenever an indexed array is starting with index
1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when
retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent
columns have indexes up to (but not including) the column count ($array["count"]). When porting
SESAM applications from other high level languages to PHP, be aware of this changed interface.
Where appropriate, the description of the respective php sesam functions include a note that the
index is zero based.
Security concerns: When allowing access to the SESAM databases, the web server user should
only have as little privileges as possible. For most databases, only read access privilege should be
granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full
control to any database for any user from the ’net! Restrict access to php scripts which must
administer the database by using password control and/or SSL security.
Migration from other SQL databases: No two SQL dialects are ever 100% compatible. When
porting SQL applications from other database interfaces to SESAM, some adaption may be required.
The following typical differences should be noted:
Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT
1320
SESAM
In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).
• $count = xxxx_num_rows();
Some databases promise to guess/estimate the number of the rows in a query result, even though
the returned value is grossly incorrect. SESAM does not know the number of rows in a query
result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...)
WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.
Notes on the use of various SQL types: SESAM does not currently support the BLOB type. A
future version of SESAM will have support for BLOB.
At the PHP interface, the following type conversions are automatically applied when retrieving SQL
fields:
1321
SESAM
When retrieving a complete row, the result is returned as an array. Empty fields are not filled in, so
you will have to check for the existence of the individual fields yourself (use isset() or empty() to test
for empty fields). That allows more user control over the appearance of empty fields (than in the case
of an empty string as the representation of an empty field).
Support of SESAM’s "multiple fields" feature: The special "multiple fields" feature of SESAM
allows a column to consist of an array of fields. Such a "multiple field" column can be created like
this:
Note that (like in this case) leading empty sub-fields are ignored, and the filled-in values are
collapsed, so that in the above example the result will appear as multi(1..2) instead of multi(2..3).
When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the
example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as
indices 1 through 3.
For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english)
(http://its.siemens.de/lobs/its/techinf/oltp/sesam/manuals/index_en.htm) or the SESAM/SQL-Server
documentation (german) (http://its.siemens.de/lobs/its/techinf/oltp/sesam/manuals/index_gr.htm), both
available online, or use the respective manuals.
1322
SESAM
<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
if (!sesam_execimm ("INSERT INTO mytable VALUES (*, ’Small Test’, <0, 8, 15>)"))
die("insert failed");
if (!sesam_commit())
die("commit failed");
}
?>
1323
SESAM
<?php
if (!sesam_connect ("mycatalog", "myschema", "otto")
die("Unable to connect to SESAM";
?>
1324
SESAM
Element Contents
$array["sqlstate"] 5 digit SQL return code (see the SESAM manual
for the description of the possible values of
SQLSTATE)
$array["rowcount"] number of affected rows in last update/insert/delete
(set after "immediate" statements only)
$array["errmsg"] "human readable" error message string (set after
errors only)
$array["errcol"] error column number of previous error (0-based; or
-1 if undefined. Set after errors only)
$array["errlin"] error line number of previous error (0-based; or -1
if undefined. Set after errors only)
<?php
// Function which prints a formatted error message,
// displaying a pointer to the syntax error in the
// SQL statement
function PrintReturncode ($exec_str) {
$err = Sesam_Diagnostic();
$colspan=4; // 4 cols for: sqlstate, errlin, errcol, rowcount
if ($err["errlin"] == -1)
--$colspan;
if ($err["errcol"] == -1)
--$colspan;
if ($err["rowcount"] == 0)
--$colspan;
echo "<TABLE BORDER>\n";
echo "<TR><TH COLSPAN=".$colspan."><FONT COLOR=red>ERROR:</FONT> ".
htmlspecialchars($err["errmsg"])."</TH></TR>\n";
if ($err["errcol"] >= 0) {
echo "<TR><TD COLSPAN=".$colspan."><PRE>\n";
$errstmt = $exec_str."\n";
for ($lin=0; $errstmt != ""; ++$lin) {
if ($lin != $err["errlin"]) { // $lin is less or greater than errlin
if (!($i = strchr ($errstmt, "\n")))
$i = "";
$line = substr ($errstmt, 0, strlen($errstmt)-strlen($i)+1);
$errstmt = substr($i, 1);
if ($line != "\n")
print htmlspecialchars ($line);
} else {
if (! ($i = strchr ($errstmt, "\n")))
1325
SESAM
$i = "";
$line = substr ($errstmt, 0, strlen ($errstmt)-strlen($i)+1);
$errstmt = substr($i, 1);
for ($col=0; $col < $err["errcol"]; ++$col)
echo (substr($line, $col, 1) == "\t") ? "\t" : ".";
echo "<FONT COLOR=RED><BLINK>\\</BLINK></FONT>\n";
print "<FONT COLOR=\"#880000\">".htmlspecialchars($line)."</FONT>";
for ($col=0; $col < $err["errcol"]; ++$col)
echo (substr ($line, $col, 1) == "\t") ? "\t" : ".";
echo "<FONT COLOR=RED><BLINK>/</BLINK></FONT>\n";
}
}
echo "</PRE></TD></TR>\n";
}
echo "<TR>\n";
echo " <TD>sqlstate=" . $err["sqlstate"] . "</TD>\n";
if ($err["errlin"] != -1)
echo " <TD>errlin=" . $err["errlin"] . "</TD>\n";
if ($err["errcol"] != -1)
echo " <TD>errcol=" . $err["errcol"] . "</TD>\n";
if ($err["rowcount"] != 0)
echo " <TD>rowcount=" . $err["rowcount"] . "</TD>\n";
echo "</TR>\n";
echo "</TABLE>\n";
}
See also: sesam_errormsg() for simple access to the error string only
1326
SESAM
Note that this isn’t usually necessary, as the open connection is automatically closed at the end of the
script’s execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is
executed.
sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined
"catalog", "schema" and "user" triple, so that any sesam function called after
sesam_disconnect() will fail.
See also: sesam_connect().
if (!sesam_execimm ($stmt))
printf ("%s<br>\n", sesam_errormsg());
See also: sesam_diagnostic() for the full set of SESAM SQL status information
1327
SESAM
Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm()
only if you know beforehand what type of statement will be executed. An attempt to use SELECT type
queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".
The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it
is only returned for symmetry with the sesam_query() function.
A special handling allows fetching "multiple field" columns (which would otherwise all have the same
column names). For each column of a "multiple field", the index name is constructed by appending the
string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared
repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the
respective query syntax. For a column declared as:
1328
SESAM
the associative indices used for the individual "multiple field" columns would be "multi(1)",
"multi(2)", and "multi(3)" respectively.
Subsequent calls to sesam_fetch_array() would return the next (or prior, or n’th next/prior, depending
on the scroll attributes) row in the result set, or FALSE if there are no more rows.
<?php
$result = sesam_query ("SELECT * FROM phone\n".
" WHERE LASTNAME=’".strtoupper($name)."’\n".
" ORDER BY FIRSTNAME", 1);
if (!$result) {
... error ...
}
// print the table:
print "<TABLE BORDER>\n";
while (($row = sesam_fetch_array ($result)) && count ($row) > 0) {
print " <TR>\n";
print " <TD>".htmlspecialchars ($row["firstname"])."</TD>\n";
print " <TD>".htmlspecialchars ($row["lastname"])."</TD>\n";
print " <TD>".htmlspecialchars ($row["phoneno"])."</TD>\n";
print " </TR>\n";
}
print "</TABLE>\n";
sesam_free_result ($result);
?>
1329
SESAM
Note that the amount of memory used up by a large query may be gigantic. Use the max_rows
parameter to limit the maximum number of rows returned, unless you are absolutely sure that your result
will not use up all available memory.
See also: sesam_fetch_row(), and sesam_field_array() to check for "multiple fields". See the description
of the sesam_query() function for a complete example using sesam_fetch_result().
1330
SESAM
<?php
$result = sesam_query ("SELECT * FROM phone\n".
" WHERE LASTNAME=’".strtoupper($name)."’\n".
" ORDER BY FIRSTNAME", 1);
if (!$result) {
... error ...
1331
SESAM
}
// print the table in backward order
print "<TABLE BORDER>\n";
$row = sesam_fetch_row ($result, SESAM_SEEK_LAST);
while (is_array ($row)) {
print " <TR>\n";
for ($col = 0; $col < $row["count"]; ++$col) {
print " <TD>".htmlspecialchars ($row[$col])."</TD>\n";
}
print " </TR>\n";
// use implied SESAM_SEEK_PRIOR
$row = sesam_fetch_row ($result);
}
print "</TABLE>\n";
sesam_free_result ($result);
?>
See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns
many rows per invocation.
1332
SESAM
• "string"
depending on the SQL type of the result. SESAM
"multiple fields" are "inlined" and treated like the
respective number of columns, each with the same
php type.
1333
SESAM
• "NUMERIC"
• "DECIMAL"
• "INTEGER"
• "SMALLINT"
• "FLOAT"
• "REAL"
• "DOUBLE"
• "DATE"
• "TIME"
• "TIMESTAMP"
describing the SQL type of the result. SESAM
"multiple fields" are "inlined" and treated like the
respective number of columns, each with the same
SQL type.
string $arr[col]["length"] The SQL "length" attribute of the SQL variable in
column(col), where col is between 0 and
$arr["count"]-1. The "length" attribute is used
with "CHARACTER" and "VARCHAR" SQL types
to specify the (maximum) length of the string
variable. SESAM "multiple fields" are "inlined" and
treated like the respective number of columns, each
with the same length attribute.
string $arr[col]["precision"] The "precision" attribute of the SQL variable in
column(col), where col is between 0 and
$arr["count"]-1. The "precision" attribute is
used with numeric and time data types. SESAM
"multiple fields" are "inlined" and treated like the
respective number of columns, each with the same
precision attribute.
1334
SESAM
See also: sesam_field_array(). It provides an easier interface to access the column names and types, and
allows for detection of "multiple fields".
1335
SESAM
After calling sesam_query() with a "select type" query, this function gives you the number of columns in
the result. Returns an integer describing the total number of columns (aka. fields) in the current
result_id result set or FALSE on error.
For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as
their respective dimension, i.e., a three-column "multiple field" counts as three columns.
See also: sesam_query() and sesam_field_array() for a way to distinguish between "multiple field"
columns and regular columns.
<?php
if (!sesam_connect ("phonedb", "demo", "otto"))
die ("cannot connect");
$result = sesam_query ("select * from phone");
if (!$result) {
$err = sesam_diagnostic();
die ($err["errmsg"]);
}
echo "<TABLE BORDER>\n";
// Add title header with column names above the result:
if ($cols = sesam_field_array ($result)) {
echo " <TR><TH COLSPAN=".$cols["count"].">Result:</TH></TR>\n";
echo " <TR>\n";
1336
SESAM
do {
// Fetch the result in chunks of 100 rows max.
$ok = sesam_fetch_result ($result, 100);
for ($row=0; $row < $ok["rows"]; ++$row) {
echo " <TR>\n";
for ($col = 0; $col < $ok["cols"]; ++$col) {
if (isset($ok[$col][$row]))
echo " <TD>" . $ok[$col][$row] . "</TD>\n";
} else {
echo " <TD>-empty-</TD>\n";
}
}
echo " </TR>\n";
}
}
while ($ok["truncated"]) { // while there may be more data
echo "</TABLE>\n";
}
// free result id
sesam_free_result($result);
?>
1337
SESAM
<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
if (sesam_execimm ("INSERT INTO mytable VALUES (*, ’Small Test’, <0, 8, 15>)")
&& sesam_execimm ("INSERT INTO othertable VALUES (*, ’Another Test’, 1)"))
sesam_commit();
else
sesam_rollback();
}
?>
1338
SESAM
offset is an optional parameter which is only evaluated (and required) if whence is either
SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.
2 Read Committed
SESAM_TXISOL_READ_COMMITTED
3 Repeatable Read
SESAM_TXISOL_REPEATABLE_READ
4 SESAM_TXISOL_SERIALIZABLE Serializable
1339
SESAM
The values set by sesam_settransaction() will override the default setting specified in the SESAM
configuration file.
<?php
sesam_settransaction (SESAM_TXISOL_REPEATABLE_READ,
SESAM_TXREAD_READONLY);
?>
1340
XCII. Funciones para el manejo de sesiones
El apoyo que PHP proporciona para las sesiones consiste en una forma de conservar ciertos datos a lo
largo de los subsiguientes accesos, lo cual le permite construir aplicaciones más personalizadas e
incrementar el atractivo de su sitio web.
Si ya está familiarizado con el tratamiento de sesiones de PHPLIB, notará que algunos conceptos son
similares al soporte de las sesiones de PHP.
A cada visitante que accede a su web se le asigna un identificador único, llamado "session id"
(identificador de sesión). Éste se almacena en una cookie por parte del usuario o se propaga en la URL.
El soporte de las sesiones le permite registrar un número arbitrario de variables que se conservarán en las
siguientes peticiones. Cuando un visitante acceda a su web, PHP comprobará automáticamente (si
session.auto_start está puesto a 1) o cuando usted lo especifique (de forma explícita mendiante
session_start() o implícita a través de session_register()) si se le ha enviado un "session id" específico
con su petición, en cuyo caso se recrean las variables que se habían guardado anteriormente.
Todas las variables registradas son almacenadas tras finalizar la petición. Las variables que están
indefinidas se marcan como no definidas. En los subsiguientes accesos, no estarán definidas por el
módulo de sesiones a menos que el usuario las defina más tarde.
Las opciones de configuración track_vars y register_globals influyen notablemente en la forma
en que las variables de la sesión se almacenan y restauran.
Nota: A partir de PHP 4.1.0, $_SESSION está disponible como variable global, al igual que $_POST,
$_GET, $_REQUEST y demás. Al contrario que $HTTP_SESSION_VARS, $_SESSION siempre es global.
Por tanto, no se debe usar global para $_SESSION.
Si track_vars está activado y register_globals está desactivado, sólo los miembros del vector
asociativo global $HTTP_SESSION_VARS pueden ser registrados como variables de la sesión. Las
variables restauradas de la sesión sólo estarán disponibles en el vector $HTTP_SESSION_VARS.
<?php
session_start();
if (isset($HTTP_SESSION_VARS[’count’])) {
$HTTP_SESSION_VARS[’count’]++;
}
else {
$HTTP_SESSION_VARS[’count’] = 0;
}
?>
1341
Sesiones
Se recomienda usar $_SESSION (o $HTTP_SESSION_VARS con PHP 4.0.6 o inferior) por seguridad y
para hacer el código más legible. Con $_SESSION o $HTTP_SESSION_VARS, no es necesario usar las
funciones session_register() / session_unregister() / session_is_registered(). Los usuarios pueden acceder
a una variable de la sesión como si se tratase de una variable normal.
<?php
session_start();
// Use $HTTP_SESSION_VARS con PHP 4.0.6 o inferior
if (!isset($_SESSION[’count’])) {
$_SESSION[’count’] = 0;
} else {
$_SESSION[’count’]++;
}
?>
<?php
session_start();
// Use $HTTP_SESSION_VARS con PHP 4.0.6 o inferior
unset($_SESSION[’count’]);
?>
Si register_globals está activado, todas las variables globales pueden ser registradas como variables
de la sesión, y las variables de la sesión serán restauradas a sus correspondientes variables globales.
Como PHP debe saber qué variables globles están registradas como variables de la sesión, los usuarios
deben registrar las variables con la función session_register(), mientras que con
1342
Sesiones
Atención
Si está usando $HTTP_SESSION_VARS/$_SESSION y desactiva register_globals,
no use session_register(), session_is_registered() ni session_unregister().
Si activa register_globals, session_unregister() debería ser usado a partir de
que las variables de la sesión sean registradas como variables globales cuando
los datos de la sesión se guardan. Se recomienda desactivar register_globals
por motivos de seguridad y rendimiendo.
<?php
if (!session_is_registered(’count’)) {
session_register("count");
$count = 0;
}
else {
$count++;
}
?>
• Cookies
• Parámetro en la URL
El módulo de sesiones admite ambas formas. Las Cookies son la mejor opción, pero como no son fiables
(los clientes no están obligados a aceptarlas), no podemos confiar en ellas. El segundo método incrusta el
"session id" directamente en las URLs.
PHP es capaz de hacerlo de forma transparente al usuario cuando se compila con
--enable-trans-sid. Si activa esta opción, las URIs relativas serán modificadas de forma que
contengan el session id automáticamente. Alternativamente, puede usar la constante SID que está
1343
Sesiones
El ejemplo siguiente demuestra cómo registrar una variable, y cómo colocar correctamente un enlace a
otra página usando la constante SID.
<?php
if (!session_is_registered(’count’)) {
session_register(’count’);
$count = 1;
}
else {
$count++;
}
?>
Hola, visitante. Has visto esta página <?php echo $count; ?> veces.
<?php
# el <?php echo SID?> (Se puede usar <?=SID?> si short tag está activado)
# es necesario para conservar el session id
# en caso de que el usuario haya desactivado las cookies
?>
Nota: Se asume que las URLs no relativas apuntan a sitios web externos, y por tanto no se añade el
SID, ya que pasar el SID a un servidor diferente podría ocasionar un agujero de seguridad.
Para implementar el almacenamiento en bases de datos o en otro tipo de almacenamiento, necesitará usar
session_set_save_handler()() para crear una colección de funciones de almacenamiento a nivel de
usuario.
El sistema de control de sesiones soporta varias opciones de configuración que puede colocar en su
archivo php.ini. Les daremos un pequeño repaso.
• session.save_handler define el nombre del controlador que se usa para almacenar y recuperar
los datos asociados a la sesión. Su valor por defecto es files.
• session.save_path define el argumento que se pasa al controlador de almacenamiento. Si elige el
controlador de archivos por defecto, esta es la ruta donde los archivos se crean. Por defecto es /tmp.
1344
Sesiones
Aviso
Si lo deja apuntando a un directorio con permiso de lectura por el resto de
usuarios, como /tmp (la opción por defecto), los demás usuarios del servidor
pueden conseguir robar las sesiones obteniéndolas de la lista de archivos de
ese directorio.
• session.name especifica el nombre de la sesión que se usa como nombre de la cookie. Sólo debería
contener caracteres alfanuméricos. Por defecto vale PHPSESSID.
• session.auto_start especifica si el módulo de las sesión inicia una sesión automáticamente al
comenzar la petición. Por defecto está 0 (desactivado).
• session.cookie_lifetime especifica la duración de la cookie en segundos que se manda al
navegador. El valor 0 significa "hasta que se cierra el navegador", y es el que se encuentra por defecto.
• session.serialize_handler define el nombre del controlador que se utiliza para guardar y
restaurar los datos. Actualmente se soportan un formato interno de PHP (cuyo nombre es php) y
WDDX (cuyo nombre es wddx). WDDX sólo está disponible si PHP está compilado con Soporte para
WDDX. Por defecto es php.
• session.gc_probability especifica la probabilidad de que se inicie la rutina gc (garbage
collection - recoleción de basura) en cada petición en porcentaje. Por defecto es 1.
• session.gc_maxlifetime especifica el número de segundos tras los cuales los datos se
considerarán como ’basura’ y serán eliminados.
• session.referer_check contiene la subcadena que usted quiera que se compruebe en cada
"HTTP Referer" (N.T.: Página desde donde proviene el enlace a la página actual). Si el "Referer" fue
enviado por el cliente y la subcadena no se ha encontrado, el session id incrustado será marcado como
inválido. Por defecto es una cadena vacía.
• session.entropy_file indica la ruta a un recurso externo (un archivo) que se usará como fuente
adicional de entropía en el proceso de creación de session id’s. Por ejemplo /dev/random o
/dev/urandom, que están disponibles en muchos sistemas Unix.
• session.entropy_length especifica el número de bytes que serán leidos del archivo indicado más
arriba. Por defecto es 0 (desactivado).
• session.use_cookies indica si el módulo puede usar cookies para guardar el session id en el lado
del cliente. Por defecto está a 1 (activado).
• session.cookie_path especifica la ruta a colocar en session_cookie. Por defecto es /.
1345
Sesiones
páginas en el caché).
• session.cache_expire especifica el tiempo-de-vida de las páginas de la sesión que se encuentran
en el caché en minutos. No tiene efecto para el limitador nocache. Por defecto vale 180.
• session.use_trans_sid indica si la inclusión del sid transparente está activada o no, si fue
activada compilando con --enable-trans-sid. Por defecto está a 1 (activado).
• url_rewriter.tags especifica qué etiquetas html serán reescritas para incluir el session id si la
inclusión del sid transparente está activada. Las etiquetas por defecto son
a=href,area=href,frame=src,input=src,form=fakeentry
1346
Sesiones
En el modo private, la cabecera Expire (caducidad) enviada al cliente puede confundir a algunos
navegadores incluyendo Mozilla. Puede evitar este problema con el modo private_no_expire. La
cabecera Expire nunca se envía al cliente en este modo.
Al comenzar la ejecución del script, el limitador de caché se reestablece al valor por defecto guardado en
session.cache_limiter. De este modo, es necesario llamar a session_cache_limiter() en cada
petición (y antes de llamar a session_start()).
<?php
session_cache_limiter(’private’);
$cache_limiter = session_cache_limiter();
1347
Sesiones
session_decode (PHP 4 )
Decodifica los datos de una sesión a partir de una cadena
session_destroy (PHP 4 )
Destruye todos los datos guardados en una sesión
<?php
// Inicializa de la sesión.
// Si está usando session_name("algo"), ¡no lo olvide ahora!
session_start();
// Destruye todas las variables de la sesión
session_unset();
// Finalmente, destruye la sesión
session_destroy();
?>
1348
Sesiones
<?php
// Inicializa la sesión.
// Si está usando session_name("algo"), ¡no lo olvide ahora!
session_start();
// Destruye todas las variables de la sesión
$_SESSION = array();
// Finalmente, destruye la sesión
session_destroy();
?>
session_encode (PHP 4 )
Codifica los datos de la sesión actual en una cadena
session_get_cookie_params (PHP 4 )
Obtiene los parámetros de la cookie de la sesión
1349
Sesiones
session_id (PHP 4 )
Lee y/o cambia el session id actual
session_is_registered (PHP 4 )
Comprueba si una variable está registrada en la sesión
Nota: Si utiliza $_SESSION (o $HTTP_SESSION_VARS con PHP 4.0.6 o inferior), use isset() para
comprobar si una variable está registrada en $_SESSION.
Atención
Si utiliza $HTTP_SESSION_VARS/$_SESSION, no use session_register(),
session_is_registered() ni session_unregister().
session_module_name (PHP 4 )
Lee y/o cambia el módulo de la sesión actual
session_name (PHP 4 )
Lee y/o cambia el nombre de la sesión actual
1350
Sesiones
<?php
$nombre_anterior = session_name("WebsiteID");
session_readonly (unknown)
Inicia una sesión - reinicializa las variables, pero sin guardar los cambios al terminar
session_register (PHP 4 )
Register one or more variables with the current session
1351
Sesiones
Atención
This registers a global variable. If you want to register a session variable inside a
function, you need to make sure to make it global using global() or use the
session arrays as noted below.
Atención
If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use
session_register(), session_is_registered() and session_unregister().
This function returns TRUE when all of the variables are successfully registered with the session.
If session_start() was not called before this function is called, an implicit call to session_start() with no
parameters will be made.
You can also create a session variable by simply setting the appropriate member of the $_SESSION or
$HTTP_SESSION_VARS (PHP < 4.1.0) array.
Nota: It is not currently possible to register resource variables in a session. For example, you can not
create a connection to a database and store the connection id as a session variable and expect the
connection to still be valid the next time the session is restored. PHP functions that return a resource
are identified by having a return type of resource in their function definitions. A list of functions that
return resources are available in the resource types appendix.
If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, assign variable to $_SESSION.
i.e. $_SESSION[’var’] = ’ABC’;
session_save_path (PHP 4 )
Lee y/o cambia la ruta donde se guardan los datos de la sesión actual
1352
Sesiones
Nota: En algunos sistemas operativos, puede que quiera especificar una ruta en un sistema de
ficheros que maneja muchos ficheros pequeños de forma eficiente. Por ejemplo, en Linux, reiserfs
puede dar un rendimiento mejor que ext2fs.
session_set_cookie_params (PHP 4 )
Cambia los parámetros de la cookie de la sesión
void session_set_cookie_params ( int duración [, string path [, string dominio [, bool segura]]]) \linebreak
Cambia los parámetros de la cookie definidos en el archivo php.ini. El efecto de esta función sólo dura
hasta que termina el script.
session_set_save_handler (PHP 4 )
Establece unas funciones para el almacenamiento de los datos de la sesión a nivel de usuario
bool session_set_save_handler ( string abrir, string cerrar, string leer, string escribir, string destruir, string gc)
\linebreak
session_set_save_handler() establece las funciones que se utilizan a nivel de usuario para el
almacenamiento y recuperación de los datos asociados a una sesión. Es lo más útil cuando se prefiere
utilizar otro método de almacenamiento distinto del proporcionaddo por las sesiones de PHP. p.ej.
Almacenar los datos de la sesión en una base de datos local. Devuelve TRUE si todo fue bien, FALSE en
caso de fallo.
Nota: El manejador "escribir" no se ejecuta hasta que se cierra la salida. Por ello, la salida de las
sentencias que coloquemos en el manejador "escribir" para el depurado nunca será enviadas al
1353
Sesiones
navegador. Si se necesita producir una salida para el depurado, se sugiere que la salida se
produzca en un archivo.
El siguiente ejemplo proporciona almacenamiento de las sesiones basado en archivos de forma similar al
manejador de sesiones por defecto de PHP files. Este ejemplo puede ser extendido fácilmente para
cubrir el almacenamiento en bases de datos usando su motor de soporte de bases de datos de PHP
favorito.
La función de lectura debe devolver siempre una cadena para que el manejador de escritura funcione
como se espera. Devuelva una cadena vacía si no hay ningún dato a leer. Los valores devueltos de otros
manejadores son convertidos a una expresión booleana. TRUE si todo ha ido correctamente, FALSE si
ha habido algún problema.
<?php
function abrir ($save_path, $session_name) {
global $sess_save_path, $sess_session_name;
$sess_save_path = $save_path;
$sess_session_name = $session_name;
return(true);
}
function cerrar() {
return(true);
}
$sess_file = "$sess_save_path/sess_$id";
if ($fp = @fopen($sess_file, "r")) {
$sess_data = fread($fp, filesize($sess_file));
return($sess_data);
} else {
return(""); // Debe devolver "" aquí.
}
$sess_file = "$sess_save_path/sess_$id";
if ($fp = @fopen($sess_file, "w")) {
return(fwrite($fp, $sess_data));
} else {
return(false);
}
1354
Sesiones
$sess_file = "$sess_save_path/sess_$id";
return(@unlink($sess_file));
}
/***********************************************
* ATENCIÓN - Necesitará implementar algún *
* tipo de rutinas recolectoras de basura aquí *
***********************************************/
function rb ($maxlifetime) {
return true;
}
session_start();
?>
session_start (PHP 4 )
Inicializar los datos de una sesión
Nota: Si está usando sesiones basadas en las cookies, debe llamar a session_start() antes de que
haya ninguna salida al navegador.
session_start() registrará un manejador de salida interno para la reescritura de las URL’s si trans-sid
está activado. Si un usuario utiliza ob_gzhandler o algo como ob_start(), el orden del manejador de
1355
Sesiones
salida es importante para que la salida sea la adecuada. Por ejemplo, el usuario debe registrar
ob_gzhandler antes de iniciar la sesión.
session_unregister (PHP 4 )
Desregistrar una variable de la sesión actual
Nota: Si utiliza $_SESSION (o $HTTP_SESSION_VARS con PHP 4.0.6 o inferior), use unset() para
eliminar una variable de la sesión actual.
Atención
Esta función no borra la variable global correspondiente a nombre, sólo evita que
la variable sea guardada como parte de la sesión. Debe llamar a unset() para
eliminar la variable global correspondiente.
Atención
Si está trabajando con $HTTP_SESSION_VARS/$_SESSION, no utilice
session_register(), session_is_registered() ni session_unregister().
session_unset (PHP 4 )
Elimina todas las variables de la sesión
Nota: Si utiliza $_SESSION (o $HTTP_SESSION_VARS con PHP 4.0.6 o inferior), use unset() en su
lugar para desregistrar una variable de la sesión. p.ej. $_SESSION = array();
1356
Sesiones
1357
XCIII. Shared Memory Functions
Shmop is an easy to use set of functions that allows php to read, write, create and delete UNIX shared
memory segments. The functions will not work on windows, as it does not support shared memory. To
use shmop you will need to compile php with the --enable-shmop parameter in your configure line.
Nota: The functions explained in the chapter begin all with shm_() in PHP 4.0.3, but in PHP 4.0.4
and later versions these names are changed to begin with shmop_().
<?php
//Now lets delete the block and close the shared memory segment
if(!shmop_delete($shm_id)) {
echo "Couldn’t mark shared memory block for deletion.
}
shmop_close($shm_id);
?>
1358
shmop
<?php
shmop_close($shm_id);
?>
<?php
shmop_delete($shm_id);
?>
int shmop_open ( int key, string flags, int mode, int size) \linebreak
1359
shmop
• "a" for access (sets IPC_EXCL) use this flag when you need to open an existing shared memory
segment
• "c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory
segment.
The third parameter is the mode, which are the permissions that you wish to assign to your memory
segment, those are the same as permission for a file. Permissions need to be passed in octal form ex.
0644. The last parameter is size of the shared memory block you wish to create in bytes.
Nota: Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment.
On success shmop_open() will return an id that you can use to access the shared memory segment
you’ve created.
<?php
$shm_id = shmop_open(0x0fff, "c", 0644, 100);
?>
<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>
1360
shmop
This example will read 50 bytes from shared memory block and place the data inside $shm_data.
<?php
$shm_size = shmop_size($shm_id);
?>
This example will put the size of shared memory block identified by $shm_id into $shm_size.
<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>
1361
shmop
This example will write data inside $my_string into shared memory block, $shm_bytes_written
will contain the number of bytes written.
1362
XCIV. Shockwave Flash functions
PHP offers the ability to create Shockwave Flash files via Paul Haeberli’s libswf module. You can
download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash. Once you have libswf all you need to do
is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib.
The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If
you unpack the libswf distribution the two files will be in one directory. Consequently you will have to
copy the files to the proper location manually.
Once you’ve successfully installed PHP with Shockwave Flash support you can then go about creating
Shockwave files from PHP. You would be surprised at what you can do, take the following code:
<?php
swf_openfile ("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2 (-100, 100, -100, 100);
swf_defineline (1, -70, 0, 70, 0, .2);
swf_definerect (4, 60, -10, 70, 0, 0);
swf_definerect (5, -60, 0, -70, 10, 0);
swf_addcolor (0, 0, 0, 0);
swf_pushmatrix ();
swf_translate (-50, 80, 0);
swf_placeobject (11, 60);
swf_popmatrix ();
1363
SWF
swf_startdoaction ();
swf_actionstop ();
swf_enddoaction ();
swf_closefile ();
?>
1364
SWF
swf_actiongeturl (PHP 4 )
Get a URL from a Shockwave Flash movie
swf_actiongotoframe (PHP 4 )
Play a frame and then stop
swf_actiongotolabel (PHP 4 )
Display a frame with the specified label
swf_actionnextframe (PHP 4 )
Go foward one frame
swf_actionplay (PHP 4 )
Start playing the flash movie from the current frame
1365
SWF
swf_actionprevframe (PHP 4 )
Go backwards one frame
swf_actionsettarget (PHP 4 )
Set the context for actions
swf_actionstop (PHP 4 )
Stop playing the flash movie at the current frame
swf_actiontogglequality (PHP 4 )
Toggle between low and high quality
swf_actionwaitforframe (PHP 4 )
Skip actions if a frame has not been loaded
1366
SWF
swf_addbuttonrecord (PHP 4 )
Controls location, appearance and active area of the current button
swf_addcolor (PHP 4 )
Set the global add color to the rgba value specified
swf_closefile (PHP 4 )
Close the current Shockwave Flash file
1367
SWF
swf_definebitmap (PHP 4 )
Define a bitmap
swf_definefont (PHP 4 )
Defines a font
swf_defineline (PHP 4 )
Define a line
void swf_defineline ( int objid, float x1, float y1, float x2, float y2, float width) \linebreak
The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given
by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the
y2 parameter. It will have a width defined by the width parameter.
swf_definepoly (PHP 4 )
Define a polygon
void swf_definepoly ( int objid, array coords, int npoints, float width) \linebreak
The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are
defined in the parameter coords). The parameter npoints is the number of overall points that are
contained in the array given by coords. The width is the width of the polygon’s border, if set to 0.0
the polygon is filled.
1368
SWF
swf_definerect (PHP 4 )
Define a rectangle
void swf_definerect ( int objid, float x1, float y1, float x2, float y2, float width) \linebreak
The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y,
y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width
of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.
swf_definetext (PHP 4 )
Define a text string
swf_endbutton (PHP 4 )
End the definition of the current button
swf_enddoaction (PHP 4 )
End the current action
swf_endshape (PHP 4 )
Completes the definition of the current shape
1369
SWF
swf_endsymbol (PHP 4 )
End the definition of a symbol
swf_fontsize (PHP 4 )
Change the font size
swf_fontslant (PHP 4 )
Set the font slant
swf_fonttracking (PHP 4 )
Set the current font tracking
swf_getbitmapinfo (PHP 4 )
Get information about a bitmap
1370
SWF
The swf_getbitmapinfo() function returns an array of information about a bitmap given by the
bitmapid parameter. The returned array has the following elements:
• "size" - The size in bytes of the bitmap.
• "width" - The width in pixels of the bitmap.
• "height" - The height in pixels of the bitmap.
swf_getfontinfo (PHP 4 )
The height in pixels of a capital A and a lowercase x
swf_getframe (PHP 4 )
Get the frame number of the current frame
swf_labelframe (PHP 4 )
Label the current frame
swf_lookat (PHP 4 )
Define a viewing transformation
1371
SWF
void swf_lookat ( double view_x, double view_y, double view_z, double reference_x, double reference_y, dou-
ble reference_z, double twist) \linebreak
The swf_lookat() function defines a viewing transformation by giving the viewing position (the
parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the
reference point is defined by the reference_x, reference_y , and reference_z parameters.
The twist controls the rotation along with viewer’s z axis.
swf_modifyobject (PHP 4 )
Modify an object
swf_mulcolor (PHP 4 )
Sets the global multiply color to the rgba value specified
swf_nextid (PHP 4 )
Returns the next free object id
1372
SWF
swf_oncondition (PHP 4 )
Describe a transition used to trigger an action list
• IdletoOverUp
• OverUptoIdle
• OverUptoOverDown
• OverDowntoOverUp
• OverDowntoOutDown
• OutDowntoOverDown
• OutDowntoIdle
• ButtonEnter (IdletoOverUp|OutDowntoOverDown)
• ButtonExit (OverUptoIdle|OverDowntoOutDown)
swf_openfile (PHP 4 )
Open a new Shockwave Flash file
void swf_openfile ( string filename, float width, float height, float framerate, float r, float g, float b) \linebreak
The swf_openfile() function opens a new file named filename with a width of width and a height of
height a frame rate of framerate and background with a red color of r a green color of g and a
blue color of b.
1373
SWF
The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you
want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and
up).
swf_ortho2 (PHP 4 )
Defines 2D orthographic mapping of user coordinates onto the current viewport
void swf_ortho2 ( double xmin, double xmax, double ymin, double ymax) \linebreak
The swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the
current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective
transformation is desired, the swf_perspective () function can be used.
void swf_ortho ( double xmin, double xmax, double ymin, double ymax, double zmin, double zmax) \linebreak
The swf_ortho() funcion defines a orthographic mapping of user coordinates onto the current viewport.
swf_perspective (PHP 4 )
Define a perspective projection transformation
void swf_perspective ( double fovy, double aspect, double near, double far) \linebreak
The swf_perspective() function defines a perspective projection transformation. The fovy parameter is
field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the
viewport that is being drawn onto. The near parameter is the near clipping plane and the far
parameter is the far clipping plane.
Nota: Various distortion artifacts may appear when performing a perspective projection, this is
because Flash players only have a two dimensional matrix. Some are not to pretty.
swf_placeobject (PHP 4 )
Place an object onto the screen
1374
SWF
swf_polarview (PHP 4 )
Define the viewer’s position with polar coordinates
void swf_polarview ( double dist, double azimuth, double incidence, double twist) \linebreak
The swf_polarview() function defines the viewer’s position in polar coordinates. The dist parameter
gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the
azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence
parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The
incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies
the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.
swf_popmatrix (PHP 4 )
Restore a previous transformation matrix
swf_posround (PHP 4 )
Enables or Disables the rounding of the translation when objects are placed or moved
1375
SWF
swf_pushmatrix (PHP 4 )
Push the current transformation matrix back unto the stack
swf_removeobject (PHP 4 )
Remove an object
swf_rotate (PHP 4 )
Rotate the current transformation
swf_scale (PHP 4 )
Scale the current transformation
swf_setfont (PHP 4 )
Change the current font
1376
SWF
The swf_setfont() sets the current font to the value given by the fontid parameter.
swf_setframe (PHP 4 )
Switch to a specified frame
swf_shapearc (PHP 4 )
Draw a circular arc
void swf_shapearc ( float x, float y, float r, float ang1, float ang2) \linebreak
The swf_shapeArc() function draws a circular arc from angle A given by the ang1 parameter to angle B
given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and
a y coordinate given by the y, the radius of the circle is given by the r parameter.
swf_shapecurveto3 (PHP 4 )
Draw a cubic bezier curve
void swf_shapecurveto3 ( float x1, float y1, float x2, float y2, float x3, float y3) \linebreak
Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points
and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair
given by x3,y3.
swf_shapecurveto (PHP 4 )
Draw a quadratic bezier curve between two points
void swf_shapecurveto ( float x1, float y1, float x2, float y2) \linebreak
The swf_shapecurveto() function draws a quadratic bezier curve from the x coordinate given by x1 and
the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The
current position is then set to the x,y coordinates given by the x2 and y2 parameters
1377
SWF
swf_shapefillbitmapclip (PHP 4 )
Set current fill mode to clipped bitmap
swf_shapefillbitmaptile (PHP 4 )
Set current fill mode to tiled bitmap
swf_shapefilloff (PHP 4 )
Turns off filling
swf_shapefillsolid (PHP 4 )
Set the current fill style to the specified color
swf_shapelinesolid (PHP 4 )
Set the current line style
1378
SWF
The swf_shapeLineSolid() function sets the current line style to the color of the rgba parameters and
width to the width parameter. If 0.0 is given as a width then no lines are drawn.
swf_shapelineto (PHP 4 )
Draw a line
swf_shapemoveto (PHP 4 )
Move the current position
swf_showframe (PHP 4 )
Display the current frame
swf_startbutton (PHP 4 )
Start the definition of a button
1379
SWF
swf_startdoaction (PHP 4 )
Start a description of an action list for the current frame
swf_startshape (PHP 4 )
Start a complex shape
swf_startsymbol (PHP 4 )
Define a symbol
swf_textwidth (PHP 4 )
Get the width of a string
swf_translate (PHP 4 )
Translate the current transformations
1380
SWF
swf_viewport (PHP 4 )
Select an area for future drawing
void swf_viewport ( double xmin, double xmax, double ymin, double ymax) \linebreak
The swf_viewport() function selects an area for future drawing for xmin to xmax and ymin to ymax,
if this function is not called the area defaults to the size of the screen.
1381
XCV. Funciones SNMP
Para usar las funciones SNMP en Unix necesita instalar el paquete UCD SNMP
(http://net-snmp.sourceforge.net/). En Windows estas funciones están solamente disponibles en NT y no
en Win95/98.
Importante: Para usar el paquete UCD SNMP, necesita definir NO_ZEROLENGTH_COMMUNITY a 1
antes de compilarlo. Despues de configurar UCD SNMP, edite config.h y busque
NO_ZEROLENGTH_COMMUNITY. Descomente la línea #define. Debería de verse como sigue:
#define NO_ZEROLENGTH_COMMUNITY 1
Si ve faltas de segmentación desconocidas en combinación con los comandos SNMP, no siga las
siguientes instrucciones. Si no desea recompilar UCD SNMP, puede compilar PHP con la opción
--enable-ucd-snmp-hack la cual trabajará entorno a las mismas características.
1382
SNMP
$quickprint = snmp_get_quick_print();
La llamada a la función superior podría devolver FALSE si quick_print está activo, y TRUE si quick_print
está activo.
snmp_get_quick_print() está solamente disponible cuando estemos usando la biblioteca UCD SNMP.
Esta función no está disponible cuando estemos usando la biblioteca Windows SNMP.
Ver: snmp_get_quick_print() para una descripción completa de lo que hace quick_print.
snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a<BR>\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a<BR>\n";
El primer valor impreso debe de ser: ’Timeticks: (0) 0:00:00.00’, donde qick_print se activa, solo se
imprimira ’0:00:00.00’.
Por defecto la biblioteca UCD SNMP devuelve valores detallados, quick_print es usado para devolver
solamente el valor.
1383
SNMP
Las cadenas son mantenidas normalmente con comillas extra, esto será corregido en versiones
posteriores.
snmp_get_quick_print() está sólo disponible cuando estemos usando la biblioteca UCD SNMP. Esta
función no está disponible cuando estemos usando la biblioteca Windows SNMP.
string snmpget ( string hostname, string community, string object_id [, int timeout [, int retries]]) \linebreak
Devuelve el valor de un objeto SNMP en caso de exito y FALSE en caso de error.
La función snmpget() es usada para leer el valor de un objeto SNMP especificado por el object_id.
El agente SNMP es especificado por el hostname y la comunidad lectora es especificada por el
parametro community.
array snmprealwalk ( string host, string community, string object_id [, int timeout [, int retries]]) \linebreak
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
string snmpget ( string hostname, string community, string object_id, string type, mixed value [, int timeout [,
int retries]]) \linebreak
1384
SNMP
Establece el valor especificado para el objeto SNMP, devolviendo TRUE en caso de exito o FALSE en
caso de error.
La función snmpset() es usada para establecer el valor de un objeto SNMP especificado por el
object_id. El agente SNMP es espcificado por el hostname y la comunidad lectora por el
parametro community.
array snmpwalk ( string hostname, string community, string object_id [, int timeout [, int retries]]) \linebreak
Devuelve una matriz de valores de objetos SMNP comenzando por el object_id() como raíz y FALSE en
caso de error.
La función snmpwalk() es usada para leer todos los valores de un agente SNMP especificado por el
hostname. Community especifica la comunidad lectora para el agente. Un object_id nulo se
toma como la raíz del arbol de los objetos SNMP y todos los objetos por debajo de ese arbol son
devueltos como una matriz. Si object_id es especificado, todos los objetos SNMP por debajo de
object_id son devueltos.
Encima de una función de llamada podrían devolverse todos los objetos SNMP del agente SNMP en
ejecución en el servidor local. Uno puede pasar por todos los valores con un bucle.
array snmpwalkoid ( string hostname, string community, string object_id [, int timeout [, int retries]]) \linebreak
Devuelve una matriz asociativa con los identificadores de los objetos y sus respectivos valores
comenzando por el object_id como raíz y FALSE en caso de error.
La función snmpwalkoid() es usada para leer todos los identificadores de objetos y sus respectivos
valores de un agente SNMP especificado por el nombre del servidor. La lectura de community
1385
SNMP
especifica la comunidad para el agente. Un object_id nulo es tomado como la raíz del arbol de
objetos SNMP y todos los objetos por debajo de este arbol son devueltos como una matriz. Si
object_id es especificado, todos los objetos SNMP inferiores al object_id son devueltos.
La existencia de snmpwalkoid() y snmpwalk() tiene razones historicas. Ambas funciones son
proporcionadas para compatibilidad hacia atrás.
La llamada a las funciones superiores devuelve todos los objetos SNMP del agente SNMP en ejecución
en el servidor local. Uno puede pasar por todos los valores con un bucle.
1386
XCVI. Socket functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
The socket extension implements a low-level interface to the socket communication functions, providing
the possibility to act as a socket server as well as a client.
For a more generic client-side socket interface, see fsockopen() and pfsockopen().
When using the socket functions described here, it is important to remember that while many of them
have identical names to their C counterparts, they often have different declarations. Please be sure to read
the descriptions to avoid confusion.
That said, those unfamiliar with socket programming can still find a lot of useful material in the
appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C
on the web, much of which can be applied, with slight modifications, to socket programming in PHP.
This example shows a simple talkback server. Change the address and port variables to suit your setup
and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000
(where the address and port match your setup). Anything you type will then be output on the server side,
and echoed back to you. To disconnect, enter ’quit’.
<?php
error_reporting(E_ALL);
$address = ’192.168.1.53’;
$port = 10000;
do {
if (($msgsock = accept_connect($sock)) < 0) {
1387
Sockets
close($sock);
?>
This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD
request, echoes the reply, and exits.
<?php
error_reporting(E_ALL);
1388
Sockets
1389
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
After the socket socket has been created using socket_create(), bound to a name with socket_bind(),
and told to listen for connections with socket_listen(), this function will accept incoming connections on
that socket. Once a successful connection is made, a new socket resource is returned, which may be used
for communication. If there are multiple connections queued on the socket, the first will be used. If there
are no pending connections, socket_accept() will block until a connection becomes present. If socket
has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), FALSE will be
returned.
The socket resource returned by socket_accept() may not be used to accept new connections. The
original listening socket socket, however, remains open and may be reused.
Returns a new socket resource on success, or FALSE on error. The actual error code can be retrieved by
calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual
explanation of the error.
See also socket_bind(), socket_connect(), socket_listen(), socket_create(), and socket_strerror().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
socket_bind() binds the name given in address to the socket described by socket, which must be a
valid socket resource created with socket_create().
The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket
is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.
1390
Sockets
The port parameter is only used when connecting to an AF_INET socket, and designates the port on the
remote host to which a connection should be made.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. The error code can be retrieved with
socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_connect(), socket_listen(), socket_create(), socket_last_error() and socket_strerror().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
This function clears the error code on the given socket or the global last socket error.
This function allows explicitely resetting the error code value either of a socket or of the extension global
last error code. This may be useful to detect within a part of the application if an error occured or not.
See also socket_last_error() and socket_strerror().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Nota: socket_close() can’t be used on PHP file resources created with fopen(), popen(),
fsockopen(), or psockopen(); it is meant for sockets created with socket_create() or socket_accept().
1391
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Initiates a connection using the socket resource socket, which must be a valid socket resource created
with socket_create().
The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket
is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.
The port parameter is only used when connecting to an AF_INET socket, and designates the port on the
remote host to which a connection should be made.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. The error code can be retrieved with
socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_bind(), socket_listen(), socket_create(), socket_last_error() and socket_strerror().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
This function is meant to ease the task of creating a new socket which only listens to accept new
connections.
socket_create_listen() create a new socket resource of type AF_INET listening on all local interfaces on
the given port waiting for new connections.
1392
Sockets
The backlog parameter defines the maximum length the queue of pending connections may grow to.
SOMAXCONN may be passed as backlog parameter, see socket_listen() for more information.
socket_create_listen() returns a new socket resource on success or FALSE on error. The error code can
be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual
explanation of the error.
Nota: If you want to create a socket which only listens on a certain interfaces you need to use
socket_create(), socket_bind() and socket_listen().
bool socket_create_pair ( int domain, int type, int protocol, array &fd) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1393
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Nota: If an invalid domain or type is given, socket_create() defaults to AF_INET and SOCK_STREAM
respectively and additionally emits an E_WARNING message.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1394
Sockets
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
If the given socket is of type AF_INET, socket_getpeername() will return the peers (remote) IP address
in dotted-quad notation (e.g. 127.0.0.1) in the address parameter and, if the optional port
parameter is present, also the associated port.
If the given socket is of type AF_UNIX, socket_getpeername() will return the UNIX filesystem path (e.g.
/var/run/daemon.sock) in the address parameter.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. socket_getpeername() may also return FALSE
if the socket type is not any of AF_INET or AF_UNIX, in which case the last socket error code is not
updated.
See also socket_getpeername(), socket_last_error() and socket_strerror().
1395
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
If the given socket is of type AF_INET, socket_getsockname() will return the local IP address in
dotted-quad notation (e.g. 127.0.0.1) in the address parameter and, if the optional port parameter
is present, also the associated port.
If the given socket is of type AF_UNIX, socket_getsockname() will return the UNIX filesystem path
(e.g. /var/run/daemon.sock) in the address parameter.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. socket_getsockname() may also return FALSE
if the socket type is not any of AF_INET or AF_UNIX, in which case the last socket error code is not
updated.
See also socket_getpeername(), socket_last_error() and socket_strerror().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1396
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1397
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1398
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Nota: socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.
1399
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
After the socket socket has been created using socket_create() and bound to a name with
socket_bind(), it may be told to listen for incoming connections on socket.
A maximum of backlog incoming connections will be queued for processing. If a connection request
arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, if the
underlying protocol supports retransmission, the request may be ignored so that retries may succeed.
Nota: The maximum number passed to the backlog parameter highly depends on the underlying
platform. On linux, it is silently truncated to SOMAXCONN. On win32, if passed SOMAXCONN, the
underlying service provider responsible for the socket will set the backlog to a maximum reasonable
value. There is no standard provision to find out the actual backlog value on this platform.
1400
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
The function socket_read() reads from the socket resource socket created by the socket_create() or
socket_accept() functions. The maximum number of bytes read is specified by the length parameter.
Otherwise you can use \r, \n, or \0 to end reading (depending on the type parameter, see below).
socket_read() returns the data as a string on success, or FALSE on error. The error code can be retrieved
with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of
the error.
Nota: socket_read() may return a zero length string ("") indicating the end of communication (i.e.
the remote end point has closed the connection).
• PHP_BINARY_READ - use the system read() function. Safe for reading binary data. (Default in
PHP >= 4.1.0)
• PHP_NORMAL_READ - reading stops at \n or \r. (Default in PHP <= 4.0.6)
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1401
Sockets
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
int socket_recvfrom ( resource socket, string &buf, int len, int flags, string &name [, int &port]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1402
Sockets
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool socket_recvmsg ( resource socket, resource iovec, array &control, int &controllen, int &flags, string &addr
[, int &port]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
int socket_select ( resource &read, resource &write, resource &except, int tv_sec [, int tv_usec]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1403
Sockets
The socket_select() accepts arrays of sockets and waits for them to change status. Those coming with
BSD sockets background will recognize that those socket resource arrays are in fact the so-called file
descriptor sets. Three independent arrays of socket resources are watched.
The sockets listed in the read array will be watched to see if characters become available for reading
(more precisely, to see if a read will not block - in particular, a socket resource is also ready on
end-of-file, in which case a socket_read() will return a zero length string).
The sockets listed in the write array will be watched to see if a write will not block.
The sockets listed in the except array will be watched for exceptions.
Aviso
On exit, the arrays are modified to indicate which socket resource actually
changed status.
You do not need to pass every array to socket_select(). You can leave it out and use an empty array or
NULL instead. Also do not forget that those arrays are passed by reference and will be modified after
socket_select() returns.
Example:
Nota: Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like
NULL directly as a parameter to a function which expects this parameter to be passed by reference.
Instead use a temporary variable or an expression with the leftmost member being a temporary
variable:
The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the
amount of time elapsed before socket_select() return. tv_sec may be zero , causing socket_select() to
1404
Sockets
return immediately. This is useful for polling. If tv_sec is NULL (no timeout), socket_select() can
block indefinitely.
On success socket_select() returns the number of socket resorces contained in the modified arrays,
which may be zero if the timeout expires before anything interesting happens. On error FALSE is
returned. The error code can be retrieved with socket_last_error().
Nota: Be sure to use the === operator when checking for an error. Since the socket_select() may
return 0 the comparison with == would evaluate to TRUE:
Nota: Be aware that some socket implementations need to be handled very carefully. A few basic
rules:
• You should always try to use socket_select() without timeout. Your program should have nothing
to do if there is no data available. Code that depends on timeouts is not usually portable and
difficult to debug.
• No socket resource must be added to any set if you do not intend to check its result after the
socket_select() call, and respond appropriately. After socket_select() returns, all socket
resources in all arrays must be checked. Any socket resource that is available for writing must be
written to, and any socket resource available for reading must be read from.
• If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write
the full amount of data you have requested. Be prepared to even only be able to read/write a
single byte.
• It’s common to most socket implementations that the only exception caught with the except
array is out-of-bound data received on a socket.
int socket_send ( resource socket, string buf, int len, int flags) \linebreak
1405
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool socket_sendmsg ( resource socket, resource iovec, int flags, string addr [, int port]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
int socket_sendto ( resource socket, string buf, int len, int flags, string addr [, int port]) \linebreak
1406
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool socket_set_option ( resource socket, int level, int optname, int ) \linebreak
1407
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1408
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
socket_strerror() takes as its errno parameter a socket error code as returned by socket_last_error()
and returns the corresponding explanatory text. This makes it a bit more pleasant to figure out why
something didn’t work; for instance, instead of having to track down a system include file to find out
what ’-111’ means, you just pass it to socket_strerror(), and it tells you what happened.
<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, 0))) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
The expected output from the above example (assuming the script is not run with root privileges):
socket_bind() failed: reason: Permission denied
1409
Sockets
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Nota: socket_write() does not necessarily write all bytes from the given buffer. It’s valid that,
depending on the network buffers etc., only a certain amount of data, even one byte, is written
though your buffer is greater. You have to watch out so you don’t unintentionally forget to transmit the
rest of your data.
Nota: It is perfectly valid for socket_write() to return zero which means no bytes have been written.
Be sure to use the === operator to check for FALSE in case of an error.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1410
Sockets
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1411
XCVII. Funciones de cadenas
Todas estas funciones manipulan cadenas de varias maneras. En las secciones sobre expresiones
regulares y manejo de URL se pueden encontrar secciones más especializadas.
1412
Cadenas
AddCSlashes (PHP 4 )
Marca una cadena con barras al estilo del C
1413
Cadenas
Esta función complementa a ord(). Vea también sprintf() con una cadena de formato %c.
1414
Cadenas
count_chars (PHP 4 )
Devuelve información sobre los caracteres usados en una cadena
1415
Cadenas
• 2 - como el 0, pero listando únicamente los valores de byte con frecuencia igual a 0.
• 3 - se devuelve una cadena que contiene todos los valores de byte utilizados.
• 4 - se devuelve una cadena que contiene todos los valores de byte no utilizados.
1416
Cadenas
echo (unknown)
Da salida a una o más cadenas
Nota: De hecho, si desea pasar más de un parámetro a echo no debe encerrarlos entre paréntesis.
1417
Cadenas
Devuelve una matriz de cadenas, cada una de las cuales es una subcadena de cadena formada mediante
su división en las fronteras marcadas por la cadena separador. Si se especifica limite, la matriz
devuelta contendrá un máximo de limite elementos con el último conteniendo el resto de la cadena.
get_html_translation_table (PHP 4 )
Devuelve la tabla de traducción utilizada por htmlspecialchars() y htmlentities()
1418
Cadenas
(preste atención a los finales de línea - el PHP utiliza una función nativa para trocear la entrada, de modo
que un archivo de Mac no funcionará en Unix).
El valor de la propiedad name queda como clave y el valor de la propiedad content queda como el valor
de la matriz devuelta, de modo que pueda usar fácilmente funciones estándar de matrices para recorrerla
o para acceder a valores individuales. Los caracteres especiales en el valor de name son sustituídos por
’_’ y el resto es convertido a minúsculas.
Fijando use_ruta_include a 1 hará que el PHP intente abrir el archivo a través de la ruta de
inclusión.
1419
Cadenas
Nótese que esta función no traduce nada más que lo mostrado más arriba. Para una traducción de
entidades completa, vea htmlentities().
Vea también htmlentities() y nl2br().
1420
Cadenas
1421
Cadenas
1422
Cadenas
The grouping fields contain arrays that define the way numbers should be grouped. For example, the
grouping field for the en_US locale, would contain a 2 item array with the values 3 and 3. The higher the
index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further
grouping is done. If an array element is equal to 0, the previous element should be used.
setlocale(LC_ALL, "en_US");
$locale_info = localeconv();
echo "<PRE>\n";
echo "--------------------------------------------\n";
echo " Monetary information for current locale: \n";
echo "--------------------------------------------\n\n";
1423
Cadenas
The constant CHAR_MAX is also defined for the use mentioned above.
See also: setlocale().
1424
Cadenas
metaphone (PHP 4 )
Calcula la clave "metáfona" de una cadena
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1425
Cadenas
$cad = "primero=valor&segundo[]=esto+funciona&segundo[]=otro";
parse_str($cad);
echo $primero; /* escribe "valor" */
echo $segundo[0]; /* escribe "esto funciona" */
echo $segundo[1]; /* escribe "otro" */
print (unknown)
Emite una cadena
1426
Cadenas
. \\ + * ? [ ^ ] ( $ )
1427
Cadenas
Si localidad es la cadena vacía "", los nombres de localidad se fijarán a partir de las variables de
entorno con los mismos nombres de las categorías anteriores, o desde "LANG".
Si la localidad es cero o "0", el ajuste de localidad no se ve afectado y sólo se devuelve el ajuste actual.
setlocale devuelve la nueva localidad, o FALSE si la funcionalidad de localización no está disponible en
la plataforma, la localidad especificada no existe o el nombre de categoría no es válido. Un nombre de
categoría no válido también produce un mensaje de aviso.
1428
Cadenas
Pasando una referencia como tercer argumento, similar_text() calculará para usted la similitud como
porcentaje. Devuelve el número de caracteres coincidentes en ambas cadenas.
1. Un especificador de relleno opcional que indica qué caracter se utilizará para rellenar el resultado
hasta el tamaño de cadena correcto. Este puede ser un espacio o un 0 (caracter cero). El valor por
defecto es rellenar con espacios. Un caracter de relleno alternativo se puede especificar prefijándolo
con una comilla simple (’). Vea los ejemplos más abajo.
1429
Cadenas
2. Un especificador de alineación opcional que indica si el resultado debe ser alineado a la izquierda o
a la derecha. Por defecto se alinea a la derecha; un caracter - aquí lo justificará a la izquierda.
3. Un número opcional, un especificador de ancho que dice el número de caracteres (mínimo) en que
debería resultar esta conversión.
4. Un especificador de precisión opcional que indica cuántos dígitos decimales deben mostrarse para
los números en coma flotante. Esta opción no tienen efecto para otros tipos que no sean double.
(Otra función útil para formatear números es number_format()).
5. Un especificador de tipo que indica el tipo a usar para tratar los datos de los argumentos. Los tipos
posibles son:
% - un caracter literal de porcentaje. No se precisa argumento.
b - el argumento es tratado como un entero y presentado como un número binario.
c - el argumento es tratado como un entero, y presentado como el caracter con dicho valor ASCII.
d - el argumento es tratado como un entero y presentado como un número decimal.
f - el argumento es tratado como un doble y presentado como un número de coma flotante.
o - el argumento es tratado como un entero, y presentado como un número octal.
s - el argumento es tratado como una cadena y es presentado como tal.
x - el argumento es tratado como un entero y presentado como un número hexadecimal (con minúsculas).
X - el argumento es tratado como un entero y presentado como un número hexadecimal (con mayúsculas).
$pelas1 = 68.75;
$pelas2 = 54.35;
$pelas = $pelas1 + $pelas2;
// echo $pelas mostrará "123.1";
$formateado = sprintf ("%01.2f", $pelas);
// echo $formateado mostrará "123.10"
1430
Cadenas
La funciónsscanf() es la función de entrada análoga de printf(). sscanf() lee del parámetro de cadena
cad y lo interpreta según el formato especificado. Si sólo se pasan dos parámetros a esta función, los
valores devueltos se harán en una matriz.
Si se pasan los parámetros opcionales, la función devolverá el número de valores asignados. Los
parámetros opcionales deben ser pasados por referencia.
string str_pad ( string entrada, int tama_relleno [, string cad_relleno [, int tipo_relleno]]) \linebreak
Esta función rellena la cadena entrada por la derecha, la izquierda o por ambos lados hasta el largo
indicado. Si no se especifica el argumento opcional cad_relleno, entrada es rellenada con
espacios. En caso contrario, será rellenada con los caracteres de cad_relleno hasta el límite.
El argumento opcional tipo_relleno puede valer STR_PAD_RIGHT, STR_PAD_LEFT, o
STR_PAD_BOTH. Si no se especifica, se asume que vale STR_PAD_RIGHT.
Si el valor de tama_relleno es negativo o menor que la longitud de la cadena de entrada, no se
produce rellenado alguno.
1431
Cadenas
$entrada = "Alien";
print str_pad($entrada, 10); // produce "Alien "
print str_pad($entrada, 10, "-=", STR_PAD_LEFT); // produce "-=-=-Alien"
print str_pad($entrada, 10, "_", STR_PAD_BOTH); // produce "__Alien___"
str_repeat (PHP 4 )
Repite una cadena
1432
Cadenas
Nota: str_replace() fue añadida en PHP 3.0.6, pero tuvo errores hasta el PHP 3.0.8.
$var1 = "Hello";
$var2 = "hello";
if (!strcasecmp ($var1, $var2)) {
echo ’$var1 es igual a $var2 en una comparación sin tener en cuenta ’
.’mayúsculas o minúsculas’;
}
1433
Cadenas
1434
Cadenas
Puede usar el parámetro opcional para especificar las etiquetas que no deben eliminarse.
stripcslashes (PHP 4 )
Desmarca la cadena marcada con addcslashes()
1435
Cadenas
strnatcasecmp (PHP 4 )
Comparación de cadenas insensible a mayúsculas y minúsculas usando un algoritmo de "orden natural"
strnatcmp (PHP 4 )
Compara cadenas usando un algoritmo de "orden natural"
1436
Cadenas
Para más información, vea la página de Martin Pool sobre Comparación de Cadenas en Orden Natural
(http://naturalordersort.org/).
De forma similar a otras funciones de comparación de cadenas, esta devuelve < 0 si cad1 es menor que
cad2; > 0 si cad1 es mayor que cad2, y 0 si son iguales.
Nótese que esta comparación es sensible a mayúsculas y minúsculas.
Vea también ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strnatcasecmp(), y strstr().
strncmp (PHP 4 )
Comparación de los n primeros caracteres de cadenas, con seguridad binaria
1437
Cadenas
Nota: Es fácil confundir los valores de retorno para "caracter encontrado en la posición 0" y
"caracter no encontrado". Aquí se indica cómo detectar la diferencia:
Si la aguja no es una cadena, se convierte a entero y se aplica como el valor ordinal de un caracter.
El parámetro opcional desplazamiento le permite especificar a partir de qué caracter del pajar
comenzar a buscar. La posición devuelta es aún relativa al comienzo de pajar.
Vea también strrpos(), strrchr(), substr(), stristr(), y strstr().
1438
Cadenas
1439
Cadenas
Nota: Nótese que esta función es sensible a mayúsculas y minúsculas. Para búsquedas no
sensibles, utilice stristr().
$email = ’[email protected]’;
$dominio = strstr ($email, ’@’);
print $dominio; // imprime @designmultimedia.com
1440
Cadenas
Nótese que sólo la primera llamada a strtok utiliza el argumento cadena. Cada llamada subsiguiente
necesita sólo el divisor a utilizar, puesto que ella guarda la posición actual en la cadena. Para comenzar
de nuevo o para dividir otra cadena, simplemente llame a strtok con el argumento de cadena y se
inicializará. Nótese que puede poner divisores múltiples como parámetro. La cadena será dividida
cuando alguno de los caracteres del argumento sea hallado.
Además tenga cuidado si sus divisores valen "0", pues evalúa como FALSE en las expresiones
condicionales.
Vea también split() y explode().
1441
Cadenas
strtr() puede llamarso sólo con dos argumentos. Si se llama de esta manera, se comporta de otro modo:
desde debe ser entonces una matriz que contenga pares cadena -> cadena que serán sustituídos en la
1442
Cadenas
cadena fuente. strtr() siempre buscará la coincidencia más larga primero y *NO* intentará sustituir nada
en lo que haya trabajado ya.
Ejemplos:
substr_count (PHP 4 )
Cuenta el número de apariciones de la subcadena
substr_replace (PHP 4 )
Sustituye texto en una parte de una cadena
string substr_replace ( string cadena, string sustituto, int comienzo [, int largo]) \linebreak
substr_replace() sustituye la parte de cadena delimitada por los parámetros comienzo y
(opcionalmente) largo por la cadena dada en sustituto. Se devuelve el resultado.
Si comienzo es positivo, la sustitución comenzará en dicha posición dentro de la cadena.
Si comienzo es negativo, la sustitución comenzará en dicha posición pero contando desde el final de
cadena.
Si se especifica el largo y es positivo, representa el largo de la porción de cadena a sustituir. Si es
negativo, representa el número de caracteres desde el final de cadena en los que dejar de sustituir. Si no
se especifica, valdrá por defecto strlen(cadena); es decir, que acabará la sustitución al final de cadena.
1443
Cadenas
<?php
$var = ’ABCDEFGH:/MNRPQR/’;
echo "Original: $var<hr>\n";
Si comienzo es negativo, la cadena devuelta comenzará en dicha posición desde el final de cadena.
Ejemplos:
1444
Cadenas
Si se especifica largo y es positivo, la cadena devuelta terminará largo caracteres tras el comienzo.
Si esto resulta en una cadena con longitud negativa (porque el comienzo está pasado el final de la
cadena), la cadena devuelta contendrá únicamente el caracter que haya en comienzo.
Si se especifica largo y es negativo, la cadena devuelta terminará a largo caracteres desde el final de
cadena. Si esto resulta en una cadena con longitud negativa, la cadena devuelta contendrá únicamente
el caracter que haya en comienzo.
Examples:
1445
Cadenas
1446
Cadenas
echo "$textonuevo\n";
El veloz murciélago
hindú comía feliz cardillo y kiwi.
1447
XCVIII. Funciones de Sybase
1448
Sybase
Nota: Esta función sólo esta disponible usando el interface de la librería CT, y no con la librería DB.
1449
Sybase
En el caso que se haga una segunda llamada a sybase_connect() con los mismos argumentos, no se
establecerá un nuevo enlace, en vez de esto, se devolverá el identificador de enlace que ya está abierto.
El enlace al servidor será cerrado tan pronto como la ejecución del script finalice, a menos que sea
cerrado antes llamando explicitamente a sybase_close().
Vea también sybase_pconnect(), sybase_close().
1450
Sybase
sybase_fetch_field() puede usarse para obtener información sobre los campos de una consulta
determinada. Si no se especifica el offset del campo, el siguiente campo que aún no halla sido tomado
por sybase_fetch_field() es el que se obtiene.
Las propiedades del objeto son:
• name - column name. si la columna es el resultado de una función, esta propiedad se establece a
computed#N, donde #N es un número de serie.
• column_source - la tabla de la cual se ha cogido la columna
• max_length - máxima longitud de la columna
• numeric - 1 si la columna es numérica
Vea también sybase_field_seek()
1451
Sybase
Nota: This function is only available using the CT library interface to Sybase, and not the DB library.
1452
Sybase
Nota: This function is only available using the CT library interface to Sybase, and not the DB library.
1453
Sybase
1454
Sybase
1455
XCIX. Tokenizer functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1456
Tokenizer functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1457
C. Funciones URL
1458
URLs
foo%20bar%40baz
1459
URLs
decodes into
foo bar@baz
Nota: rawurldecode() does not decode plus symbols (’+’) into spaces. urldecode() does.
-_.
have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in
RFC1738 for protecting literal characters from being interpreted as special URL delimiters, and for
protecting URL’s from being mangled by transmission media with character conversions (like some
email systems). For example, if you want to include a password in an FTP URL:
1460
URLs
1461
CI. Funciones sobre variables
1462
Variables
empty (unknown)
Determina si una variable está definida
$var = ’122.34343The’;
$float_value_of_var = floatval ($var);
print $float_value_of_var; // prints 122.34343
1463
Variables
$b = array(1,1,2,3,5,8);
$arr = get_defined_vars();
// print $b
print_r($arr["b"]);
$c = mysql_connect();
echo get_resource_type($c)."\n";
// prints: mysql link
$fp = fopen("foo","w");
1464
Variables
echo get_resource_type($fp)."\n";
// prints: file
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc)."\n";
// prints: domxml document
• "integer"
• "double"
• "string"
• "array"
• "object"
• "unknown type"
1465
Variables
The prefix parameter is used as a variable name prefix, prepended before all variable’s name imported
into the global scope. So if you have a GET value named "userid", and provide a prefix "pref_", then
you’ll get a global variable named $pref_userid.
If you’re interested in importing other variables into the global scope, such as SERVER, consider using
extract().
Nota: Although the prefix parameter is optional, you will get an E_NOTICE level error if you
specify no prefix, or specify an empty string as a prefix. This is a possible security hazard. Notice
level errors are not displayed using the default error reporting level.
print $rvar_foo;
1466
Variables
is_bool (PHP 4 )
Finds out whether a variable is a boolean
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1467
Variables
1468
Variables
is_numeric (PHP 4 )
Finds whether a variable is a number or a numeric string
is_resource (PHP 4 )
Finds whether a variable is a resource
1469
Variables
Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource
or not scalar.
function show_var($var) {
if (is_scalar($var)) {
echo $var;
} else {
var_dump($var);
}
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");
show_var($pi);
// prints: 3.1416
show_var($proteins)
// prints:
// array(3) {
// [0]=>
// string(10) "hemoglobin"
// [1]=>
// string(20) "cytochrome c oxidase"
// [2]=>
// string(10) "ferredoxin"
// }
Nota: is_scalar() does not consider resource type values to be scalar as resources are abstract
datatypes which are currently based on integers. This implementation detail should not be relied
upon, as it may change.
See also is_bool(), is_numeric(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array(), and
is_integer().
1470
Variables
isset (unknown)
Determina si una varible está definida
$a = "test";
echo isset($a); // true
unset($a);
echo isset($a); // false
print_r (PHP 4 )
Prints human-readable information about a variable
Sugerencia: Como con todo lo que presenta un resultado directamente en el navegador, se pueden
utilizar las funciones de control de salida para capturar el resultado de esta función y grabarlo - por
ejemplo - in una cadena literal.
<pre>
<?php
$a = array (’a’ => ’apple’, ’b’ => ’banana’, ’c’ => array (’x’,’y’,’z’));
print_r ($a);
1471
Variables
?>
</pre>
<pre>
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
</pre>
Nota: Prior to PHP 4.0.4, print_r() will continue forever if given an array or object that contains a
direct or indirect reference to itself. An example is print_r($GLOBALS) because $GLOBALS is itself a
global variable that contains a reference to itself.
1472
Variables
Nota: In PHP 3, object properties will be serialized, but methods are lost. PHP 4 removes that
limitation and restores both properties and methods. Please see the Serializing Objects section of
Classes and Objects for more information.
• "integer"
• "double"
• "string"
• "array"
• "object"
1473
Variables
Devuelve TRUE si se lleva a cabo con éxito; en otro caso devuelve FALSE.
Ver también gettype().
Nota: It’s possible to set a callback-function which will be called, if an undefined class should be
instanciated during unserializing. (to prevent getting an incomplete object
"__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess-file to define
’unserialize_callback_func’. Everytime an undefined class should be instanciated, it’ll be called. To
disable this feature just empty this setting.
$serialized_object=’O:1:"a":1:{s:5:"value";s:3:"100";}’;
function mycallback($classname) {
// just include a file containing your classdefinition
// you get $classname to figure out which classdefinition is required
}
1474
Variables
Nota: In PHP 3, methods are not preserved when unserializing a serialized object. PHP 4 removes
that limitation and restores both properties and methods. Please see the Serializing Objects section
of Classes and Objects or more information.
unset (unknown)
Destruye una variable dada
unset( $foo );
unset( $bar[’quux’] );
1475
Variables
Sugerencia: Como con todo lo que presenta un resultado directamente en el navegador, se pueden
utilizar las funciones de control de salida para capturar el resultado de esta función y grabarlo - por
ejemplo - in una cadena literal.
<pre>
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_dump ($a);
/* output:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
*/
$b = 3.1;
$c = TRUE;
var_dump($b,$c);
/* output:
float(3.1)
1476
Variables
bool(true)
*/
?>
</pre>
<pre>
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export ($a);
/* output:
array (
0 => 1,
1 => 2,
2 =>
array (
0 => ’a’,
1 => ’b’,
2 => ’c’,
),
)
*/
$b = 3.1;
$v = var_export($b, TRUE);
echo $v;
/* output:
3.1
*/
?>
</pre>
1477
Variables
1478
CII. vpopmail functions
1479
vpopmail functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1480
vpopmail functions
bool vpopmail_add_domain_ex ( string domain, string passwd [, string quota [, string bounce [, bool apop]]])
\linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
bool vpopmail_add_domain ( string domain, string dir, int uid, int gid) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1481
vpopmail functions
bool vpopmail_add_user ( string user, string domain, string password [, string gecos [, bool apop]]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1482
vpopmail functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1483
vpopmail functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1484
vpopmail functions
bool vpopmail_auth_user ( string user, string domain, string password [, string apop]) \linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1485
vpopmail functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1486
vpopmail functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1487
vpopmail functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1488
CIII. W32api functions
1489
W32api functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1490
W32api functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1491
W32api functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1492
CIV. Funciones WDDX
Estas funciones permiten el uso de WDDX (http://www.openwddx.org/).
Debe saber que todas las funciones que serializan variables usan el primer elemento de un array para
determinar si este ha de serializarse en forma de array o como estructura. Si el primer elemento esta
indexado por una cadena, se serializa como estructura, y en caso contrario, como array.
<?php
print wddx_serialize_value("Ejemplo de PHP a paquete WDDX", "Paquete PHP");
?>
<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");
$packet = wddx_packet_end($packet_id);
print $packet;
?>
1493
WDDX
1494
WDDX
<?php
$a = 1;
$b = 5.5;
$c = array("azul", "naranja", "violeta");
$d = "colores";
1495
CV. Funciones de intérprete XML
Introducción
Acerca de XML
XML (eXtensible Markup Language) es un formato de información para el intercambio de documentos
estructurado en la "Web" Es un estándar definido por el consorcio de la "World Wide Web" (W3C). Se
puede encontrar información sobre XML y tecnologís relacionadas en http://www.w3.org/XML/.
Instalación
Esta extensión usa expat, que se puede encontrar en http://www.jclark.com/xml/. El Makefile que viene
con expat no crea una biblioteca por defecto, se puede usar esta regla de make para eso:
libexpat.a: $(OBJS)
ar -rc $@ $(OBJS)
ranlib $@
1496
XML
XML. Cada intérprete XML tiene también unos cuantos parámetros que se pueden ajustar.
Los gestores de eventos XML definidos son:
Case Folding
Las funciones manejadoras de elementos pueden tomar sus nombres de elementos "case-folded".
Case-folding se define en el estándar XML como "un proceso aplicado a una secuencia de caracteres, en
el cual aquellos identificados como sin-mayúsculas son reemplazados por sus equivalentes en
1497
XML
mayúsculas". En otras palabras, cuando se trata de XML, case-folding simplemente significa poner en
mayúsculas.
Por defecto, todos los nombres de elementos que se pasan a las funciones gestoras estan "pasados a
mayúsculas". Esta conducta puede ser observada y controlada por el analizador XML con las funciones
xml_parser_get_option() y xml_parser_set_option(), respectivamente.
Códigos de Error
Las siguientes constantes se definen para códigos de error XML (como los devuelve xml_parse()):
XML_ERROR_NONE
XML_ERROR_NO_MEMORY
XML_ERROR_SYNTAX
XML_ERROR_NO_ELEMENTS
XML_ERROR_INVALID_TOKEN
XML_ERROR_UNCLOSED_TOKEN
XML_ERROR_PARTIAL_CHAR
XML_ERROR_TAG_MISMATCH
XML_ERROR_DUPLICATE_ATTRIBUTE
XML_ERROR_JUNK_AFTER_DOC_ELEMENT
XML_ERROR_PARAM_ENTITY_REF
XML_ERROR_UNDEFINED_ENTITY
XML_ERROR_RECURSIVE_ENTITY_REF
XML_ERROR_ASYNC_ENTITY
XML_ERROR_BAD_CHAR_REF
XML_ERROR_BINARY_ENTITY_REF
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
XML_ERROR_MISPLACED_XML_PI
XML_ERROR_UNKNOWN_ENCODING
XML_ERROR_INCORRECT_ENCODING
XML_ERROR_UNCLOSED_CDATA_SECTION
XML_ERROR_EXTERNAL_ENTITY_HANDLING
Codificación de caracteres
La extension XML de PHP soporta el conjunto de caracteres Unicode (http://www.unicode.org/) a través
de diferentes codificaciones de caracteres. Hay dos tipos de codificaciones de caracteres, coficación de
fuente y codificación de destino. La representación interna de PHP del documento está siempre
codificada con UTF-8.
La codificación de fuente se hace cuando un documento XML es interpretado. Al crear un intérprete
XML , se puede especificar una codificación de fuente (esta codificación no se puede cambiar má tarde
durante el tiempo de vida del intérprete XML). Las codificaciones de fuente soportadas son
ISO-8859-1, US-ASCII y UTF-8. Las dos primeras son codificaciones de byte-único, lo que significa
que cada carácter se representa por un solo byte. UTF-8 puede codificar caracteres compuestos por un
número variable de bits (hasta 21) en de uno a cuatro bytes. La codificación fuente por defecto usada por
PHP es ISO-8859-1.
La codificación de destino se hace cuando PHP pasa datos a las funciones gestoras XML. Cuando se crea
un intérprete XML, la codificación de destino se crea igual a la codificación de fuente, pero se puede
cambiar en cualquier momento. La codificación de destino afectará a la información de los caracteres así
1498
XML
Algunos Ejemplos
Aquí hay algunos ejemplos de archivos de comandos PHP que interpretan documentos XML.
$file = "data.xml";
$depth = array();
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}
1499
XML
xml_parser_free($xml_parser);
Este ejemplo transforma etiquetas de un documento XML directamente a etiquetas HTML. Los
elementos no encontrados en el "array de traducción ("map array") son ignorados. Por supuesto, este
ejemplo solamente funcionará con un tipo de documentos XML específico.
$file = "data.xml";
$map_array = array(
"BOLD" => "B",
"EMPHASIS" => "I",
"LITERAL" => "TT"
);
$xml_parser = xml_parser_create();
// usa case-folding para que estemos seguros de encontrar la etiqueta
// en $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}
1500
XML
$file = "xmltest.xml";
function trustedFile($file) {
// solamente confía en archivos locales que nos pertenezcan
if (!eregi("^([a-z]+)://", $file)
&& fileowner($file) == getmyuid()) {
return true;
}
return false;
}
1501
XML
function new_xml_parser($file) {
global $parser_file;
1502
XML
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
xml_set_processing_instruction_handler($xml_parser, "PIHandler");
xml_set_default_handler($xml_parser, "defaultHandler");
xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");
print "<pre>";
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d\n",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
print "</pre>";
print "parse complete\n";
xml_parser_free($xml_parser);
?>
Ejemplo 4. xmltest.xml
<?xml version=’1.0’?>
<!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
<!ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
<TITLE>Title &plainEntity;</TITLE>
<para>
<informaltable>
<tgroup cols="3">
1503
XML
<tbody>
<row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
<row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
</tbody>
</tgroup>
</informaltable>
</para>
&systemEntity;
<sect1 id="about">
<title>About this Document</title>
<para>
<!-- this is a comment -->
<?php print ’Hi! This is PHP version ’.phpversion(); ?>
</para>
</sect1>
</chapter>
Ejemplo 5. xmltest2.xml
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
<element attrib="value"/>
&testEnt;
<?php print "This is some more PHP code being executed."; ?>
</foo>
1504
XML
Cada b representa un bit que puede ser usado para almacenar datos de caracteres.
code
Un código de error de xml_get_error_code().
1505
XML
Devuelve una cadena con una descripción textual del código de error code, o FALSE si no se encontró
descripción.
parser
Una referencia al analizador XML del que obtener el índice del byte.
Esta función devuelve FALSE si parser no referencia un analizador válido, o si no devuelve en qué
índice de byte se encuentra el buffer de datos del analizador (empezando en 0).
parser
Una referencia al analizador XML del que obtener el número de columna.
Esta función devuelve FALSE si parser no referencia un analizador válido, o si no devuelve en qué
columna de la línea actual (como se obtiene de xml_get_current_line_number()) en la que se encuentra
el analizador.
parser
Una referencia al analizador XML del que obtener el número de línea.
1506
XML
Esta función devuelve FALSE si parser no referencia un analizador válido, o si no devuelve en qué
línea se encuentra actualmente el buffer de datos del analizador.
parser
Una referencia al analizador XML del que obtener el código de error.
Esta función devuelve FALSE si parser no referencia un analizador válido, o si no devuelve uno de los
códigos de error listados en la sección de códigos de error.
int xml_parse_into_struct ( resource parser, string data, array &values, array &index) \linebreak
This function parses an XML file into 2 parallel array structures, one (index) containing pointers to the
location of the appropriate values in the values array. These last two parameters must be passed by
reference.
Below is an example that illustrates the internal structure of the arrays being generated by the function.
We use a simple note tag embeded inside a para tag, and then we parse this an print out the structures
generated:
1507
XML
Index array
Array
(
[PARA] => Array
(
[0] => 0
[1] => 2
)
Vals array
Array
(
[0] => Array
(
[tag] => PARA
[type] => open
[level] => 1
)
Event-driven parsing (based on the expat library) can get complicated when you have an XML document
that is complex. This function does not produce a DOM style object, but it generates structures amenable
of being transversed in a tree fashion. Thus, we can create objects representing the data in the XML file
easily. Let’s consider the following XML file representing a small database of aminoacids information:
1508
XML
<?xml version="1.0"?>
<moldb>
<molecule>
<name>Alanine</name>
<symbol>ala</symbol>
<code>A</code>
<type>hydrophobic</type>
</molecule>
<molecule>
<name>Lysine</name>
<symbol>lys</symbol>
<code>K</code>
<type>charged</type>
</molecule>
</moldb>
And some code to parse the document and generate the appropriate objects:
<?php
class AminoAcid {
var $name; // aa name
var $symbol; // three letter symbol
var $code; // one letter code
var $type; // hydrophobic, charged or neutral
function readDatabase($filename) {
// read the xml database of aminoacids
$data = implode("",file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
xml_parse_into_struct($parser,$data,$values,$tags);
xml_parser_free($parser);
1509
XML
function parseMol($mvalues) {
for ($i=0; $i < count($mvalues); $i++)
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
return new AminoAcid($mol);
}
$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);
?>
After executing parsemoldb.php, the variable $db contains an array of AminoAcid objects, and the
output of the script confirms that:
1510
XML
parser
Una referencia al analizador XML que se va a utilizar.
data
Conjunto de información que se analizará. Un documento puede ser analizado por trozos llamando
varias veces a xml_parse() con nueva información, siempre que se establezca el parámetro
isFinal y sea TRUE cuando el último dato sea analizado.
isFinal (optional)
Si existe y es TRUE, data es el último pedazo de información envíado en este análisis.
Cuando el documento XML es analizado, se hacen llamadas a los gestores para los eventos configurados
tantas veces como sea necesario, después de que esta función devuelva TRUE o FALSE.
Devuelve TRUE si el análisis se realiza con éxito, FALSE si no tiene éxito, o si parser no referencia a
un analizador válido. Para análisis fallidos, se puede recuperar información de error con
xml_get_error_code(), xml_error_string(), xml_get_current_line_number(),
xml_get_current_column_number() y xml_get_current_byte_index().
1511
XML
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
encoding (opcional)
Qué codificación de caracteres debería usar el analizador. Las siguientes codificación de caracteres
están soportadas:
ISO-8859-1 (por defecto)
US-ASCII
UTF-8
Esta función crea un analizador XML y devuelve un índice para usarlo con otras funciones XML.
Devuelve FALSE en caso de fallo.
parser
Una referencia al analizador XML que se liberará.
Esta función devuelve FALSE si parser no referencia un analizador válido, o si no libera el analizador
y devuelve TRUE.
1512
XML
parser
Una referencia al analizador XML del que obtener opciones.
option
Qué opción recuperar. Ver xml_parser_set_option() para una lista de opciones.
Esta función devuelve FALSE si parser no referencia un analizador válido, o si la opción no pudo ser
establecida. Si no, se devuelve la opción.
Mirar xml_parser_set_option() para la lista de opciones.
parser
Una referencia al analizador XML en el que establecer opciones.
option
Opción que se establecerá. Ver más abajo.
value
El nuevo valor de la opción.
Esta función devuelve FALSE si parser no referencia un analizador válido, o si la opción no pudo ser
establecida. Si no, la opción se establece y devuelve TRUE.
Las opciones siguientes están disponibles:
1513
XML
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
data
El segundo parámetro, data, contiene los datos caracteres como string.
Si una función gestora se establece como la cadena vacía, o FALSE, el gestor en cuestión se deshabilita.
Se devuelve TRUE si se estableció el gestor, FALSE si parser no es un analizador.
En la actualidad no hay soporte para gestores objeto/método.
1514
XML
La función nombrada en handler debe aceptar dos parámetros: handler ( int parser, string data)
\linebreak
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
data
El segundo parámetro, data, contiene los caracteres de dato. Esto puede ser la declaración XML,
la declaración de tipo de documento, entidades u otros datos para los cuales no existe otro gestor.
Si una función gestora se establece como la cadena vacía, o FALSE, el gestor en cuestión se deshabilita.
Se devuelve TRUE si se estableció el gestor, FALSE si parser no es un analizador.
En la actualidad no hay soporte para gestores objeto/método.
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
name
El segundo parámetro, name, contiene el nombre del elemento para el que se llama a este gestor. Si
la propiedad de case-folding tiene efecto para este analizador, el nombre del elemento estará en
mayúsculas.
attribs
El tercer parámetro, attribs, contiene un array asociativo con los atributos de los elementos (si
hay). Las claves de este array son los nombres de los atributos, los valores son los valores de los
atributos. Los nombres de los atributos están en mayúsculas (case-folded) con el mismo criterio que
los nombres de los elementos. Los valores de los atributos no sufren las consecuencias de
case-folding.
El orden original de los atributos se puede recuperar recorriendo attribs del modo usual, usando
each(). La primera clave del array es el el primer atributo, y así sucesivamente.
1515
XML
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
name
El segundo parámetro, name, contiene el nombre del elemento para el que se llama a este gestor. Si
la propiedad de case-folding tiene efecto para este analizador, el nombre del elemento estará en
mayúsculas.
Si una función gestora se establece como la cadena vacía, o FALSE, el gestor en cuestión se deshabilita.
Se devuelve TRUE si se establecieron los gestores, FALSE si parser no es un analizador.
En la actualidad no hay soporte para gestores objeto/método.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Nota: En lugar de un nombre de función, se pueden proporcionar una matriz que contenga una
referencia a un objeto o el nombre de un método.
1516
XML
Establece la función gestora de declaraciones de notación para el analizador XML parser. handler
es un string que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por
parser.
La función llamada por handler debe aceptar cinco parámetros, y debería devolver un valor entero. Si
el valor devuelto desde el gestor (handler) es falso (lo cual ocurrirá si no se devuelve un valor), el
analizador XML dejará de analizar y xml_get_error_code() devolverá
XML_ERROR_EXTERNAL_ENTITY_HANDLING. int handler ( int parser, string
openEntityNames, string base, string systemId, string publicId) \linebreak
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
openEntityNames
El segundo parámetro, openEntityNames, es una lista, separada por espacios, de los nombres
de las entidades que se abren para el análisis de esta entidad (incluido el nombre de la entidad
referenciada).
base
Esta es la base para resolver el identificador de sistema (systemid) de la entidad externa. En la
actualidad este parámetro es siempre la cadena vacía.
systemId
El cuarto parámetro, systemId, es el identificador del sistema tal como se especificó en la
declaración de la entidad.
publicId
El quinto parámetro, publicId, es el identificador público como se especificó en la declaración
de la entidad, o una cadena vacía si no se especificó ninguno; el espacio en blanco en el
identificador público se habrá normalizado como se requiere en las especificaciones XML.
Si una función gestora se establece como la cadena vacía, o FALSE, el gestor en cuestión se deshabilita.
Se devuelve TRUE si se estableció el gestor, FALSE si parser no es un analizador.
En la actualidad no hay soporte para gestores objeto/método.
1517
XML
Una declaración de notación es parte del DTD del documento y tiene el siguiente formato:
<!NOTATION name
{systemId | publicId}
>
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
notationName
Este es el nombre de la notación, como se describió arriba en el formato de notación.
base
Esta es la base para resolver el identificador de sistema (systemId) de la declaración. En la
actualidad este parámetro es siempre la cadena vacía.
systemId
Identificador de sistema de la declaración de notación externa.
publicId
Identificador público de la declaración de notación externa.
Si una función gestora se establece como la cadena vacía, o FALSE, el gestor en cuestión se deshabilita.
Se devuelve TRUE si se estableció el gestor, FALSE si parser no es un analizador.
En la actualidad no hay soporte para gestores objeto/método.
xml_set_object (PHP 4 )
Usa un analizador XML dentro de un objecto
<?php
class xml {
var $parser;
1518
XML
function xml() {
$this->parser = xml_parser_create();
xml_set_object($this->parser,&$this);
xml_set_element_handler($this->parser,"tag_open","tag_close");
xml_set_character_data_handler($this->parser,"cdata");
}
function parse($data) {
xml_parse($this->parser,$data);
}
function tag_open($parser,$tag,$attributes) {
var_dump($parser,$tag,$attributes);
}
function cdata($parser,$cdata) {
var_dump($parser,$cdata);
}
function tag_close($parser,$tag) {
var_dump($parser,$tag);
}
<?
1519
XML
target
data?>
Puedes poner código PHP en esa etiqueta, pero ten en cuenta una limitación: en una PI XML, la etiqueta
de fin de la PI (?>) no puede ser citada, por lo que esta secuencia de caracteres no debería aparecer en el
código PHP que insertes con las PIs en documentos XML. Si lo hace, el resto del código PHP, así como
la etiqueta de fin de PI "real", serán tratados como datos de caracteres.
La función nombrada en handler debe aceptar tres parámetros: handler ( int parser, string target,
string data) \linebreak
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
target
El segundo parámetro, target, contiene el objetivo PI.
data
El tercer parámetro, data, contiene los datos PI.
Si una función gestora se establece como la cadena vacía, o FALSE, el gestor en cuestión se deshabilita.
Se devuelve TRUE si se estableció el gestor, FALSE si parser no es un analizador.
En la actualidad no hay soporte para gestores objeto/método.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Nota: En lugar de un nombre de función, se pueden proporcionar una matriz que contenga una
referencia a un objeto o el nombre de un método.
1520
XML
parser
El primer parámetro, parser, es una referencia al analizador XML que llama al gestor.
entityName
El nombre de la entidad que va a ser definida.
base
Esta es la base para resolver el identificador de sistema (systemId) de la entidad externa.
Actualmente este parámetro siempre será una cadena vacía.
systemId
Identificador de Sistema para la entidad externa.
publicId
Identificador público para la entidad externa.
notationName
Nombre de la notación de esta entidad (ver xml_set_notation_decl_handler()).
Si una función gestora se establece como la cadena vacía, o FALSE, el gestor en cuestión se deshabilita.
Se devuelve TRUE si se estableció el gestor, FALSE si parser no es un analizador.
En la actualidad no hay soporte para gestores objeto/método.
1521
CVI. XMLRPC functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
1522
XMLRPC function
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1523
XMLRPC function
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1524
XMLRPC function
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1525
XMLRPC function
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
mixed xmlrpc_server_call_method ( resource server, string xml, mixed user_data [, array output_options])
\linebreak
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1526
XMLRPC function
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1527
XMLRPC function
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1528
XMLRPC function
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1529
CVII. XSLT functions
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas
funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede
cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este
módulo es tu responsabiliad.
Introduction
Installation
This extension uses Sabloton and expat, which can both be found at http://www.gingerall.com/. Binaries
are provided as well as source.
On UNIX, run configure with the --with-sablot and --enable-sablot-errors-descriptive
options. The Sablotron library should be installed somewhere your compiler can find it.
1530
XSLT
xslt_output_process (unknown)
unknown
1531
XSLT
xh
A reference to the XSLT parser.
log
This parameter is either a boolean value which toggles logging on and off, or a string containing
the logfile in which log errors too.
1532
XSLT
This function allows you to set the file in which you want XSLT log messages to, XSLT log messages are
different than error messages, in that log messages are not actually error messages but rather messages
related to the state of the XSLT processor. They are useful for debugging XSLT, when something goes
wrong.
By default logging is disabled, in order to enable logging you must first call xslt_set_log() with a
boolean parameter which enables logging, then if you want to set the log file to debug to, you must then
pass it a string containing the filename:
<?php
$xh = xslt_create();
xslt_set_log($xh, true);
xslt_set_log($xh, getcwd() . ’myfile.log’);
xslt_free($xh);
?>
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1533
XSLT
array(
[get_all] => get all handler,
[open] => open handler,
[get] => get handler,
[put] => put handler,
[close] => close handler
)
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1534
CVIII. YAZ
The yaz() functions wrap the YAZ API. The home page of the project is http://www.indexdata.dk/yaz/.
Information about the phpyaz module can be found at http://www.indexdata.dk/phpyaz/.
PHP/YAZ is much simpler to use than the C API for YAZ but less flexible. The intent is to make it easy
to build basic client functions. It supports persistent stateless connections very similar to those offered by
the various SQL APIs that are available for PHP. This means that sessions are stateless but shared
amongst users, thus saving the connect and INIT steps in many cases.
Before compiling PHP with the PHP/YAZ module you’ll need the YAZ toolkit. Build YAZ and install it.
Build PHP with your favourite modules and add option --with-yaz. Your task is roughly the following:
gunzip -c yaz-1.6.tar.gz|tar xf -
gunzip -c php-4.0.X.tar.gz|tar xf -
cd yaz-1.6
./configure --prefix=/usr
make
make install
cd ../php-4.0.X
./configure --with-yaz=/usr/bin
make
make install
PHP/YAZ keeps track of connections with targets (Z-Associations). A positive integer represents the ID
of a particular association.
The script below demonstrates the parallel searching feature of the API. When invoked it either prints a
query form (if no arguments are supplied) or if there are arguments (term and one or more hosts) it
searches the targets in array host.
Ejemplo 1. YAZ()
1535
YAZ
1536
YAZ
In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each
field is mapped to their BIB-1 equivalent. It is assumed that variable $id is a target ID.
$field["ti"] = "1=4";
$field["au"] = "1=1";
$field["isbn"] = "1=7";
yaz_ccl_conf($id,$field);
int yaz_ccl_parse ( int id, string query, array & result) \linebreak
This function invokes the CCL parser. It converts a given CCL FIND query to an RPN query which may
be passed to the yaz_search() function to perform a search. To define a set of valid CCL fields call
yaz_ccl_conf() prior to this function. If the supplied query was successfully converted to RPN, this
1537
YAZ
function returns TRUE, and the index rpn of the supplied array result holds a valid RPN query. If the
query could not be converted (because of invalid syntax, unknown field, etc.) this function returns FALSE
and three indexes are set in the resulting array to indicate the cause of failure: errorcodeCCL error
code (integer), errorstringCCL error string, and errorposapproximate position in query of failure
(integer is character position).
1538
YAZ
1539
YAZ
This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item
Order Extended Service to Transport ILL (Profile/1). See this (http://www.nlc-bnc.ca/iso/ill/stanprf.htm)
and the specification (http://www.nlc-bnc.ca/iso/ill/document/standard/z-ill-1a.pdf). The args parameter
must be a hash array with information about the Item Order request to be sent. The key of the hash is the
name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key
item-id,ISBN.
The ILL-Request parameters are:
protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
1540
YAZ
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note
There are also a few parameters that are part of the Extended Services Request package and the
ItemOrder package:
package-name
user-id
1541
YAZ
contact-name
contact-phone
contact-email
itemorder-item
1542
YAZ
int yaz_scan ( int id, string type, string startterm [, array flags]) \linebreak
This function prepares for a Z39.50 Scan Request. Argument id specifies target ID. Starting term point
for the scan is given by startterm. The form in which is the starting term is specified is given by
type. Currently type rpn is supported. The optional flags specifies additional information to control
the behaviour of the scan request. Three indexes are currently read from the flags: number (number of
terms requested), position (preferred position of term) and stepSize (preferred step size). To actually
tranfer the Scan Request to the target and receive the Scan Response, yaz_wait() must be called. Upon
completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.
The syntax of startterm is similar to the RPN query as described in yaz_search(). The startterm
consists of zero or more @attr-operator specifications, then followed by exactly one token.
1543
YAZ
}
echo ’</table>’;
} else {
echo "Scan failed. Error: " . yaz_error($id) . "<br>";
}
}
Sort Flags
a
Sort ascending
1544
YAZ
Sort descending
s
Case sensitive sorting
To sort on Bib1 attribute title, case insensitive, and ascending you’d use the following sort criteria:
1=4 ia
If the secondary sorting criteria should be author, case sensitive and ascending you’d use:
1=4 ia 1=1003 sa
1545
CIX. NIS funciona
NIS ( anteriormente llamado Paginas Amarillas ) permite la administracion de red de los archivos de
administracion importantes (e.g.El archivo de contraseñas). Para mas informacion dirigirse a las paginas
de ayuda de NIS y a la direccion. Introduccion a YP/NIS
(http://www.desy.de/~sieversm/ypdoku/ypdoku/ypdoku.html) Hay tambien un libro llamado
gestionando NFS Y NIS (http://www.oreilly.com/catalog/nfs/noframes.html) por Hal Stern.
Para obtener estas funciones de trabajo, usted tiene que configure PHP con -- con- yp.
1546
NIS
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.
1547
NIS
yp_first (unknown)
devuelve la primera clave emparejada con el nombrado mapa.
yp_first(nombre de la funcion)() Retorna la primera clave de valor pareada del mapa nombrado en el
dominio, de otra manera FALSO.
1548
NIS
<?php
$number = yp_master ($domain, $mapname);
echo "Master for this map is: " . $master;
?>
1549
NIS
<?php
$number = yp_order($domain,$mapname);
echo "Order number for this map is: " . $number;
?>
1550
NIS
1551
CX. Zip File Functions (Read Only Access)
This module uses the functions of the ZZIPlib (http://zziplib.sourceforge.net/) library by Guido Draheim
to transparently read ZIP compressed archives and the files inside them.
Please note that ZZIPlib only provides a subset of functions provided in a full implementation of the ZIP
compression algorithm and can only read ZIP file archives. A normal ZIP utility is needed to create the
ZIP file archives read by this library.
Zip support in PHP is not enabled by default. You will need to use the --with-zip configuration option
when compiling PHP to enable zip support. This module requires ZZIPlib version >= 0.10.6.
Nota: Zip support before PHP 4.1.0 is experimental. This section reflects the Zip extension as it
exists in PHP 4.1.0 and later.
Example Usage
This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The
test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.
<?php
$zip = zip_open("/tmp/test2.zip");
if ($zip) {
zip_entry_close($zip_entry);
}
echo "\n";
zip_close($zip);
1552
Zip
?>
1553
Zip
1554
Zip
Nota: Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is
read only access. Please see fopen() for an explanation of various modes, including "rb".
Nota: Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates
the result of the operation and is not needed for reading or closing the directory entry.
1555
Zip
Nota: The length parameter should be the uncompressed length you wish to read.
Returns the data read, or FALSE if the end of the file is reached.
See also zip_entry_open(), zip_entry_close() and zip_entry_filesize().
1556
CXI. Funciones de Compresión
Este módulo usa la función de zlib (http://www.gzip.org/zlib/) de Jean-loup Gailly y Mark Adler para
leer y grabar archivos comprimidos .gz, de un modo transparente. Con este módulo, es requisito usar una
versión de zlib igual o posterior a 1.0.9.
Este módulo contiene versiones de la mayoría de las funciones de Sistema de archivos que funcionan con
los archivos comprimidos con gzip (y con los no-comprimidos tambien, pero no con conectores
(sockets)).
<?php
$filename = tempnam(’/tmp’, ’zlibtest’).’.gz’;
print "<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Sólo es una prueba, prueba, prueba,prueba, prueba, prueba!\n";
// Abre el archivo para escribirlo con máximo de compresión
$zp = gzopen($filename, "w9");
// Escribe la cadena en él
gzwrite($zp, $s);
// Cierra el fichero
gzclose($zp);
// Abre el fichero para lectura
$zp = gzopen($filename, "r");
// Lee 3 caracteres
print gzread($zp, 3);
// Salida hasta el final del fichero, para cerrarlo luego.
gzpassthru($zp);
print "\n";
// Abre el fichero y muestra su contenido (por segunda vez).
if (readgzfile($filename) != strlen($s)) {
echo "Error con las funciones zlib!";
}
unlink($filename);
print "<pre>\n</h1></body>\n</html>\n";
?>
1557
Zlib
Nota: This is not the same as gzip compression, which includes some header data. See gzencode()
for gzip compression.
1558
Zlib
Nota: level was added in PHP 4.2, before PHP 4.2 gzencode() only had the data and (optional)
encoding_mode parameters..
The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:
<?php
$data = implode("", file("bigfile.txt"));
$gzdata = gzencode($data, 9);
$fp = fopen("bigfile.txt.gz", "w");
fwrite($fp, $gzdata);
fclose($fp);
?>
For more information on the GZIP file format, see the document: GZIP file format specification version
4.3 (http://www.ietf.org/rfc/rfc1952.txt) (RFC 1952).
See also gzcompress(). gzuncompress(), gzdeflate(), gzinflate().
1559
Zlib
1560
Zlib
1561
Zlib
Se puede usar el tercer parámetro opcional, poniéndolo a "1", si se quiere buscar también el fichero en la
trayectoria include_path.
1562
Zlib
$filename = "/usr/local/algo.txt.gz";
$zd = gzopen( $filename, "r" );
$contents = gzread( $zd, 10000 );
gzclose( $zd );
1563
Zlib
Devuelve la posición dentro del fichero referido por zp; p.e., su desplazamiento en el cuerpo del archivo.
Si hay algún error, devuelve falso.
El puntero al archivo-gz debe ser válido y debe apuntar a un archivo correctamente abierto con gzopen().
Ver también gzopen(), gzseek() y gzrewind().
1564
Zlib
1565
Parte V. Extending PHP 4.0
1566
Capítulo 25. Overview
"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few
megabytes of source code, and to hack a system like this quite a few things have to be learned and
considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is
not the most scientific and professional approach, but the method that’s the most fun and gives the best
end results. In the following sections, you’ll learn quickly how to get the most basic extensions to work
almost instantly. After that, you’ll learn about Zend’s advanced API functionality. The alternative would
have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a
complete look at the big picture before doing anything practical. Although this is the "better" method, as
no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which
is why we’ve decided on the direct approach.
Note that even though this chapter tries to impart as much knowledge as possible about the inner
workings of PHP, it’s impossible to really give a complete guide to extending PHP that works 100% of
the time in all cases. PHP is such a huge and complex package that its inner workings can only be
understood if you make yourself familiar with it by practicing, so we encourage you to work with the
source.
1. The interpreter part analyzes the input code, translates it, and executes it.
2. The functionality part implements the functionality of the language (its functions, etc.).
3. The interface part talks to the Web server, etc.
Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the
complete PHP package. Zend itself really forms only the language core, implementing PHP at its very
basics with some predefined functions. PHP contains all the modules that actually create the language’s
outstanding capabilities.
The following sections discuss where PHP can be extended and how it’s done.
1567
Capítulo 26. Extension Possibilities
1568
Capítulo 26. Extension Possibilities
As shown in Figura 25-1 above, PHP can be extended primarily at three points: external modules,
built-in modules, and the Zend engine. The following sections discuss these options.
External Modules
External modules can be loaded at script runtime using the function dl(). This function loads a shared
object from disk and makes its functionality available to the script to which it’s being bound. After the
script is terminated, the external module is discarded from memory. This method has both advantages
and disadvantages, as described in the following table:
Advantages Disadvantages
External modules don’t require recompiling of The shared objects need to be loaded every time a
PHP. script is being executed (every hit), which is very
slow.
The size of PHP remains small by "outsourcing" External additional files clutter up the disk.
certain functionality.
Every script that wants to use an external module’s
functionality has to specifically include a call to dl(),
or the extension tag in php.ini needs to be
modified (which is not always a suitable solution).
To sum up, external modules are great for third-party products, small additions to PHP that are rarely
used, or just for testing purposes. To develop additional functionality quickly, external modules provide
the best results. For frequent usage, larger implementations, and complex code, the disadvantages
outweigh the advantages.
Third parties might consider using the extension tag in php.ini to create additional external modules
to PHP. These external modules are completely detached from the main package, which is a very handy
feature in commercial environments. Commercial distributors can simply ship disks or archives
containing only their additional modules, without the need to create fixed and solid PHP binaries that
don’t allow other modules to be bound to them.
Built-in Modules
Built-in modules are compiled directly into PHP and carried around with every PHP process; their
functionality is instantly available to every script that’s being run. Like external modules, built-in
modules have advantages and disadvantages, as described in the following table:
Advantages Disadvantages
No need to load the module specifically; the Changes to built-in modules require recompiling of
functionality is instantly available. PHP.
No external files clutter up the disk; everything The PHP binary grows and consumes more
resides in the PHP binary. memory.
1569
Capítulo 26. Extension Possibilities
Built-in modules are best when you have a solid library of functions that remains relatively unchanged,
requires better than poor-to-average performance, or is used frequently by many scripts on your site. The
need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in
modules are not ideal when rapid development of small additions is required.
1570
Capítulo 27. Source Layout
1571
Capítulo 27. Source Layout
Nota: Prior to working through the rest of this chapter, you should retrieve clean, unmodified source
trees of your favorite Web server. We’re working with Apache (available at http://www.apache.org/)
and, of course, with PHP (available at http://www.php.net/ - does it need to be said?).
Make sure that you can compile a working PHP environment by yourself! We won’t go into this issue
here, however, as you should already have this most basic ability when studying this chapter.
Before we start discussing code issues, you should familiarize yourself with the source tree to be able to
quickly navigate through PHP’s files. This is a must-have ability to implement and debug extensions.
After extracting the PHP archive, you’ll see a directory layout similar to that in Figura 27-1.
Directory Contents
php-4 Main PHP source files and main header files; here you’ll find all of PHP’s API definitions, macros, etc. (importan
ext Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been inte
pear Directory for the PHP class repository. At the time of this writing, this is still in the design phase, but it’s being tr
sapi Contains the code for the different server abstraction layers.
TSRM Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
Zend Location of Zend’s file; here you’ll find all of Zend’s API definitions, macros, etc. (important).
Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you
should take a close look at the following files:
• php.h, located in the main PHP directory. This file contains most of PHP’s macro and API
definitions.
• zend.h, located in the main Zend directory. This file contains most of Zend’s macros and definitions.
• zend_API.h, also located in the Zend directory, which defines Zend’s API.
You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend
executor, the PHP initialization file support, and such. After reading these files, take the time to navigate
around the package a little to see the interdependencies of all files and modules - how they relate to each
1572
Capítulo 27. Source Layout
other and especially how they make use of each other. This also helps you to adapt to the coding style in
which PHP is authored. To extend PHP, you should quickly adapt to this style.
Extension Conventions
Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules
described in the following sections.
Macros
For almost every important task, Zend ships predefined macros that are extremely handy. The tables and
figures in the following sections describe most of the basic functions, structures, and macros. The macro
definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at
these files after having studied this chapter. (Although you can go ahead and read them now, not
everything will make sense to you yet.)
Memory Management
Resource management is a crucial issue, especially in server software. One of the most valuable
resources is memory, and memory management should be handled with extreme care. Memory
management has been partially abstracted in Zend, and you should stick to this abstraction for obvious
reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to
determine whether a block is in use, automatically freeing unused blocks and blocks with lost references,
and thus prevent memory leaks. The functions to be used are described in the following table:
Function Description
emalloc() Serves as replacement for malloc().
efree() Serves as replacement for free().
estrdup() Serves as replacement for strdup().
estrndup() Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function t
ecalloc() Serves as replacement for calloc().
erealloc() Serves as replacement for realloc().
emalloc(), estrdup(), estrndup(), ecalloc(), and erealloc() allocate internal memory; efree() frees these
previously allocated blocks. Memory handled by the e*() functions is considered local to the current
process and is discarded as soon as the script executed by this process is terminated.
1573
Capítulo 27. Source Layout
Aviso
To allocate resident memory that survives termination of the current script, you can
use malloc() and free(). This should only be done with extreme care, however,
and only in conjunction with demands of the Zend API; otherwise, you risk memory
leaks.
Zend also features a thread-safe resource manager to provide better native support for multithreaded Web
servers. This requires you to allocate local structures for all of your global variables to allow concurrent
threads to be run. Because the thread-safe mode of Zend was not finished back when this was written, it
is not yet extensively covered here.
String Handling
Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc.,
which don’t require additional memory allocation for storing their values. If you want to return a string
from a function, introduce a new string variable to the symbol table, or do something similar, you have to
make sure that the memory the string will be occupying has previously been allocated, using the
aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it
somewhere in your head for now - we’ll get back to it shortly.)
1574
Capítulo 27. Source Layout
Complex Types
Complex types such as arrays and objects require different treatment. Zend features a single API for
these types - they’re stored using hash tables.
Nota: To reduce complexity in the following source examples, we’re only working with simple types
such as integers at first. A discussion about creating more advanced types follows later in this
chapter.
1575
Capítulo 28. PHP’s Automatic Build System
1576
Capítulo 28. PHP’s Automatic Build System
PHP 4 features an automatic build system that’s very flexible. All modules reside in a subdirectory of the
ext directory. In addition to its own sources, each module consists of an M4 file (for example, see
http://www.gnu.org/manual/m4/html_mono/m4.html) for configuration and a Makefile.in file, which is
responsible for compilation (the results of autoconf and automake; for example, see
http://sourceware.cygnus.com/autoconf/autoconf.html and
http://sourceware.cygnus.com/automake/automake.html).
Both files are generated automatically, along with .cvsignore, by a little shell script named ext_skel
that resides in the ext directory. As argument it takes the name of the module that you want to create.
The shell script then creates a directory of the same name, along with the appropriate config.m4 and
Makefile.in files.
Step by step, the process looks like this:
This instruction creates the aforementioned files. To include the new module in the automatic
configuration and build process, you have to run buildconf, which regenerates the configure script
by searching through the ext directory and including all found config.m4 files.
Finally, running configure parses all configuration options and generates a makefile based on those
options and the options you specify in Makefile.in.
Ejemplo 28-1shows the previously generated Makefile.in:
There’s not much to tell about this one: It contains the names of the input and output files. You could also
specify build instructions for other files if your module is built from multiple source files.
The default config.m4 shown in Ejemplo 28-2’/> is a bit more complex:
1577
Capítulo 28. PHP’s Automatic Build System
If you’re unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit
confusing at first; but it’s actually quite easy.
Note: Everything prefixed with dnl is treated as a comment and is not parsed.
The config.m4 file is responsible for parsing the command-line options passed to configure at
configuration time. This means that it has to check for required external files and do similar configuration
and setup tasks.
The default file creates two configuration directives in the configure script: --with-my_module and
--enable-my_module. Use the first option when referring external files (such as the --with-apache
directive that refers to the Apache directory). Use the second option when the user simply has to decide
whether to enable your extension. Regardless of which option you use, you should uncomment the other,
unnecessary one; that is, if you’re using --enable-my_module, you should remove support for
--with-my_module, and vice versa.
By default, the config.m4 file created by ext_skel accepts both directives and automatically enables
your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the
default behavior to include your module into the PHP binary when desired by the user (by explicitly
specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to
== "yes":
This would require you to use --enable-my_module each time when reconfiguring and recompiling
PHP.
Note: Be sure to run buildconf every time you change config.m4!
We’ll go into more details on the M4 macros available to your configuration scripts later in this chapter.
For now, we’ll simply use the default files. The sample sources on the CD-ROM all have working
config.m4 files. To include them into the PHP build process, simply copy the source directories to your
PHP ext directory, run buildconf, and then include the sample modules you want by using the
appropriate --enable-* directives with configure.
1578
Capítulo 29. Creating Extensions
1579
Capítulo 29. Creating Extensions
We’ll start with the creation of a very simple extension at first, which basically does nothing more than
implement a function that returns the integer it receives as parameter. Ejemplo 29-1 shows the source.
RETURN_LONG(parameter);
}
1580
Capítulo 29. Creating Extensions
This code contains a complete PHP module. We’ll explain the source code in detail shortly, but first we’d
like to discuss the build process. (This will allow the impatient to experiment before we dive into API
discussions.)
Nota: The example source makes use of some features introduced with the Zend version used in
PHP 4.1.0 and above, it won’t compile with older PHP 4.0.x versions.
Compiling Modules
There are basically two ways to compile modules:
• Use the provided "make" mechanism in the ext directory, which also allows building of dynamic
loadable modules.
• Compile the sources manually.
The first method should definitely be favored, since, as of PHP 4.0, this has been standardized into a
sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it’s
hard to understand at first. We’ll provide a more detailed introduction to this later in the chapter, but first
let’s work with the default files.
The second method is good for those who (for some reason) don’t have the full PHP source tree
available, don’t have access to all files, or just like to juggle with their keyboard. These cases should be
extremely rare, but for the sake of completeness we’ll also describe this method.
Compiling Using Make. To compile the sample sources using the standard mechanism, copy all their
subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an
updated configure script containing appropriate options for the new extension. By default, all the
sample sources are disabled, so you don’t have to fear breaking your build process.
After you run buildconf, configure --help shows the following additional modules:
The module shown earlier in Ejemplo 29-1 can be enabled with --enable-first_module or
--enable-first_module=yes.
Compiling Manually. To compile your modules manually, you need the following commands:
Action Command
Compiling cc -fpic -DCOMPILE_DL=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
1581
Capítulo 29. Creating Extensions
The command to compile the module simply instructs the compiler to generate position-independent
code (-fpic shouldn’t be omitted) and additionally defines the constant COMPILE_DL to tell the module
code that it’s compiled as a dynamically loadable module (the test module above checks for this; we’ll
discuss it shortly). After these options, it specifies a number of standard include paths that should be used
as the minimal set to compile the source files.
Note: All include paths in the example are relative to the directory ext. If you’re compiling from another
directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory,
and (if necessary), the directory in which your module resides.
The link command is also a plain vanilla command instructing linkage as a dynamic module.
You can include optimization options in the compilation command, although these have been omitted in
this example (but some are included in the makefile template described in an earlier section).
Note: Compiling and linking manually as a static module into the PHP binary involves very long
instructions and thus is not discussed here. (It’s not very efficient to type all those commands.)
1582
Capítulo 30. Using Extensions
1583
Capítulo 30. Using Extensions
Depending on the build process you selected, you should either end up with a new PHP binary to be
linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the
example file first_module.c as a shared object, your result file should be first_module.so. To use
it, you first have to copy it to a place from which it’s accessible to PHP. For a simple test procedure, you
can copy it to your htdocs directory and try it with the source in Ejemplo 30-1. If you compiled it into
the PHP binary, omit the call to dl(), as the module’s functionality is instantly available to your scripts.
Aviso
For security reasons, you should not put your dynamic modules into publicly
accessible directories. Even though it can be done and it simplifies testing, you
should put them into a separate directory in production environments.
<?php
$param = 2;
$return = first_module($param);
?>
Calling this PHP file in your Web browser should give you the output shown in Figura 30-1.
If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for
the specified shared object, loads it, and makes its functions available to PHP. The module exports the
1584
Capítulo 30. Using Extensions
function first_module(), which accepts a single parameter, converts it to an integer, and returns the result
of the conversion.
If you’ve gotten this far, congratulations! You just built your first extension to PHP.
1585
Capítulo 31. Troubleshooting
1586
Capítulo 31. Troubleshooting
Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only
problem that could arise is that the compiler will complain about missing definitions or something
similar. In this case, make sure that all header files are available and that you specified their path
correctly in the compilation command. To be sure that everything is located correctly, extract a clean
PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a
safe compilation environment. If this fails, try manual compilation.
PHP might also complain about missing functions in your module. (This shouldn’t happen with the
sample sources if you didn’t modify them.) If the names of external functions you’re trying to access
from your module are misspelled, they’ll remain as "unlinked symbols" in the symbol table. During
dynamic loading and linkage by PHP, they won’t resolve because of the typing errors - there are no
corresponding symbols in the main binary. Look for incorrect declarations in your module file or
incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it
doesn’t occur with static modules. Errors in static modules show up at compile time.
1587
Capítulo 32. Source Discussion
1588
Capítulo 32. Source Discussion
Now that you’ve got a safe build environment and you’re able to include the modules into PHP files, it’s
time to discuss how everything works.
Module Structure
All PHP modules follow a common structure:
• Header file inclusions (to include all required macros, API definitions, etc.)
• C declaration of exported functions (required to declare the Zend function block)
• Declaration of the Zend function block
• Declaration of the Zend module block
• Implementation of get_module()
• Implementation of all exported functions
ZEND_FUNCTION ( my_function );
ZEND_FUNCTION declares a new C function that complies with Zend’s internal API. This means that the
function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as
parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of
the above definitions would look like this:
1589
Capítulo 32. Source Discussion
Since the interpreter and executor core have been separated from the main PHP package, a second API
defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few
of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to
macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever
possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval
are identical. zval is Zend’s definition; pval is PHP’s definition (actually, pval is an alias for zval now).
As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval.
When writing code, you should always use zval to conform to the new Zend API.
The parameter list of this declaration is very important; you should keep these parameters in mind (see
Tabla 32-1 for descriptions).
Parameter Description
ht The number of arguments passed to the Zend function. You should not touch this directly, but instead us
return_value This variable is used to pass any return values of your function back to PHP. Access to this variable is be
this_ptr Using this variable, you can gain access to the object in which your function is contained, if it’s used wi
return_value_used This flag indicates whether an eventual return value from this function will actually be used by the callin
executor_globals This variable points to global settings of the Zend engine. You’ll find this useful when creating new vari
1590
Capítulo 32. Source Discussion
} zend_function_entry;
Entry Description
fname Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, fir
handler Pointer to the C function responsible for handling calls to this function. For example, see the standard macr
func_arg_types Allows you to mark certain parameters so that they’re forced to be passed by reference. You usually should
zend_function_entry firstmod_functions[] =
{
ZEND_FE(first_module, NULL)
{NULL, NULL, NULL}
};
You can see that the last entry in the list always has to be {NULL, NULL, NULL}. This marker has to be
set for Zend to know when the end of the list of exported functions is reached.
Nota: You cannot use the predefined macros for the end marker, as these would try to refer to a
function named "NULL"!
The macro ZEND_FE (short for ’Zend Function Entry’) simply expands to a structure entry in
zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your
C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C
function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good
practice), keep this in mind.
Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.
Tabla 32-2 shows a list of all the macros that you can use to define functions.
Note: You can’t use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with
ZEND_FUNCTION. However, it’s perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and
PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is
not recommended; instead, you’re advised to use the ZEND_* macros only.
1591
Capítulo 32. Source Discussion
struct _zend_module_entry {
unsigned short size;
unsigned int zend_api;
unsigned char zend_debug;
unsigned char zts;
char *name;
zend_function_entry *functions;
int (*module_startup_func)(INIT_FUNC_ARGS);
int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
int (*request_startup_func)(INIT_FUNC_ARGS);
int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
char *version;
int (*global_startup_func)(void);
int (*global_shutdown_func)(void);
};
Entry Description
size, zend_api, zend_debug and zts Usually filled with the "STANDARD_MODULE_HEADER", which fills these four member
name Contains the module name (for example, "File functions", "Socket function
functions Points to the Zend function block, discussed in the preceding section.
module_startup_func This function is called once upon module initialization and can be used to do one-time
module_shutdown_func This function is called once upon module shutdown and can be used to do one-time de
request_startup_func This function is called once upon every page request and can be used to do one-time in
request_shutdown_func This function is called once after every page request and works as counterpart to requ
info_func When phpinfo() is called in a script, Zend cycles through all loaded modules and calls
version The version of the module. You can use NO_VERSION_YET if you don’t want to give th
Remaining structure elements These are used internally and can be prefilled by using the macro STANDARD_MODULE
zend_module_entry firstmod_module_entry =
{
STANDARD_MODULE_HEADER,
1592
Capítulo 32. Source Discussion
"First Module",
firstmod_functions,
NULL, NULL, NULL, NULL, NULL,
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES,
};
This is basically the easiest and most minimal set of values you could ever use. The module name is set
to First Module, then the function list is referenced, after which all startup and shutdown functions are
marked as being unused.
For reference purposes, you can find a list of the macros involved in declared startup and shutdown
functions in Tabla 32-3. These are not used in our basic example yet, but will be demonstrated later on.
You should make use of these macros to declare your startup and shutdown functions, as these require
special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are
automatically included into the function declaration when using the predefined macros. If you declare
your functions manually and the PHP developers decide that a change in the argument list is necessary,
you’ll have to change your module sources to remain compatible.
Macro Description
ZEND_MINIT(module) Declares a function for module startup. The generated name will be zend_minit_<module
ZEND_MSHUTDOWN(module) Declares a function for module shutdown. The generated name will be zend_mshutdown_<
ZEND_RINIT(module) Declares a function for request startup. The generated name will be zend_rinit_<module
ZEND_RSHUTDOWN(module) Declares a function for request shutdown. The generated name will be zend_rshutdown_<m
ZEND_MINFO(module) Declares a function for printing module information, used when phpinfo() is called. The gene
Creation of get_module()
This function is special to all dynamic loadable modules. Take a look at the creation via the
ZEND_GET_MODULE macro first:
#if COMPILE_DL_FIRSTMOD
ZEND_GET_MODULE(firstmod)
#endif
The function implementation is surrounded by a conditional compilation statement. This is needed since
the function get_module() is only required if your module is built as a dynamic extension. By specifying
a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the
compilation instructions required to build a dynamic extension), you can instruct your module whether
you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the
implementation of get_module() is simply left out.
1593
Capítulo 32. Source Discussion
get_module() is called by Zend at load time of the module. You can think of it as being invoked by the
dl() call in your script. Its purpose is to pass the module information block back to Zend in order to
inform the engine about the module contents.
If you don’t implement a get_module() function in your dynamic loadable module, Zend will
compliment you with an error message when trying to access it.
ZEND_FUNCTION(first_module)
{
long parameter;
RETURN_LONG(parameter);
}
The function declaration is done using ZEND_FUNCTION, which corresponds to ZEND_FE in the function
entry table (discussed earlier).
After the declaration, code for checking and retrieving the function’s arguments, argument conversion,
and return value generation follows (more on this later).
Summary
That’s it, basically - there’s nothing more to implementing PHP modules. Built-in modules are structured
similarly to dynamic modules, so, equipped with the information presented in the previous sections,
you’ll be able to fight the odds when encountering PHP module source files.
Now, in the following sections, read on about how to make use of PHP’s internals to build powerful
extensions.
1594
Capítulo 33. Accepting Arguments
1595
Capítulo 33. Accepting Arguments
One of the most important issues for language extensions is accepting and dealing with data passed via
arguments. Most extensions are built to deal with specific input data (or require parameters to perform
their specific actions), and function arguments are the only real way to exchange data between the PHP
level and the C level. Of course, there’s also the possibility of exchanging data using predefined global
values (which is also discussed later), but this should be avoided by all means, as it’s extremely bad
practice.
PHP doesn’t make use of any formal function declarations; this is why call syntax is always completely
dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For
example, it’s possible to call a function using only one argument at one time and four arguments the next
time - both invocations are syntactically absolutely correct.
if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;
If the function is not called with two arguments, it exits with an error message. The code snippet above
makes use of the tool macro WRONG_PARAM_COUNT, which can be used to generate a standard error
message (see Figura 33-1).
This macro prints a default error message and then returns to the caller. Its definition can also be found in
zend_API.h and looks like this:
1596
Capítulo 33. Accepting Arguments
As you can see, it calls an internal function named wrong_param_count() that’s responsible for printing
the warning. For details on generating customized error messages, see the later section "Printing
Information."
Retrieving Arguments
New parameter parsing API: This chapter documents the new Zend parameter parsing API
introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and
4.1.0 .
Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have
standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using
the new parameter parsing API. It greatly simplifies the process of receiving parameteres, but it has a
drawback in that it can’t be used for functions that expect variable number of parameters. But since the
vast majority of functions do not fall into those categories, this parsing API is recommended as the new
standard way.
The prototype for parameter parsing function looks like this:
The first argument to this function is supposed to be the number of actual parameters passed to your
function, so ZEND_NUM_ARGS() can be used for that. The second parameter should always be
TSRMLS_CC macro. The third argument is a string that specifies the number and types of arguments your
function is expecting, similar to how printf format string specifies the number and format of the output
values it should operate on. And finally the rest of the arguments are pointers to variables which should
receive the values from the parameters.
zend_parse_parameters() also performs type conversions whenever possible, so that you always
receive the data in the format you asked for. Any type of scalar can be converted to another one, but
conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.
If the parameters could be obtained successfully and there were no errors during type conversion, the
function will return SUCCESS, otherwise it will return FAILURE. The function will output informative
error messages, if the number of received parameters does not match the requested number, or if type
conversion could not be performed.
Here are some sample error messages:
Of course each error message is accompanied by the filename and line number on which it occurs.
1597
Capítulo 33. Accepting Arguments
• l - long
• d - double
• s - string (with possible null bytes) and its length
• b - boolean
• r - resource, stored in zval*
• a - array, stored in zval*
• o - object (of any class), stored in zval*
• O - object (of class specified by class entry), stored in zval*
• z - the actual zval*
The following characters also have a meaning in the specifier string:
• | - indicates that the remaining parameters are optional. The storage variables corresponding to
these parameters should be initialized to default values by the extension, since they will not be touched
by the parsing function if the parameters are not passed.
• / - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows,
to provide a copy of the parameter, unless it’s a reference.
• ! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If
NULL value is passed by the user, the storage pointer will be set to NULL.
The best way to illustrate the usage of this function is through examples:
1598
Capítulo 33. Accepting Arguments
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAIL-
URE) {
return;
}
/* Get only the first three parameters (useful for varargs functions). */
zval *z;
zend_bool b;
zval *r;
if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) {
return;
}
Note that in the last example we pass 3 for the number of received parameters, instead of
ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function
expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you
will have to use zend_get_parameters_array_ex() to obtain them.
The parsing function has an extended version that allows for an additional flags argument that controls its
actions.
The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to
not output any error messages during its operation. This is useful for functions that expect several sets of
completely different arguments, but you will have to output your own error messages.
For example, here is how you would get either a set of three longs or a string:
1599
Capítulo 33. Accepting Arguments
get_active_function_name(TSRMLS_C));
return;
}
With all the abovementioned ways of receiving function parameters you should have a good handle on
this process. For even more example, look through the source code for extensions that are shipped with
PHP - they illustrate every conceivable situation.
After having checked the number of arguments, you need to get access to the arguments themselves. This
is done with the help of zend_get_parameters_ex():
zval **parameter;
All arguments are stored in a zval container, which needs to be pointed to twice. The snippet above tries
to retrieve one argument and make it available to us via the parameter pointer.
zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of
arguments to retrieve (which should match the number of arguments with which the function has been
called; this is why it’s important to check for correct call syntax). The second argument (and all
following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn’t it?) All these pointers
are required because Zend works internally with **zval; to adjust a local **zval in our
function,zend_get_parameters_ex() requires a pointer to it.
The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating
(unsurprisingly) success or failure of the argument processing. A failure is most likely related to an
incorrect number of arguments being specified, in which case you should exit with
WRONG_PARAM_COUNT.
To retrieve more than one argument, you can use a similar snippet:
1600
Capítulo 33. Accepting Arguments
zend_get_parameters_ex() only checks whether you’re trying to retrieve too many parameters. If the
function is called with five arguments, but you’re only retrieving three of them with
zend_get_parameters_ex(), you won’t get an error but will get the first three parameters instead.
Subsequent calls of zend_get_parameters_ex() won’t retrieve the remaining arguments, but will get the
same arguments again.
zval **parameter_array[4];
First, the number of arguments is checked to make sure that it’s in the accepted range. After that,
zend_get_parameters_array_ex() is used to fill parameter_array with valid pointers to the argument
values.
A very clever implementation of this can be found in the code handling PHP’s fsockopen() located in
ext/standard/fsock.c, as shown in Ejemplo 33-1. Don’t worry if you don’t know all the functions
used in this source yet; we’ll get to them shortly.
pval **args[5];
1601
Capítulo 33. Accepting Arguments
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
FLS_FETCH();
switch(arg_count) {
case 5:
convert_to_double_ex(args[4]);
conv = (unsigned long) (Z_DVAL_P(args[4]) * 1000000.0);
timeout.tv_sec = conv / 1000000;
timeout.tv_usec = conv % 1000000;
/* fall-through */
case 4:
if (!PZVAL_IS_REF(*args[3])) {
php_error(E_WARNING,"error string argument to fsockopen not passed by reference"
}
pval_copy_constructor(*args[3]);
ZVAL_EMPTY_STRING(*args[3]);
/* fall-through */
case 3:
if (!PZVAL_IS_REF(*args[2])) {
php_error(E_WARNING,"error argument to fsockopen not passed by reference");
return;
}
ZVAL_LONG(*args[2], 0);
break;
}
convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_P(args[1]);
fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the
function checks for the correct range of arguments. Then it uses a fall-through mechanism in a
switch() statement to deal with all arguments. The switch() statement starts with the maximum
number of arguments being passed (five). After that, it automatically processes the case of four
arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages.
1602
Capítulo 33. Accepting Arguments
After having processed the last case, it exits the switch() statement and does the minimal argument
processing needed if the function is invoked with only two arguments.
This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable
number of arguments.
Accessing Arguments
To access arguments, it’s necessary for each argument to have a clearly defined type. Again, PHP’s
extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking,
it’s possible for a caller to pass any kind of data to your functions, whether you want it or not. If you
expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won’t notice.
To work around this, you have to use a set of API functions to force a type conversion on every argument
that’s being passed (see Tabla 33-1).
Note: All conversion functions expect a **zval as parameter.
Function Description
convert_to_boolean_ex() Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubl
convert_to_long_ex() Forces conversion to a long, the default integer type. NULL values, Booleans, resourc
convert_to_double_ex() Forces conversion to a double, the default floating-point type. NULL values, Booleans
convert_to_string_ex() Forces conversion to a string. Strings remain untouched. NULL values are converted t
convert_to_array_ex(value) Forces conversion to an array. Arrays remain untouched. Objects are converted to an a
convert_to_object_ex(value) Forces conversion to an object. Objects remain untouched. NULL values are converted
convert_to_null_ex(value) Forces the type to become a NULL value, meaning empty.
Nota: You can find a demonstration of the behavior in cross_conversion.php on the accompanying
CD-ROM. Figura 33-2 shows the output.
1603
Capítulo 33. Accepting Arguments
Using these functions on your arguments will ensure type safety for all data that’s passed to you. If the
supplied type doesn’t match the required type, PHP forces dummy contents on the resulting value (empty
strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.
Following is a quote from the sample module discussed previously, which makes use of the conversion
functions:
zval **parameter;
convert_to_long_ex(parameter);
RETURN_LONG(Z_LVAL_P(parameter));
After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also
forms the return value of this function. Understanding access to the contents of the value requires a short
discussion of the zval type, whose definition is shown in Ejemplo 33-2.
struct _zval_struct {
/* Variable information */
zvalue_value value; /* value */
unsigned char type; /* active type */
unsigned char is_ref;
short refcount;
};
1604
Capítulo 33. Accepting Arguments
Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to
_zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the
value structure, type, and reference information. The substructure zvalue_value is a union that contains
the variable’s contents. Depending on the variable’s type, you’ll have to access different members of this
union. For a description of both structures, see Tabla 33-2, Tabla 33-3 and Tabla 33-4.
Entry Description
value Union containing this variable’s contents. See Tabla 33-3 for a description.
type Contains this variable’s type. For a list of available types, see Tabla 33-4.
is_ref 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount The number of references that exist for this variable. For every new reference to the value stored in this variable, th
Entry Description
lval Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dval Use this property if the variable is of the type IS_DOUBLE.
str This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the
ht This entry points to the variable’s hash table entry if the variable is an array.
obj Use this property if the variable is of the type IS_OBJECT.
Constant Description
IS_NULL Denotes a NULL (empty) value.
IS_LONG A long (integer) value.
IS_DOUBLE A double (floating point) value.
IS_STRING A string.
IS_ARRAY Denotes an array.
IS_OBJECT An object.
IS_BOOL A Boolean value.
IS_RESOURCE A resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANT A constant (defined) value.
To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on.
Because all values are stored in a union, trying to access data with incorrect union members results in
meaningless output.
Accessing arrays and objects is a bit more complicated and is discussed later.
1605
Capítulo 33. Accepting Arguments
my_function(&$parameter);
But this is not the case with regular parameters! All other parameters that are not passed by reference are
in a read-only state.
This requires you to make sure that you’re really working with a reference - otherwise you might
produce unwanted results. To check for a parameter being passed by reference, you can use the macro
PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in
in Ejemplo 33-3.
zval *parameter;
1606
Capítulo 33. Accepting Arguments
zval **parameter;
/* retrieve parameter */
zend_get_parameters_ex(1, ¶meter);
1607
Capítulo 33. Accepting Arguments
SEPARATE_ZVAL uses emalloc() to allocate the new zval container, which means that even if you don’t
deallocate this memory yourself, it will be destroyed automatically upon script termination. However,
doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM.
Note: As you can easily work around the lack of write access in the "traditional" API (with
zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this
chapter.
1608
Capítulo 34. Creating Variables
1609
Capítulo 34. Creating Variables
When exchanging data from your own extensions with PHP scripts, one of the most important issues is
the creation of variables. This section shows you how to deal with the variable types that PHP supports.
Overview
To create new variables that can be seen "from the outside" by the executing script, you need to allocate a
new zval container, fill this container with meaningful values, and then introduce it to Zend’s internal
symbol table. This basic process is common to all variable creations:
zval *new_variable;
/* set type and variable contents here, see the following sections */
/* introduce this variable by the name "new_variable_name" into the symbol ta-
ble */
ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable);
The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using
INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference
count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it’s a good
idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for
speed (and you don’t have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but
this isn’t recommended because it doesn’t ensure data integrity.
ZEND_SET_SYMBOL takes care of introducing the new variable to Zend’s symbol table. This macro
checks whether the value already exists in the symbol table and converts the new symbol to a reference if
so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a
crucial issue and you’d like to keep memory usage low.
Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying
EG(active_symbol_table), you get access to the currently active symbol table, dealing with the
active, local scope. The local scope may differ depending on whether the function was invoked from
within a function.
If you need to optimize for speed and don’t care about optimal memory usage, you can omit the check
for an existing variable with the same value and instead force insertion into the symbol table by using
zend_hash_update():
zval *new_variable;
/* set type and variable contents here, see the following sections */
1610
Capítulo 34. Creating Variables
/* introduce this variable by the name "new_variable_name" into the symbol ta-
ble */
zend_hash_update(
EG(active_symbol_table),
"new_variable_name",
strlen("new_variable_name") + 1,
&new_variable,
sizeof(zval *),
NULL
);
zval *new_variable;
//
// set type and variable contents here
//
// introduce this variable by the name "new_variable_name" into the global sym-
bol table
ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);
The macro ZEND_SET_SYMBOL is now being called with a reference to the main, global symbol table by
referring EG(symbol_table).
Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use
EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it
requires a pointer.
Similarly, to get a more efficient version, you can hardcode the symbol table update:
zval *new_variable;
//
// set type and variable contents here
//
// introduce this variable by the name "new_variable_name" into the global sym-
bol table
zend_hash_update(
&EG(symbol_table),
1611
Capítulo 34. Creating Variables
"new_variable_name",
strlen("new_variable_name") + 1,
&new_variable,
sizeof(zval *),
NULL
);
Ejemplo 34-1 shows a sample source that creates two variables - local_variable with a local scope and
global_variable with a global scope (see Figure 9.7). The full example can be found on the CD-ROM.
Note: You can see that the global variable is actually not accessible from within the function. This is
because it’s not imported into the local scope using global $global_variable; in the PHP source.
ZEND_FUNCTION(variable_creation)
{
zval *new_var1, *new_var2;
MAKE_STD_ZVAL(new_var1);
MAKE_STD_ZVAL(new_var2);
ZVAL_LONG(new_var1, 10);
ZVAL_LONG(new_var2, 5);
RETURN_NULL();
Longs (Integers)
Now let’s get to the assignment of data to variables, starting with longs. Longs are PHP’s integers and are
very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you
1612
Capítulo 34. Creating Variables
can see that the long data type is directly contained in the union, namely in the lval field. The
corresponding type value for longs is IS_LONG (see Ejemplo 34-2).
zval *new_long;
MAKE_STD_ZVAL(new_long);
new_long->type = IS_LONG;
new_long->value.lval = 10;
zval *new_long;
MAKE_STD_ZVAL(new_long);
ZVAL_LONG(new_long, 10);
Doubles (Floats)
Doubles are PHP’s floats and are as easy to assign as longs, because their value is also contained directly
in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.
zval *new_double;
MAKE_STD_ZVAL(new_double);
new_double->type = IS_DOUBLE;
new_double->value.dval = 3.45;
zval *new_double;
MAKE_STD_ZVAL(new_double);
ZVAL_DOUBLE(new_double, 3.45);
1613
Capítulo 34. Creating Variables
Strings
Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend’s
internal data structures need to be allocated using Zend’s own memory-management functions.
Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings,
you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";
MAKE_STD_ZVAL(new_string);
new_string->type = IS_STRING;
new_string->value.str.len = strlen(string_contents);
new_string->value.str.val = estrdup(string_contents);
Note the usage of Zend’s estrdup() here. Of course, you can also use the predefined macro
ZVAL_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";
MAKE_STD_ZVAL(new_string);
ZVAL_STRING(new_string, string_contents, 1);
ZVAL_STRING accepts a third parameter that indicates whether the supplied string contents should be
duplicated (using estrdup()). Setting this parameter to 1 causes the string to be duplicated; 0 simply uses
the supplied pointer for the variable contents. This is most useful if you want to create a new variable
referring to a string that’s already allocated in Zend internal memory.
If you want to truncate the string at a certain position or you already know its length, you can use
ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to
be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.
To create empty strings, set the string length to 0 and use empty_string as contents:
new_string->type = IS_STRING;
new_string->value.str.len = 0;
new_string->value.str.val = empty_string;
MAKE_STD_ZVAL(new_string);
ZVAL_EMPTY_STRING(new_string);
1614
Capítulo 34. Creating Variables
Booleans
Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:
zval *new_bool;
MAKE_STD_ZVAL(new_bool);
new_bool->type = IS_BOOL;
new_bool->value.lval = 1;
The corresponding macros for this type are ZVAL_BOOL (allowing specification of the value) as well as
ZVAL_TRUE and ZVAL_FALSE (which explicitly set the value to TRUE and FALSE, respectively).
Arrays
Arrays are stored using Zend’s internal hash tables, which can be accessed using the zend_hash_*()
API. For every array that you want to create, you need a new hash table handle, which will be stored in
the ht member of the zval.value container.
There’s a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you
call array_init().
zval *new_array;
MAKE_STD_ZVAL(new_array);
if(array_init(new_array) != SUCCESS)
{
// do error handling here
}
Function Description
add_assoc_long(zval *array, char *key, long Adds an element of type long.
n);()
add_assoc_unset(zval *array, char *key);() Adds an unset element.
add_assoc_bool(zval *array, char *key, int b);() Adds a Boolean element.
add_assoc_resource(zval *array, char *key, int Adds a resource to the array.
r);()
1615
Capítulo 34. Creating Variables
Function Description
add_index_long(zval *array, uint idx, long n);() Adds an element of type long.
add_index_unset(zval *array, uint idx);() Adds an unset element.
add_index_bool(zval *array, uint idx, int b);() Adds a Boolean element.
add_index_resource(zval *array, uint idx, int Adds a resource to the array.
r);()
add_index_double(zval *array, uint idx, double Adds a floating-point value.
d);()
add_index_string(zval *array, uint idx, char *str, Adds a string to the array. The flag duplicate
int duplicate);() specifies whether the string contents have to be
copied to Zend internal memory.
add_index_stringl(zval *array, uint idx, char Adds a string with the desired length length to the
*str, uint length, int duplicate);() array. This function is faster and binary-safe.
Otherwise, behaves like add_index_string()().
Function Description
add_next_index_long(zval *array, long n);() Adds an element of type long.
add_next_index_unset(zval *array);() Adds an unset element.
add_next_index_bool(zval *array, int b);() Adds a Boolean element.
add_next_index_resource(zval *array, int r);() Adds a resource to the array.
add_next_index_double(zval *array, double d);() Adds a floating-point value.
add_next_index_string(zval *array, char *str, int Adds a string to the array. The flag duplicate
duplicate);() specifies whether the string contents have to be
copied to Zend internal memory.
add_next_index_stringl(zval *array, char *str, Adds a string with the desired length length to the
uint length, int duplicate);() array. This function is faster and binary-safe.
Otherwise, behaves like add_index_string()().
All these functions provide a handy abstraction to Zend’s internal hash API. Of course, you can also use
the hash functions directly - for example, if you already have a zval container allocated that you want to
1616
Capítulo 34. Creating Variables
insert into an array. This is done using zend_hash_update()() for associative arrays (see Ejemplo 34-3)
and zend_hash_index_update() for indexed arrays (see Ejemplo 34-4):
MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);
if(array_init(new_array) == FAILURE)
{
// do error handling here
}
ZVAL_LONG(new_element, 10);
MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);
if(array_init(new_array) == FAILURE)
{
// do error handling here
}
ZVAL_LONG(new_element, 10);
1617
Capítulo 34. Creating Variables
Note: To return arrays from a function, use array_init() and all following actions on the predefined
variable return_value (given as argument to your exported function; see the earlier discussion of the call
interface). You do not have to use MAKE_STD_ZVAL on this.
Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array),
which is also recommended for compatibility and style reasons.
Objects
Since objects can be converted to arrays (and vice versa), you might have already guessed that they have
a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there’s a
different API for creating them.
To initialize an object, you use the function object_init():
zval *new_object;
MAKE_STD_ZVAL(new_object);
if(object_init(new_object) != SUCCESS)
{
// do error handling here
}
You can use the functions described in Tabla 34-4 to add members to your object.
Function Description
add_property_long(zval *object, char *key, long l);() Adds a long to the object.
add_property_unset(zval *object, char *key);() Adds an unset property to the obj
add_property_bool(zval *object, char *key, int b);() Adds a Boolean to the object.
add_property_resource(zval *object, char *key, long r);() Adds a resource to the object.
add_property_double(zval *object, char *key, double d);() Adds a double to the object.
add_property_string(zval *object, char *key, char *str, int duplicate);() Adds a string to the object.
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() Adds a string of the specified leng
add_property_zval(zval *obect, char *key, zval *container):() Adds a zval container to the obj
Resources
Resources are a special kind of data type in PHP. The term resources doesn’t really refer to any special
kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in
a special resource list within Zend. Each entry in the list has a correspondending type definition that
denotes the kind of resource to which it refers. Zend then internally manages all references to this
1618
Capítulo 34. Creating Variables
resource. Access to a resource is never possible directly - only via a provided API. As soon as all
references to a specific resource are lost, a corresponding shutdown function is called.
For example, resources are used to store database links and file descriptors. The de facto standard
implementation can be found in the MySQL module, but other modules such as the Oracle module also
make use of resources.
Nota: In fact, a resource can be a pointer to anything you need to handle in your functions (e.g.
pointer to a structure) and the user only has to pass a single resource variable to your function.
To create a new resource you need to register a resource destruction handler for it. Since you can store
any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed.
This works by registering your own resource destruction handler to Zend which in turn gets called by
Zend whenever your resource can be freed (whether manually or automatically). Registering your
resource handler within Zend returns you the resource type handle for that resource. This handle is
needed whenever you want to access a resource of this type later and is most of time stored in a global
static variable within your extension. There is no need to worry about thread safety here because you
only register your resource handler once during module initialization.
The Zend function to register your resource handler is defined as:
There are two different kinds of resource destruction handlers you can pass to this function: a handler for
normal resources and a handler for persistent resources. Persistent resources are for example used for
database connection. When registering a resource, either of these handlers must be given. For the other
handler just pass NULL.
zend_register_list_destructors_ex() accepts the following parameters:
void *ptr;
int type;
int refcount;
1619
Capítulo 34. Creating Variables
} zend_rsrc_list_entry;
typedef struct {
int resource_link;
int resource_type;
} my_resource;
Our resource destruction handler is probably going to look something like this:
// You most likely cast the void pointer to your structure type
do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}
Nota: One important thing to mention: If your resource is a rather complex structure which also
contains pointers to memory you allocated during runtime you have to free them before freeing the
resource itself!
1. create a global variable within the extension holding the resource ID so it can be accessed from
every function which needs it
2. define the resource name
3. write the resource destruction handler
1620
Capítulo 34. Creating Variables
// Somewhere in your extension, define the variable for your registered resources.
// If you wondered what ’le’ stands for: it simply means ’list entry’.
static int le_myresource;
[...]
[...]
PHP_MINIT_FUNCTION(my_extension) {
To actually register a new resource you use can either use the zend_register_resource() function or the
ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for
both map 1:1 it’s a good idea to always use macros to be upwards compatible:
1621
Capítulo 34. Creating Variables
if (rsrc_result) {
rsrc_result->value.lval = rsrc_id;
rsrc_result->type = IS_RESOURCE;
}
return rsrc_id;
The returned rsrc_id uniquly identifies the newly registered resource. You can use the macro
RETURN_RESOURE to return it to the user:
RETURN_RESOURCE(rsrc_id)
Nota: It is common practice that if you want to return the resource immidiately to the user you specify
the return_value as the zval * container.
Zend now keeps track of all references to this resource. As soon as all references to the resource are lost,
the destructor that you previously registered for this resource is called. The nice thing about this setup is
that you don’t have to worry about memory leakages introduced by allocations in your module - just
register all memory allocations that your calling script will refer to as resources. As soon as the script
decides it doesn’t need them anymore, Zend will find out and tell you.
Now that the user got his resource, at some point he is passing it back to one of your functions. The
value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the
resource with the following macro: ZEND_FETCH_RESOURCE:
rsrc This is your pointer which will point to your previously registered resource.
rsrc_type This is the typecast argument for your pointer, e.g. myresource *.
rsrc_id This is the address of the zval *container the user passed to your function, e.g. &z_resource if
default_rsrc_id This integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_name This is the name of the requested resource. It’s a string and is used when the resource can’t be foun
resource_type The resource_type you got back when registering the resource destruction handler. In our exam
This macro has no return value. It is for the developers convenience and takes care of TSRMLS
arguments passing and also does check if the resource could be fetched. It throws a warning message and
returns the current PHP function with NULL if there was a problem retrieving the resource.
To force removal of a resource from the list, use the function zend_list_delete(). You can also force the
reference count to increase if you know that you’re creating another reference for a previously allocated
value (for example, if you’re automatically reusing a default database link). For this case, use the
function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find().
The complete API can be found in zend_list.h.
1622
Capítulo 34. Creating Variables
Macro Description
SET_VAR_STRING(name, value) Creates a new string.
SET_VAR_STRINGL(name, value, length) Creates a new string of the specified length. This
macro is faster than SET_VAR_STRING and also
binary-safe.
SET_VAR_LONG(name, value) Creates a new long.
SET_VAR_DOUBLE(name, value) Creates a new double.
Creating Constants
Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed
without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and
FALSE, to name just two.
To create your own constants, you can use the macros in Tabla 34-6. All the macros create a constant
with the specified name and value.
You can also specify flags for each constant:
Macro
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags)
1623
Capítulo 34. Creating Variables
1624
Capítulo 35. Duplicating Variable Contents: The
Copy Constructor
1625
Capítulo 35. Duplicating Variable Contents: The Copy Constructor
Sooner or later, you may need to assign the contents of one zval container to another. This is easier said
than done, since the zval container doesn’t contain only type information, but also references to places in
Zend’s internal data. For example, depending on their size, arrays and objects may be nested with lots of
hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using
only a reference to them (at most).
To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in
languages that support operator overloading, with the express purpose of copying complex types. If you
define an object in such a language, you have the possibility of overloading the "=" operator, which is
usually responsible for assigning the contents of the lvalue (result of the evaluation of the left side of the
operator) to the rvalue (same for the right side).
Overloading means assigning a different meaning to this operator, and is usually used to assign a
function call to an operator. Whenever this operator would be used on such an object in a program, this
function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can
perform the operation it intends the "=" operator to have (usually an extended form of copying).
This same form of "extended copying" is also necessary for PHP’s zval containers. Again, in the case of
an array, this extended copying would imply re-creation of all hash table entries relating to this array. For
strings, proper memory allocation would have to be assured, and so on.
Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was
pval_copy_constructor()).
A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then
returns the argument:
zval *parameter;
The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications,
however, it gets interesting: The container of parameter is assigned to the (predefined) return_value
container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy
constructor works directly with the supplied argument, and the standard return values are FAILURE on
failure and SUCCESS on success.
If you omit the call to the copy constructor in this example, both parameter and return_value would point
to the same internal data, meaning that return_value would be an illegal additional reference to the same
data structures. Whenever changes occurred in the data that parameter points to, return_value might be
affected. Thus, in order to create separate copies, the copy constructor must be used.
The copy constructor’s counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the
constructor.
1626
Capítulo 36. Returning Values
1627
Capítulo 36. Returning Values
Returning values from your functions to PHP was described briefly in an earlier section; this section
gives the details. Return values are passed via the return_value variable, which is passed to your
functions as argument. The return_value argument consists of a zval container (see the earlier discussion
of the call interface) that you can freely modify. The container itself is already allocated, so you don’t
have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.
To make returning values from functions easier and to prevent hassles with accessing the internal
structures of the zval container, a set of predefined macros is available (as usual). These macros
automatically set the correspondent type and value, as described in Tabla 36-1 and Tabla 36-2.
Nota: The macros in Tabla 36-1 automatically return from your function, those in Tabla 36-2 only set
the return value; they don’t return from your function.
Macro Description
RETURN_RESOURCE(resource) Returns a resource.
RETURN_BOOL(bool) Returns a Boolean.
RETURN_NULL() Returns nothing (a NULL value).
RETURN_LONG(long) Returns a long.
RETURN_DOUBLE(double) Returns a double.
RETURN_STRING(string, duplicate) Returns a string. The duplicate flag indicates
whether the string should be duplicated using
estrdup().
RETURN_STRINGL(string, length, Returns a string of the specified length; otherwise,
duplicate) behaves like RETURN_STRING. This macro is faster
and binary-safe, however.
RETURN_EMPTY_STRING() Returns an empty string.
RETURN_FALSE Returns Boolean false.
RETURN_TRUE Returns Boolean true.
Tabla 36-2. Predefined Macros for Setting the Return Value of a Function
Macro Description
RETVAL_RESOURCE(resource) Sets the return value to the specified resource.
RETVAL_BOOL(bool) Sets the return value to the specified Boolean value.
RETVAL_NULL Sets the return value to NULL.
RETVAL_LONG(long) Sets the return value to the specified long.
RETVAL_DOUBLE(double) Sets the return value to the specified double.
RETVAL_STRING(string, duplicate) Sets the return value to the specified string and
duplicates it to Zend internal memory if desired (see
also RETURN_STRING).
1628
Capítulo 36. Returning Values
RETVAL_STRINGL(string, length, Sets the return value to the specified string and
duplicate) forces the length to become length (see also
RETVAL_STRING). This macro is faster and
binary-safe, and should be used whenever the string
length is known.
RETVAL_EMPTY_STRING Sets the return value to an empty string.
RETVAL_FALSE Sets the return value to Boolean false.
RETVAL_TRUE Sets the return value to Boolean true.
Complex types such as arrays and objects can be returned by using array_init() and object_init(), as
well as the corresponding hash functions on return_value. Since these types cannot be constructed of
trivial information, there are no predefined macros for them.
1629
Capítulo 37. Printing Information
1630
Capítulo 37. Printing Information
Often it’s necessary to print messages to the output stream from your module, just as print() would be
used within a script. PHP offers functions for most generic tasks, such as printing warning messages,
generating output for phpinfo(), and so on. The following sections provide more details. Examples of
these functions can be found on the CD-ROM.
zend_printf()
zend_printf() works like the standard printf(), except that it prints to Zend’s output stream.
zend_error()
zend_error() can be used to generate error messages. This function accepts two arguments; the first is
the error type (see zend_errors.h), and the second is the error message.
Tabla 37-1 shows a list of possible values (see Figura 37-1). These values are also referred to in
php.ini. Depending on which error type you choose, your messages will be logged.
Error Description
E_ERROR Signals an error and terminates execution of the script immediately .
E_WARNING Signals a generic warning. Execution continues.
E_PARSE Signals a parser error. Execution continues.
E_NOTICE Signals a notice. Execution continues. Note that by default the display of this type of error message
E_CORE_ERROR Internal error by the core; shouldn’t be used by user-written modules.
E_COMPILE_ERROR Internal error by the compiler; shouldn’t be used by user-written modules.
E_COMPILE_WARNING Internal warning by the compiler; shouldn’t be used by user-written modules.
1631
Capítulo 37. Printing Information
php_info_print_table_start();
php_info_print_table_header(2, "First column", "Second column");
php_info_print_table_row(2, "Entry in first row", "Another entry");
php_info_print_table_row(2, "Just to fill", "another row here");
php_info_print_table_end();
Execution Information
You can also print execution information, such as the current file being executed. The name of the
function currently being executed can be retrieved using the function get_active_function_name(). This
function returns a pointer to the function name and doesn’t accept any arguments. To retrieve the name of
the file currently being executed, use zend_get_executed_filename(). This function accesses the
executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are
automatically available to every function that’s called directly by Zend (they’re part of the
INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the
executor globals in another function that doesn’t have them available automatically, call the macro
TSRMLS_FETCH() once in that function; this will introduce them to your local scope.
Finally, the line number currently being executed can be retrieved using the function
zend_get_executed_lineno(). This function also requires the executor globals as arguments. For
examples of these functions, see Ejemplo 37-2.
1632
Capítulo 37. Printing Information
1633
Capítulo 38. Startup and Shutdown Functions
1634
Capítulo 38. Startup and Shutdown Functions
Startup and shutdown functions can be used for one-time initialization and deinitialization of your
modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block),
there are global, module, and request startup and shutdown events.
The global startup functions are called once when PHP starts up; similarly, the global shutdown
functions are called once when PHP shuts down. Please note that they’re really only called once, not
when a new Apache process is being created!
The module startup and shutdown functions are called whenever a module is loaded and needs
initialization; the request startup and shutdown functions are called every time a request is processed
(meaning that a file is being executed).
For dynamic extensions, module and request startup/shutdown events happen at the same time.
Declaration and implementation of these functions can be done with macros; see the earlier section
"Declaration of the Zend Module Block" for details.
1635
Capítulo 39. Calling User Functions
1636
Capítulo 39. Calling User Functions
You can call user functions from your own modules, which is very handy when implementing callbacks;
for example, for array walking, searching, or simply for event-based programs.
User functions can be called with the function call_user_function_ex(). It requires a hash value for the
function table you want to access, a pointer to an object (if you want to call a method), the function
name, return value, number of arguments, argument array, and a flag indicating whether you want to
perform zval separation.
Note that you don’t have to specify both function_table and object; either will do. If you want to call a
method, you have to supply the object that contains this method, in which case
call_user_function()automatically sets the function table to this object’s function table. Otherwise, you
only need to specify function_table and can set object to NULL.
Usually, the default function table is the "root" function table containing all function entries. This
function table is part of the compiler globals and can be accessed using the macro CG. To introduce the
compiler globals to your function, call the macro TSRMLS_FETCH once.
The function name is specified in a zval container. This might be a bit surprising at first, but is quite a
logical step, since most of the time you’ll accept function names as parameters from calling functions
within your script, which in turn are contained in zval containers again. Thus, you only have to pass your
arguments through to this function. This zval must be of type IS_STRING.
The next argument consists of a pointer to the return value. You don’t have to allocate memory for this
container; the function will do so by itself. However, you have to destroy this container (using
zval_dtor()) afterward!
Next is the parameter count as integer and an array containing all necessary parameters. The last
argument specifies whether the function should perform zval separation - this should always be set to 0.
If set to 1, the function consumes less memory but fails if any of the parameters need separation.
Ejemplo 39-1 shows a small demonstration of calling a user function. The code calls a function that’s
supplied to it as argument and directly passes this function’s return value through as its own return value.
Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way
here (since they should be separate values, the assignment might be safe), but this is bulletproof.
zval **function_name;
zval *retval;
if((*function_name)->type != IS_STRING)
{
zend_error(E_ERROR, "Function requires string argument");
1637
Capítulo 39. Calling User Functions
TSRMSLS_FETCH();
*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);
<?php
dl("call_userland.so");
function test_function()
{
return("hello");
$return_value = call_userland("test_function");
1638
Capítulo 40. Initialization File Support
1639
Capítulo 40. Initialization File Support
PHP 4 features a redesigned initialization file support. It’s now possible to specify default initialization
entries directly in your code, read and change these values at runtime, and create message handlers for
change notifications.
To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning
of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to
create entries.
PHP_INI_BEGIN()
PHP_INI_ENTRY("first_ini_entry", "has_string_value", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("second_ini_entry", "2", PHP_INI_SYSTEM, OnChangeSecond)
PHP_INI_ENTRY("third_ini_entry", "xyz", PHP_INI_USER, NULL)
PHP_INI_END()
The PHP_INI_ENTRY() macro accepts four parameters: the entry name, the entry value, its change
permissions, and a pointer to a change-notification handler. Both entry name and value must be specified
as strings, regardless of whether they really are strings or integers.
The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the
php3.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional
configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without
restrictions. There’s also a fourth level, PHP_INI_PERDIR, for which we couldn’t verify its behavior yet.
The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these
initialization entries is changed, this handler is called. Such a handler can be declared using the
PHP_INI_MH macro:
PHP_INI_MH(OnChangeSecond)
{
zend_printf("Message caught, our ini entry has been changed to %s<br>", new_value);
return(SUCCESS);
The new value is given to the change handler as string in the variable new_value. When looking at the
definition of PHP_INI_MH, you actually have a few parameters to use:
All these definitions can be found in php_ini.h. Your message handler will have access to a structure
that contains the full entry, the new value, its length, and three optional arguments. These optional
arguments can be specified with the additional macros PHP_INI_ENTRY1 (allowing one additional
1640
Capítulo 40. Initialization File Support
Macro Description
INI_INT(name) Returns the current value of entry name as integer (long).
INI_FLT(name) Returns the current value of entry name as float (double).
INI_STR(name) Returns the current value of entry name as string. Note: This string is not duplicated, but instead p
INI_BOOL(name) Returns the current value of entry name as Boolean (defined as zend_bool, which currently means
INI_ORIG_INT(name) Returns the original value of entry name as integer (long).
INI_ORIG_FLT(name) Returns the original value of entry name as float (double).
INI_ORIG_STR(name) Returns the original value of entry name as string. Note: This string is not duplicated, but instead
INI_ORIG_BOOL(name) Returns the original value of entry name as Boolean (defined as zend_bool, which currently mean
Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup
and shutdown functions, using the macros REGISTER_INI_ENTRIES() and
UNREGISTER_INI_ENTRIES():
ZEND_MINIT_FUNCTION(mymodule)
{
REGISTER_INI_ENTRIES();
ZEND_MSHUTDOWN_FUNCTION(mymodule)
{
UNREGISTER_INI_ENTRIES();
1641
Capítulo 41. Where to Go from Here
1642
Capítulo 41. Where to Go from Here
You’ve learned a lot about PHP. You now know how to create dynamic loadable modules and statically
linked extensions. You’ve learned how PHP and Zend deal with internal storage of variables and how you
can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks
such as printing informational texts, automatically introducing variables to the symbol table, and so on.
Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on
how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that
you take the time to study the header files and some modules (especially the ones in the ext/standard
directory and the MySQL module, as these implement commonly known functionality). This will give
you an idea of how other people have used the API functions - particularly those that didn’t make it into
this chapter.
1643
Capítulo 42. Reference: Some Configuration
Macros
1644
Capítulo 42. Reference: Some Configuration Macros
config.m4
The file config.m4 is processed by buildconf and must contain all the instructions to be executed
during configuration. For example, these can include tests for required external files, such as header files,
libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of
which are described in Tabla 42-1.
Macro Description
AC_MSG_CHECKING(message) Prints a "checking <message>
AC_MSG_RESULT(value) Gives the result to AC_MSG_C
AC_MSG_ERROR(message) Prints message as error messa
AC_DEFINE(name,value,description) Adds #define to php_confi
AC_ADD_INCLUDE(path) Adds a compiler include path;
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) Specifies an additional library
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) Quite a powerful macro, addin
PHP_EXTENSION(modulename, [shared]) This macro is a must to call fo
1645
Capítulo 43. API Macros
1646
Capítulo 43. API Macros
A set of macros was introduced into Zend’s API that simplify access to zval containers (see Tabla 43-1).
Macro Refers to
Z_LVAL(zval) (zval).value.lval
Z_DVAL(zval) (zval).value.dval
Z_STRVAL(zval) (zval).value.str.val
Z_STRLEN(zval) (zval).value.str.len
Z_ARRVAL(zval) (zval).value.ht
Z_LVAL_P(zval) (*zval).value.lval
Z_DVAL_P(zval) (*zval).value.dval
Z_STRVAL_P(zval_p) (*zval).value.str.val
Z_STRLEN_P(zval_p) (*zval).value.str.len
Z_ARRVAL_P(zval_p) (*zval).value.ht
Z_LVAL_PP(zval_pp) (**zval).value.lval
Z_DVAL_PP(zval_pp) (**zval).value.dval
Z_STRVAL_PP(zval_pp) (**zval).value.str.val
Z_STRLEN_PP(zval_pp) (**zval).value.str.len
Z_ARRVAL_PP(zval_pp) (**zval).value.ht
1647