0% found this document useful (0 votes)
732 views

005.13 M319 OpenSSL Functions

Uploaded by

Alberthian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
732 views

005.13 M319 OpenSSL Functions

Uploaded by

Alberthian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 573

OCI8

Ejemplo 1. Code examples

<?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

1. An X.509 resource returned from openssl_x509_read


2. A string having the format file://path/to/cert.pem; the named file must contain a PEM
encoded certificate
3. A string containing the content of a certificate, PEM encoded

• 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

encoded certificate/private key (it may contain both)


4. A string containing the content of a certificate/key, PEM encoded
5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a
key specified using the file:// or textual content notation above, and $passphrase represents a
string containing the passphrase for that private key

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:

Tabla 1. PKCS7 CONSTANTS

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

Nota: These constants were added in 4.0.6.

1078
OpenSSL

openssl_csr_export_to_file (PHP 4 >= 4.2.0)


Exports a CSR to file or a var

bool openssl_csr_export_to_file ( resource csr, string outfilename [, bool notext]) \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.

openssl_csr_export (PHP 4 >= 4.2.0)


Exports a CSR to file or a var

bool openssl_csr_export ( resource csr, string out [, bool notext]) \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.

1079
OpenSSL

openssl_csr_new (PHP 4 >= 4.2.0)


Generates a privkey and CSR

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.

openssl_csr_sign (PHP 4 >= 4.2.0)


Signs a cert with another CERT

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

openssl_error_string (PHP 4 >= 4.0.6)


Return openSSL error message

mixed openssl_error_string ( void) \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 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

Ejemplo 1. openssl_error_string() example

// lets assume you just called an openssl function that failed


while($msg = openssl_error_string())
echo $msg . "<br />\n";

Nota: This function was added in 4.0.6.

openssl_free_key (PHP 4 >= 4.0.4)


Free key resource

void openssl_free_key ( resource key_identifier) \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.

1081
OpenSSL

openssl_free_key() frees the key associated with the specified key_identifier from memory.

openssl_get_privatekey (PHP 4 >= 4.0.4)


Prepare a PEM formatted private key for use

resource openssl_get_privatekey ( mixed key [, string passphrase]) \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 a positive key resource identifier on success, or FALSE on error.


openssl_get_privatekey() parses the PEM formatted private key specified by key and prepares it for
use by other functions. The optional parameter passphrase must be used if the specified key is
encrypted (protected by a passphrase).

openssl_get_publickey (PHP 4 >= 4.0.4)


Extract public key from certificate and prepare it for use

resource openssl_get_publickey ( mixed certificate) \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 a positive key resource identifier on success, or FALSE on error.


openssl_get_publickey() extracts the public key from an X.509 certificate specified by certificate
and prepares it for use by other functions.

openssl_open (PHP 4 >= 4.0.4)


Open sealed data

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.

Ejemplo 1. openssl_open() example

// $sealed and $env_key are assumed to contain the sealed data


// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it


$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open


if (openssl_open($sealed, $open, $env_key, $pkeyid))
echo "here is the opened data: ", $open;
else
echo "failed to open data";

// free the private key from memory


openssl_free_key($pkeyid);

See also openssl_seal().

openssl_pkcs7_decrypt (PHP 4 >= 4.0.6)


Decrypts an S/MIME encrypted message

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

Ejemplo 1. openssl_pkcs7_decrypt() example

// $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

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key))


echo "decrypted!";
else
echo "failed to decrypt!";

Nota: This function was added in 4.0.6.

openssl_pkcs7_encrypt (PHP 4 >= 4.0.6)


Encrypt an S/MIME message

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.

Ejemplo 1. openssl_pkcs7_encrypt() example

// 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,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am


to collect your forged passport!

HQ
EOD;

// load key
$key = implode("", file("nighthawk.pem"));

// save message to file


$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// 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

openssl_pkcs7_sign (PHP 4 >= 4.0.6)


sign an S/MIME message

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.

Ejemplo 1. openssl_pkcs7_sign() example

// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD

You have my authorization to spend $10,000 on dinner expenses.

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

Nota: This function was added in 4.0.6.

openssl_pkcs7_verify (PHP 4 >= 4.0.6)


Verifies the signature of an S/MIME signed message

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.

Nota: This function was added in 4.0.6.

openssl_pkey_export_to_file (PHP 4 >= 4.2.0)


Gets an exportable representation of a key into a file

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.

openssl_pkey_export (PHP 4 >= 4.2.0)


Gets an exportable representation of a key into a string or file

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.

openssl_pkey_new (PHP 4 >= 4.2.0)


Generates a new private key

resource openssl_pkey_new ( [array configargs]) \linebreak

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.

openssl_private_decrypt (PHP 4 >= 4.0.6)


Decrypts data with private key

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.

openssl_private_encrypt (PHP 4 >= 4.0.6)


Encrypts data with private key

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.

openssl_public_decrypt (PHP 4 >= 4.0.6)


Decrypts data with public key

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.

openssl_public_encrypt (PHP 4 >= 4.0.6)


Encrypts data with public key

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.

openssl_seal (PHP 4 >= 4.0.4)


Seal (encrypt) data

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.

Ejemplo 1. openssl_seal() example

// $data is assumed to contain the data to be sealed

// fetch public keys for our recipients, and ready them


$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);

1091
OpenSSL

// Repeat for second recipient


$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

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

// free the keys from memory


openssl_free_key($pk1);
openssl_free_key($pk2);

See also openssl_open().

openssl_sign (PHP 4 >= 4.0.4)


Generate signature

bool openssl_sign ( string data, string signature, mixed priv_key_id) \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.

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.

Ejemplo 1. openssl_sign() example

// $data is assumed to contain the data to be signed

// fetch private key from file and ready it


$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);

1092
OpenSSL

$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory


openssl_free_key($pkeyid);

See also openssl_verify().

openssl_verify (PHP 4 >= 4.0.4)


Verify signature

int openssl_verify ( string data, string signature, mixed pub_key_id) \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 1 if the signature is correct, 0 if it is incorrect, and -1 on error.


openssl_verify() verifies that the signature is correct for the specified data using the public key
associated with pub_key_id. This must be the public key corresponding to the private key used for
signing.

Ejemplo 1. openssl_verify() example

// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it


$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not


$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1)
echo "good";
elseif ($ok == 0)

1093
OpenSSL

echo "bad";
else
echo "ugly, error checking signature";

// free the key from memory


openssl_free_key($pubkeyid);

See also openssl_sign().

openssl_x509_check_private_key (PHP 4 >= 4.2.0)


Checks if a private key corresponds to a CERT

bool openssl_x509_check_private_key ( mixed cert, mixed key) \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.

openssl_x509_checkpurpose (PHP 4 >= 4.0.6)


Verifies if a certificate can be used for a particular purpose

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.

Tabla 1. openssl_x509_checkpurpose() purposes

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!

Nota: This function was added in 4.0.6.

openssl_x509_export_to_file (PHP 4 >= 4.2.0)


Exports a CERT to file or a var

bool openssl_x509_export_to_file ( mixed x509, string outfilename [, bool notext]) \linebreak

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.

openssl_x509_export (PHP 4 >= 4.2.0)


Exports a CERT to file or a var

bool openssl_x509_export ( mixed x509, string outfilename [, bool notext]) \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.

openssl_x509_free (PHP 4 >= 4.0.6)


Free certificate resource

void openssl_x509_free ( resource x509cert) \linebreak

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.

Nota: This function was added in 4.0.6.

openssl_x509_parse (PHP 4 >= 4.0.6)


Parse an X509 certificate and return the information as an array

array openssl_x509_parse ( mixed x509cert [, bool shortnames]) \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_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.

Nota: This function was added in 4.0.6.

openssl_x509_read (PHP 4 >= 4.0.6)


Parse an X.509 certificate and return a resource identifier for it

resource openssl_x509_read ( mixed x509certdata) \linebreak

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.

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource


identifier for it.

Nota: This function was added in 4.0.6.

1098
LXXII. Funciones Oracle

1099
Oracle

Ora_Bind (PHP 3, PHP 4 )


Vincula una variable PHP a un parámetro 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";
?>

Ora_Close (PHP 3, PHP 4 )


Cierra un cursor Oracle

int ora_close ( int cursor) \linebreak


Devuelve verdadero si el cierre fué exitoso, o falso de lo contrario. Los detalles de los errores se
recuperan usando las funciones ora_error() y ora_errorcode().
Esta función cierra un cursor de datos abierto con ora_open().

Ora_ColumnName (PHP 3, PHP 4 )


toma el nombre de una columna de resultados Oracle

string Ora_ColumnName ( int cursor, int column) \linebreak

1100
Oracle

Devuelve el nomre de un campo/columna column en el cursor cursor. el nombre devuelto estará en


letras mayúsculas.

Ora_ColumnSize (PHP 3, PHP 4 )


get size of Oracle result column

int Ora_ColumnSize ( int cursor, int column) \linebreak


Returns the size of the Oracle column column on the cursor cursor. Column 0 is the first column.

Ora_ColumnType (PHP 3, PHP 4 )


toma el tipo de una columna de resultados Oracle

string Ora_ColumnType ( int cursor, int column) \linebreak


Devuelve el nombre del tipo de datos del campo o columna column en el cursor cursor. Se devolverá
un tipo de datos, de entre los siguientes:
"VARCHAR2"
"VARCHAR"
"CHAR"
"NUMBER"
"LONG"
"LONG RAW"
"ROWID"
"DATE"
"CURSOR"

Ora_Commit (PHP 3, PHP 4 )


realiza una transacción Oracle

int ora_commit ( int conn) \linebreak


Devuelve verdadero si es exitosa, de lo cantrario devuelve falso. Puede verse los detalles del error usando
las funciones ora_error() y ora_errorcode(). Esta función realiza una transacción Oracle. Se define como
transacción cualquier cambio en una conexión dada, desde la última tarea/retroceso en la ejecucion
(rollback), anulación de la ejecución automática de tareas (autocommit), o cuando se ha establecido la
conexión.

Ora_CommitOff (PHP 3, PHP 4 )


deshabilita el modo automatico de ejecucion de tareas (autocommit)

1101
Oracle

int ora_commitoff ( int conn) \linebreak


Devuelve verdadero si se ejecuta con éxito, sino devuelve falso. Los pormenores del error en cuestion,
pueden revisarse invocando las funciones ora_error() y ora_errorcode().
Esta función deshabilita la ejecucion automatica luego de cada instancia ora_exec().

Ora_CommitOn (PHP 3, PHP 4 )


Habilita la ejecucion automática de tareas (autocommit)

int ora_commiton ( int conn) \linebreak


Esta función habilita la ejecucion automatica luego de cada instancia ora_exec() en la conexión dada.
Devuelve verdadero si se ejecuta con éxito, sino devuelve falso. Los pormenores del error en cuestion,
pueden revisarse invocando las funciones ora_error() y ora_errorcode().

Ora_Do (PHP 3, PHP 4 )


Parse, Exec, Fetch

int ora_do ( int conn, string query) \linebreak


This function is quick combination of ora_parse(), ora_exec() and ora_fetch(). It will parse and execute a
statement, then fetch the first result row.
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error()
and ora_errorcode() functions.
See also ora_parse(),ora_exec(), and ora_fetch().

Ora_Error (PHP 3, PHP 4 )


toma los mensajes de error de Oracle

string Ora_Error ( int cursor_or_connection) \linebreak


Devuelve los mensajes de error en la forma XXX-NNNNN donde XXX es la procedencia del error y
NNNNN es la identificación del mensaje de error.

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

Ora_ErrorCode (PHP 3, PHP 4 )


captura el código de error Oracle

int Ora_ErrorCode ( int cursor_or_connection) \linebreak


Devuelve el codigo numérico de error de la última declaración ejecutada en el cursor o conexion
espacificada.

Nota: El soporte para las identificaciones de conexión fue agregado en la versión 3.0.4.

Ora_Exec (PHP 3, PHP 4 )


ejecuta las declaraciones interpretadas en un cursor Oracle

int ora_exec ( int cursor) \linebreak


Devuelve verdadero ante la ejecución exitosa, de lo contrario, devuelve falso. Los detalles del error
pueden verse invocando las funciones ora_error() y ora_errorcode().

Ora_Fetch_Into (PHP 3, PHP 4 )


Fetch a row into the specified result array

int ora_fetch_into ( int cursor, array result [, int flags]) \linebreak


Fetches a row of data into an array. The flags has two flag values: if the ORA_FETCHINTO_NULLS flag
is set, columns with NULL values are set in the array; and if the ORA_FETCHINTO_ASSOC flag is set, an
associative array is created.
Returns the number of columns fetched.

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’];
?>

See also ora_parse(),ora_exec(), ora_fetch(), and ora_do().

Ora_Fetch (PHP 3, PHP 4 )


extrae una fila de datos a partir de un cursor

int ora_fetch ( int cursor) \linebreak


Devuelve verdadero (se extrajo una fila) o falso (no hay mas filas, o ha ocurrido un error). Si ocurre un
error, los detalles del mismo pueden verse invocando las funciones ora_error() y ora_errorcode(). Si no
hubo errores, ora_errorcode() devolverá 0. Recupera una hilera de datos partiendo de un cursor
especificado.

Ora_GetColumn (PHP 3, PHP 4 )


toma datos de la fila extraída

mixed ora_getcolumn ( int cursor, mixed column) \linebreak


Devuelve la columna de datos. Si hay un error, se devuelve falso y ora_errorcode() devulve un valor
distinto de cero. Note, de igual manera, que la busqueda de un resultado Falso en esta función, puede
resultar verdadera, aún en casos en que no ocurran errores:(resultado NULO, cadenas vacias, valor 0 o
cadenas "0"). Extrae los datos para una columna o resultado de función.

Ora_Logoff (PHP 3, PHP 4 )


cierra una conexión Oracle

1104
Oracle

int ora_logoff ( int connection) \linebreak


Devuelve verdadero si es exitosa, o falso si hay errores. Los detalles del error pueden verse invocando las
funciones ora_error() y ora_errorcode(). Cierra la sesión de trabajo del usuario, y lo desconecta del
servidor.

Ora_Logon (PHP 3, PHP 4 )


Abre una conexión Oracle

int ora_logon ( string usuario, string contraseña) \linebreak


Establece una conexión entre PHP y una base de datos Oracle, con los datos de nombre de usuario y
contraseña especificados.
Las conexiones pueden llevarse adelante usando SQL*Net indicando el nombre TNS al usuario de
este modo:

$conn = Ora_Logon("usuario@TNSNAME", "contraseña");

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().

Ora_Numcols (PHP 3, PHP 4 )


Returns the number of columns

int ora_numcols ( int cursor_ind) \linebreak


ora_numcols() returns the number of columns in a result. Only returns meaningful values after an
parse/exec/fetch sequence.
See also ora_parse(),ora_exec(), ora_fetch(), and ora_do().

Ora_Numrows (PHP 3, PHP 4 )


Returns the number of rows

int ora_numrows ( int cursor_ind) \linebreak


ora_numrows() returns the number of rows in a result.

1105
Oracle

Ora_Open (PHP 3, PHP 4 )


abre un cursor Oracle

int ora_open ( int connection) \linebreak


Abre un cursor asociado con la conexión.
Devuelve el índice del cursor o Falso si hay un error. Los detalles del error pueden verse invocando las
funciones ora_error() y ora_errorcode().

Ora_Parse (PHP 3, PHP 4 )


interpreta una declaración SQL

int ora_parse ( int cursor_ind, string sql_statement, int defer) \linebreak


Esta función interpreta una declaración SQL o un bloque PL/SQL y los asocia con el cursor dado.
Devuelve 0 si se ejecuta con exito, o -1 ante un error.

Ora_pLogon (PHP 3, PHP 4 )


Open a persistent Oracle connection

int ora_plogon ( string user, string password) \linebreak


Establishes a persistent connection between PHP and an Oracle database with the given username and
password.
See also ora_logon().

Ora_Rollback (PHP 3, PHP 4 )


retrocede en la lista de transacciones (hace un roll back)

int ora_rollback ( int connection) \linebreak


Deshace una transaccion Oracle. (Ver ora_commit() para la definición de transacción.)
Devuelve verdadero si tiene éxito, o falso si hay un error. Los detalles del error pueden verse invocando
las funciones ora_error() y ora_errorcode().

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

This will just connect to SQL Server.

1107
OvrimosSQL

ovrimos_close (PHP 4 >= 4.0.3)


Closes the connection to ovrimos

void ovrimos_close ( int connection) \linebreak


ovrimos_close() is used to close the specified connection.
ovrimos_close() closes a connection to Ovrimos. This has the effect of rolling back uncommitted
transactions.

ovrimos_commit (PHP 4 >= 4.0.3)


Commits the transaction

int ovrimos_commit ( int connection_id) \linebreak


ovrimos_commit() is used to commit the transaction.
ovrimos_commit() commits the transaction.

ovrimos_connect (PHP 4 >= 4.0.3)


Connect to the specified database

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.

Ejemplo 1. ovrimos_connect() Example

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

ovrimos_cursor (PHP 4 >= 4.0.3)


Returns the name of the cursor

int ovrimos_cursor ( int result_id) \linebreak


ovrimos_cursor() is used to get the name of the cursor.
ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or
deletes.

ovrimos_exec (PHP 4 >= 4.0.3)


Executes an SQL statement

int ovrimos_exec ( int connection_id, string query) \linebreak


ovrimos_exec() is used to execute an SQL statement.
ovrimos_exec() executes an SQL statement (query or update) and returns a result_id or FALSE.
Evidently, the SQL statement should not contain parameters.

ovrimos_execute (PHP 4 >= 4.0.3)


Executes a prepared SQL statement

int ovrimos_execute ( int result_id [, array parameters_array]) \linebreak


ovrimos_execute() is used to execute an SQL statement.
ovrimos_execute() executes a prepared statement. Returns TRUE or FALSE. If the prepared statement
contained parameters (question marks in the statement), the correct number of parameters should be
passed in an array. Notice that I don’t follow the PHP convention of placing just the name of the optional
parameter inside square brackets. I couldn’t bring myself on liking it.

ovrimos_fetch_into (PHP 4 >= 4.0.3)


Fetches a row from the result set

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.

Ejemplo 1. A fetch into example

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

This example will fetch a row.

ovrimos_fetch_row (PHP 4 >= 4.0.3)


Fetches a row from the result set

int ovrimos_fetch_row ( int result_id [, int how [, int row_number]]) \linebreak


ovrimos_fetch_row() is used to fetch a row from the result set.
ovrimos_fetch_row() fetches a row from the result set. Column values should be retrieved with other
calls. Returns TRUE or FALSE.

1110
OvrimosSQL

Ejemplo 1. A fetch row example

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

This will fetch a row and print the result.

ovrimos_field_len (PHP 4 >= 4.0.3)


Returns the length of the output column

int ovrimos_field_len ( int result_id, int field_number) \linebreak


ovrimos_field_len() is used to get the length of the output column.
ovrimos_field_len() returns the length of the output column at the (1-based) index specified.

ovrimos_field_name (PHP 4 >= 4.0.3)


Returns the output column name

int ovrimos_field_name ( int result_id, int field_number) \linebreak


ovrimos_field_name() is used to get the output column name.

1111
OvrimosSQL

ovrimos_field_name() returns the output column name at the (1-based) index specified.

ovrimos_field_num (PHP 4 >= 4.0.3)


Returns the (1-based) index of the output column

int ovrimos_field_num ( int result_id, string field_name) \linebreak


ovrimos_field_num() is used to get the (1-based) index of the output column.
ovrimos_field_num() returns the (1-based) index of the output column specified by name, or FALSE.

ovrimos_field_type (PHP 4 >= 4.0.3)


Returns the (numeric) type of the output column

int ovrimos_field_type ( int result_id, int field_number) \linebreak


ovrimos_field_type() is used to get the (numeric) type of the output column.
ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified.

ovrimos_free_result (PHP 4 >= 4.0.3)


Frees the specified result_id

int ovrimos_free_result ( int result_id) \linebreak


ovrimos_free_result() is used to free the result_id.
ovrimos_free_result() frees the specified result_id. Returns TRUE.

ovrimos_longreadlen (PHP 4 >= 4.0.3)


Specifies how many bytes are to be retrieved from long datatypes

int ovrimos_longreadlen ( int result_id, int length) \linebreak


ovrimos_longreadlen() is used to specify how many bytes are to be retrieved from long datatypes.
ovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar
and long varbinary). Default is zero. Regardless of its taking a result_id as an argument, it currently sets
this parameter for all result sets. Returns TRUE.

1112
OvrimosSQL

ovrimos_num_fields (PHP 4 >= 4.0.3)


Returns the number of columns

int ovrimos_num_fields ( int result_id) \linebreak


ovrimos_num_fields() is used to get the number of columns.
ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.

ovrimos_num_rows (PHP 4 >= 4.0.3)


Returns the number of rows affected by update operations

int ovrimos_num_rows ( int result_id) \linebreak


ovrimos_num_rows() is used to get the number of rows affected by update operations.
ovrimos_num_rows() returns the number of rows affected by update operations.

ovrimos_prepare (PHP 4 >= 4.0.3)


Prepares an SQL statement

int ovrimos_prepare ( int connection_id, string query) \linebreak


ovrimos_prepare() is used to prepare an SQL statement.
ovrimos_prepare() prepares an SQL statement and returns a result_id (or FALSE on failure).

Ejemplo 1. Connect to Ovrimos SQL Server and prepare a statement

<?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

echo "Prepare not ok!\n";


}
ovrimos_close ($conn);
}
?>

This will connect to Ovrimos SQL Server, prepare a statement and the execute it.

ovrimos_result_all (PHP 4 >= 4.0.3)


Prints the whole result set as an HTML table

int ovrimos_result_all ( int result_id [, string format]) \linebreak


ovrimos_result_all() is used to print an HTML table containing the whole result set.
ovrimos_result_all() prints the whole result set as an HTML table. Returns TRUE or FALSE.

Ejemplo 1. Prepare a statement, execute, and view the result

<?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

Ejemplo 2. Ovrimos_result_all with meta-information

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

Ejemplo 3. ovrimos_result_all example

<?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

ovrimos_result (PHP 4 >= 4.0.3)


Retrieves the output column

int ovrimos_result ( int result_id, mixed field) \linebreak


ovrimos_result() is used to retrieve the output column.
ovrimos_result() retrieves the output column specified by ’field’, either as a string or as an 1-based
index.

ovrimos_rollback (PHP 4 >= 4.0.3)


Rolls back the transaction

int ovrimos_rollback ( int connection_id) \linebreak


ovrimos_rollback() is used to roll back the transaction.
ovrimos_rollback() rolls back the transaction.

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.

Ejemplo 1. Output Control example

<?php

ob_start();
echo "Hello\n";

setcookie ("cookiename", "cookiedata");

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

flush (PHP 3, PHP 4 )


Flush the output buffer

void flush ( void) \linebreak


Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc.) This
effectively tries to push all the output so far to the user’s browser.

ob_clean (PHP 4 >= 4.2.0)


Clean (erase) the output buffer

void ob_clean ( void) \linebreak


This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean() does.
See also ob_flush(), ob_end_flush() and ob_end_clean().

ob_end_clean (PHP 4 )
Clean (erase) the output buffer and turn off output buffering

void ob_end_clean ( void) \linebreak


This function discards the contents of the output buffer and turns off output buffering.
See also ob_start() and ob_end_flush().

ob_end_flush (PHP 4 )
Flush (send) the output buffer and turn off output buffering

void ob_end_flush ( void) \linebreak


This function will send the contents of the output buffer (if any) and turn output buffering off. If you
want to further process the buffer’s contents you have to call ob_get_contents() before ob_end_flush() as
the buffer contents are discarded after ob_get_contents() is called.
See also ob_start(), ob_get_contents(), and ob_end_clean().

1118
Output Control

ob_flush (PHP 4 >= 4.2.0)


Flush (send) the output buffer

void ob_flush ( void) \linebreak


This function will send the contents of the output buffer (if any). If you want to further process the
buffer’s contents you have to call ob_get_contents() before ob_flush() as the buffer contents are
discarded after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.
See also ob_get_contents(), ob_clean(), ob_end_flush() and ob_end_clean().

ob_get_contents (PHP 4 )
Return the contents of the output buffer

string ob_get_contents ( void) \linebreak


This will return the contents of the output buffer or FALSE, if output buffering isn’t active.
See also ob_start() and ob_get_length().

ob_get_length (PHP 4 >= 4.0.2)


Return the length of the output buffer

string ob_get_length ( void) \linebreak


This will return the length of the contents in the output buffer or FALSE, if output buffering isnt’t active.
See also ob_start() and ob_get_contents().

ob_get_level (PHP 4 >= 4.2.0)


Return the nesting level of the output buffering mechanism

int ob_get_level ( void) \linebreak


This will return the level of nested output buffering handlers.
See also ob_start() and ob_get_contents().

1119
Output Control

ob_get_status (PHP 4 >= 4.2.0)


Get status of output buffers

array ob_get_status ( [bool full_status]) \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.

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 (PHP 4 >= 4.0.4)


ob_start callback function to gzip output buffer

string ob_gzhandler ( string buffer [, int mode]) \linebreak

Nota: mode was added in PHP 4.0.5.

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.

Ejemplo 1. ob_gzhandler() Example

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.
</html>
<body>

1120
Output Control

See also ob_start() and ob_end_flush().

ob_implicit_flush (PHP 4 )
Turn implicit flush on/off

void ob_implicit_flush ( [int flag]) \linebreak


ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit
flushing will result in a flush operation after every output call, so that explicit calls to flush() will no
longer be needed.
Turning implicit flushing on will disable output buffering, the output buffers current output will be sent
as if ob_end_flush() had been called.
See also flush(), ob_start(), and ob_end_flush().

ob_start (PHP 4 )
Turn on output buffering

void ob_start ( void) \linebreak


This function will turn output buffering on. While output buffering is active no output is sent from the
script, instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To
output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will
silently discard the buffer contents.
See also ob_get_contents(), ob_end_flush(), ob_end_clean(), and ob_implicit_flush()

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:

Ejemplo 1. Overloading a PHP class

<?php

class OO
{
var $a = 111;
var $elem = array(’b’ => 9, ’c’ => 42);

// Callback method for getting a property


function __get($prop_name, &$prop_value)
{
if (isset($this->elem[$prop_name])) {
$prop_value = $this->elem[$prop_name];
return true;
} else {
return false;
}
}

// Callback method for setting a property


function __set($prop_name, $prop_value)
{
$this->elem[$prop_name] = $prop_value;
return true;
}
}

// Here we overload the OO object

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:

// add a new item to the $elem array in OO


$o->x = 56;

// instantiate stdclass (it is built-in in PHP 4)


// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it


// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>

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

overload (PHP 4 >= 4.2.0)


Enable property and method call overloading for a class

void overload ( [string class_name]) \linebreak


The overload() function will enable property and method call overloading for a class identified by
class_name. See an example in the introductory section of this part.

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.

Ejemplo 1. Creating a PDF document with pdflib 0.6

<?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>";
?>

The PHP script getpdf.php3 just outputs the pdf document.

<?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:

Ejemplo 2. Creating a PDF document with pdflib 2.x

<?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 PHP script getpdf.php3 is the same as above.

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

Ejemplo 3. pdfclock example from pdflib 2.x distribution

<?php
$pdffilename = "clock.pdf";
$radius = 200;
$margin = 20;
$pagecount = 40;

$fp = fopen($pdffilename, "w");


$pdf = pdf_open($fp);
pdf_set_info_creator($pdf, "pdf_clock.php3");
pdf_set_info_author($pdf, "Uwe Steinmann");
pdf_set_info_title($pdf, "Analog Clock");

while($pagecount-- > 0) {

1127
PDF

pdf_begin_page($pdf, 2 * ($radius + $margin), 2 * ($radius + $margin));

pdf_set_transition($pdf, 4); /* wipe */


pdf_set_duration($pdf, 0.5);

pdf_translate($pdf, $radius + $margin, $radius + $margin);


pdf_save($pdf);
pdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

/* 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();

/* draw hour hand */


pdf_save($pdf);
pdf_rotate($pdf,-(($ltime[’minutes’]/60.0)+$ltime[’hours’]-3.0)*30.0);
pdf_moveto($pdf, -$radius/10, -$radius/20);
pdf_lineto($pdf, $radius/2, 0.0);
pdf_lineto($pdf, -$radius/10, $radius/20);
pdf_closepath($pdf);
pdf_fill($pdf);
pdf_restore($pdf);

/* draw minute hand */


pdf_save($pdf);
pdf_rotate($pdf,-(($ltime[’seconds’]/60.0)+$ltime[’minutes’]-15.0)*6.0);
pdf_moveto($pdf, -$radius/10, -$radius/20);
pdf_lineto($pdf, $radius * 0.8, 0.0);
pdf_lineto($pdf, -$radius/10, $radius/20);
pdf_closepath($pdf);
pdf_fill($pdf);
pdf_restore($pdf);

/* draw second hand */

1128
PDF

pdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);


pdf_setlinewidth($pdf, 2);
pdf_save($pdf);
pdf_rotate($pdf, -(($ltime[’seconds’] - 15.0) * 6.0));
pdf_moveto($pdf, -$radius/5, 0.0);
pdf_lineto($pdf, $radius, 0.0);
pdf_stroke($pdf);
pdf_restore($pdf);

/* draw little circle at center */


pdf_circle($pdf, 0, 0, $radius/30);
pdf_fill($pdf);

pdf_restore($pdf);

pdf_end_page($pdf);
}

$pdf = pdf_close($pdf);
fclose($fp);
echo "<A HREF=getpdf.php3?filename=".$pdffilename.">finished</A>";
?>

The PHP script getpdf.php3 just outputs the pdf document.


<?php
$fp = fopen($filename, "r");
header("Content-type: application/pdf");
fpassthru($fp);
fclose($fp);
?>

1129
PDF

pdf_add_annotation (PHP 3>= 3.0.12, PHP 4 )


Adds annotation

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

pdf_add_bookmark (PHP 4 >= 4.0.1)


Adds bookmark for current page

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.

pdf_add_launchlink (PHP 4 >= 4.0.5)


Add a launch annotation for current page

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

pdf_add_locallink (PHP 4 >= 4.0.5)


Add a link annotation for current page

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.

pdf_add_note (PHP 4 >= 4.0.5)


Add a note annotation for current page

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

PDF_add_outline (PHP 3>= 3.0.6, PHP 4 )


Adds bookmark for current page

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.

pdf_add_pdflink (PHP 3>= 3.0.12, PHP 4 )


Adds file link annotation for current page

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

pdf_add_thumbnail (PHP 4 >= 4.0.5)


Adds thumbnail for current page

int pdf_add_thumbnail ( int pdf object, int image) \linebreak


Add an existing image as thumbnail for the current page.

pdf_add_weblink (PHP 3>= 3.0.12, PHP 4 )


Adds weblink for current page

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.

PDF_arc (PHP 3>= 3.0.6, PHP 4 )


Draws an arc

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().

pdf_arcn (PHP 4 >= 4.0.5)


Draws an arc (clockwise)

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

pdf_attach_file (PHP 4 >= 4.0.5)


Adds a file attachement for current page

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

PDF_begin_page (PHP 3>= 3.0.6, PHP 4 )


Starts new page

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

See also PDF_end_page().

pdf_begin_pattern (PHP 4 >= 4.0.5)


Starts new pattern

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.

pdf_begin_template (PHP 4 >= 4.0.5)


Starts new template

void pdf_begin_template ( int pdf object, float width, float height) \linebreak
Start a new template definition.

PDF_circle (PHP 3>= 3.0.6, PHP 4 )


Draws a circle

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().

PDF_clip (PHP 3>= 3.0.6, PHP 4 )


Clips to current path

void pdf_clip ( int pdf document) \linebreak


The PDF_clip() function clips all drawing to the current path.

1133
PDF

PDF_close_image (PHP 3>= 3.0.7, PHP 4 )


Closes an image

void pdf_close_image ( int image) \linebreak


The PDF_close_image() function closes an image which has been opened with any of the
PDF_open_xxx() functions.
See also PDF_open_jpeg(), PDF_open_gif(), PDF_open_memory_image().

pdf_close_pdi_page (PHP 4 >= 4.0.5)


Close the page handle

void pdf_close_pdi_page ( int pdf object, int pagehandle) \linebreak


Close the page handle, and free all page-related resources.

pdf_close_pdi (PHP 4 >= 4.0.5)


Close the input PDF document

void pdf_close_pdi ( int pdf object, int dochandle) \linebreak


Close all open page handles, and close the input PDF document.

PDF_close (PHP 3>= 3.0.6, PHP 4 )


Closes a pdf document

void pdf_close ( int pdf document) \linebreak


The PDF_close() function closes the pdf document.

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

See also PDF_open(), fclose().

PDF_closepath_fill_stroke (PHP 3>= 3.0.6, PHP 4 )


Closes, fills and strokes current path

void pdf_closepath_fill_stroke ( int pdf document) \linebreak


The PDF_closepath_fill_stroke() function closes, fills the interior of the current path with the current
fill color and draws current path.
See also PDF_closepath(), PDF_stroke(), PDF_fill(), PDF_setgray_fill(), PDF_setgray(),
PDF_setrgbcolor_fill(), PDF_setrgbcolor().

PDF_closepath_stroke (PHP 3>= 3.0.6, PHP 4 )


Closes path and draws line along path

void pdf_closepath_stroke ( int pdf document) \linebreak


The PDF_closepath_stroke() function is a combination of PDF_closepath() and PDF_stroke(). It also
clears the path.
See also PDF_closepath(), PDF_stroke().

PDF_closepath (PHP 3>= 3.0.6, PHP 4 )


Closes path

void pdf_closepath ( int pdf document) \linebreak


The PDF_closepath() function closes the current path. This means, it draws a line from current point to
the point where the first line was started. Many functions like PDF_moveto(), PDF_circle() and
PDF_rect() start a new path.

pdf_concat (PHP 4 >= 4.0.5)


Concatenate a matrix to the CTM

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.

PDF_continue_text (PHP 3>= 3.0.6, PHP 4 )


Outputs text in next line

void pdf_continue_text ( int pdf document, string text) \linebreak


The PDF_continue_text() function outputs the string in text in the next line. The distance between the
lines can be set with PDF_set_leading().
See also PDF_show_xy(), PDF_set_leading(), PDF_set_text_pos().

PDF_curveto (PHP 3>= 3.0.6, PHP 4 )


Draws a curve

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().

pdf_delete (PHP 4 >= 4.0.5)


Deletes a PDF object

void pdf_delete ( int pdf object) \linebreak


Delete the PDF object, and free all internal resources.

PDF_end_page (PHP 3>= 3.0.6, PHP 4 )


Ends a page

void pdf_end_page ( int pdf document) \linebreak


The PDF_end_page() function ends a page. Once a page is ended it cannot be modified anymore.
See also PDF_begin_page().

1136
PDF

pdf_end_pattern (PHP 4 >= 4.0.5)


Finish pattern

void pdf_end_pattern ( int pdf object) \linebreak


Finish the pattern definition.

pdf_end_template (PHP 4 >= 4.0.5)


Finish template

void pdf_end_template ( int pdf object) \linebreak


Finish the template definition.

PDF_endpath (PHP 3>= 3.0.6, PHP 4 )


Ends current path

void pdf_endpath ( int pdf document) \linebreak


The PDF_endpath() function ends the current path but does not close it.
See also PDF_closepath().

PDF_fill_stroke (PHP 3>= 3.0.6, PHP 4 )


Fills and strokes current path

void pdf_fill_stroke ( int pdf document) \linebreak


The PDF_fill_stroke() function fills the interior of the current path with the current fill color and draws
current path.
See also PDF_closepath(), PDF_stroke(), PDF_fill(), PDF_setgray_fill(), PDF_setgray(),
PDF_setrgbcolor_fill(), PDF_setrgbcolor().

PDF_fill (PHP 3>= 3.0.6, PHP 4 )


Fills current path

void pdf_fill ( int pdf document) \linebreak

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().

pdf_findfont (PHP 4 >= 4.0.5)


Prepare font for later use with pdf_setfont().

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.

Ejemplo 1. pdf_findfont() example

<?php

$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);


if ($font) {
pdf_setfont($pdf, $font, 10);
}

?>

pdf_get_buffer (PHP 4 >= 4.0.5)


Fetch the buffer containig the generated PDF data.

string pdf_get_buffer ( int pdf object) \linebreak


Get the contents of the PDF output buffer. The result must be used by the client before calling any other
PDFlib function.

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().

pdf_get_image_height (PHP 3>= 3.0.12, PHP 4 )


Returns height of an image

string pdf_get_image_height ( int pdf object, int image) \linebreak


pdf_get_image_height() is deprecated, use pdf_get_value() instead.

pdf_get_image_width (PHP 3>= 3.0.12, PHP 4 )


Returns width of an image

string pdf_get_image_width ( int pdf object, int image) \linebreak


The pdf_get_image_width() is deprecated, use pdf_get_value() instead.

pdf_get_majorversion (PHP 4 >= 4.2.0)


Returns the major version number of the PDFlib

1139
PDF

int pdf_get_majorversion ( void) \linebreak


Returns the major version number of the PDFlib.

pdf_get_minorversion (PHP 4 >= 4.2.0)


Returns the minor version number of the PDFlib

int pdf_get_majorversion ( void) \linebreak


Returns the minor version number of the PDFlib.

PDF_get_parameter (PHP 4 >= 4.0.1)


Gets certain parameters

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().

pdf_get_pdi_parameter (PHP 4 >= 4.0.5)


Get some PDI string parameters

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.

pdf_get_pdi_value (PHP 4 >= 4.0.5)


Gets some PDI numerical parameters

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

PDF_get_value (PHP 4 >= 4.0.1)


Gets certain numerical value

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().

pdf_initgraphics (PHP 4 >= 4.0.5)


Resets graphic state

void pdf_initgraphics ( int pdf object) \linebreak


Reset all implicit color and graphics state parameters to their defaults.

PDF_lineto (PHP 3>= 3.0.6, PHP 4 )


Draws a line

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().

pdf_makespotcolor (PHP 4 >= 4.0.5)


Makes a spotcolor

void pdf_makespotcolor ( int pdf object, string spotname) \linebreak


Make a named spot color from the current color.

PDF_moveto (PHP 3>= 3.0.6, PHP 4 )


Sets current point

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.

pdf_new (PHP 4 >= 4.0.5)


Creates a new pdf object

int pdf_new ( ) \linebreak


Create a new PDF object, using default error handling and memory management.

pdf_open_CCITT (PHP 4 >= 4.0.5)


Opens a new image file with raw CCITT data

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.

pdf_open_file (PHP 4 >= 4.0.5)


Opens a new pdf object

int pdf_open_file ( int pdf object [, string filename]) \linebreak


Create a new PDF file using the supplied file name. If filename is empty the PDF document will be
generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer()
function.
The following example shows how to create a pdf document in memory and how to output it correctly.

Ejemplo 1. Creating a PDF document in memory

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

?>

PDF_open_gif (PHP 3>= 3.0.7, PHP 4 )


Opens a GIF image

int pdf_open_gif ( int pdf document, string filename) \linebreak


The PDF_open_gif() function opens an image stored in the file with the name filename. The format
of the image has to be gif. The function returns a pdf image identifier.

Ejemplo 1. Including a gif image

<?php
$im = PDF_open_gif($pdf, "test.gif");
pdf_place_image($pdf, $im, 100, 100, 1);
pdf_close_image($pdf, $im);
?>

See also PDF_close_image(), PDF_open_jpeg(), PDF_open_memory_image(),


PDF_execute_image(), PDF_place_image(), PDF_put_image().

pdf_open_image_file (PHP 3 CVS only, PHP 4 )


Reads an image from a file

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

pdf_open_image (PHP 4 >= 4.0.5)


Versatile function for images

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

PDF_open_jpeg (PHP 3>= 3.0.7, PHP 4 )


Opens a JPEG image

int pdf_open_jpeg ( int pdf document, string filename) \linebreak


The PDF_open_jpeg() function opens an image stored in the file with the name filename. The format
of the image has to be jpeg. The function returns a pdf image identifier.
See also PDF_close_image(), PDF_open_gif(), PDF_open_png(), PDF_open_memory_image(),
PDF_execute_image(), PDF_place_image(), PDF_put_image().

PDF_open_memory_image (PHP 3>= 3.0.10, PHP 4 )


Opens an image created with PHP’s image functions

int pdf_open_memory_image ( int pdf document, int image) \linebreak


The PDF_open_memory_image() function takes an image created with the PHP’s image functions and
makes it available for the pdf document. The function returns a pdf image identifier.

Ejemplo 1. Including a memory image

<?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

See also PDF_close_image(), PDF_open_jpeg(), PDF_open_gif(), PDF_open_png()


PDF_execute_image(), PDF_place_image(), PDF_put_image().

pdf_open_pdi_page (PHP 4 >= 4.0.5)


Prepare a page

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

pdf_open_pdi (PHP 4 >= 4.0.5)


Opens a PDF file

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

int pdf_open_png ( int pdf, string png_file) \linebreak


The PDF_open_png() function opens an image stored in the file with the name filename. The format
of the image has to be png. The function returns a pdf image identifier.

Ejemplo 1. Including a PNG image

<?php
$im = PDF_open_png ($pdf, "test.png");
pdf_place_image ($pdf, $im, 100, 100, 1);
pdf_close_image ($pdf, $im);
?>

See also PDF_close_image(), PDF_open_jpeg(), PDF_open_gif(), PDF_open_memory_image(),


PDF_execute_image(), PDF_place_image(), PDF_put_image().

1145
PDF

pdf_open_tiff (PHP 4 )
Deprecated: Opens a TIFF image

int pdf_open_tiff ( int PDF-document, string filename) \linebreak


Deprecated.
See also pdf_open_image(),

PDF_open (PHP 3>= 3.0.6, PHP 4 )


Opens a new pdf document

int pdf_open ( int file, int info) \linebreak


The PDF_open() function opens a new pdf document. The corresponding file has to be opened with
fopen() and the file descriptor passed as argument file. info is the info structure that has to be created
with pdf_get_info(). The info structure will be deleted within this function.

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.

See also fopen(), PDF_get_info(), PDF_close().

PDF_place_image (PHP 3>= 3.0.7, PHP 4 )


Places an image on the page

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

pdf_place_pdi_page (PHP 4 >= 4.0.6)


Places an image on the page

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.

PDF_rect (PHP 3>= 3.0.6, PHP 4 )


Draws a rectangle

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().

PDF_restore (PHP 3>= 3.0.6, PHP 4 )


Restores formerly saved environment

void pdf_restore ( int pdf document) \linebreak


The PDF_restore() function restores the environment saved with PDF_save(). It works like the
postscript command grestore.

Ejemplo 1. Save and Restore

<?php PDF_save($pdf);
// do all kinds of rotations, transformations, ...
PDF_restore($pdf) ?>

See also PDF_save().

PDF_rotate (PHP 3>= 3.0.6, PHP 4 )


Sets rotation

void pdf_rotate ( int pdf document, double angle) \linebreak


The PDF_rotate() function sets the rotation in degress to angle.

1147
PDF

PDF_save (PHP 3>= 3.0.6, PHP 4 )


Saves the current environment

void pdf_save ( int pdf document) \linebreak


The PDF_save() function saves the current environment. It works like the postscript command gsave.
Very useful if you want to translate or rotate an object without effecting other objects. PDF_save()
should always be followed by PDF_restore() to restore the environment before PDF_save().
See also PDF_restore().

PDF_scale (PHP 3>= 3.0.6, PHP 4 )


Sets scaling

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

<?php PDF_scale($pdf, 72.0, 72.0);


PDF_lineto($pdf, 1, 1);
PDF_stroke($pdf);
?>

PDF_set_border_color (PHP 3>= 3.0.12, PHP 4 )


Sets color of border around links and annotations

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().

PDF_set_border_dash (PHP 4 >= 4.0.1)


Sets dash style of border around links and annotations

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().

PDF_set_border_style (PHP 3>= 3.0.12, PHP 4 )


Sets style of border around links and annotations

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().

PDF_set_char_spacing (PHP 3>= 3.0.6, PHP 4 )


Sets character spacing

void pdf_set_char_spacing ( int pdf document, double space) \linebreak


The PDF_set_char_spacing() function sets the spacing between characters.
See also PDF_set_word_spacing(), PDF_set_leading().

PDF_set_duration (PHP 3>= 3.0.6, PHP 4 )


Sets duration between pages

void pdf_set_duration ( int pdf document, double duration) \linebreak


The PDF_set_duration() function set the duration between following pages in seconds.
See also PDF_set_transition().

PDF_set_font (PHP 3>= 3.0.6, PHP 4 )


Selects a font face and size

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

PDF_set_horiz_scaling (PHP 3>= 3.0.6, PHP 4 )


Sets horizontal scaling of text

void pdf_set_horiz_scaling ( int pdf document, double scale) \linebreak


The PDF_set_horiz_scaling() function sets the horizontal scaling to scale percent.

pdf_set_info_author (PHP 3>= 3.0.6, PHP 4 )


Fills the author field of the document

bool pdf_set_info_author ( int pdfdoc, string author) \linebreak


This function is deprecate, use pdf_set_info() instead.

pdf_set_info_creator (PHP 3>= 3.0.6, PHP 4 )


Fills the creator field of the document

bool pdf_set_info_creator ( int pdfdoc, string creator) \linebreak


This function is deprecate, use pdf_set_info() instead.

1150
PDF

pdf_set_info_keywords (PHP 3>= 3.0.6, PHP 4 )


Fills the keywords field of the document

bool pdf_set_info_keywords ( int pdfdoc, string keywords) \linebreak


This function is deprecate, use pdf_set_info() instead.

pdf_set_info_subject (PHP 3>= 3.0.6, PHP 4 )


Fills the subject field of the document

bool pdf_set_info_subject ( int pdfdoc, string subject) \linebreak


This function is deprecate, use pdf_set_info() instead.

pdf_set_info_title (PHP 3>= 3.0.6, PHP 4 )


Fills the title field of the document

bool pdf_set_info_title ( int pdfdoc, string title) \linebreak


This function is deprecate, use pdf_set_info() instead.

PDF_set_info (PHP 4 >= 4.0.1)


Fills a field of the document information

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.

Ejemplo 1. Setting document information

<?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_begin_page($pdfdoc, 595, 842);


pdf_end_page($pdfdoc);
pdf_close($pdfdoc);
?>

Nota: This function replaces PDF_set_info_keywords(), PDF_set_info_title(),


PDF_set_info_subject(), PDF_set_info_creator(), PDF_set_info_sybject().

PDF_set_leading (PHP 3>= 3.0.6, PHP 4 )


Sets distance between text lines

void pdf_set_leading ( int pdf document, double distance) \linebreak


The PDF_set_leading() function sets the distance between text lines. This will be used if text is output
by PDF_continue_text().
See also PDF_continue_text().

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().

PDF_set_text_matrix (PHP 3>= 3.0.6)


Sets the text matrix

void pdf_set_text_matrix ( int pdf document, array matrix) \linebreak


The PDF_set_text_matrix() function sets a matrix which describes a transformation applied on the
current text font. The matrix has to passed as an array with six elements.

1152
PDF

PDF_set_text_pos (PHP 3>= 3.0.6, PHP 4 )


Sets text position

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().

PDF_set_text_rendering (PHP 3>= 3.0.6, PHP 4 )


Determines how text is rendered

void pdf_set_text_rendering ( int pdf document, int mode) \linebreak


The PDF_set_text_rendering() function determines how text is rendered. The possible values for mode
are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to cliping path,
5=stroke text and add it to clipping path, 6=fill and stroke text and add it to cliping path, 7=add it to
clipping path.

PDF_set_text_rise (PHP 3>= 3.0.6, PHP 4 )


Sets the text rise

void pdf_set_text_rise ( int pdf document, double rise) \linebreak


The PDF_set_text_rise() function sets the text rising to rise points.

PDF_set_value (PHP 4 >= 4.0.1)


Sets certain numerical value

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().

PDF_set_word_spacing (PHP 3>= 3.0.6, PHP 4 )


Sets spacing between words

1153
PDF

void pdf_set_word_spacing ( int pdf document, double space) \linebreak


The PDF_set_word_spacing() function sets the spacing between words.
See also PDF_set_char_spacing(), PDF_set_leading().

pdf_setcolor (PHP 4 >= 4.0.5)


Sets fill and stroke color

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.

// Set fill and stroke colors to white.


pdf_setcolor($pdf, "both", "rgb", 1, 1, 1);

For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.

// Set fill and stroke colors to white.


pdf_setcolor($pdf, "both", "cmyk", 0, 0, 0, 1);

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().

PDF_setdash (PHP 3>= 3.0.6, PHP 4 )


Sets dash 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.

PDF_setflat (PHP 3>= 3.0.6, PHP 4 )


Sets flatness

void pdf_setflat ( int pdf document, double value) \linebreak


The PDF_setflat() function sets the flatness to a value between 0 and 100.

pdf_setfont (PHP 4 >= 4.0.5)


Set the current font

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().

PDF_setgray_fill (PHP 3>= 3.0.6, PHP 4 )


Sets filling color to gray value

void pdf_setgray_fill ( int pdf document, double gray value) \linebreak


The PDF_setgray_fill() function sets the current gray value to fill a path.
See also PDF_setrgbcolor_fill().

PDF_setgray_stroke (PHP 3>= 3.0.6, PHP 4 )


Sets drawing color to gray value

void pdf_setgray_stroke ( int pdf document, double gray value) \linebreak


The PDF_setgray_stroke() function sets the current drawing color to the given gray value.
See also PDF_setrgbcolor_stroke().

1155
PDF

PDF_setgray (PHP 3>= 3.0.6, PHP 4 )


Sets drawing and filling color to gray value

void pdf_setgray ( int pdf document, double gray value) \linebreak


The PDF_setgray() function sets the current drawing and filling color to the given gray value.
See also PDF_setrgbcolor_stroke(), PDF_setrgbcolor_fill().

PDF_setlinecap (PHP 3>= 3.0.6, PHP 4 )


Sets linecap parameter

void pdf_setlinecap ( int pdf document, int value) \linebreak


The PDF_setlinecap() function sets the linecap parameter between a value of 0 and 2.

PDF_setlinejoin (PHP 3>= 3.0.6, PHP 4 )


Sets linejoin parameter

void pdf_setlinejoin ( int pdf document, long value) \linebreak


The PDF_setlinejoin() function sets the linejoin parameter between a value of 0 and 2.

PDF_setlinewidth (PHP 3>= 3.0.6, PHP 4 )


Sets line width

void pdf_setlinewidth ( int pdf document, double width) \linebreak


The PDF_setlinewidth() function sets the line width to width.

pdf_setmatrix (PHP 4 >= 4.0.5)


Sets current transformation matrix

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

PDF_setmiterlimit (PHP 3>= 3.0.6, PHP 4 )


Sets miter limit

void pdf_setmiterlimit ( int pdf document, double value) \linebreak


The PDF_setmiterlimit() function sets the miter limit to a value greater of equal than 1.

pdf_setpolydash (PHP 4 >= 4.0.5)


Sets complicated dash pattern

void pdf_setpolydash ( int pdf object, float * dasharray) \linebreak


Set a more complicated dash pattern defined by an array.

PDF_setrgbcolor_fill (PHP 3>= 3.0.6, PHP 4 )


Sets filling color to rgb color value

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().

PDF_setrgbcolor_stroke (PHP 3>= 3.0.6, PHP 4 )


Sets drawing color to rgb color value

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().

PDF_setrgbcolor (PHP 3>= 3.0.6, PHP 4 )


Sets drawing and filling color to rgb color value

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().

PDF_show_xy (PHP 3>= 3.0.6, PHP 4 )


Output text at given position

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_show (PHP 3>= 3.0.6, PHP 4 )


Output text at current position

void pdf_show ( int pdf document, string text) \linebreak


The PDF_show() function outputs the string text at the current position using the current font.
See also PDF_show_xy(), PDF_set_text_pos(), PDF_set_font().

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.

PDF_stringwidth (PHP 3>= 3.0.6, PHP 4 )


Returns width of text using current font

double pdf_stringwidth ( int pdf document, string text) \linebreak


The PDF_stringwidth() function returns the width of the string in text by using the current font. It
requires a font to be set before with PDF_set_font().
See also PDF_set_font().

PDF_stroke (PHP 3>= 3.0.6, PHP 4 )


Draws line along path

void pdf_stroke ( int pdf document) \linebreak


The PDF_stroke() function draws a line along current path. The current path is the sum of all line
drawing. Without this function the line would not be drawn.
See also PDF_closepath(), PDF_closepath_stroke().

PDF_translate (PHP 3>= 3.0.6, PHP 4 )


Sets origin of coordinate system

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

<?php PDF_moveto($pdf, 0, 0);


PDF_lineto($pdf, 100, 100);
PDF_stroke($pdf);
PDF_translate($pdf, 100, 100);
PDF_moveto($pdf, 0, 0);
PDF_lineto($pdf, 100, 100);

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

pfpro_cleanup (PHP 4 >= 4.0.2)


Shuts down the Payflow Pro library

void pfpro_cleanup ( void) \linebreak


pfpro_cleanup() is used to shutdown the Payflow Pro library cleanly. It should be called after you have
processed any transactions and before the end of your script. However you may omit this call, in which
case this extension will automatically call pfpro_cleanup() after your script terminates.
See also pfpro_init().

pfpro_init (PHP 4 >= 4.0.2)


Initialises the Payflow Pro library

void pfpro_init ( void) \linebreak


pfpro_init() is used to initialise the Payflow Pro library. You may omit this call, in which case this
extension will automatically call pfpro_init() before the first transaction.
See also pfpro_cleanup().

pfpro_process_raw (PHP 4 >= 4.0.2)


Process a raw transaction with 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.

Ejemplo 1. Payflow Pro raw example

<?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");
}

echo "Verisign raw response was ".$response;

pfpro_cleanup();

?>

pfpro_process (PHP 4 >= 4.0.2)


Process a transaction with Payflow Pro

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.

Ejemplo 1. Payflow Pro example

<?php

pfpro_init();

1163
Verisign Payflow Pro

$transaction = array(USER => ’mylogin’,


PWD => ’mypassword’,
TRXTYPE => ’S’,
TENDER => ’C’,
AMT => 1.50,
ACCT => ’4111111111111111’,
EXPDATE => ’0904’
);

$response = pfpro_process($transaction);

if (!$response) {
die("Couldn’t establish link to Verisign.\n");
}

echo "Verisign response code was ".$response[RESULT];


echo ", which means: ".$response[RESPMSG]."\n";

echo "\nThe transaction request: ";


print_r($transaction);

echo "\nThe response: ";


print_r($response);

pfpro_cleanup();

?>

pfpro_version (PHP 4 >= 4.0.2)


Returns the version of the Payflow Pro software

string pfpro_version ( void) \linebreak


pfpro_version() returns the version string of the Payflow Pro library. At the time of writing, this was
L211.

1164
LXXVIII. opciones e información de PHP

1165
opciones/información PHP

assert_options (PHP 4 )
Set/get the various assert flags

mixed assert_options ( int what [, mixed value]) \linebreak


Using assert_options() you may set the various assert() control options or just query their current
settings.

Tabla 1. Assert Options

option ini-parameter default description


ASSERT_ACTIVE assert.active 1 enable assert() evaluation
ASSERT_WARNING assert.warning 1 issue a PHP warning for
each failed assertion
ASSERT_BAIL assert.bail 0 terminate execution on
failed assertions
ASSERT_QUIET_EVAL assert.quiet_eval 0 disable error_reporting
during assertion
expression evaluation
ASSERT_CALLBACK assert_callback (NULL) user function to call on
failed assertions

assert_options() will return the original setting of any option or FALSE on errors.

assert (PHP 4 )
Checks if assertion is FALSE

int assert ( string|bool assertion) \linebreak


assert() will check the given assertion and take appropriate action if its result is FALSE.
If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a
string assertion are less overhead when assertion checking is off and messages containing the
assertion expression when an assertion fails.
Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for
conditions that should always be TRUE and that indicate some programming errors if not or to check for
the presence of certain features like extension functions or certain system limits and features.
Assertions should not be used for normal runtime operations like input parameter checks. As a rule of
thumb your code should always be able to work correctly if assertion checking is not activated.
The behavior of assert() may be configured by assert_options() or by .ini-settings described in that
functions manual page.
The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback
function to be set to handle failed assertions.

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)

Ejemplo 1. Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options (ASSERT_ACTIVE, 1);
assert_options (ASSERT_WARNING, 0);
assert_options (ASSERT_QUIET_EVAL, 1);

// Create a handler function


function my_assert_handler ($file, $line, $code) {
echo "<hr>Assertion Failed:
File ’$file’<br>
Line ’$line’<br>
Code ’$code’<br><hr>";
}

// Set up the callback


assert_options (ASSERT_CALLBACK, ’my_assert_handler’);

// Make an assertion that should fail


assert (’mysql_query ("")’);
?>

dl (PHP 3, PHP 4 )
Loads a PHP extension at runtime

bool dl ( string library) \linebreak


Loads the PHP extension given by the parameter library. The library parameter is only the
filename of the extension to load which also depends on your platform. For example, the sockets
extension (if compiled as a shared module, not the default!) would be called sockets.so on unix
platforms whereas it is called php_sockets.dll on the windows platform.

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

• whether PHP has been built with --enable-debug or not


• whether PHP has been built with (experimental) ZTS (Zend Thread Safety) support or not
• the current internal ZEND_MODULE_API_NO (Zend internal module API number, which is basically
the date on which a major module API change happened, e.g. 20010901)
Taking into account the above, the directory then defaults to <php-install-
directory>/lib/php/extension/<debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO,
e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or
/usr/local/php/lib/php/extensions/no-debug-zts-20010901.

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 !

Nota: dl() is case sensitive on unix platforms.

See also Extension Loading Directives and extension_loaded().

extension_loaded (PHP 3>= 3.0.10, PHP 4 )


averigua si una extensión ha sido cargada

1168
opciones/información PHP

bool extension_loaded ( string name) \linebreak


Devuelve TRUE si la extensión identificada por name (nombre) está cargada. Puede ver el nombre de
varias extensiones utilizando phpinfo().
Véase también phpinfo().

Nota: Esta función fue añadida en 3.0.10.

get_cfg_var (PHP 3, PHP 4 )


Obtiene el valor de una opción de configuración de PHP.

string get_cfg_var ( string varname) \linebreak


Devuelve el valor actual de una variable de configuración de PHP especificada en varname, o FALSE si
ocurre un error.
No devolverá información de la configuracion cuando el PHP fue compilado, o leído desde un fichero de
configuración Apache (utilizando las directivas php3_configuration_option directives).
Para comprobar si el sistema está utilizando un fichero de configuración, intente recuperar el valor de
cfg_file_path. Si está disponible, se está utilizando un fichero de configuración.

get_current_user (PHP 3, PHP 4 )


Obtiene el nombre del propietario del script PHP actual.

string get_current_user ( void) \linebreak


Devuelve el nombre del propietario del script PHP actual.
Véase también getmyuid(), getmypid(), getmyinode(), y getlastmod().

get_defined_constants (PHP 4 >= 4.1.0)


Returns an associative array with the names of all the constants and their values

array get_defined_constants ( void) \linebreak


This function returns the names and values of all the constants currently defined. This includes those
created by extensions as well as those created with the define() function.
For example the line below

1169
opciones/información PHP

print_r (get_defined_constants());

will print a list like:

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
)

See also get_loaded_extensions(), get_defined_functions() and get_defined_vars().

get_extension_funcs (PHP 4 )
Returns an array with the names of the functions of a module

array get_extension_funcs ( string module_name) \linebreak


This function returns the names of all the functions defined in the module indicated by module_name.
For example the lines below

print_r (get_extension_funcs ("xml"));


print_r (get_extension_funcs ("gd"));

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

array get_included_files ( void) \linebreak


Returns an array of the names of all files that have been included using include(), include_once(),
require() or require_once().
Files that are included or required multiple times only show up once in the returned array.

Nota: Files included using the auto_prepend_file configuration directive are not included in the
returned array.

Ejemplo 1. get_included_files() Example

<?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";
}

?>

will generate the following output:

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().

See also: include(), include_once(), require(), require_once(), and get_required_files().

get_loaded_extensions (PHP 4 )
Returns an array with the names of all modules compiled and loaded

array get_loaded_extensions ( void) \linebreak


This function returns the names of all the modules compiled and loaded in the PHP interpreter.
For example the line below

print_r (get_loaded_extensions());

will print a list like:

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
)

See also: get_extension_funcs().

1172
opciones/información PHP

get_magic_quotes_gpc (PHP 3>= 3.0.6, PHP 4 )


Obtiene el valor de la configuración activa actual de las comillas mágicas gpc.

long get_magic_quotes_gpc ( void) \linebreak


Devuelve el valor de la configuración activa actual de magic_quotes_gpc. (0 desactivado, 1 activado)
Véase también get_magic_quotes_runtime(), set_magic_quotes_runtime().

get_magic_quotes_runtime (PHP 3>= 3.0.6, PHP 4 )


Obtiene el valor de la configuración activa actual de magic_quotes_runtime.

long get_magic_quotes_runtime ( void) \linebreak


Devuelve el valor de la configuración activa actual de magic_quotes_runtime. (0 desactivado, 1 activado)
Véase también get_magic_quotes_gpc(), set_magic_quotes_runtime().

get_required_files (PHP 4 )
Returns an array with the names of included or required files

array get_required_files ( void) \linebreak


As of PHP 4.0.4, this function is an alias for get_included_files()
In PHP 4.0.1pl2 and previous versions get_required_files() assumed that the required files ended in the
extension .php, other extensions would not be returned. The array returned by get_required_files() was
an associative array and only listed files included by require() and require_once().
See also: require(), require_once(), include(), include_once(), and get_included_files().

getenv (PHP 3, PHP 4 )


Obtiene el valor de una variable de entorno

string getenv ( string varname) \linebreak


Devuelve el valor de la variable de entorno varname, o FALSE en caso de error.

$ip = getenv("REMOTE_ADDR"); // get the ip number of the user

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

getlastmod (PHP 3, PHP 4 )


Recupera la fecha/hora de la última modificación de la página.

int getlastmod ( void) \linebreak


Devuelve la fecha/hora de la última modificación de la página actual. El valor devuelto está en formato
de fecha/hora Unix, adecuado para que sirva a date(). Devuelve FALSE en caso de error.

Ejemplo 1. ejemplo getlastmod()

// outputs e.g. ’Last modified: March 04 1998 20:43:59.’


echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() );

Véase también date(), getmyuid(), get_current_user(), getmyinode(), y getmypid().

getmygid (PHP 4 >= 4.1.0)


Get PHP script owner’s GID

int getmygid ( void) \linebreak


Returns the group ID of the current script, or FALSE on error.
See also getmyuid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().

getmyinode (PHP 3, PHP 4 )


Recupera el inodo del script actual.

int getmyinode ( void) \linebreak


Devuelve el inodo del script actual, o FALSE en caso de error.
Véase también getmyuid(), get_current_user(), getmypid(), y getlastmod().

1174
opciones/información PHP

getmypid (PHP 3, PHP 4 )


Obtiene el ID de proceso de PHP.

int getmypid ( void) \linebreak


Devuelve el ID del proceso PHP actual, o FALSE en caso de error.
Advierta que cuando se ejecuta como un módulo de servidor, diferentes llamadas del script no garantizan
que tengan distintos pids.
Véase también getmyuid(), get_current_user(), getmyinode(), y getlastmod().

getmyuid (PHP 3, PHP 4 )


Obtiene el UID del propietario del script PHP.

int getmyuid ( void) \linebreak


Devuelve el ID de usuario del script actual, o FALSE en caso de error.
Véase también getmypid(), get_current_user(), getmyinode(), y getlastmod().

getrusage (PHP 3>= 3.0.7, PHP 4 )


Obtiene el consumo actual de recursos.

array getrusage ( [int who]) \linebreak


Es un interface a getrusage(2). Devuelve un array asociativo que contiene los datos devueltos de la
llamada del sistema. Si who (quien) es 1, getrusage debería llamarse con RUSAGE_CHILDREN. Todas
las entradas son accesibles utilizando sus nombres de campo documentados.

Ejemplo 1. Ejemplo Getrusage

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

Vea la página man de system para más detalles.

ini_alter (PHP 4 )
Changes the value of a configuration option

1175
opciones/información PHP

string ini_alter ( string varname, string newvalue) \linebreak


Changes the value of a configuration option, returns FALSE on failure, and the previous value of the
configuration option on success.

Nota: This is an alias of ini_set()

See also ini_get(), ini_get_all(), ini_restore(), and ini_set()

ini_get_all (PHP 4 >= 4.2.0)


Gets all configuration options

array ini_get_all ( [string extension]) \linebreak


Returns all the registered configuration options as an associative array. If optional extension
parameter is set, returns only options specific for that extension.
See also: ini_alter(), ini_restore(), ini_get(), and ini_set()

ini_get (PHP 4 )
Gets the value of a configuration option

string ini_get ( string varname) \linebreak


Returns the value of the configuration option on success, an empty string on failure.
See also get_cfg_var(), ini_get_all(), ini_alter(), ini_restore(), and ini_set()

ini_restore (PHP 4 )
Restores the value of a configuration option

string ini_restore ( string varname) \linebreak


Restores a given configuration option to its original value.
See also: ini_alter(), ini_get(), ini_get_all(), and ini_set()

1176
opciones/información PHP

ini_set (PHP 4 )
Sets the value of a configuration option

string ini_set ( string varname, string newvalue) \linebreak


Sets the value of the given configuration option. Returns the old value on success, FALSE on failure. The
configuration option will keep this new value during the script’s execution, and will be restored at the
script’s ending.
Not all the available options can be changed using ini_set(). Below is a table with a list of all PHP
options (as of PHP 4.2.0), indicating which ones can be changed/set and at what level.

Tabla 1. Configuration options

Name Default Changeable


com.allow_dcom "0" PHP_INI_SYSTEM
com.autoregister_typelib "0" PHP_INI_SYSTEM
com.autoregister_verbose "0" PHP_INI_SYSTEM
com.autoregister_casesensitive "1" PHP_INI_SYSTEM
com.typelib_file "" PHP_INI_SYSTEM
crack.default_dictionary NULL PHP_INI_SYSTEM
exif.encode_unicode "ISO-8859-15" PHP_INI_ALL
exif.decode_unicode_motorola "UCS-2BE" PHP_INI_ALL
exif.decode_unicode_intel "UCS-2LE" PHP_INI_ALL
exif.encode_jis "" PHP_INI_ALL
exif.decode_jis_motorola "JIS" PHP_INI_ALL
exif.decode_jis_intel "JIS" PHP_INI_ALL
fbsql.allow_persistent "1" PHP_INI_SYSTEM
fbsql.generate_warnings "0" PHP_INI_SYSTEM
fbsql.autocommit "1" PHP_INI_SYSTEM
fbsql.max_persistent "-1" PHP_INI_SYSTEM
fbsql.max_links "128" PHP_INI_SYSTEM
fbsql.max_connections "128" PHP_INI_SYSTEM
fbsql.max_results "128" PHP_INI_SYSTEM
fbsql.batchSize "1000" PHP_INI_SYSTEM
fbsql.default_host NULL PHP_INI_SYSTEM
fbsql.default_user "_SYSTEM" PHP_INI_SYSTEM
fbsql.default_password "" PHP_INI_SYSTEM
fbsql.default_database "" PHP_INI_SYSTEM
fbsql.default_database_password "" PHP_INI_SYSTEM
hwapi.allow_persistent "0" PHP_INI_SYSTEM

1177
opciones/información PHP

Name Default Changeable


hyerwave.allow_persistent "0" PHP_INI_SYSTEM
hyperwave.default_port "418" PHP_INI_ALL
iconv.input_encoding ICONV_INPUT_ENCODING PHP_INI_ALL
iconv.output_encoding ICONV_OUTPUT_ENCODING PHP_INI_ALL
iconv.internal_encoding ICONV_INTERNAL_ENCODINGPHP_INI_ALL

ifx.allow_persistent "1" PHP_INI_SYSTEM


ifx.max_persistent "-1" PHP_INI_SYSTEM
ifx.max_links "-1" PHP_INI_SYSTEM
ifx.default_host NULL PHP_INI_SYSTEM
ifx.default_user NULL PHP_INI_SYSTEM
ifx.default_password NULL PHP_INI_SYSTEM
ifx.blobinfile "1" PHP_INI_ALL
ifx.textasvarchar "0" PHP_INI_ALL
ifx.byteasvarchar "0" PHP_INI_ALL
ifx.charasvarchar "0" PHP_INI_ALL
ifx.nullformat "0" PHP_INI_ALL
ingres.allow_persistent "1" PHP_INI_SYSTEM
ingres.max_persistent "-1" PHP_INI_SYSTEM
ingres.max_links "-1" PHP_INI_SYSTEM
ingres.default_database NULL PHP_INI_ALL
ingres.default_user NULL PHP_INI_ALL
ingres.default_password NULL PHP_INI_ALL
ibase.allow_persistent "1" PHP_INI_SYSTEM
ibase.max_persistent "-1" PHP_INI_SYSTEM
ibase.max_links "-1" PHP_INI_SYSTEM
ibase.default_user NULL PHP_INI_ALL
ibase.default_password NULL PHP_INI_ALL
ibase.timestampformat "%m/%d/%Y%H:%M:%S" PHP_INI_ALL
ibase.dateformat "%m/%d/%Y" PHP_INI_ALL
ibase.timeformat "%H:%M:%S" PHP_INI_ALL
java.class.path NULL PHP_INI_ALL
java.home NULL PHP_INI_ALL
java.library.path NULL PHP_INI_ALL
java.library JAVALIB PHP_INI_ALL
java.library NULL PHP_INI_ALL
ldap.max_links "-1" PHP_INI_SYSTEM
mbstring.detect_order NULL PHP_INI_ALL
mbstring.http_input NULL PHP_INI_ALL

1178
opciones/información PHP

Name Default Changeable


mbstring.http_output NULL PHP_INI_ALL
mbstring.internal_encoding NULL PHP_INI_ALL
mbstring.substitute_character NULL PHP_INI_ALL
mbstring.func_overload "0" PHP_INI_SYSTEM
mcrypt.algorithms_dir NULL PHP_INI_ALL
mcrypt.modes_dir NULL PHP_INI_ALL
mime_magic.magicfile "/usr/share/misc/magic.mime" PHP_INI_SYSTEM
mssql.allow_persistent "1" PHP_INI_SYSTEM
mssql.max_persistent "-1" PHP_INI_SYSTEM
mssql.max_links "-1" PHP_INI_SYSTEM
mssql.max_procs "25" PHP_INI_ALL
mssql.min_error_severity "10" PHP_INI_ALL
mssql.min_message_severity "10" PHP_INI_ALL
mssql.compatability_mode "0" PHP_INI_ALL
mssql.connect_timeout "5" PHP_INI_ALL
mssql.timeout "60" PHP_INI_ALL
mssql.textsize "-1" PHP_INI_ALL
mssql.textlimit "-1" PHP_INI_ALL
mssql.batchsize "0" PHP_INI_ALL
mssql.datetimeconvert "1" PHP_INI_ALL
mysql.allow_persistent "1" PHP_INI_SYSTEM
mysql.max_persistent "-1" PHP_INI_SYSTEM
mysql.max_links "-1" PHP_INI_SYSTEM
mysql.default_host NULL PHP_INI_ALL
mysql.default_user NULL PHP_INI_ALL
mysql.default_password NULL PHP_INI_ALL
mysql.default_port NULL PHP_INI_ALL
mysql.default_socket NULL PHP_INI_ALL
ncurses.value "42" PHP_INI_ALL
ncurses.string "foobar" PHP_INI_ALL
odbc.allow_persistent "1" PHP_INI_SYSTEM
odbc.max_persistent "-1" PHP_INI_SYSTEM
odbc.max_links "-1" PHP_INI_SYSTEM
odbc.default_db NULL PHP_INI_ALL
odbc.default_user NULL PHP_INI_ALL
odbc.default_pw NULL PHP_INI_ALL
odbc.defaultlrl "4096" PHP_INI_ALL
odbc.defaultbinmode "1" PHP_INI_ALL

1179
opciones/información PHP

Name Default Changeable


odbc.check_persistent "1" PHP_INI_SYSTEM
pfpro.defaulthost "test.signio.com"
pfpro.defaulthost "test-payflow.verisign.com"
pfpro.defaultport "443" PHP_INI_ALL
pfpro.defaulttimeout "30" PHP_INI_ALL
pfpro.proxyaddress "" PHP_INI_ALL
pfpro.proxyport "" PHP_INI_ALL
pfpro.proxylogon "" PHP_INI_ALL
pfpro.proxypassword "" PHP_INI_ALL
pgsql.allow_persistent "1" PHP_INI_SYSTEM
pgsql.max_persistent "-1" PHP_INI_SYSTEM
pgsql.max_links "-1" PHP_INI_SYSTEM
pgsql.auto_reset_persistent "0" PHP_INI_SYSTEM
pgsql.ignore_notice "0" PHP_INI_ALL
pgsql.log_notice "0" PHP_INI_ALL
session.save_path "/tmp" PHP_INI_ALL
session.name "PHPSESSID" PHP_INI_ALL
session.save_handler "files" PHP_INI_ALL
session.auto_start "0" PHP_INI_ALL
session.gc_probability "1" PHP_INI_ALL
session.gc_maxlifetime "1440" PHP_INI_ALL
session.serialize_handler "php" PHP_INI_ALL
session.cookie_lifetime "0" PHP_INI_ALL
session.cookie_path "/" PHP_INI_ALL
session.cookie_domain "" PHP_INI_ALL
session.cookie_secure "" PHP_INI_ALL
session.use_cookies "1" PHP_INI_ALL
session.use_only_cookies "0" PHP_INI_ALL
session.referer_check "" PHP_INI_ALL
session.entropy_file "" PHP_INI_ALL
session.entropy_length "0" PHP_INI_ALL
session.cache_limiter "nocache" PHP_INI_ALL
session.cache_expire "180" PHP_INI_ALL
session.use_trans_sid "1" PHP_INI_ALL
session.encode_sources "globals track"
extname.global_value "42" PHP_INI_ALL
extname.global_string "foobar" PHP_INI_ALL
assert.active "1" PHP_INI_ALL

1180
opciones/información PHP

Name Default Changeable


assert.bail "0" PHP_INI_ALL
assert.warning "1" PHP_INI_ALL
assert.callback NULL PHP_INI_ALL
assert.quiet_eval "0" PHP_INI_ALL
safe_mode_protected_env_vars SAFE_MODE_PROTECTED_ENV_VARS
PHP_INI_SYSTEM

safe_mode_allowed_env_vars SAFE_MODE_ALLOWED_ENV_VARS
PHP_INI_SYSTEM

url_rewriter.tags "a=href area=href


url_rewriter.tags "a=href area=href
sybct.allow_persistent "1" PHP_INI_SYSTEM
sybct.max_persistent "-1" PHP_INI_SYSTEM
sybct.max_links "-1" PHP_INI_SYSTEM
sybct.min_server_severity "10" PHP_INI_ALL
sybct.min_client_severity "10" PHP_INI_ALL
sybct.hostname NULL PHP_INI_ALL
tokenizer.global_value "42" PHP_INI_ALL
tokenizer.global_string "foobar" PHP_INI_ALL
vpopmail.directory "" PHP_INI_ALL
zlib.output_compression "0" PHP_INI_SYSTEM|PHP_INI_PERDIR

zlib.output_compression_level "-1" PHP_INI_ALL


define_syslog_variables "0" PHP_INI_ALL
highlight.bg HL_BG_COLOR PHP_INI_ALL
highlight.comment HL_COMMENT_COLOR PHP_INI_ALL
highlight.default HL_DEFAULT_COLOR PHP_INI_ALL
highlight.html HL_HTML_COLOR PHP_INI_ALL
highlight.keyword HL_KEYWORD_COLOR PHP_INI_ALL
highlight.string HL_STRING_COLOR PHP_INI_ALL
allow_call_time_pass_reference "1" PHP_INI_SYSTEM|PHP_INI_PERDIR

asp_tags "0" PHP_INI_SYSTEM|PHP_INI_PERDIR

display_errors "1" PHP_INI_ALL


display_startup_errors "0" PHP_INI_ALL
enable_dl "1" PHP_INI_SYSTEM
expose_php "1" PHP_INI_SYSTEM
html_errors "1" PHP_INI_SYSTEM
xmlrpc_errors "0" PHP_INI_SYSTEM

1181
opciones/información PHP

Name Default Changeable


xmlrpc_error_number "0" PHP_INI_ALL
ignore_user_abort "0" PHP_INI_ALL
implicit_flush "0" PHP_INI_PERDIR|PHP_INI_SYSTEM

log_errors "0" PHP_INI_ALL


log_errors_max_len "1024" PHP_INI_ALL
ignore_repeated_errors "0" PHP_INI_ALL
ignore_repeated_source "0" PHP_INI_ALL
magic_quotes_gpc "1" PHP_INI_ALL
magic_quotes_runtime "0" PHP_INI_ALL
magic_quotes_sybase "0" PHP_INI_ALL
output_buffering "0" PHP_INI_PERDIR|PHP_INI_SYSTEM

output_handler NULL PHP_INI_PERDIR|PHP_INI_SYSTEM

register_argc_argv "1" PHP_INI_ALL


register_globals "0" PHP_INI_PERDIR|PHP_INI_SYSTEM

safe_mode "1" PHP_INI_SYSTEM


safe_mode "0" PHP_INI_SYSTEM
safe_mode_include_dir NULL PHP_INI_SYSTEM
safe_mode_gid "0" PHP_INI_SYSTEM
short_open_tag DEFAULT_SHORT_OPEN_TAG PHP_INI_SYSTEM|PHP_INI_PERDIR

sql.safe_mode "0" PHP_INI_SYSTEM


track_errors "0" PHP_INI_ALL
y2k_compliance "0" PHP_INI_ALL
unserialize_callback_func NULL PHP_INI_ALL
arg_separator.output "&" PHP_INI_ALL
arg_separator.input "&" PHP_INI_SYSTEM|PHP_INI_PERDIR

auto_append_file NULL PHP_INI_ALL


auto_prepend_file NULL PHP_INI_ALL
doc_root NULL PHP_INI_SYSTEM
default_charset SAPI_DEFAULT_CHARSET PHP_INI_ALL
default_mimetype SAPI_DEFAULT_MIMETYPE PHP_INI_ALL
error_log NULL PHP_INI_ALL
extension_dir PHP_EXTENSION_DIR PHP_INI_SYSTEM
gpc_order "GPC" PHP_INI_ALL

1182
opciones/información PHP

Name Default Changeable


include_path PHP_INCLUDE_PATH PHP_INI_ALL
max_execution_time "30" PHP_INI_ALL
open_basedir NULL PHP_INI_SYSTEM
safe_mode_exec_dir "1" PHP_INI_SYSTEM
upload_max_filesize "2M" PHP_INI_SYSTEM
file_uploads "1" PHP_INI_ALL
post_max_size "8M" PHP_INI_SYSTEM
upload_tmp_dir NULL PHP_INI_SYSTEM
user_dir NULL PHP_INI_SYSTEM
variables_order NULL PHP_INI_ALL
error_append_string NULL PHP_INI_ALL
error_prepend_string NULL PHP_INI_ALL
SMTP "localhost" PHP_INI_ALL
smtp_port 25 PHP_INI_ALL
browscap NULL PHP_INI_SYSTEM
error_reporting NULL PHP_INI_ALL
memory_limit "8M" PHP_INI_ALL
precision "14" PHP_INI_ALL
sendmail_from NULL PHP_INI_ALL
sendmail_path DEFAULT_SENDMAIL_PATH PHP_INI_SYSTEM
disable_functions "" PHP_INI_SYSTEM
allow_url_fopen "1" PHP_INI_ALL
always_populate_raw_post_data "0" PHP_INI_ALL
xbithack "0" PHP_INI_ALL
engine "1" PHP_INI_ALL
last_modified "0" PHP_INI_ALL
child_terminate "0" PHP_INI_ALL
async_send "0" PHP_INI_ALL

Tabla 2. Definition of PHP_INI_* constants

Constant Value Meaning


PHP_INI_USER 1 Entry can be set in user scripts
PHP_INI_PERDIR 2 Entry can be set in .htaccess
PHP_INI_SYSTEM 4 Entry can be set in php.ini or
httpd.conf
PHP_INI_ALL 7 Entry can be set anywhere

1183
opciones/información PHP

See also: ini_alter(), ini_get(), and ini_restore()

php_logo_guid (PHP 4 )
Obtiene el guid logo

string php_logo_guid ( void) \linebreak

Nota: Esta funcionalidad fue añadida en PHP4 Beta 4.

php_sapi_name (PHP 4 >= 4.0.1)


Returns the type of interface between web server and PHP

string php_sapi_name ( void) \linebreak


php_sapi_name() returns a lowercase string which describes the type of interface between web server
and PHP (Server API, SAPI). In CGI PHP, this string is "cgi", in mod_php for Apache, this string is
"apache" and so on.

Ejemplo 1. php_sapi_name() Example

$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";

php_uname (PHP 4 >= 4.0.2)


Returns information about the operating system PHP was built on

string php_uname ( void) \linebreak

1184
opciones/información PHP

php_uname() returns a string with a description of the operating system PHP is built on.

Ejemplo 1. php_uname() Example

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

void phpcredits ( [int flag]) \linebreak


This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate
HTML codes to insert the information in a page. flag is optional, and it defaults to CREDITS_ALL. To
generate a custom credits page, you may want to use the flag parameter. For example to print the
general credits, you will use somewhere in your code:

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

Tabla 1. Pre-defined phpcredits() flags

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

See also: phpinfo(), phpversion(), and php_logo_guid().

phpinfo (PHP 3, PHP 4 )


Recupera gran cantidad de información de PHP.

int phpinfo ( void) \linebreak


Obtiene gran cantidad de información sobre el estado actual de PHP. Esto incluye información sobre las
opciones de compilación y extensiones de PHP, la versión PHP, información y entorno del servidor (si

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().

phpversion (PHP 3, PHP 4 )


Obtiene la versión actual de PHP.

string phpversion ( void) \linebreak


Devuelve una cadena de carácteres que contiene la versión del parser PHP que está ejecutándose
actualmente.

Ejemplo 1. ejemplo phpversion()

// prints e.g. ’Current PHP version: 3.0rel-dev’


echo "Current PHP version: ".phpversion();

Véase también phpinfo().

putenv (PHP 3, PHP 4 )


Establece el valor de una variable de entorno.

void putenv ( string setting) \linebreak


Añade setting (valor) al entorno.

Ejemplo 1. Establecer una Variable de Entorno

putenv("UNIQID=$uniqid");

set_magic_quotes_runtime (PHP 3>= 3.0.6, PHP 4 )


Establece el valor de la configuración activa actual de magic_quotes_runtime.

long set_magic_quotes_runtime ( int new_setting) \linebreak


Establece el valor de la configuración activa actual de magic_quotes_runtime. (0 desactivado, 1 activado)

1187
opciones/información PHP

Véase también get_magic_quotes_gpc(), get_magic_quotes_runtime().

set_time_limit (PHP 3, PHP 4 )


limita el tiempo máximo de ejecución

void set_time_limit ( int seconds) \linebreak


Establece el número de segundos que se le permite a un script ejecutarse. Si éste es alcanzado, el script
devuelve un error de tipo fatal. El límite por defecto es 30 segundos o, si existe, el valor
max_execution_time definido en el fichero de configuración. Si seconds (segundos) se establece a cero,
no se impone ningún límite.
Cuando se llama, set_time_limit() reinicia el contador del timeout a cero. En otras palabras, si el timeout
es el de por defecto de 30 segundos, y después de 25 segundos de ejecución del script se realiza una
llamada set_time_limit(20), el script se ejecutará durante un total de 45 segundos antes de alcanzar su
límite.
Advierta que set_time_limit() no tiene efecto cuando PHP se ejecuta en modo seguro (safe mode). No
hay otra opción que que desactivar el modo seguro o cambiar el límite de tiempo en el fichero de
configuración.

version_compare (PHP 4 >= 4.1.0)


Compares two "PHP-standardized" version number strings

int version_compare ( string version1, string version2 [, string operator]) \linebreak


version_compare() compares two "PHP-standardized" version number strings. This is useful if you
would like to write programs working only on some versions of PHP.
version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and +1 if
the second is lower.
If you specify the third optional operator argument, you can test for a particular relationship. The
possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively. Using this
argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.

Ejemplo 1. version_compare() Example

// prints -1
echo version_compare("4.0.4", "4.0.6");

// these all print 1


echo version_compare("4.0.4", "4.0.6", "<");
echo version_compare("4.0.6", "4.0.6", "eq");

1188
opciones/información PHP

zend_logo_guid (PHP 4 )
Obtiene el guid zend

string zend_logo_guid ( void) \linebreak

Nota: Esta funcionalidad fue añadida en PHP4 Beta 4.

zend_version (PHP 4 )
Gets the version of the current Zend engine

string zend_version ( void) \linebreak


Returns a string containing the version of the currently running PHP parser.

Ejemplo 1. zend_version() Example

// prints e.g. ’Zend engine version: 1.0.4’


echo "Zend engine version: " . zend_version();

See also phpinfo(), phpcredits(), php_logo_guid(), and phpversion().

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

posix_ctermid (PHP 3>= 3.0.13, PHP 4 )


Recoge el nombre de ruta de la terminal de control

string posix_ctermid ( void ) \linebreak


Necesita ser escrito.

posix_getcwd (PHP 3>= 3.0.13, PHP 4 )


Nombre de ruta del directorio actual

string posix_getcwd ( void ) \linebreak


Necesita ser escrito cuanto antes.

posix_getegid (PHP 3>= 3.0.10, PHP 4 )


Devuelve el ID de grupo efectivo del proceso actual

int posix_getegid ( void ) \linebreak


Devuelve el valor numérico ID de grupo efectivo del proceso actual. Vea también posix_getgrgid() para
información sobre como convertir este número en un nombre de grupo manejable.

posix_geteuid (PHP 3>= 3.0.10, PHP 4 )


Devuelve el ID de usuario efectivo del proceso actual

int posix_geteuid ( void ) \linebreak


Devuelve el valor numérico ID de usuario efectivo del proceso actual. Vea también posix_getpwuid()
para información sobre como convertir este número en un nombre de usuario manejable.

posix_getgid (PHP 3>= 3.0.10, PHP 4 )


Devuelve el ID de grupo real del proceso actual

int posix_getgid ( void ) \linebreak


Devuelve el valor númerico ID de grupo real del proceso actual. Vea también posix_getgrgid() para
información sobre como convertir esto en un nombre de grupo manejable.

1191
POSIX

posix_getgrgid (PHP 3>= 3.0.13, PHP 4 )


Devuelve información sobre un grupo a trave del id de grupo

array posix_getgrgid ( int gid) \linebreak


Necesita ser escrito.

posix_getgrnam (PHP 3>= 3.0.13, PHP 4 )


Devuelve información sobre un grupo a traves del nombre

array posix_getgrnam ( string name) \linebreak


Necesita ser escrito.

posix_getgroups (PHP 3>= 3.0.10, PHP 4 )


Devuelve el conjunto de grupos del proceso actual

array posix_getgroups ( void ) \linebreak


Devuelve un vector de enteros que contiene los ids numéricos de grupo de el conjunto de grupos del
proceso actual. Vea también posix_getgrgid() para información sobre como convertir esto en nombres de
grupo manejables.

posix_getlogin (PHP 3>= 3.0.13, PHP 4 )


Devuelve el nombre de usuario

string posix_getlogin ( void ) \linebreak


Devuelve el nombre de usuario (login) que es dueño del proceso actual. Vea posix_getpwnam() para
información sobre como conseguir mas datos de este usuario.

posix_getpgid (PHP 3>= 3.0.10, PHP 4 )


Recoge el id del grupo de procesos para el control de trabajo

int posix_getpgid ( int pid) \linebreak


Devuelve el identificador de grupo de procesos del proceso pid.

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.

posix_getpgrp (PHP 3>= 3.0.10, PHP 4 )


Devuelve el identificador de grupo del proceso actual

int posix_getpgrp ( void ) \linebreak


Devuelve el identificador de grupo de proceso del proceso actual. Vea POSIX.1 y la página de manual
getpgrp(2) de su sistema POSIX para más información de grupos de procesos.

posix_getpid (PHP 3>= 3.0.10, PHP 4 )


Devuelve el identificador del proceso actual

int posix_getpid ( void ) \linebreak


Devuelve el identificador de proceso del proceso actual.

posix_getppid (PHP 3>= 3.0.10, PHP 4 )


Devuelve el identificador del proceso padre

int posix_getppid ( void ) \linebreak


Devuelve el identificador de proceso del proceso padre del proceso actual.

posix_getpwnam (PHP 3>= 3.0.13, PHP 4 )


Devuelve información sobre un usuario a traves del nombre de usuario

array posix_getpwnam ( string username) \linebreak


Devuelve un vector asociativo conteniendo información sobre un usuario referenciado por un nombre
alfanumérico, pasado a la función en el parametro username.
Los elementos del vector devuelto son:

1193
POSIX

Elemento Descripción

Tabla 1. El vector de información de usuario

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.

posix_getpwuid (PHP 3>= 3.0.13, PHP 4 )


Devuelve información sobre un usuario a traves de su id

array posix_getpwuid ( int uid) \linebreak


Devuelve un vector asociativo que contiene información sobre un usuario referenciado con un ID de
usuario, pasado por el parámetro uid.
Los elementos del array son:

1194
POSIX

Tabla 1. El vector de información del usuario

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.

posix_getrlimit (PHP 3>= 3.0.10, PHP 4 )


Devuelve información sobre los limites de recursos del sistema

array posix_getrlimit ( void ) \linebreak


Necesita ser escrita tan pronto como sea posible.

posix_getsid (PHP 3>= 3.0.10, PHP 4 )


Consigue el sid actual del proceso

1195
POSIX

int posix_getsid ( int pid) \linebreak


Devuelve el sid del proceso pid. Si pid es 0, se devolverá el sid del proceso actual.
Esta no es una función POSIX, pero es normal en sistemas System V. Si su sistema no soporta esta
función a nivel de sistema, esta función PHP devolverá siempre FALSE.

posix_getuid (PHP 3>= 3.0.10, PHP 4 )


Devuelve el ID de usuario real del proceso actual

int posix_getuid ( void ) \linebreak


Devuelve el valor numerico ID de usuario real del proceso actual. Vea también posix_getpwuid() para
información sobre como convertir este ID en un nombre de usuario manejable.

posix_isatty (PHP 3>= 3.0.13, PHP 4 )


Determina si un descriptor de fichero esta en una terminal interactiva

bool posix_isatty ( int fd) \linebreak


Necesita ser escrito.

posix_kill (PHP 3>= 3.0.13, PHP 4 )


Manda una señal a un proceso

bool posix_kill ( int pid, int sig) \linebreak


Manda la señal sig al proceso con el identificador de proceso pid. Devuelve FALSE, si no puede enviar
la señal.Si sí la envia devuelve TRUE .
Vea también la página de manual kill(2) de su sistema POSIX, la cual contiene información adicional
sobre los identificadores de proceso negativos, el pid especial 0, el pid especial -1, y la señal numero 0.

posix_mkfifo (PHP 3>= 3.0.13, PHP 4 )


Crea un fichero especial fifo (los llamados pipe o tuberias)

bool posix_getcwd ( string pathname, int mode) \linebreak


Necesita ser escrito lo más pronto posible.

1196
POSIX

posix_setegid (PHP 4 >= 4.0.2)


Set the effective GID of the current process

bool posix_setegid ( int gid) \linebreak


Set the effective group ID of the current process. This is a privileged function and you need appropriate
privileges (usually root) on your system to be able to perform this function.
Returns TRUE on success, FALSE otherwise.

posix_seteuid (PHP 4 >= 4.0.2)


Set the effective UID of the current process

bool posix_seteuid ( int uid) \linebreak


Set the real user ID of the current process. This is a privileged function and you need appropriate
privileges (usually root) on your system to be able to perform this function.
Returns TRUE on success, FALSE otherwise. See also posix_setgid().

posix_setgid (PHP 3>= 3.0.13, PHP 4 )


Asigna el GID efectivo del proceso actual

bool posix_setgid ( int gid) \linebreak


Asigna el ID de grupo real del proceso actual. Esta es una función privilegiada y necesitas los privilegion
apropiados (normalmente root) en tu sistema para realizar esta función. El orden apropiado de llamada es
posix_setgid() primero, posix_setuid() después.
Devuelve TRUE si tiene éxito, FALSE en caso contrario.

posix_setpgid (PHP 3>= 3.0.13, PHP 4 )


Asigna el id de grupo de procesos para el control de trabajos

int posix_setpgid ( int pid, int pgid) \linebreak


Inserta el proceso pid en el grupo de procesos pgid. Vea POSIX.1 y la página de manual setsid(2) de
su sistema POSIX para más información sobre grupos de procesos y control de trabajo. Devuelve TRUE
si tiene éxito y FALSE en caso contrario.

1197
POSIX

posix_setsid (PHP 3>= 3.0.13, PHP 4 )


Convierte el proceso actual en lider de sesión

int posix_setsid ( void ) \linebreak


Convierte el proceso actual en lider de sesión. Vea POSIX.1 y la página de manual setsid(2) en su sistema
POSIX para más informacion en grupos de proceso y control de trabajos. Devuelve el id de sesión.

posix_setuid (PHP 3>= 3.0.13, PHP 4 )


Asigna el UID efectivo del proceso actual

bool posix_setuid ( int uid) \linebreak


Asigna el ID de usuario real al proceso actual. Esta es una función privilegiada y necesitas los privilegios
apropiados (normalmente root) en tu sistema para realizar esta función.
Devuelve TRUE si tiene exito, FALSE en caso contrario. Vea también posix_setgid().

posix_times (PHP 3>= 3.0.13, PHP 4 )


Recoge el tiempo de los procesos

array posix_times ( void ) \linebreak


Devuelve un hash de cadenas con información sobre el uso de CPU del proceso actual. Los índices del
hash son
• ticks - el numero de ticks de reloj que han pasado desde el reinicio.
• utime - tiempo de usuario usado por el proceso actual.
• stime - tiempo de sistema usado por el proceso actual.
• cutime - tiempo de usuario usado por el proceso actual e hijos.
• cstime - tiempo de sistema usado por el proceso actual e hijos.

posix_ttyname (PHP 3>= 3.0.13, PHP 4 )


Determina el nombre del dispositivo terminal

string posix_ttyname ( int fd) \linebreak


Necesita ser escrito.

1198
POSIX

posix_uname (PHP 3>= 3.0.10, PHP 4 )


Consigue el nombre del sistema

array posix_uname ( void ) \linebreak


Devuelve un hash de cadenas con información sobre el sistema. Los índices del hash son
• sysname - nombre del sistema operativo (e.g. Linux)
• nodename - nombre del sistema (e.g. valiant)
• release - release del sistema operativo (e.g. 2.2.10)
• version - versión del sistema operativo (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)
• machine - arquitectura del sistema (e.g. i586)

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.

Tabla 1. Postmaster y PHP

Postmaster PHP Estado


postmaster & pg_connect("", "", "", "", OK
"dbname");
postmaster -i & pg_connect("", "", "", "", OK
"dbname");
postmaster & pg_connect("localhost", "", "", "", Unable to connect to PostgreSQL
"dbname"); server: connectDB() failed: Is the
postmaster running and accepting
TCP/IP (with -i) connection at
’localhost’ on port ’5432’? in
/path/to/file.php3 on line 20.
(Imposible conectar al servidor
PostgreSQL, la llamada
connectDB() ha fallado: ¿Está
funcionando el postmaster
aceptando conextiones TCP/IP
(con -i) en ’localhost’ en el puerto
’5432’? en /path/to/file.php3 en
linea 20.
postmaster -i & pg_connect("localhost", "", "", "", OK
"dbname");

Uno puede establecer una conexión con el siguiente comando:


Para usar el interface de objetos grandes (large object o lo), es necesario encapsularlo en un bloque de
transacción. Un bloque de transacción empieza con un begin y si la transacción fue valida termina con

1200
PostgreSQL

commit y end. Si la transacción falla debe ser cerrada con abort y rollback.

Ejemplo 1. Usando Objetos Grandes (lo)

<?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

pg_affected_rows (PHP 4 >= 4.2.0)


Returns number of affected records(tuples)

int pg_affected_rows ( resource result) \linebreak


pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT,
UPDATE, and DELETE queries executed by pg_query(). If no tuple is affected by this function, it will
return 0.

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

Nota: This function used to be called pg_cmdtuples().

See also pg_query() and pg_num_rows().

pg_cancel_query (PHP 4 >= 4.2.0)


Cancel async query

bool pg_cancel_query ( resource connection) \linebreak


pg_cancel_query() cancel asynchronous query sent by pg_send_query(). You cannot cancel query
executed by pg_query().
See also pg_send_query() and pg_connection_busy()

pg_client_encoding (PHP 3 CVS only, PHP 4 >= 4.0.3)


Get the client encoding

string pg_client_encoding ( [resource connection]) \linebreak

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().

See also pg_set_client_encoding().

pg_Close (PHP 3, PHP 4 )


Cierra una conexión PostgreSQL

bool pg_close ( int connection) \linebreak


Devuelve FALSE si connection no es un indice de conexión valido y TRUE en cualquier otro caso. Cierra
la conexión a la base de datos PostgreSQL asociada con el indice de conexión pasado como parámetro.

pg_Connect (PHP 3, PHP 4 )


Abre una conexión

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().

pg_connection_busy (PHP 4 >= 4.2.0)


Get connection is busy or not

1203
PostgreSQL

bool pg_connection_busy ( resource connection) \linebreak


pg_connection_busy() returns TRUE if the connection is busy. If it is busy, a previous query is still
executing. If pg_get_result() is called, it will be blocked.
See also pg_connection_status() and pg_get_result()

pg_connection_reset (PHP 4 >= 4.2.0)


Reset connection (reconnect)

bool pg_connection_reset ( resource connection) \linebreak


pg_connection_reset() resets the connection. It is useful for error recovery. Devuelve TRUE si todo fue
bien, FALSE en caso de fallo.
See also pg_connect(), pg_pconnect() and pg_connection_status()

pg_connection_status (PHP 4 >= 4.2.0)


Get connection status

int pg_connection_status ( resource connection) \linebreak


pg_connection_status() returns a connection status. Possible statuses are PGSQL_CONNECTION_OK and
PGSQL_CONNECTION_BAD.

See also pg_connection_busy().

pg_convert (PHP 4 CVS only)


Convert associative array value into suitable for SQL statement.

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.

Nota: This function is experimental.

See also pg_metadata()

1204
PostgreSQL

pg_copy_from (PHP 4 >= 4.2.0)


Insert records into a table from an array

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

pg_copy_to (PHP 4 >= 4.2.0)


Copy a table to an array

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

pg_DBname (PHP 3, PHP 4 )


Nombre de la base de datos

string pg_dbname ( int connection) \linebreak


Devuelve el nombre de la base de datos a la cual es el índice de conexión con PostgreSQL está
conectado, o FALSE si connection no es un índice de conexión válido.

pg_delete (PHP 4 CVS only)


Delete records.

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

$res = pg_delete($db, ’post_log’, $_POST);


if ($res) {
echo "POST data is deleted: $res\n";
}
else {
echo "User must have sent wrong inputs\n";
}
?>

Nota: This function is experimental.

See also pg_convert()

pg_end_copy (PHP 4 >= 4.0.3)


Sync with PostgreSQL backend

bool pg_end_copy ( [resource connection]) \linebreak


pg_end_copy() syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL
server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued,
otherwise the PostgreSQL server may get out of sync with the frontend and will report an error.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
For further details and an example, see also pg_put_line().

pg_escape_bytea (PHP 4 >= 4.2.0)


Escape binary for bytea type

string pg_escape_bytea ( string data) \linebreak


pg_escape_bytea() escapes string for bytea datatype. It returns escaped string.

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

See also pg_escape_string()

pg_escape_string (PHP 4 >= 4.2.0)


Escape string for text/char type

string pg_escape_string ( string data) \linebreak


pg_escape_string() escapes string for text/char datatype. It returns escaped string for PostgreSQL. Use
of this functon is recommended instead of addslashes().

Nota: This function requires PostgreSQL 7.2 or later.

See also pg_escape_bytea()

pg_Fetch_Array (PHP 3>= 3.0.1, PHP 4 )


obtiene una fila en la forma de un array

array pg_fetch_array ( int result, int row [, int result_type]) \linebreak


Devuelve: Un array que se corresponde con la fila obtenida, o FALSE si no hay más filas.
pg_fetch_array() es una versión extendida de pg_fetch_row(). Además de almacenar los datos en los
índices numericos del array resultante, también almacena los datos usando índices asociativos,
empleando para ello el nombre del campo como la llave o índice.
El tercer parámetro opcional result_type en pg_fetch_array() es una constante y puede tomar
cualquiera de los siguientes valores: PGSQL_ASSOC, PGSQL_NUM, y PGSQL_BOTH.

Nota: Result_type se añadio en PHP 4.0.

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

Ejemplo 1. PostgreSQL fetch array

<?php
$conn = pg_pconnect("","","","","publisher");
if (!$conn) {
echo "An error occured.\n";
exit;
}

$result = pg_Exec ($conn, "SELECT * FROM authors");


if (!$result) {
echo "An error occured.\n";
exit;
}

$arr = pg_fetch_array ($result, 0);


echo $arr[0] . " <- array\n";

$arr = pg_fetch_array ($result, 1);


echo $arr["author"] . " <- array\n";
?>

pg_Fetch_Object (PHP 3>= 3.0.1, PHP 4 )


obtener una fila en forma de objeto

object pg_fetch_object ( int result, int row [, int result_type]) \linebreak


Devuelve: Un objeto cuyas propiedades se corresponden con los campos de la fila obtenida, o FALSE si
no hay más filas.
pg_fetch_object() es parecida a pg_fetch_array(), con una diferencia - se devuelve un objeto, en vez de
un array. Indirectamente, eso significa que solo puedes acceder a los datos por medio de su nombre de
campo, y no a través de sus posiciones (los números son nombres de propiedad invalidos).
El tercer parámetro opcional result_type en pg_fetch_object() es una constante y puede tomar
cualquiera de los siguientes valores: PGSQL_ASSOC, PGSQL_NUM, y PGSQL_BOTH.

Nota: Result_type se añadio en PHP 4.0.

Referente a la velocidad, la función es identica a pg_fetch_array(), y practicamente tan rápida como


pg_fetch_row() (la diferencia es insignificante).
Ver también: pg_fetch_array() y pg_fetch_row().

1208
PostgreSQL

Ejemplo 1. Postgres fetch object

<?php
$database = "verlag";
$db_conn = pg_connect ("localhost", "5432", "", "", $database);
if (!$db_conn): ?>
<H1>Failed connecting to postgres database <? echo $database ?></H1> <?
exit;
endif;

$qu = pg_exec ($db_conn, "SELECT * FROM verlag ORDER BY autor");


$row = 0; // postgres needs a row counter other dbs might not

while ($data = pg_fetch_object ($qu, $row)):


echo $data->autor." (";
echo $data->jahr ."): ";
echo $data->titel."<BR>";
$row++;
endwhile; ?>

<PRE><?php
$fields[] = Array ("autor", "Author");
$fields[] = Array ("jahr", " Year");
$fields[] = Array ("titel", " Title");

$row= 0; // postgres needs a row counter other dbs might not


while ($data = pg_fetch_object ($qu, $row)):
echo "----------\n";
reset ($fields);
while (list (,$item) = each ($fields)):
echo $item[1].": ".$data->$item[0]."\n";
endwhile;
$row++;
endwhile;
echo "----------\n"; ?>
</PRE> <?php
pg_freeResult ($qu);
pg_close ($db_conn);
?>

pg_fetch_result (PHP 4 >= 4.2.0)


Returns values from a result resource

mixed pg_fetch_result ( resource result, int row, mixed field) \linebreak


pg_fetch_result() returns values from a result resource returned by pg_query(). row is integer.
field is field name(string) or field index (integer). The row and field specify what cell in the table

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.

pg_Fetch_Row (PHP 3>= 3.0.1, PHP 4 )


obtiene la fila como un array enumerado

array pg_fetch_row ( int result, int row) \linebreak


Devuelve: Un array que se corresponde con la fila obtenida, o FALSE en el caso de que no haya más filas.
pg_fetch_row() obtiene una fila de datos a partir del resultado asociado con el identificador de resultado
especificado. La fila se devuelve en forma de array. Cada columna del resultado se almacena en una
posición del array, empezando a partir de la posición 0.
Las siguientes llamadas a pg_fetch_row() devolverán la fila siguiente en el conjunto resultado, o falso en
el caso de que no haya más filas que devolver.
Ver también: pg_fetch_array(), pg_fetch_object(), pg_result().

Ejemplo 1. Postgres fetch row

<?php
$conn = pg_pconnect("","","","","publisher");
if (!$conn) {
echo "An error occured.\n";
exit;
}

$result = pg_Exec ($conn, "SELECT * FROM authors");


if (!$result) {
echo "An error occured.\n";
exit;
}

$row = pg_fetch_row ($result, 0);


echo $row[0] . " <- row\n";

$row = pg_fetch_row ($result, 1);


echo $row[0] . " <- row\n";

$row = pg_fetch_row ($result, 2);


echo $row[1] . " <- row\n";
?>

1210
PostgreSQL

pg_field_is_null (PHP 4 >= 4.2.0)


Test if a field is NULL

int pg_field_is_null ( resource result, int row, mixed field) \linebreak


pg_field_is_null() test if a field is NULL or not. It returns 1 if the field in the given row is NULL. It returns
0 if the field in the given row is NOT NULL. Field can be specified as column index (number) or
fieldname (string). Row numbering starts at 0.

Nota: This function used to be called pg_fieldisnull().

pg_field_name (PHP 4 >= 4.2.0)


Returns the name of a field

string pg_field_name ( resource result, int field_number) \linebreak


pg_field_name() returns the name of the field occupying the given field_number in the given
PostgreSQL result resource. Field numbering starts from 0.

Nota: This function used to be called pg_fieldname().

See also pg_field_num().

pg_field_num (PHP 4 >= 4.2.0)


Returns the field number of the named field

int pg_field_num ( resource result, string field_name) \linebreak


pg_field_num() will return the number of the column (field) slot that corresponds to the field_name
in the given PostgreSQL result resource. Field numbering starts at 0. This function will return -1 on
error.

Nota: This function used to be called pg_fieldnum().

1211
PostgreSQL

See also pg_field_name().

pg_field_prtlen (PHP 4 >= 4.2.0)


Returns the printed length

int pg_field_prtlen ( resource result, int row_number, string field_name) \linebreak


pg_field_prtlen() returns the actual printed length (number of characters) of a specific value in a
PostgreSQL result. Row numbering starts at 0. This function will return -1 on an error.

Nota: This function used to be called pg_field_prtlen().

See also pg_field_size().

pg_field_size (PHP 4 >= 4.2.0)


Returns the internal storage size of the named field

int pg_field_size ( resource result, int field_number) \linebreak


pg_field_size() returns the internal storage size (in bytes) of the field number in the given PostgreSQL
result. Field numbering starts at 0. A field size of -1 indicates a variable length field. This function
will return FALSE on error.

Nota: This function used to be called pg_fieldsize().

See also pg_field_len() and pg_field_type().

pg_field_type (PHP 4 >= 4.2.0)


Returns the type name for the corresponding field number

string pg_field_type ( resource result, int field_number) \linebreak


pg_field_type() returns a string containing the type name of the given field_number in the given
PostgreSQL result resource. Field numbering starts at 0.

Nota: This function used to be called pg_fieldtype().

1212
PostgreSQL

See also pg_field_len() and pg_field_name().

pg_free_result (PHP 4 >= 4.2.0)


Free result memory

bool pg_free_result ( resource result) \linebreak


pg_free_result() only needs to be called if you are worried about using too much memory while your
script is running. All result memory will automatically be freed when the script is finished. But, if you
are sure you are not going to need the result data anymore in a script, you may call pg_free_result() with
the result resource as an argument and the associated result memory will be freed. It returns true on
success and false if an error occurs.

Nota: This function used to be called pg_freeresult().

See also pg_query().

pg_get_result (PHP 4 >= 4.2.0)


Get asynchronous query result

resource pg_get_result ( [resource connection]) \linebreak


pg_get_result() get result resource from async query executed by pg_send_query(). pg_send_query()
can send multiple queries to PostgreSQL server and pg_get_result() is used to get query result one by
one. It returns result resource. If there is no more results, it returns FALSE.

pg_Host (PHP 3, PHP 4 )


Devuelve el nombre del host

string pg_host ( int connection_id) \linebreak


pg_Host() devuelve el nombre del host al que identificador conexión PostgreSQL pasado está conectado.

pg_insert (PHP 4 CVS only)


Insert array into table.

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";
}
?>

Nota: This function is experimental.

See also pg_convert()

pg_last_error (PHP 4 >= 4.2.0)


Get the last error message string of a connection

string pg_last_error ( resource connection) \linebreak


pg_last_error() returns the last error message for given connection.
Error messages may be overwritten by internal PostgreSQL(libpq) function calls. It may not return
appropriate error message, if multiple errors are occured inside a PostgreSQL module function.
Use pg_result_error(), pg_result_status() and pg_connection_status() for better error handling.

Nota: This function used to be called pg_errormessage().

See also pg_result_error().

1214
PostgreSQL

pg_last_notice (PHP 4 >= 4.0.6)


Returns the last notice message from PostgreSQL server

string pg_last_notice ( resource connection) \linebreak


pg_last_notice() returns the last notice message from the PostgreSQL server specified by
connection. The PostgreSQL server sends notice messages in several cases, e.g. if the transactions
can’t be continued. With pg_last_notice(), you can avoid issuing useless queries, by checking whether
the notice is related to the transaction or not.

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().

pg_last_oid (PHP 4 >= 4.2.0)


Returns the last object’s oid

int pg_last_oid ( resource result) \linebreak


pg_last_oid() is used to retrieve the oid assigned to an inserted tuple (record) if the result resource is
used from the last command sent via pg_query() and was an SQL INSERT. Returns a positive integer if
there was a valid oid. It returns FALSE if an error occurs or the last command sent via pg_query() was
not an INSERT or INSERT is failed.
OID field became an optional field from PostgreSQL 7.2. When OID field is not defined in a table,
programmer must use pg_result_status() to check if record is is inserted successfully or not.

Nota: This function used to be called pg_getlastoid().

See also pg_query() and pg_result_status()

1215
PostgreSQL

pg_lo_close (PHP 4 >= 4.2.0)


Close a large object

bool pg_lo_close ( resource large_object) \linebreak


pg_lo_close() closes a Large Object. large_object is a resource for the large object from
pg_lo_open().
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: This function used to be called pg_loclose().

See also pg_lo_open(), pg_lo_create() and pg_lo_import().

pg_lo_create (PHP 4 >= 4.2.0)


Create a large object

int pg_lo_create ( resource connection) \linebreak


pg_lo_create() creates a Large Object and returns the oid of the large object. connection specifies a
valid database connection opened by pg_connect() or pg_pconnect(). PostgreSQL access modes
INV_READ, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with
both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and
above). It returns large object oid otherwise. It returns FALSE, if an error occurred,
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: This function used to be called pg_locreate().

pg_lo_export (PHP 4 >= 4.2.0)


Export a large object to file

bool pg_lo_export ( int oid, string pathname [, resource connection]) \linebreak


The oid argument specifies oid of the large object to export and the pathname argument specifies the
pathname of the file. It returns FALSE if an error occurred, TRUE otherwise.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: This function used to be called pg_loexport().

1216
PostgreSQL

See also pg_lo_import().

pg_lo_import (PHP 4 >= 4.2.0)


Import a large object from file

int pg_lo_import ( [resource connection, string pathname]) \linebreak


In versions before PHP 4.2.0 the syntax of this function was different, see the following definition:
int pg_lo_import ( [resource connection, string pathname]) \linebreak
The pathname argument specifies the pathname of the file to be imported as a large object. It returns
FALSE if an error occurred, oid of the just created large object otherwise.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: Cuando safe-mode (modo-seguro) está activado, PHP comprueba si el fichero(s)/directorios


que vas a utilizar, tienen la misma UID que el script que está siendo ejecutado.

Nota: This function used to be called pg_loimport().

See also pg_lo_export() and pg_lo_open().

pg_lo_open (PHP 4 >= 4.2.0)


Open a large object

resource pg_lo_open ( resource connection, int oid, string mode) \linebreak


pg_lo_open() open a Large Object and returns large object resource. The resource encapsulates
information about the connection. oid specifies a valid large object oid and mode can be either "r", "w",
or "rw". It returns FALSE if there is an error.

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.

Nota: This function used to be called pg_loopen().

1217
PostgreSQL

See also pg_lo_close() and pg_lo_create().

pg_lo_read_all (PHP 4 >= 4.2.0)


Read a entire large object and send straight to browser

int pg_lo_read_all ( resource large_object) \linebreak


pg_lo_read_all() reads a large object and passes it straight through to the browser after sending all
pending headers. Mainly intended for sending binary data like images or sound. It returns number of
bytes read. It returns FALSE, if an error occurred.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: This function used to be called pg_loreadall().

See also pg_lo_read().

pg_lo_read (PHP 4 >= 4.2.0)


Read a large object

string pg_lo_read ( resource large_object, int len) \linebreak


pg_lo_read() reads at most len bytes from a large object and returns it as a string. large_object
specifies a valid large object resource andlen specifies the maximum allowable size of the large object
segment. It returns FALSE if there is an error.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: This function used to be called pg_loread().

See also pg_lo_read_all().

pg_lo_seek (PHP 4 >= 4.2.0)


Seeks position of large object

bool pg_lo_seek ( resource large_object, int offset [, int whence]) \linebreak


pg_lo_seek() seeks position of large object resource. whence is PGSQL_SEEK_SET,
PGSQL_SEEK_CUR or PGSQL_SEEK_END.

1218
PostgreSQL

See also pg_lo_tell().

pg_lo_tell (PHP 4 >= 4.2.0)


Returns current position of large object

int pg_lo_tell ( resource large_object) \linebreak


pg_lo_tell() returns current position (offset from the beginning of large object).
See also pg_lo_seek().

pg_lo_unlink (PHP 4 >= 4.2.0)


Delete a large object

bool pg_lo_unlink ( resource connection, int oid) \linebreak


pg_lo_unlink() deletes a large object with the oid. It returns TRUE on success, otherwise returns FALSE.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: This function used to be called pg_lo_unlink().

See also pg_lo_create() and pg_lo_import().

pg_lo_write (PHP 4 >= 4.2.0)


Write a large object

int pg_lo_write ( resource large_object, string data) \linebreak


pg_lo_write() writes at most to a large object from a variable data and returns the number of bytes
actually written, or FALSE in the case of an error. large_object is a large object resource from
pg_lo_open().
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.

Nota: This function used to be called pg_lo_write().

See also pg_lo_create() and pg_lo_open().

1219
PostgreSQL

pg_metadata (PHP 4 CVS only)


Get metadata for table.

array pg_metadata ( resource connection, string table_name) \linebreak


pg_metadata() returns table definition for table_name as array. If there is error, it returns FALSE

Nota: This function is experimental.

See also pg_convert()

pg_num_fields (PHP 4 >= 4.2.0)


Returns the number of fields

int pg_num_fields ( resource result) \linebreak


pg_num_fields() returns the number of fields (columns) in a PostgreSQL result. The argument is a
result resource returned by pg_query(). This function will return -1 on error.

Nota: This function used to be called pg_numfields().

See also pg_num_rows() and pg_affected_rows().

pg_num_rows (PHP 4 >= 4.2.0)


Returns the number of rows

int pg_num_rows ( resource result) \linebreak


pg_num_rows() will return the number of rows in a PostgreSQL result resource. result is a query
result resource returned by pg_query(). This function will return -1 on error.

Nota: Use pg_affected_rows() to get number of rows affected by INSERT, UPDATE and DELETE
query.

Nota: This function used to be called pg_numrows().

See also pg_num_fields() and pg_affected_rows().

1220
PostgreSQL

pg_Options (PHP 3, PHP 4 )


Devuelve opciones

string pg_options ( int connection_id) \linebreak


pg_Options() devuelve una cadena que contiene las opciones especificadas en el identificador de
conexión con PostgreSQL dado.

pg_pConnect (PHP 3, PHP 4 )


Crea una conexión persistente con una base de datos

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.

pg_Port (PHP 3, PHP 4 )


Devuelve el número de puerto

int pg_port ( int connection_id) \linebreak


pg_Port() devuelve el número del puerto al que el identificador de conexión con PostgreSQL está
conectado.

pg_put_line (PHP 4 >= 4.0.3)


Send a NULL-terminated string to PostgreSQL backend

bool pg_put_line ( [resource connection, string data]) \linebreak


pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is useful for
example for very high-speed inserting of data into a table, initiated by starting a PostgreSQL

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.

See also pg_end_copy().

Ejemplo 1. High-speed insertion of data into a table

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

pg_query (PHP 4 >= 4.2.0)


Execute a query

resource pg_query ( resource connection, string query) \linebreak


pg_query() returns a query result resource if query could be executed. It returns FALSE on failure or if
connection is not a valid connection. Details about the error can be retrieved using the pg_last_error()
function if connection is valid. pg_last_error() sends an SQL statement to the PostgreSQL database
specified by the connection resource. The connection must be a valid connection that was
returned by pg_connect() or pg_pconnect(). The return value of this function is an query result resource
to be used to access the results from other PostgreSQL functions such as pg_fetch_array().

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.

See also pg_connect(), pg_pconnect(), pg_fetch_array(), pg_fetch_object(), pg_num_rows(), and


pg_affected_rows().

pg_result_error (PHP 4 >= 4.2.0)


Get error message associated with result

string pg_result_error ( resource result) \linebreak


pg_result_error() returns error message associated with result resource. Therefore, user has better
chance to get better error message than pg_last_error().
See also pg_query(), pg_send_query(), pg_get_result(), pg_last_error() and pg_last_notice()

pg_result_status (PHP 4 >= 4.2.0)


Get status of query result

int pg_result_status ( resource result) \linebreak


pg_result_status() returns status of result resource. Possible retun values are PGSQL_EMPTY_QUERY,
PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_TO, PGSQL_COPY_FROM,
PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR.
See also pg_connection_status().

pg_select (PHP 4 CVS only)


Select records.

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

// This is safe, since $_POST is converted autotmatically


$rec = pg_select($db, ’post_log’, $_POST);
if ($rec) {
echo "Records selected\n";
var_dump($rec);
}
else {
echo "User must have sent wrong inputs\n";
}
?>

Nota: This function is experimental.

See also pg_convert()

pg_send_query (PHP 4 >= 4.2.0)


Send asynchronous query

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

pg_set_client_encoding (PHP 3 CVS only, PHP 4 >= 4.0.3)


Set the client encoding

int pg_set_client_encoding ( [resource connection, string encoding]) \linebreak


pg_set_client_encoding() sets the client encoding and return 0 if success or -1 if error.
encoding is the client encoding and can 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. Available encoding depends on your PostgreSQL and libpq version. Refer to PostgreSQL
manual for supported encodings for your PostgreSQL.

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().

See also pg_client_encoding().

pg_trace (PHP 4 >= 4.0.1)


Enable tracing a PostgreSQL connection

bool pg_trace ( string pathname [, string mode [, resource connection]]) \linebreak


pg_trace() enables tracing of the PostgreSQL frontend/backend communication to a debugging file
specified as pathname. To fully understand the results, one needs to be familiar with the internals of
PostgreSQL communication protocol. For those who are not, it can still be useful for tracing errors in
queries sent to the server, you could do for example grep ’^To backend’ trace.log and see what query
actually were sent to the PostgreSQL server. For more information, refer to PostgreSQL manual.
Filename and mode are the same as in fopen() (mode defaults to ’w’), connection specifies the
connection to trace and defaults to the last one opened.
It returns TRUE if pathname could be opened for logging, FALSE otherwise.
See also fopen() and pg_untrace().

pg_tty (PHP 3, PHP 4 )


Devuelve el nombre del tty

string pg_tty ( int connection_id) \linebreak


pg_tty() devuelve el nombre del tty hacia el que se dirije la salida de depuración del lado del servidor en
el identificador de conexión de PostgreSQL dado.

pg_untrace (PHP 4 >= 4.0.1)


Disable tracing of a PostgreSQL connection

bool pg_untrace ( [resource connection]) \linebreak


Stop tracing started by pg_trace(). connection specifies the connection that was traced and defaults to
the last one opened.
Returns always TRUE.

1225
PostgreSQL

See also pg_trace().

pg_update (PHP 4 CVS only)


Update table.

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";
}
?>

Nota: This function is experimental.

See also pg_convert()

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.

Tabla 1. Supported Signals

SIGFPE SIGCONT SIGKILL


SIGSTOP SIGUSR1 SIGTSTP
SIGHUP SIGUSR2 SIGTTIN
SIGINT SIGSEGV SIGTTOU
SIGQUIT SIGPIPE SIGURG
SIGILL SIGALRM SIGXCPU
SIGTRAP SIGTERM SIGXFSZ
SIGABRT SIGSTKFLT SIGVTALRM
SIGIOT SIGCHLD SIGPROF
SIGBUS SIGCLD SIGWINCH
SIGPOLL SIGIO SIGPWR
SIGSYS

Process Control Example


This example forks off a daemon process with a signal handler.

Ejemplo 1. Process Control Example

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
}

// detatch from the controlling terminal


if (!posix_setsid()) {
die("could not detach from terminal");
}

// setup signal handlers


pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks


while(1) {

// do something interesting here

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

pcntl_exec (PHP 4 >= 4.2.0)


Executes specified program in current process space

bool pcntl_exec ( string path [, array args [, array envs]]) \linebreak

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

pcntl_fork (PHP 4 >= 4.1.0)


Forks the currently running process

int pcntl_fork ( void) \linebreak


The pcntl_fork() function creates a child process that differs from the parent process only in it’s PID and
PPID. Please see your system’s fork(2) man page for specific details as to how fork works on your
system.
On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is
returned in the child’s thread of execution. On failure, a -1 will be returned in the parent’s context, no
child process will be created, and a PHP error is raised.

Ejemplo 1. pcntl_fork() Example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
// we are the parent
} else {
// we are the child
}

?>

See also pcntl_waitpid() and pcntl_signal().

1229
PCNTL

pcntl_signal (PHP 4 >= 4.1.0)


Installs a signal handler

bool pcntl_signal ( int signo, mixed handle) \linebreak


The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal
handler is set to handler which may be the name of a user created function, or either of the two global
constants SIG_IGN or SIG_DFL.
pcntl_signal() returns TRUE on success or FALSE on failure.

Ejemplo 1. pcntl_signal() Example

<?php

// signal handler function


function sig_handler($signo) {

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 "Installing signal handler...\n";

// setup signal handlers


pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

print "Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id


posix_kill(posix_getpid(), SIGUSR1);

print "Done\n"

?>

1230
PCNTL

See also pcntl_fork() and pcntl_waitpid().

pcntl_waitpid (PHP 4 >= 4.1.0)


Waits on or returns the status of a forked child

int pcntl_waitpid ( int pid, int status, int options) \linebreak


The pcntl_waitpid() function suspends execution of the current process until a child as specified by the
pid argument has exited, or until a signal is delivered whose action is to terminate the current process or
to call a signal handling function. If a child as requested by pid has already exited by the time of the call
(a so-called "zombie" process), the function returns immediately. Any system resources used by the child
are freed. Please see your system’s waitpid(2) man page for specific details as to how waitpid works on
your system.
pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was
used and no child was available
The value of pid can be one of the following:

Tabla 1. possible values for pid

< -1 wait for any child process whose process group ID


is equal to the absolute value of pid.
-1 wait for any child process; this is the same
behaviour that the wait function exhibits.
0 wait for any child process whose process group ID
is equal to that of the calling process.
> 0 wait for the child whose process ID is equal to the
value of pid.

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:

Tabla 2. possible values for options

WNOHANG return immediately if no child has exited.


WUNTRACED return for children which are stopped, and whose
status has not been reported.

1231
PCNTL

See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(),


pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().

pcntl_wexitstatus (PHP 4 >= 4.1.0)


Returns the return code of a terminated child

int pcntl_wexitstatus ( int status) \linebreak


Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned
TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifexited().

pcntl_wifexited (PHP 4 >= 4.1.0)


Returns TRUE if status code represents a successful exit

int pcntl_wifexited ( int status) \linebreak


Returns TRUE if the child status code represents a successful exit.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wexitstatus().

pcntl_wifsignaled (PHP 4 >= 4.1.0)


Returns TRUE if status code represents a termination due to a signal

int pcntl_wifsignaled ( int status) \linebreak


Returns TRUE if the child process exited because of a signal which was not caught.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_signal().

pcntl_wifstopped (PHP 4 >= 4.1.0)


Returns TRUE if child process is currently stopped

1232
PCNTL

int pcntl_wifstopped ( int status) \linebreak


Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the
call to pcntl_waitpid() was done using the option WUNTRACED.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid().

pcntl_wstopsig (PHP 4 >= 4.1.0)


Returns the signal which caused the child to stop

int pcntl_wstopsig ( int status) \linebreak


Returns the number of the signal which caused the child to stop. This function is only useful if
pcntl_wifstopped() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifstopped().

pcntl_wtermsig (PHP 4 >= 4.1.0)


Returns the signal which caused the child to terminate

int pcntl_wtermsig ( int status) \linebreak


Returns the number of the signal that caused the child process to terminate. This function is only useful
if pcntl_wifsignaled() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid(), pcntl_signal() and pcntl_wifsignaled().

1233
LXXXII. Funciones de ejecución de programas

1234
Ejecución de programas

escapeshellarg (PHP 4 >= 4.0.3)


escape a string to be used as a shell argument

string escapeshellarg ( string arg) \linebreak


escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes
allowing you to pass a string directly to a shell function and having it be treated as a single safe argument.
This function should be used to escape individual arguments to shell functions coming from user input.
The shell functions include exec(), system() and the backtick operator. A standard use would be:

system("ls ".escapeshellarg($dir));

See also exec(), popen(), system(), and the backtick operator.

escapeshellcmd (PHP 3, PHP 4 )


enmascara los metacaracteres del intérprete de ordenes

string escapeshellcmd ( string command) \linebreak


EscapeShellCmd() enmascara cualquier carácter en una cadena de caracteres que pueda usarse para
introducir fraudulentamente una orden al intérprete de órdenes para que éste ejecute instrucciones
arbitrarias. Esta función se debería usar para asegurarse que cualquier dato que venga del usuario se
enmascare antes de que éste se le pase a las funciones exec() o system(), o al operador ‘ (apóstrofe
invertido) . Un uso habitual podría ser:

system(EscapeShellCmd($cmd))

Véase también exec(), popen(), system(), y el operador ‘ (apóstrofe invertido).

exec (PHP 3, PHP 4 )


Ejecuta un programa externo

string exec ( string command [, string array [, int return_var]]) \linebreak

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

passthru (PHP 3, PHP 4 )


Ejecuta un programa externo y muestra su salida literal

string passthru ( string command [, int return_var]) \linebreak


La función passthru() es similar a la función exec() en que ejecuta una orden (command). Si existe el
parámetro return_var, el valor de estado devuelto por la orden Unix se guardará ahí. Esta función
debería usarse en lugar de exec() o system() cuando la salida de la orden Unix sean datos binarios que
deban ser pasados directamente al navegador. Un uso típico de ello es ejecutar algo como las utilidades
pbmplus las cuales pueden dar como resultado directamente el flujo de datos de una imagen. Poniendo el
content-type a image/gif y llamando al programa pbmplus para mostrar un gif, usted puede crear
archivos de órdenes PHP que generen directamente imágenes.
Véase también exec(), system(), popen(), EscapeShellCmd(), y el operador ‘ (apóstrofe invertido).

proc_close (PHP 4 CVS only)


Close a process opened by proc_open and return the exit code of that process.

int proc_close ( resource process) \linebreak


proc_close() is similar to popen() except that it only works on processes opened by proc_open().
proc_close() waits for the process to terminate, and returns it’s exit code. If you have open pipes to that
process, you should fclose() them prior to calling this function in order to avoid a deadlock - the child
process may not be able to exit while the pipes are open.

1236
Ejecución de programas

proc_open (PHP 4 CVS only)


Execute a command and open file pointers for input/output

resource proc_open ( string cmd, array descriptorspec, array pipes) \linebreak


proc_open() is similar to popen() but provides a much greater degree of control over the program
execution. cmd is the command to be executed by the shell. descriptorspec is an indexed array
where the key represents the descriptor number and the value represents how PHP will pass that
descriptor to the child process. pipes will be set to an indexed array of file pointers that correspond to
PHP’s end of any pipes that are created. The return value is a resource representing the process; you
should free it using proc_close() when you are finished with it.

$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

fwrite($pipes[0], "<?php echo \"Hello World!\"; ?>");


fclose($pipes[0]);

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

echo "command returned $return_value\n";


}

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: This function was introduced in PHP 4.3.0.

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

string shell_exec ( string cmd) \linebreak


This function is identical to the backtick operator.

system (PHP 3, PHP 4 )


Ejecuta un programa externo y muestra su salida

string system ( string command [, int return_var]) \linebreak


system() se parece a la versión C de la función de mismo nombre en que ejecuta la orden indicada en
command y muestra el resultado. Si se indica una variable como segundo parámetro, el código de estado
devuelto por la orden ejecutada se guardará en esta 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.
La llamada a system() también intenta vaciar automáticamente el buffer de salida del servidor web
después de cada línea de salida si PHP está funcionando como un módulo del servidor.
Devuelve la última línea de la orden en caso de éxito, y falso en caso de fallo.
Si necesita ejecutar una orden y obtener de vuelta todo los datos del mismo sin interferencias, use la
función PassThru().
Véase también exec(), PassThru(), popen(), EscapeShellCmd(), y el operador ‘ (apóstrofe invertido).

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

void printer_abort ( resource handle) \linebreak


This function deletes the printers spool file.
handle must be a valid handle to a printer.

Ejemplo 1. printer_abort() example

$handle = printer_open();
printer_abort($handle);
printer_close($handle);

printer_close (unknown)
Close an open printer connection

void printer_close ( resource handle) \linebreak


This function closes the printer connection. printer_close() also closes the active device context.
handle must be a valid handle to a printer.

Ejemplo 1. printer_close() example

$handle = printer_open();
printer_close($handle);

printer_create_brush (unknown)
Create a new brush

mixed printer_create_brush ( int style, string color) \linebreak


The function creates a new brush and returns a handle to it. A brush is used to fill shapes. For an example
see printer_select_brush(). color must be a color in RGB hex format, i.e. "000000" for black, style
must be one of the following constants:

1240
Printer

• PRINTER_BRUSH_SOLID: creates a brush with a solid color.


• PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).
• PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).
• PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).
• PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).
• PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).
• PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).
• PRINTER_BRUSH_CUSTOM : creates a custom brush from an BMP file. The second parameter is
used to specify the BMP instead of the RGB color code.

printer_create_dc (unknown)
Create a new device context

void printer_create_dc ( resource handle) \linebreak


The function creates a new device context. A device context is used to customize the graphic objects of
the document. handle must be a valid handle to a printer.

Ejemplo 1. printer_create_dc() example

$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

mixed printer_create_pen ( int style, int width, string color) \linebreak


The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an
example see printer_select_pen(). color must be a color in RGB hex format, i.e. "000000" for black,
width specifies the width of the pen whereas style must be one of the following constants:
• PRINTER_PEN_SOLID: creates a solid pen.
• PRINTER_PEN_DASH: creates a dashed pen.
• PRINTER_PEN_DOT: creates a dotted pen.
• PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.
• PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.

1242
Printer

• PRINTER_PEN_INVISIBLE: creates an invisible pen.

printer_delete_brush (unknown)
Delete a brush

bool printer_delete_brush ( resource handle) \linebreak


The function deletes the selected brush. For an example see printer_select_brush(). It returns TRUE on
success, or FALSE otherwise. handle must be a valid handle to a brush.

printer_delete_dc (unknown)
Delete a device context

bool printer_delete_dc ( resource handle) \linebreak


The function deletes the device context and returns TRUE on success, or FALSE if an error occurred. For
an example see printer_create_dc(). handle must be a valid handle to a printer.

printer_delete_font (unknown)
Delete a font

bool printer_delete_font ( resource handle) \linebreak


The function deletes the selected font. For an example see printer_select_font(). It returns TRUE on
success, or FALSE otherwise. handle must be a valid handle to a font.

printer_delete_pen (unknown)
Delete a pen

bool printer_delete_pen ( resource handle) \linebreak


The function deletes the selected pen. For an example see printer_select_pen(). It returns TRUE on
success, or FALSE otherwise. handle must be a valid handle to a pen.

1243
Printer

printer_draw_bmp (unknown)
Draw a bmp

void printer_draw_bmp ( resource handle, string filename, int x, int y) \linebreak


The function simply draws an bmp the bitmap filename at position x, y. handle must be a valid
handle to a printer.
The function returns TRUE on success, or otherwise FALSE.

Ejemplo 1. printer_draw_bmp() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_draw_bmp($handle, "c:\\image.bmp", 1, 1);

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

Ejemplo 1. printer_draw_chord() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");


printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");


printer_select_brush($handle, $brush);

printer_draw_chord($handle, 1, 1, 500, 500, 1, 1, 500, 1);

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.

Ejemplo 1. printer_draw_elipse() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");


printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");


printer_select_brush($handle, $brush);

1245
Printer

printer_draw_elipse($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_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.

Ejemplo 1. printer_draw_line() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");


printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 10, 1000, 10);


printer_draw_line($handle, 1, 60, 500, 60);

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.

Ejemplo 1. printer_draw_pie() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");


printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");


printer_select_brush($handle, $brush);

printer_draw_pie($handle, 1, 1, 500, 500, 1, 1, 500, 1);

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

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.

Ejemplo 1. printer_draw_rectangle() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");


printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");


printer_select_brush($handle, $brush);

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_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

Ejemplo 1. printer_draw_roundrect() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");


printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");


printer_select_brush($handle, $brush);

printer_draw_roundrect($handle, 1, 1, 500, 500, 200, 200);

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

void printer_draw_text ( resource printer_handle, string text, int x, int y) \linebreak


The function simply draws text at position x, y using the selected font. printer_handle must be a
valid handle to a printer.

Ejemplo 1. printer_draw_text() example

$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

bool printer_end_doc ( resource handle) \linebreak


Closes a new document in the printer spooler. The document is now ready for printing. For an example
see printer_start_doc(). handle must be a valid handle to a printer.

printer_end_page (unknown)
Close active page

bool printer_end_page ( resource handle) \linebreak


The function closes the active page in the active document. For an example see printer_start_doc().
handle must be a valid handle to a printer.

printer_get_option (unknown)
Retrieve printer configuration data

mixed printer_get_option ( resource handle, string option) \linebreak


The function retrieves the configuration setting of option. handle must be a valid handle to a printer.
Take a look at printer_set_option() for the settings that can be retrieved, additionally the following
settings can be retrieved:
• PRINTER_DEVICENAME returns the devicename of the printer.
• PRINTER_DRIVERVERSION returns the printer driver version.

Ejemplo 1. printer_get_option() example

$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

array printer_list ( int enumtype [, string name [, int level]]) \linebreak


The function enumerates available printers and their capabilities. level sets the level of information
request. Can be 1,2,4 or 5. enumtype must be one of the following predefined constants:
• PRINTER_ENUM_LOCAL: enumerates the locally installed printers.
• PRINTER_ENUM_NAME: enumerates the printer of name, can be a server, domain or print provider.
• PRINTER_ENUM_SHARED: this parameter can’t be used alone, it has to be OR’ed with other
parameters, i.e. PRINTER_ENUM_LOCAL to detect the locally shared printers.
• PRINTER_ENUM_DEFAULT: (Win9.x only) enumerates the default printer.
• PRINTER_ENUM_CONNECTIONS: (WinNT/2000 only) enumerates the printers to which the user
has made connections.
• PRINTER_ENUM_NETWORK: (WinNT/2000 only) enumerates network printers in the computer’s
domain. Only valid if level is 1.
• PRINTER_ENUM_REMOTE: (WinNT/2000 only) enumerates network printers and print servers in
the computer’s domain. Only valid if level is 1.

Ejemplo 1. printer_list() example

/* detect locally shared printer */


var_dump( printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED) );

printer_logical_fontheight (unknown)
Get logical font height

int printer_logical_fontheight ( resource handle, int height) \linebreak


The function calculates the logical font height of height. handle must be a valid handle to a printer.

Ejemplo 1. printer_logical_fontheight() example

$handle = printer_open();
print printer_logical_fontheight($handle, 72);
printer_close($handle);

1251
Printer

printer_open (unknown)
Open connection to a printer

mixed printer_open ( [string devicename]) \linebreak


This function tries to open a connection to the printer devicename, and returns a handle on success or
FALSE on failure.

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.

Ejemplo 1. printer_open() example

$handle = printer_open("HP Deskjet 930c");


$handle = printer_open();

printer_select_brush (unknown)
Select a brush

void printer_select_brush ( resource printer_handle, resource brush_handle) \linebreak


The function selects a brush as the active drawing object of the actual device context. A brush is used to
fill shapes. If you draw an rectangle the brush is used to draw the shapes, while the pen is used to draw
the border. If you haven’t selected a brush before drawing shapes, the shape won’t be filled.
printer_handle must be a valid handle to a printer. brush_handle must be a valid handle to a
brush.

Ejemplo 1. printer_select_brush() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");


printer_select_pen($handle, $pen);
$brush = printer_create_brush(PRINTER_BRUSH_CUSTOM, "c:\\brush.bmp");
printer_select_brush($handle, $brush);

1252
Printer

printer_draw_rectangle($handle, 1,1,500,500);

printer_delete_brush($brush);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");


printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1,501,500,1001);
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

void printer_select_font ( resource printer_handle, resource font_handle) \linebreak


The function selects a font to draw text. printer_handle must be a valid handle to a printer.
font_handle must be a valid handle to a font.

Ejemplo 1. printer_select_font() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -


50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

1253
Printer

printer_select_pen (unknown)
Select a pen

void printer_select_pen ( resource printer_handle, resource pen_handle) \linebreak


The function selects a pen as the active drawing object of the actual device context. A pen is used to draw
lines and curves. I.e. if you draw a single line the pen is used. If you draw an rectangle the pen is used to
draw the borders, while the brush is used to fill the shape. If you haven’t selected a pen before drawing
shapes, the shape won’t be outlined. printer_handle must be a valid handle to a printer.
pen_handle must be a valid handle to a pen.

Ejemplo 1. printer_select_pen() example

$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "2222FF");


printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);

printer_set_option (unknown)
Configure the printer connection

bool printer_set_option ( resource handle, int option, mixed value) \linebreak


The function sets the following options for the current connection. handle must be a valid handle to a
printer. For option can be one of the following constants:
• PRINTER_COPIES: sets how many copies should be printed, value must be an integer.
• PRINTER_MODE: specifies the type of data (text, raw or emf), value must be a string.
• PRINTER_TITLE: specifies the name of the document, value must be a string.
• PRINTER_ORIENTATION : specifies the orientation of the paper, value can be either
PRINTER_ORIENTATION_PORTRAIT or PRINTER_ORIENTATION_LANDSCAPE
• PRINTER_RESOLUTION_Y: specifies the y-resolution in DPI, value must be an integer.

1254
Printer

• PRINTER_RESOLUTION_X: specifies the x-resolution in DPI, value must be an integer.


• PRINTER_PAPER_FORMAT: specifies the a predefined paper format, set value to
PRINTER_FORMAT_CUSTOM if you want to specify a custom format with
PRINTER_PAPER_WIDTH and PRINTER_PAPER_LENGTH. value can be one of the following
constants.
• PRINTER_FORMAT_CUSTOM : let’s you specify a custom paper format.
• PRINTER_FORMAT_LETTER: specifies standard letter format (8 1/2- by 11-inches).
• PRINTER_FORMAT_LETTER: specifies standard legal format (8 1/2- by 14-inches).
• PRINTER_FORMAT_A3: specifies standard A3 format (297- by 420-millimeters).
• PRINTER_FORMAT_A4: specifies standard A4 format (210- by 297-millimeters).
• PRINTER_FORMAT_A5: specifies standard A5 format (148- by 210-millimeters).
• PRINTER_FORMAT_B4: specifies standard B4 format (250- by 354-millimeters).
• PRINTER_FORMAT_B5: specifies standard B5 format (182- by 257-millimeter).
• PRINTER_FORMAT_FOLIO: specifies standard FOLIO format (8 1/2- by 13-inch).

• PRINTER_PAPER_LENGTH: if PRINTER_PAPER_FORMAT is set to


PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifies a custom paper length in
mm, value must be an integer.
• PRINTER_PAPER_WIDTH: if PRINTER_PAPER_FORMAT is set to
PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifies a custom paper width in mm,
value must be an integer.
• PRINTER_SCALE: specifies the factor by which the printed output is to be scaled. the page size is
scaled from the physical page size by a factor of scale/100. for example if you set the scale to 50, the
output would be half of it’s original size. value must be an integer.
• PRINTER_BACKGROUND_COLOR: specifies the background color for the actual device context,
value must be a string containing the rgb information in hex format i.e. "005533".
• PRINTER_TEXT_COLOR: specifies the text color for the actual device context, value must be a
string containing the rgb information in hex format i.e. "005533".
• PRINTER_TEXT_ALIGN : specifies the text alignment for the actual device context, value can be
combined through OR’ing the following constants:
• PRINTER_TA_BASELINE: text will be aligned at the base line.
• PRINTER_TA_BOTTOM : text will be aligned at the bottom.
• PRINTER_TA_TOP: text will be aligned at the top.
• PRINTER_TA_CENTER: text will be aligned at the center.
• PRINTER_TA_LEFT: text will be aligned at the left.
• PRINTER_TA_RIGHT: text will be aligned at the right.

1255
Printer

Ejemplo 1. printer_set_option() example

$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

bool printer_start_doc ( resource handle [, string document]) \linebreak


The function creates a new document in the printer spooler. A document can contain multiple pages, it’s
used to schedule the print job in the spooler. handle must be a valid handle to a printer. The optional
parameter document can be used to set an alternative document name.

Ejemplo 1. printer_start_doc() example

$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

bool printer_start_page ( resource handle) \linebreak


The function creates a new page in the active document. For an example see printer_start_doc().
handle must be a valid handle to a printer.

1256
Printer

printer_write (unknown)
Write data to the printer

bool printer_write ( resource handle, string content) \linebreak


Writes content directly to the printer, and returns TRUE on success or FALSE if it failed.
handle must be a valid handle to a printer.

Ejemplo 1. printer_write() example

$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

pspell_add_to_personal (PHP 4 >= 4.0.2)


Agrega la palabra a la lista personal de palabras

int pspell_add_to_personal ( int dictionary_link, cadena palabra) \linebreak


pspell_add_to_personal() agrega una palabra a la lista personal de palabras. Si usas
pspell_new_config() con pspell_config_personal() para abrir el diccionario, puedes salvar la lista de
palabras luego, con pspell_save_wordlist(). Nota: Esta función no funcionará hasta que tengas pspell
.11.2 y aspell .32.5 o superior.

Ejemplo 1. pspell_add_to_personal()

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config ($pspell_config);

pspell_add_to_personal ($pspell_link, "Vlad");


pspell_save_wordlist ($pspell_link);

pspell_add_to_session (PHP 4 >= 4.0.2)


Agrega la palabra a la lista de palabras en la sesión actual

int pspell_add_to_session ( int dictionary_link, cadena palabra) \linebreak


pspell_add_to_session() agrega la palabra a la lista de palabras asociada con la sesión actual. Esto es
muy similar a pspell_add_to_personal()

pspell_check (PHP 4 >= 4.0.2)


Check a word

bool pspell_check ( int dictionary_link, string word) \linebreak


pspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.

1259
Pspell

Ejemplo 1. pspell_check()

$pspell_link = pspell_new ("en");

if (pspell_check ($pspell_link, "testt")) {


echo "This is a valid spelling";
} else {
echo "Sorry, wrong spelling";
}

pspell_clear_session (PHP 4 >= 4.0.2)


Limpia la sesión actual

int pspell_clear_session ( int dictionary_link) \linebreak


pspell_clear_session() limpia la sesión actual. La lista de palabras actual queda vacía, y, por ejemplo, si
intentas salvarla con pspell_save_wordlist(), nada ocurre.

Ejemplo 1. pspell_add_to_personal()

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config ($pspell_config);

pspell_add_to_personal ($pspell_link, "Vlad");


pspell_clear_session ($pspell_link);
pspell_save_wordlist ($pspell_link); //"Vlad" will not be saved

pspell_config_create (PHP 4 >= 4.0.2)


Create a config used to open a dictionary

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:

• PSPELL_FAST - Fast mode (least number of suggestions)

• PSPELL_NORMAL - Normal mode (more suggestions)


• PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Ejemplo 1. pspell_config_create()

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_personal ($pspell_config, "en");

pspell_config_ignore (PHP 4 >= 4.0.2)


Ignore words less than N characters long

int pspell_config_ignore ( int dictionary_link, int n) \linebreak


pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function
allows short words to be skipped by the spellchecker. Words less then n characters will be skipped.

1261
Pspell

Ejemplo 1. pspell_config_ignore()

$pspell_config = pspell_config_create ("en");


pspell_config_ignore($pspell_config, 5);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "abcd"); //will not result in an error

pspell_config_mode (PHP 4 >= 4.0.2)


Change the mode number of suggestions returned

int pspell_config_mode ( int dictionary_link, int mode) \linebreak


pspell_config_mode() should be used on a config before calling pspell_new_config(). This function
determines how many suggestions will be returned by pspell_suggest().
The mode parameter is the mode in which spellchecker will work. There are several modes available:

• PSPELL_FAST - Fast mode (least number of suggestions)

• PSPELL_NORMAL - Normal mode (more suggestions)


• PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

Ejemplo 1. pspell_config_mode()

$pspell_config = pspell_config_create ("en");


pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");

pspell_config_personal (PHP 4 >= 4.0.2)


Set a file that contains personal wordlist

int pspell_config_personal ( int dictionary_link, string file) \linebreak

1262
Pspell

pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal


wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the
file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save
personal wordlist to. The file should be writable by whoever php runs as (e.g. nobody). Please, note that
this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Ejemplo 1. pspell_config_personal()

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config ($pspell_config);
pspell_check ($pspell_link, "thecat");

pspell_config_repl (PHP 4 >= 4.0.2)


Set a file that contains replacement pairs

int pspell_config_repl ( int dictionary_link, string file) \linebreak


pspell_config_repl() should be used on a config before calling pspell_new_config(). The replacement
pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was
not found in the list, pspell_store_replacement() can be used to store a replacement pair and then
pspell_save_wordlist() to save the wordlist along with the replacement pairs. The file should be writable
by whoever php runs as (e.g. nobody). Please, note that this function will not work unless you have
pspell .11.2 and aspell .32.5 or later.

Ejemplo 1. pspell_config_repl()

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config ($pspell_config);
pspell_check ($pspell_link, "thecat");

1263
Pspell

pspell_config_runtogether (PHP 4 >= 4.0.2)


Consider run-together words as valid compounds

int pspell_config_runtogether ( int dictionary_link, bool flag) \linebreak


pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This
function determines whether run-together words will be treated 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.

Ejemplo 1. pspell_config_runtogether()

$pspell_config = pspell_config_create ("en");


pspell_config_runtogether ($pspell_config, true);
$pspell_link = pspell_new_config ($pspell_config);
pspell_check ($pspell_link, "thecat");

pspell_config_save_repl (PHP 4 >= 4.0.2)


Determine whether to save a replacement pairs list along with the wordlist

int pspell_config_save_repl ( int dictionary_link, bool flag) \linebreak


pspell_config_save_repl() should be used on a config before calling pspell_new_config(). It determines
whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is
no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved
by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved. Please, note
that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_new_config (PHP 4 >= 4.0.2)


Load a new dictionary with settings based on a given config

int pspell_new_config ( int config) \linebreak


pspell_new_config() opens up a new dictionary with settings specified in a config, created with with
pspell_config_create() and modified with pspell_config_*() functions. This method provides you with
the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().
The config parameter is the one returned by pspell_config_create() when the config was created.

1264
Pspell

Ejemplo 1. pspell_new_config()

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config ($pspell_config);

pspell_new_personal (PHP 4 >= 4.0.2)


Load a new dictionary with personal wordlist

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:

• PSPELL_FAST - Fast mode (least number of suggestions)

• PSPELL_NORMAL - Normal mode (more suggestions)

• PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

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

$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws",


"en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER));

pspell_new (PHP 4 >= 4.0.2)


Load a new dictionary

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_FAST - Fast mode (least number of suggestions)


• PSPELL_NORMAL - Normal mode (more suggestions)

• PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

• 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()

$pspell_link = pspell_new ("en", "", "", "",


(PSPELL_FAST|PSPELL_RUN_TOGETHER));

pspell_save_wordlist (PHP 4 >= 4.0.2)


Save the personal wordlist to a file

int pspell_save_wordlist ( int dictionary_link) \linebreak


pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be
open with pspell_new_personal(), and the location of files to be saved specified with
pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not
work unless you have pspell .11.2 and aspell .32.5 or later.

Ejemplo 1. pspell_add_to_personal()

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/tmp/dicts/newdict");
$pspell_link = pspell_new_config ($pspell_config);

pspell_add_to_personal ($pspell_link, "Vlad");


pspell_save_wordlist ($pspell_link);

pspell_store_replacement (PHP 4 >= 4.0.2)


Store a replacement pair for a word

int pspell_store_replacement ( int dictionary_link, string misspelled, string correct) \linebreak

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

$pspell_config = pspell_config_create ("en");


pspell_config_personal ($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl ($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config ($pspell_config);

pspell_store_replacement ($pspell_link, $misspelled, $correct);


pspell_save_wordlist ($pspell_link);

pspell_suggest (PHP 4 >= 4.0.2)


Suggest spellings of a word

array pspell_suggest ( int dictionary_link, string word) \linebreak


pspell_suggest() returns an array of possible spellings for the given word.

Ejemplo 1. pspell_suggest()

$pspell_link = pspell_new ("en");

if (!pspell_check ($pspell_link, "testt")) {


$suggestions = pspell_suggest ($pspell_link, "testt");

foreach ($suggestions as $suggestion) {


echo "Possible spelling: $suggestion<br>";
}
}

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

void readline_add_history ( string line) \linebreak


Esta función añade una línea al historial de líneas de comandos.

readline_clear_history (PHP 4 )
Borra el historial

boolean readline_clear_history ( void ) \linebreak


Esta función borra por completo el historial de la línea de comandos.

readline_completion_function (PHP 4 )
Registra una función de completitud

boolean readline_completion_function ( string line) \linebreak


Esta función registra una función de completitud. Debe proporcionar el nombre de una función existente
que acepte una línea de comandos parcial y devuelva una array con posibles coincidencias. Es el mismo
tipo de funcionalidad que se obtiene al pulsar la tecla de tabulación cuando se está usando el Bash.

readline_info (PHP 4 )
Establece/Obtiene diversas variables internas de readline

mixed readline_info ( [string varname [, string newvalue]]) \linebreak


Si es llamada sin parámetros, esta función devuelve un array con los valores de todas las opciones que
readline usa. Los elementos vendrán indexados por los siguientes valores: done, end, erase_empty_line,
library_version, line_buffer, mark, pending_input, point, prompt, readline_name, y terminal_name.
Si es llamada con un parámetros, devuelve el valor de esa opción. Si es llamada con dos parámetros, el
valor de la opción será cambiado al parámetro dado.

readline_list_history (PHP 4 )
Lista el historial

1270
Readline

array readline_list_history ( void ) \linebreak


Esta función devuelve un array con el historial de líneas de comandos completo. Los elementos están
indexados por enteros comenzando por el cero.

readline_read_history (PHP 4 )
Lee un historial

boolean readline_read_history ( string filename) \linebreak


Esta función lee un historial de comandos desde un fichero.

readline_write_history (PHP 4 )
Escribe el historial

boolean readline_write_history ( string filename) \linebreak


Esta función escribe el historial de comandos en un archivo.

readline (PHP 4 )
Lee una línea

string readline ( [string prompt]) \linebreak


Esta función devuelve una única cadena del usuario. Puede especificar una cadena que se mostrará al
usuario. La línea devuelta tiene el indicador final de nueva línea eliminado. Necesita añadir esta línea al
historial usando la función readline_add_history().

Ejemplo 1. readline()

//obtiene 3 comandos del usuario


for ($i=0; $i < 3; $i++) {
$line = readline ("Comando: ");
readline_add_history ($line);
}

//Vuelca el historial
print_r (readline_list_history());

//Vuelca las variables


print_r (readline_info());

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_file (PHP 3>= 3.0.13, PHP 4 )


Recodifica de fichero a fichero segun una peticion de recodificacion.

bool recode_file ( int input, int output) \linebreak


Recodifica el fichero definido por input a el fichero definido por output, segun la peticion de
recodificacion request. Devuelve FALSE si no puede realizar la recodificacion, TRUE si todo va bien.
Esta funcion no procesa ficheros remotos (URLs). Los dos ficheros deben de ser locales en el sistema.

recode_string (PHP 3>= 3.0.13, PHP 4 )


Recodifica una cadena literal segun una peticion de recodificacion.

string recode_string ( string request, string string) \linebreak


Recodifica la cadena string segun una peticion de recodificacion request. Devuelve FALSE si no
puede realizar la recodificacion, TRUE si todo va bien.
Una simple peticion "recode" podria ser "lat1..iso646-de". Ver tambien la documentacion de GNU
Recode de tu instalacion para obtener instrucciones detalladas sobre peticiones de recodificacion.

recode (PHP 4 )
Recode a string according to a recode request

string recode ( string request, string string) \linebreak

Nota: This is an alias for recode_string(). It has been added in PHP 4.

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.

Ejemplo 1. Ejemplos de patrones válidos

• /<\/\w+>/
• |(\d{3})-\d+|Sm
• /^(?i)php[34]/

Ejemplo 2. Ejemplos de patrones no válidos

• /href=’(.*)’ - falta el delimitador de fin


• /\w+\s*\w+/J - el modificador ’J’ es desconocido
• 1-\d3-\d3-\d4| - falta el delimitador de inicio

Nota: Para las funciones de expresiones compatibles con Perl se necesita PHP 4 o PHP 3.0.9 o
superior.

1274
PCRE

Modificadores de Patrones (unknown)


describe los modificadores posibles en los patrones de expresiones regulares (regex)

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.

Nota: Este modificador fue añadido en PHP 4.0.

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.

Sintaxis de los Patrones (unknown)


describe la sintaxis de PCRE regex

La librería PCRE es un conjunto de funciones que implementan emparejamientos


dados patrones de expresiones regulares usando la misma sintaxis y semántica que
Perl 5, con unas pocas diferencias (ver más adelante). La actual versión
corresponde a Perl 5.005.

Las diferencias descritas aquí son con respecto a Perl 5.005.

1. Por defecto, un carácter de espacio en blanco es cualquier carácter


que la función isspace() de la librería C reconozca, así es posible
compilar PCRE con tablas alternativas de tipos de caracteres. Normalmente

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.

2. PCRE no permite repetir cuantificadores sobre sentencias hacia adelante.


Perl las permite, pero no de la forma que puedas pensar.
Por ejemplo, (?!a){3} no dice que los próximos tres caracteres no son "a".
En realidad significa que los siguientes caracteres no son "a" tres veces.

3. Los subpatrones encontrados dentro de sentencias de más adelante


negativas son contados, pero sus entradas en el vector de desplazamientos
no son definidas. Perl define sus variables numéricas desde cualquiera de
tales patrones que son casados antes de que la sentencia falle emparejar
algo, pero solo si las sentencies de más adelante negativas contienen una
opción sola.

4. Aunque los caracteres de cero binario son soportados en la cadena de


entrada, no son permitidos en un patrón porque son pasados como un cadena
típica de C, terminada por cero. La secuencia de escape "\0" puede ser
usada en el patrón para representar el cero binario.

5. Las siguientes secuencias de Perl no son soportadas:


\l, \u, \L, \U, \E, \Q. En efecto, estas son implementadas por
manipuladores de cadenas típicos de Perl y no son parte de los patrones del
motor de búsqueda.

6. La secuencia \G de Perl no es soportada ya que no es relevante para


emparejamientos de patrones sencillos.

7. Obviamente, PCRE no soporta el constructor (?{code})

8. Hay algunas diferencias en Perl 5.005_02 respecto a las definiciones


de las cadenas de captura cuando parte de un patrón es repetido. Por
ejemplo, casando "aba" con el patrón /^(a(b)?)+$/ define $2 al valor "b",
pero emparejando "aabbaa" con /^(aa(bb)?)+$/ deja $2 sin definir. Sin
embargo, si el patrón es cambiado a /^(aa(b(b))?)+$/ entones $2 (y $3) son
definidos.

En Perl 5.004 $2 es definido en ambos casos, y también es cierto en PCRE.


Si en el futuro Perl cambia a una regla diferente, PCRE puede cambiar para
seguirla.

9. Otra discrepancia aún no resuelta es que en Perl 5.005_02 el patrón


/^(a)?(?(1)a|b)+$/ casa la cadena "a", pero en PCRE eso no es así. Sin
embargo, en ambos Perl y PCRE /^(a)?a/ empareja "a" dejando $1 sin definir.

1277
PCRE

10. PCRE da algunas extensiones para facilitar las expresiones de PERL:

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

(b) Si es definido PCRE_DOLLAR_ENDONLY y PCRE_MULTILINE no lo es, el


carácter especial $ sólo casa con el final de la cadena.

(c) Si se define PCRE_EXTRA, una barra invertida seguida de una letra sin
un significado especial provoca un error.

(d) Si defines PCRE_UNGREEDY, la voracidad de los cuantificadores de


repetición es invertida, esto es, por defecto son no codiciosos, pero
seguidos por una interrogación si lo son.

La sintaxis y la semántica de las expresiones soportadas por PCRE es


descrita a continuación. Las expresiones son descritas en la documentación
del Perl y en numerosos libros, algunos de los cuales tienen mucho
ejemplares, Jeffrey Friedl’s "Mastering Regular Expressions", publicado
por O’Reilly (ISBN 1-56592-257-3), las cubre con gran detalle. La presente
descripción es propuesta como documentación de referencia.

Una expresión es un patrón que es emparejada repetidamente, dada una cadena


de entrada, de izquierda a derecha. Muchos caracteres se representan a ellos
mismos en el patrón. Como un ejemplo trivial, el patrón

The quick brown fox

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.

Hay dos diferentes conjuntos de caracteres especiales: aquellos que son


reconocidos en cualquier parte en el patrón excepto dentro corchetes (’[’ y ’]’),
y aquellos que son reconocidos dentro. Fuera de los corchetes, los caracteres
especiales son:

\ carácter de escape genérico con diferentes usos

1278
PCRE

^ secuencia de inicio de la cadena de entrada (o línea, en modo multilínea)


$ secuencia de fin de la cadena de entrada (o línea, en modo multilínea)
. empareja cualquier carácter excepto el de nueva línea (por defecto)
[ inicia definición de clase de caracteres
| inicio de opción alternativa
( inicio de subpatrón
) fin de subpatrón
? amplia el significado de (
también es el cuantificador 0 ó 1
también es el cuantificador minimizado
* cero o más cuantificadores
+ uno o más cuantificadores
{ inicia el cuantificador min/max

Parte de un patrón dentro de corchetes ([]) es llamado un "character class"


(clase de caracteres). En una clase de caracteres los únicos caracteres
especiales son:

\ carácter de escape genérico


^ niega la clase, pero sólo si el primer carácter
- indica un rango de caracteres
] finaliza la clase de caracteres

Las secciones siguientes describen el uso de cada uno de los caracteres


especiales (meta caracteres).

BARRA INVERTIDA

El carácter de barra invertida tiene varios usos. Primero, si es seguido


por un carácter que no sea alfanumérico, toma el significado que el
carácter pueda tener. Este uso de la barra invertida, como un carácter de
escape, se aplica tanto dentro como fuera de las clases de caracteres.

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

Si el patrón es compilado con la opción PCRE_EXTENDED , los espacios en


blanco en el patrón (fuera de una clase de caracteres) y los caracteres entre
un "#" fuera de una clase de caracteres y el carácter de nueva línea
son ignorado. Una barra invertida de escape puede usarse para
incluir un espacio en blanco o el carácter "#" como parte del patrón.

Un segundo uso de la barra invertida sirve para codificar caracteres no


imprimibles en los patrones de una manera visible. No hay restricciones
sobre la apariencia de los caracteres no imprimibles, quitando el cero

1279
PCRE

binario de terminación de un patrón, pero cuando un patrón es preparado


con un editor de texto, normalmente es fácil utilizar una de las siguientes
secuencias de escape que representan sus caracteres binarios:

\a alarma, esto es, el carácter BEL (07 en hexadecimal)


\cx "control-x", donde x es cualquier carácter
\e escape (1B en hexadecimal)
\f nueva página (0C en hexadecimal)
\n nueva línea (0A en hexadecimal)
\r retorno de carro (0D en hexadecimal)
\t tabulador (09 en hexadecimal)
\xhh carácter con código hh en hexadecimal
\ddd carácter con código ddd en octal

El efecto de "\cx" es como sigue: si "x" es una letra minúscula,


es convertida a mayúscula. Entonces el sexto bit del carácter (40 en
hexadecimal) es invertido. Esto es, "\cz" es 1A en hexadecimal, pero "\c{"
es 3B en hexadecimal, mientras "\c;" es 7B en hexadecimal.

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.

Dentro de una clase carácter, o si el número decimal es mayor que nueve y


no ha habido tantos subpatrones capturados PCRE relee los tres dígitos
octales siguientes a la barra invertida y genera un byte desde los ocho
bits menos significativos del valor. Cualquier dígito a continuación se
representa a él mismo. Por ejemplo:

\040 es otro modo de escribir un espacio


\40 es lo mismo, siempre que haya menos de cuarenta subpatrones abiertos
\7 siempre es una referencia atrás
\11 puede ser una referencia atrás o un tabulador
\011 siempre es un tabulador
\0113 es el carácter con código octal 113 (ya que no puede haber más de

1280
PCRE

noventa y nueve referencias atrás)


\377 es un byte con todos sus bits a uno
\81 puede ser una referencia atrás o un cero binario seguido por
dos caracteres "8" y "1"

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

El tercer uso de la barra invertida es para especificar los tipos de


caracteres genéricos:

\d cualquier un dígito decimal


\D cualquier carácter que no sea un dígito decimal
\s cualquier carácter de espacio en blanco (whitespace)
\S cualquier carácter que no sea un espacio en blanco
\w cualquier carácter de "palabra"
\W cualquier carácter que no se de "palabra"

Cada pareja de secuencia de escape divide el conjunto global de caracteres


en dos. Cualquier carácter dado empareja en uno y sólo uno de cada pareja.

Un carácter de "palabra" es cualquier letra o dígito o el carácter subrayado,


esto es, cualquier carácter puede ser parte de una "palabra" en Perl. La
definición de letras y dígitos es controlada por la tabla de caracteres de
PERL, y puede ser variada si las especificaciones regionales son tomadas en
cuenta (ver "Soporte regional más adelante"). Por ejemplo, en Francia algunos
caracteres tienen un código superior a 128, para representar las letras
acentuadas, y son emparejados por \w.

Estas secuencias de tipos de caracteres pueden aparecer tanto dentro como


fuera de las clases carácter. Cada una casa un carácter del tipo apropiado.
Si el punto de casamiento actual es el final de la cadena, todo ello falla,
ya que no hay más caracteres que casar.

El cuarto uso de la barra invertida es para ciertas sentencias (assertions).


Una sentencia especifica una condición que tiene que ser encontrada en
un punto particular de un emparejamiento, sin utilizar ningún carácter de la
cadena de entrada. El uso de subpatrones para sentencias más complicadas
es descrito después. Las sentencias de barra invertida son

\b limites de palabra
\B no sean limites de palabra
\A inicio de la cadena de entrada (independiente del modo multilínea)

1281
PCRE

\Z fin de la cadena de entrada o de una nueva línea delante del final


(independiente del modo multilínea)
\z fin de la cadena de entrada (independiente de modo multilínea)

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)

Un límite de palabra es una posición en la cadena de entrada donde un


carácter y el anterior no emparejan con \w o \W (por ejemplo, uno casa con
\w y el otro con \W), o el principio o el final de la cadena si el primero
o el último carácter emparejan con \w, respectivamente.

Las sentencias \A, \Z y \z se diferencian de los tradicionales circunflejo


y dólar (ver más adelante) en que sólo emparejan el inicio y fin de la
cadena de entrada sin tener en cuenta las opciones definidas. No les afectan
las opciones PCRE_NOTBOL o PCRE_NOTEOL. La diferencia entre \Z y \z es que
\Z casa antes una nueva línea que es el último carácter de la cadena como
también el final de la cadena, sin embargo \z sólo casa el final.

CIRCUNFLEJO Y DOLAR

Fuera de una clase carácter, en el modo de emparejamiento por defecto, el


carácter circunflejo es una sentencia la cual es verdadera sólo si el punto
de casamiento actual es el inicio de la cadena de entrada. Dentro de una
clase carácter, el circunflejo tiene significado completamente distinto
(ver más adelante).

El circunflejo no necesita ser el primer carácter del patrón si son posibles


un número de alternativas, pero será la primera cosa en cada alternativa
en la cual aparezca si el patrón casa esa opción.
Si todas las alternativas posibles empiezan con un circunflejo, esto es,
si el patrón es obligado a casar sólo con en el inicio de la cadena de entrada,
se dice que es un patrón "anclado". También hay otros constructores que
pueden hacer que un patrón sea anclado.

Un carácter de dólar es una sentencia que es verdadera sólo si el


punto de emparejamiento actual es el final de la cadena de entrada, o
inmediatamente antes de un carácter de nueva línea, el cual es el último
carácter en la cadena, por defecto. El dólar no necesita ser el último
carácter del patrón si hay varias alternativas, pero será el último elemento
en cualquier alternativa en el que aparezca. El dólar no tiene
un significado especial en una clase carácter.

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

El significado de los caracteres circunflejo y dólar cambia si la opción


PCRE_MULTILINE es definida. Cuando éste es el caso, casan, respectivamente,
inmediatamente antes y después de un carácter "\n" interno,
además de emparejar con el inicio y el final de la cadena. Por ejemplo, el
patrón /^abc$/ casa con la cadena de entrada "def\nabc" en modo multilínea,
pero en otro modo no. Consecuentemente, los patrones anclados son en modo
línea ya que todas las opciones que empiezan con "^" no son ancladas en modo
multilínea. La opción PCRE_DOLLAR_ENDONLY es ignorada si PCRE_MULTILINE es
definido.

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.

Si una clase carácter casa con un carácter único en la cadena; el carácter


debe estar en el conjunto de los caracteres definidos por la clase, a menos
que el primero sea un circunflejo, en cuyo caso el carácter de la cadena de
entrada no debe estar en el conjunto definido por la clase. Si un circunflejo
es necesitado como un miembro de la clase, asegúrate que no es el primero o
es precedido por una barra invertida.

Por ejemplo, la clase carácter [aeiou] empareja cualquier vocal minúscula,


mientras [^aeiou] casa cualquier carácter que no sea una vocal minúscula.
Ten en cuenta que un circunflejo es una notación convenida para especificar
los caracteres que están en la clase enumerando los que no lo están. No es
una sentencia: consume un carácter de la cadena de entrada y falla si
el punto actual es final.

Cuando se define el emparejamiento sin tener en cuenta mayúsculas y minúsculas


(caseless), cualquier letra en una clase representa ambas, por ejemplo,

1283
PCRE

un patrón caseless [aeiou] empareja tanto "A" como "a" y un caseless


[^aeiou] no casa con "A"

El carácter de nueva línea nunca es tratado de un modo especial en una


clase carácter, aunque se hallan definido cualquiera de las opciones
PCRE_DOTALL o PCRE_MULTILINE. Una clase como [^a] siempre casa con una
nueva línea.

El carácter de menos puede ser usado para especificar un rango de caracteres


en una clase miembro. Por ejemplo, [d-m] casa con cualquier letra entre d
y m ambas incluidas. Si un carácter de menos es necesitado en una clase,
debe ser precedido por una barra invertida o aparecer en una posición donde
no pueda ser interpretado como indicador de una rango, normalmente al inicio
o al final de la clase.

No es posible tener el carácter literal "]" como el de final de un rango.


Un patrón como [W-]46] es interpretado como una clase de dos caracteres
("W" y "-") seguido por la cadena literal "46]", por lo que emparejaría con
"W46]" o "-46]". Sin embargo, si el carácter "]" es precedido con una barra
invertida es tomado por el final del rango, así [W-\]46] es interpretado
como una clase conteniendo un rango seguido por dos caracteres. La
representación octal o hexadecimal de "]" puede ser usada para finalizar
un rango.

Los rangos trabajan en la secuencia ASCII. Se pueden especificar mediante


la representación numérica de los mismos, por ejemplo [\000-\037]. Si
un rango que incluye letras es usado cuando es definida la opción de no
tener en cuenta mayúsculas y minúsculas casan ambas. Por ejemplo, [W-c]
es equivalente a [][\^_‘wxyzabc], teniendo en cuenta mayúsculas y
minúsculas, y si la tabla de caracteres para la región "fr" es usada,
entonces [\xc8-\xcb] empareja los caracteres E acentuados en ambos casos.

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.

Todos los caracteres no alfanuméricos y los diferentes a \, -, ^ (al


principio) y ] no tienen un significado especial en una clase, y éstos
tampoco si son definidos convenientemente.

BARRA VERTICAL

Los caracteres de barra vertical son usados para separar patrones


alternativos. Por ejemplo, el patrón

1284
PCRE

gilbert|sullivan

casa con "gilbert" o "sullivan". Cualquier cantidad de opciones pueden ser


implementadas, y una alternativa vacía se permite (emparejando la
cadena vacía). El proceso de casamiento intenta cada una de izquierda a
derecha, y la primera que valga es usada. Si las alternativas están dentro
de un subpatrón, "valga" significa que casa el resto del patrón principal
como también la alternativa en el subpatrón.

DEFINIENDO LAS OPCIONES INTERNAS

Las definiciones de PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL,


y PCRE_EXTENDED pueden ser cambiadas desde dentro del patrón mediante
una secuencia de letras de opciones de Perl encerradas entre "(?" y ")".
Las letras de opciones son

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.

El ámbito de estas opciones cambia dependiendo dónde ocurra la definición.


Las definiciones que son hechas fuera de subpatrones (como antes), el efecto es
el mismo que si la opción se define o elimina al inicio del casamiento. Los
siguientes patrones se comportan todos de la misma manera:

(?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.

Si un cambio de opción sucede dentro de un subpatrón, el efecto es diferente.


Esto es un cambio respecto de la conducta de Perl 5.005. Un cambio de opción
dentro de un subpatrón afecta sólo a la parte del subpatrón que lo sigue,

1285
PCRE

por eso

(a(?i)b)c

empareja abc y aBc y ninguna otra cadena (asumiendo que no es usado


PCRE_CASELESS). De este modo, las opciones pueden ser hechas para
tener diferente significado en diferente partes del patrón. Cualquier
cambio realizado en una alternativa provoca que todo el subpatrón la use.
Por ejemplo,

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

Las opciones específicas PCRE PCRE_UNGREEDY y PCRE_EXTRA pueden ser


cambiadas del mismo modo que las opciones compatibles con Perl usando
los caracteres U y X respectivamente. La bandera (?X) es especial ya que
siempre debe aparecer antes que cualquier otra en el patrón, incluso cuando
es definida a nivel superior. Es mejor ponerla en el inicio.

SUBPATRONES

Los subpatrones son delimitados por paréntesis y pueden estar anidados.


Marcando parte de un patrón como un subpatrón permite dos cosas:

1. Define un conjunto de opciones. Por ejemplo, el patrón

cat(aract|erpillar|)

empareja con "cat", "cataract", or "caterpillar". Sin los paréntesis,


casaría "cataract", "erpillar" o la cadena vacía.

2. Define el subpatrón como un subpatrón capturado. Cuando el patrón sea


emparejado por completo, esa porción de la cadena de entrada que casa con
el subpatrón es devuelta mediante el argumento ovector
de pcre_exec(). Los paréntesis abiertos son contados de
izquierda a derecha (empezando por uno) para definir los números de
subpatrones capturados.

Por ejemplo, si la cadena "the red king" es casada con el patrón

the ((red|white) (king|queen))

las subcadenas capturadas son "red king", "red", y "king" y los números
son 1,2 y 3

1286
PCRE

El hecho de que los paréntesis realicen dos funciones no siempre es útil.


A menudo, hay veces que un subpatrón agrupado es necesitado sin una
querer una captura. Si un paréntesis abierto le sigue "?:", el
subpatrón no hace ninguna captura, y no es contado cuando compute el
número de subpatrones capturados. Por ejemplo, si la cadena "the white
queen" es casada con el patrón

the ((?:red|white) (king|queen))

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.

Como un atajo, si cualquier definición de opción es necesitada al inicio


de un subpatrón no capturado, las letras de opciones pueden aparecer entre
"?" y ":". Así los dos patrones

(?i:saturday|sunday)
(?:(?i)saturday|sunday)

emparejan como el mismo conjunto de cadena de entrada exactamente. Ya que


las alternativas son intentadas de izquierda a derecha, y las opciones
no son dejadas de tener en cuenta hasta que el final de subpatrón se
alcanza, una definición de opción en una alternativa afecta al resto, por
eso el patrón anterior empareja tanto con "SUNDAY" como con "Saturday".

REPETICION

La repetición es especificada por cuantificadores, la cual puede utilizarla


cualquiera de los siguientes elementos:

un carácter, posiblemente precedido por el meta carácter .


una clase carácter
una referencia atrás (ver la próxima sección)
un subpatrón con paréntesis (a menos que sea una sentencia, ver más adelante)

El cuantificador de repetición general indica un número mínimo y un máximo


de casamientos permitidos, dando los dos números entre llaves, separados
por coma. El número debe ser menor que 65536, y el primero debe ser menor
o igual que el segundo. Por ejemplo:

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.

Se permite el cuantificado {0}, provocando que la expresión se comporte


como si el elemento anterior y el cuantificador no estuvieran presentes.

Por conveniencia (y compatibilidad histórica) los cuantificadores más comunes


tienen abreviaciones de un solo carácter.

* es equivalente a {0,}
+ es equivalente a {1,}
? es equivalente a {0,1}

Es posible construir bucles infinitos mediante un subpatrón que pueda


casar ningún carácter con un cuantificador que no tenga límite superior,
por ejemplo:

(a?)*

Las primeras versiones de Perl y PCRE dan un error en tiempo de compilación


para tales patrones. Sin embargo, ya que existen casos donde esto puede ser
útil, esto patrones son aceptados ahora, pero si cualquier repetición del
subpatrón no casa ningún carácter, el bucle es roto.

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

/* first command */ not comment /* second comment */

falla, porque casa la cadena entera debido a la voracidad del elemento .*

1288
PCRE

Sin embargo, si un cuantificador le siguw un signo de interrogación


entonces cesa la voracidad y empareja el mínimo número de veces posibles,
así el patrón

/\*.*?\*/

hace las cosas correctamente con los comentarios en C. El significado de


los cuantificadores variables no es cambiado en otro modo, justo el número
preferido de casamientos. No confundas el uso de las interrogaciones con
su uso como un cuantificador mas. Ya que tiene dos usos, a veces puede
parecer doble, como en

\d??\d

el cual empareja un dígito normalmente, pero puede casar dos si ese el


único modo de casar el resto del patrón.

Si se define la opción PCRE_UNGREEDY (la cual no es posible en Perl)


entonces los cuantificadores no son voraces por defecto, pero uno puede
serlo seguido por una interrogación. En otras palabras, invierte la conducta
por defecto.

Cuando un subpatrón entre paréntesis es cuantificado con un número mínimo


de repeticiones superior a uno o con un límite máximo, se necesita más
almacenamiento para compilar el patrón, en proporción al tamaño del mínimo
o del máximo.

Si un patrón empieza con .* o .{0,} y la opción PCRE_DOTALL (equivalente


a /s del Perl) es definida, esta permitiendo el . para casar nuevas líneas,
entonces el patrón es anclado implícitamente. PCRE trata tales patrones
como si estuvieran precedidos por \A. En los casos donde se conoce que la
cadena de entrada no contiene nuevas líneas, es conveniente definir
PCRE_DOTALL cuando el patrón empieza con .* para obtener esta optimización
o usar ^ para indicar explícitamente anclamiento.

Cuando un subpatrón capturado es repetido, el valor capturado es la


subcadena que empareja la iteración final. Por ejemplo, el patrón

(tweedle[dume]{3}\s*)+

con la cadena de entrada "tweedledum tweedledee" el valor de la subcadena


capturada es "tweedledee". Sin embargo, si hay subpatrones capturados
anidadamente, los valores capturados correspondientes pueden haber sido
definidos en las iteraciones anteriores. Por ejemplo, después de casar
"aba" con

/(a|(b))+/

1289
PCRE

el valor de la segunda subcadena capturada es "b".

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.

Sin embargo, si el número decimal seguido por la barra invertida es menor


que diez, siempre es tomado como una referencia atrás, y da error sólo si
no hay los suficientes subpatrones capturados en todo el patrón. En otras
palabras, los paréntesis que son referidos no necesitan estar a la
izquierda de la referencia para un número menor de diez. Examina la sección
anterior titulada "Barra invertida" para más detalles del manejo de los
dígitos con la barra invertida.

Una referencia atrás empareja si casa el subpatrón capturado en el actual


punto de la cadena de entrada, mejor que casar cualquier subpatrón de la
misma. Así el patrón

(sens|respons)e and \1ibility

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.

Puede haber más de una referencia atrás en el mismo subpatrón. Si un


subpatrón no ha sido usado en un emparejamiento particular, entonces
cualquier referencia atrás siempre fallara. Por ejemplo, el patró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

Una sentencia es un test sobre los caracteres siguiendo o precediendo el


punto actual de emparejamiento que no consume caracteres. Las sentencias
codificadas como \b, \B, \A, \Z, \z, ^ y $ son descritas después. Las
sentencias más complejas son codificadas como subpatrones. Hay dos clases:
aquellas que condicionan más adelante de la posición actual en la cadena
de entrada (lookahead)y las que lo hacen en este punto (lookbehind).

Un subpatrón de sentencia es emparejado del modo típico, excepto que no


hace que el punto actual de emparejamiento cambie. Sentencias que condicionan
más adelante empiezan con (?= para sentencias afirmativas y (?! para las
negativas

\w+(?=;)

empareja una palabra seguida por un punto y coma. pero no incluye el


punto y coma en el casamiento, y

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

encuentra una ocurrencia de "bar" que no es precedida por "foo".


Los contenidos de un sentencia de punto actual están limitados para que todas
las cadenas que emparejen deban tener una longitud fijada. Sin embargo, si
hay varias alternativas, no todas tienen que tener la misma longitud. Así

(?<=bullock|donkey)

es permitido, pero

(?<!dogs?|cats?)

da error en tiempo de compilación. Opciones que emparejen diferentes


longitudes de cadenas son permitidas sólo a nivel superior de la sentencia
de punto actual. Ésta es una extensión comparada con Perl 5.005, la cual
requiere que todas las opciones a casar tengan la misma longitud. Una
sentencia como

(?<=ab(c|de))

no es permitida, ya que sus opciones a nivel superior pueden casar dos


longitudes diferentes, pero es aceptable si se rescribe para usar dos
opciones a nivel superior:

(?<=abc|abde)

La implementación de sentencias de punto actual es, para cada alternativa,


mover temporalmente la posición actual hacia atrás por la longitud fijada
e intentar casar. Si no hay suficientes caracteres antes de la posición
actual, fallará. Las sentencias de punto actual en unión con subpatrones de
sólo una vez pueden ser particularmente útiles para emparejamientos de finales
de cadenas; un ejemplo es dado al final de la sección sobre subpatrones
de una sola vez.

Varias sentencias (de cualquier tipo) pueden suceder consecutivamente.


Por ejemplo,

(?<=\d{3})(?<!999)foo

empareja "foo" precedido por tres dígitos que no sean "999".


Además, las sentencias puede ser anidadas en cualquier combinación. Por
ejemplo,

(?<=(?<!foo)bar)baz

empareja una ocurrencia de "baz" que es precedida por "bar" la cual no sea
precedida por "foo".

1292
PCRE

Los subpatrones de sentencias no son subpatrones capturados, y no pueden


ser repetidos, ya que no tiene sentido la misma cosa varias veces. Si una
sentencia contiene subpatrones capturados dentro de ella, éstos son siempre
contados para el propósito de la numeración de los subpatrones capturados
en todo el patrón. Las subcadenas capturadas son tenidas en cuenta para
las sentencias afirmativas, pero no para las negativas (no tiene sentido).

El contador de sentencias llega hasta un máximo de doscientos subpatrones


con paréntesis.

SUBPATRONES DE UNA SOLA VEZ

Maximizando y minimizando las repeticiones para ver si un número diferente


de éstas permite al resto del patrón emparejar, causa múltiples evaluaciones
de la cadena de entrada. A veces es útil prevenir esto, cambiando el patrón
o provocando que la repetición falle pronto, cuando el creador del patrón
conoce que no hay puntos en común.

Considera, por ejemplo, el patrón \d+foo cuando se aplica a esta cadena de


entrada

123456bar

Después de emparejar los seis dígitos falla al emparejar "foo", la acción


normal del casamiento es intentar otra vez con sólo cinco dígitos que
emparejen con el elemento \d+, y entonces con cuatro, y así, antes de fallar.
Subpatrones de una sola vez dan el modo de especificar que una parte del
patrón tiene que emparejar, no es re-evaluado de esta manera, así el
casamiento fallará al emparejar "foo" la primera vez. La notación es otra
clase de paréntesis especial, iniciado con (?gt; como en este ejemplo:

(?>\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.

Una descripción alternativa es que un subpatrón de este tipo case los


caracteres de la cadena que un patrón fijo emparejaría, si estuviera anclado
en el punto actual de la cadena de entrada.

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.

Esta construcción, por supuesto, puede contener subpatrones arbitriamente

1293
PCRE

complicados y pueden estar anidados.

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$

cuando se aplica a una cadena larga con la cual no empareja. Ya que el


casamiento va de izquierda a derecha, PCRE buscará cada "a" en la cadena
y entonces verá si lo que sigue casa con el resto del patrón. Si el patrón
se escribe así

^.*abcd$

entonces el .* inicial casará primero la cadena entera, pero cuando esto


falle, volverá atrás para emparejar todo menos el último carácter, entonces
los dos últimos y así sucesivamente. Otra vez la búsqueda de "a" cubre la
cadena completa, de derecha a izquierda, de esta manera no se mejora. Sin
embargo, si el patrón fuese este

^(?>.*)(?<=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

Es posible hacer que el casamiento procese un subpatrón condicionalmente


o elegir entre dos subpatrones alternativos, dependiendo del resultado
de una sentencia o si un subpatrón capturado previamente casó o no.

Las dos formas posibles de subpatrones condicionales son

(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)

Si la condición es satisfecha, el yes-pattern es usado; sino el no-pattern


es utilizado si existe. Si hay más de dos alternativas en el subpatrón, se
produce un error en tiempo de compilación.

Hay dos clases de condiciones. Si el texto entre los paréntesis consiste


de una secuencia de dígitos, entonces la condición es verdadera si el
subpatrón capturado de ese número ha sido casado previamente. Consideremos
el siguiente patrón, contiene espacios en blanco para hacerlo más leíble

1294
PCRE

(asumimos la opción PCRE_EXTENDED) y lo dividimos en tres partes para


facilitar la discusión:

( \( )? [^()]+ (?(1) \) )

La primera parte empareja un paréntesis opcional abierto, y si el carácter


esta presente, lo define como la primera subcadena capturada. La segunda
parte casa uno o más caracteres que no están entre paréntesis. La tercera
parte es un subpatrón condicional que examina si el primer conjunto de
paréntesis casa o no. Si fuera así, esto es, si la cadena de entrada
empieza por un paréntesis abierto, la condición es cierta, y el yes-pattern
es ejecutado y un paréntesis de cierre es requerido. De otro modo, ya que
no-pattern no esta presente, el subpatrón no casa con nada. En otras
palabras, este patrón casa una secuencia de datos sin paréntesis
opcionalmente limitada por ellos.

Si la condición no es una secuencia de dígitos, debe ser una sentencia.


Esto puede ser una sentencia de más adelante positiva o negativa o una
de punto actual. Consideremos este patrón, otra vez conteniendo espacios
en blanco sin significado y con la segunda alternativa en la siguiente línea:

(?(?=[^a-z]*[a-z])
\d{2}[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )

La condición es una sentencia de más adelante positiva que empareja una


secuencia opcional de cualquier cosas menos letras seguido por una letra.
En otras palabras, examina la presencia de al menos una letra en la cadena
de entrada. Si una letra es encontrada, la cadena es casada con la primera
alternativa; sino lo es con la segunda. Este patrón casa cadenas de una de
estas dos formas dd-aaa-dd o dd-dd-dd, donde aaa son letra y dd son dígitos.

COMENTARIOS

La secuencia (?# marca el inicio de un comentario el cual continua hasta


el primer paréntesis. Los paréntesis anidados no son permitidos. Los
caracteres que forman un comentario no forman parte del patrón de
emparejamiento.

Si la opción PCRE_EXTENDED es definida, un carácter # fuera de una clase


carácter crea un comentario que continua hasta la próxima línea del patrón.

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

optimización de expresiones regulares para un rendimiento eficiente.

Cuando un patrón empieza con .* y la opción PCRE_DOTALL está definida, el


patrón es anclado implícitamente por PCRE, ya que sólo puede casar el inicio
de la cadena de entrada. Sin embargo, si PCRE_DOTALL no es definido, PCRE
no puede hacer esta optimización, ya que el meta carácter . no tiene porque
casar con una nueva línea y si la cadena de entrada contiene varias nuevas
líneas, el patrón puede emparejar desde el carácter inmediatamente siguiente
a uno de ellos en vez del inicio. Por ejemplo, el patrón

(.*) second

casa la cadena de entrada "first\nand second" (donde \n representa un carácter


de nueva línea) con la primera subcadena capturada empezando con "and".
En otras palabras, PCRE tiene que intentar los casamientos iniciándolos
después de cada nueva línea en la cadena de entrada.

Si estas usando un patrón con cadenas de entrada que no contienen nuevas


líneas, el mejor rendimiento se obtiene definiendo PCRE_DOTALL o iniciando
el patrón con ^.* para indicar anclamiento explícito. Esto previene a PCRE
tener que examinar toda la cadena de entrada buscando nuevas líneas para
empezar de nuevo.

preg_grep (PHP 4 )
Devuelve un array con los elementos que casen con el patrón

array preg_grep ( string pattern, array input) \linebreak


preg_grep() devuelve un array conteniendo los elementos del array input que emparejen con el patrón
(pattern) dado.

Ejemplo 1. Ejemplo de la función preg_grep()

preg_grep("/^(\d+)?\.\d+$/", $array); // encuentra todos los números reales en el array

Nota: Esta función fue añadida en PHP 4.0.

1296
PCRE

preg_match_all (PHP 3>= 3.0.9, PHP 4 )


Realiza un completo emparejamiento de expresiones

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.

preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test


print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n"

Esta ejemplo dará como resultado:

<b>example: </b>, <div align=left>this is a test</div>


example: , this is a test

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.

preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test


print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n"

Este ejemplo dará como resultado:

<b>example: </b>, example:


<div align=left>this is a test</div>, this is a test

1297
PCRE

En este caso, $matches[0] es el primer conjunto de emparejamientos y $matches[0][0] tiene el


casamiento completo, $matches[0][1] el del primer subpatrón y así sucesivamente. Similarmente,
$matches[1] es el segundo conjunto de emparejamientos, etc.

Si order no es dado, se asume PREG_PATTERN_ORDER.


Devuelve el número de casamientos completos, FALSE si no hubo o se produjo error.

Ejemplo 1. Obtener los número de teléfonos de un texto.

preg_match_all("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x",


"Call 555-1212 or 1-800-555-1212", $phones);

Examina también preg_match(), preg_replace() y preg_split().

preg_match (PHP 3>= 3.0.9, PHP 4 )


Realiza un emparejamiento dada una expresión

int preg_match ( string pattern, string subject [, array matches]) \linebreak


Busca en subject para un emparejamiento, dada la expresión pattern.
Si matches es dado, entonces será definido con el resultado de la búsqueda. $matches[0] contendrá el
texto que empareja con el patrón en su totalidad. $matches[1] tendrá la cadena que empareje con el
primer subpatrón que esté entre paréntesis y así sucesivamente.
Devuelve TRUE si se encontró en la cadena un emparejamiento dado el patrón pattern, FALSE si no se
produjo o hubo un error.

Ejemplo 1. Obtener el número de la siguiente página dada una cadena

if (preg_match("/page\s+#(\d+)/i", "Go to page #9.", $parts))


print "Next page is $parts[1]"; // La siguiente página es $parts[1]
else
print "Page not found."; // Página no encontrada

Examinar también preg_match_all(), preg_replace(), y preg_split().

preg_quote (PHP 3>= 3.0.9, PHP 4 )


Prepara los caracteres de expresiones

1298
PCRE

string preg_quote ( string str) \linebreak


preg_quote() toma str y pone una barra invertida (\) delante de todo carácter que sea parte de la
sintaxis de las expresiones. Es útil si tienes una cadena en tiempo de ejecución y puede contener
caracteres especiales.
Los caracteres especiales de las expresiones son:

. \\ + * ? [ ^ ] $ ( ) { } = ! < > | :

Nota: Esta función fue añadida en PHP 3.0.9.

preg_replace_callback (PHP 4 >= 4.0.5)


Perform a regular expression search and replace using a callback

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().

preg_replace (PHP 3>= 3.0.9, PHP 4 )


Lleva a cabo la búsqueda de una expresión y su sustitución

mixed preg_replace ( mixed pattern, mixed replacement, mixed subject) \linebreak


Busca en subject los emparejamientos con pattern y los sustituye por replacement.
replacement puede contener referencias de la forma \\n. Éstas serán sustituidas por el texto
obtenido por el patrón del paréntesis nésimo. n puede tener un valor de cero a noventa y nueve, y \\0 se
refiere al texto casado por el patrón completo. Para obtener el número del subpatrón de búsqueda, los
paréntesis abiertos son contados de izquierda derecha tomando el primero como uno.
Si el patrón no es encontrado en subject, entonces no se realizarán cambios.
Todos los parámetros de la función preg_replace() pueden ser un array.
Si subject es un array, entonces la búsqueda y sustitución es realizada para todos los elementos de
subject, y el valor devuelto es también un array.

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().

Nota: Este modificador fue añadido en PHP 4.0.

Ejemplo 1. Sustituir varios valores

$patterns = array("/(19|20\d{2})-(\d{1,2})-(\d{1,2})/", "/^\s*{(\w+)}\s*=/");


$replace = array("\\3/\\4/\\1", "$\\1 =");
print preg_replace($patterns, $replace, "{startDate} = 1999-5-27");

Esta ejemplo dará como resultado:

$startDate = 5/27/1999

Ejemplo 2. Usar el modificador /e

preg_replace("/(<\/?)(\w+)([^>]*>)/e", "’\\1’.strtoupper(’\\2’).’\\3’", $html_body);

Pondrá en mayúscula todos los tags HTML del texto de entrada.

Examina también preg_match(), preg_match_all(), y preg_split().

preg_split (PHP 3>= 3.0.9, PHP 4 )


Divide una cadena dada una expresión

array preg_split ( string pattern, string subject [, int limit [, int flags]]) \linebreak

Nota: El parámetro flags fue añadido en la Beta 3 de PHP

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().

Ejemplo 1. Obtener las partes de una cadena de búsqueda

$keywords = preg_split("/[\s,]+/", "hypertext language, programming");

Examinar también preg_match(), preg_match_all(), y preg_replace().

1301
LXXXVIII. qtdom functions

1302
qtdom functions

qdom_error (PHP 4 >= 4.0.5)


Returns the error string from the last QDOM operation or FALSE if no errors occured

string qdom_error ( void) \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.

qdom_tree (PHP 4 >= 4.0.4)


creates a tree of an xml string

object qdom_tree ( string ) \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.

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.

Ejemplo 1. Ejemplos de expresiones regulares

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. */

ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)",


$string,$regs);
/* Pone tres palabras separadas por espacios
en $regs[1], $regs[2] y $regs[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

ereg_replace (PHP 3, PHP 4 )


reemplaza expresiones regulares

string ereg_replace ( string pattern, string replacement, string string) \linebreak


Esta función examina string buscando coincidencias de pattern, y reemplaza el texto encontrado
con replacement.
Devuelve la cadena modificada. Si no hay coincidencias que reemplazar, devuelve la cadena original.
Si pattern contiene subcadenas entre paréntesis, replacement puede contener subcadenas de la
forma \\cifra, que serán reemplazadas por el texto que coincide con la subcadena entre paréntesis que
ocupa el lugar indicado por la cifra; \\0 produce el contenido total de la cadena. Se pueden usar hasta
nueve subcadenas. Los paréntesis pueden anidarse; en este caso se cuentan los paréntesis de apertura.
Si no se encuentran coincidencias en string, se devuelve string sin cambios.
Por ejemplo, el siguiente fragmento de código imprime "This was a test" tres veces:

Ejemplo 1. ereg_replace() example

$string = "This is a test";


echo ereg_replace( " is", " was", $string );
echo ereg_replace( "( )is", "\\1was", $string );
echo ereg_replace( "(( )is)", "\\2was", $string );

Ver también ereg(), eregi(), y eregi_replace().

ereg (PHP 3, PHP 4 )


Coincidencia de expresiones regulares

int ereg ( string pattern, string string [, array regs]) \linebreak


Busca en string las coincidencias con la expresión regular pattern.
Si se encuentran coincidencias con subcadenas entre paréntesis de pattern y la función se ha llamado
con el tercer argumento regs, las coincidencias se almacenarán en los elementos de regs. $regs[1]
contendrá la subcadena que empieza en el primer paréntesis izquierdo; $regs[2] la que comienza en el
segundo, etc. $regs[0] contendrá una copia de string.
La búsqueda diferencia mayúsculas y minúsculas.
Devuelve un valor verdadero si se encontró alguna coincidencia, o falso in no se encontraron
coincidencias u ocurrió algún error.
El siguiente fragmento de código toma una fecha en formato ISO (AAAA-MM-DD) y la imprime en
formato DD.MM.AAAA:

1306
Regexps

Ejemplo 1. ereg() example

if ( ereg( "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs ) ) {


echo "$regs[3].$regs[2].$regs[1]";
} else {
echo "Invalid date format: $date";
}

Ver también eregi(), ereg_replace(), y eregi_replace().

eregi_replace (PHP 3, PHP 4 )


reemplaza expresiones regularse sin diferenciar mayúsculas y minúsculas

string eregi_replace ( string pattern, string replacement, string string) \linebreak


Esta función es idéntica a ereg_replace(), excepto en que ignora la distinción entre mayúsculas y
minúsculas.
Ver también ereg(), eregi(), y ereg_replace().

eregi (PHP 3, PHP 4 )


coincidencia de expresiones regulares sin diferenciar mayúsculas y minúsculas

int eregi ( string pattern, string string [, array regs]) \linebreak


Esta función es idéntica a ereg(), excepto en que ignora la distinción entre mayúsculas y minúsculas.
Ver también ereg(), ereg_replace(), y eregi_replace().

split (PHP 3, PHP 4 )


divide la cadena en elementos de un array según una expresión regular

array split ( string pattern, string string [, int limit]) \linebreak


Devuelve un array de cadenas, cada una de las cuales es una subcadena de string formada al dividir
esta en los límites formados por la expresión regular pattern. Si ocurre un error, devuelve un valor
falso.
Para obtener los cinco primeros campos de una línea de /etc/passwd:

1307
Regexps

Ejemplo 1. split() example

$passwd_list = split( ":", $passwd_line, 5 );

Para examinar una fecha que puede estar delimitada por barras, puntos o guiones:

Ejemplo 2. split() example

$date = "04/30/1973"; // Los delimitadores pueden ser barras, puntos o guiones


list( $month, $day, $year ) = split( ’[/.-]’, $date );
echo "Month: $month; Day: $day; Year: $year<br>\n";

Observar que pattern distingue entre mayúsculas y minúsculas.


Observar que si no se necesita la potencia de las expresiones regulares, es más rápido utilizar explode(),
que no carga el motor de expresiones regulares.
Por favor, observar que pattern es una expresión regular. Si se quiere dividir con alguno de los
caracteres especiales de las expresiones regulares, se necesita protegerlo antes. Si pareciera que split() (o
cualquier otra función de regex) está haciendo algo irregular, léase el archivo regex.7, incluido en el
subdirectorio regex de la distribución de PHP. Está en formato de página de manual, por lo que para
leerlo es necesaria una orden como man /usr/local/src/regex/regex.7.
Ver también: explode() e implode().

spliti (PHP 4 >= 4.0.1)


Split string into array by regular expression case insensitive

array spliti ( string pattern, string string [, int limit]) \linebreak


This function is identical to split() except that this ignores case distinction when matching alphabetic
characters.
See also preg_spliti(), split(), explode(), and implode().

sql_regcase (PHP 3, PHP 4 )


construye una expresión regular para buscar coincidencias sin diferenciar mayúsculas y minúsculas

string sql_regcase ( string string) \linebreak


Devuelve una expresión regular válida que coincide con string sin distinguir mayúsculas y
minúsculas. Esta expresión es string con cada carácter convertido a una expresión entre corchetes que

1308
Regexps

contiene el carácter en mayúscula y minúscula, si es posible; en caso contrario, contiene el carácter


original dos veces.

Ejemplo 1. sql_regcase() example

echo sql_regcase( "Foo bar" );

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.

Tabla 1. Limites de la memoria compartida del SO Unix

SHMMAX máximo tamaño de memoria compartida,


normalmente 131072 bytes
SHMMIN minimo tamaño de memoria compartida, por lo
general 1 byte
SHMMNI máxima cantidad de segmentos de memoria
compartida, normalmente 100
SHMSEG máximo de memoria compartida por proceso,
normalmente 6

1310
Semaphore

ftok (PHP 4 >= 4.2.0)


Convert a pathname and a project identifier to a System V IPC key

int ftok ( string pathname, string proj) \linebreak

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

msg_get_queue (PHP 4 CVS only)


Create or attach to a message queue

int msg_get_queue ( int key [, int perms]) \linebreak


msg_get_queue() returns an id that can be used to access the System V message queue with the given
key. The first call creates the message queue with the optional perms (default: 0666). A second call to
msg_get_queue() for the same key will return a different message queue identifier, but both identifiers
access the same underlying message queue. If the message queue already exists, the perms will be
ignored.
See also: msg_remove_queue(), msg_receive(), msg_send(), msg_stat_queue() and msg_set_queue().
This function was introduced in PHP 4.3.0 (not yet released).

msg_receive (PHP 4 CVS only)


Receive a message from a message queue

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

Tabla 1. Flag values for msg_receive

MSG_IPC_NOWAIT If there are no messages of the


desiredmsgtype, return immediately and do not
wait. The function will fail and return an integer
value corresponding to ENOMSG.
MSG_EXCEPT Using this flag in combination with a
desiredmsgtype greater than 0 will cause the
function to receive the first message that is not equal
to desiredmsgtype.
MSG_NOERROR If the message is longer than maxsize, setting this
flag will truncate the message to maxsize and will
not signal an error.

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

msg_remove_queue (PHP 4 CVS only)


Destroy a message queue

bool msg_remove_queue ( int queue) \linebreak


msg_remove_queue() destroys the message queue specified by the queue. Only use this function when
all processes have finished working with the message queue and you need to release the system resources
held by it.

1312
Semaphore

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

msg_send (PHP 4 CVS only)


Send a message to a message queue

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

msg_set_queue (PHP 4 CVS only)


Set information in the message queue data structure

bool msg_set_queue ( int queue, array data) \linebreak


msg_set_queue() allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode
and msg_qbytes fields of the underlying message queue data structure. You specify the values you
require by setting the value of the keys that you require in the data array.
Changing the data structure will require that PHP be running as the same user that created the the queue,
owns the queue (as determined by the existing msg_perm.xxx fields), or be running with root privileges.
root privileges are required to raise the msg_qbytes values above the system defined limit.
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

msg_stat_queue (PHP 4 CVS only)


Returns information from the message queue data structure

array msg_stat_queue ( int queue) \linebreak


msg_stat_queue() returns the message queue meta data for the message queue specified by the queue.
This is useful, for example, to determine which process sent the message that was just received.
The return value is an array whose keys and values have the following meanings:

Tabla 1. Array structure for msg_stat_queue

msg_perm.uid The uid of the owner of the queue.


msg_perm.gid The gid of the owner of the queue.
msg_perm.mode The file access mode of the queue.
msg_stime The time that the last message was sent to the
queue.
msg_rtime The time that the last message was received from
the queue.
msg_ctime The time that the queue was last changed.
msg_qnum The number of messages waiting to be read from
the queue.
msg_qbytes The number of bytes of space currently available in
the queue to hold sent messages until they are
received.
msg_lspid The pid of the process that sent the last message to
the queue.
msg_lrpid The pid of the process that received the last
message from the queue.

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

sem_acquire (PHP 3>= 3.0.6, PHP 4 )


adquiere un semáforo, lo toma para sí

int sem_acquire ( int sem_identifier) \linebreak


Devuelve: Verdadero si hay éxito, falso si hay errores
sem_acquire() Produce un bloqueo (de ser necesario) hasta que el semáforo puede adquirirse. Un
proceso intentando adquirir un semáforo ya adquirido, se bloqueará permanentemente si adquiriendo el

1314
Semaphore

semáforo, excede su valor de max_acquire.


Despues de procesar una petición, cualquier semáforo adquirido por un proceso, que no sea
explícitamente liberado, será liberado automñaticamente, generando un mensaje de alerta.
Véase tambien: sem_get() and sem_release().

sem_get (PHP 3>= 3.0.6, PHP 4 )


obtiene la identificacion de un semáforo (semaphore id)

int sem_get ( int key [, int max_acquire [, int perm]]) \linebreak


Devuelve: Un identificador positivo de semáforo en caso de éxito, o falso en caso de error.
sem_get() Devuelve un id que puede usarse para acceder al semáforo de System V con la llave dada. El
semáforo se usa si es necesario usando los bits de permisos especificados en perm (por defecto 0666). El
número de procesos que pueden adquirir el semáforo simultáneamente, se define en max_acquire (por
defecto es 1). Actualmente este valor se fija sólo si el proceso determina que es el único relacionado
actualmente al semáforo.
Una segunda llamada a sem_get() para la misma llave, devolverá un id de semáforo diferente, pero con
ambos identificadoes, se accederá al mismo semáforo.
Véase también: sem_acquire() y sem_release().

sem_release (PHP 3>= 3.0.6, PHP 4 )


release a semaphore

int sem_release ( int sem_identifier) \linebreak


Returns: TRUE on success, FALSE on error
sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a
warning is generated.
After releasing the semaphore, sem_acquire() may be called to re-acquire it.
Véase tambien: sem_get() y sem_acquire().

sem_remove (PHP 4 >= 4.1.0)


Remove a semaphore

bool sem_remove ( int sem_identifier) \linebreak


Returns: TRUE on success, FALSE on error.

1315
Semaphore

sem_remove() removes the semaphore sem_identifier if it has been created by sem_get(),


otherwise generates a warning.
After removing the semaphore, it is no more accessible.
See also: sem_get(), sem_release() and sem_acquire().

Nota: This function does not work on Windows systems. It was added on PHP 4.1.0.

shm_attach (PHP 3>= 3.0.6, PHP 4 )


Crea o abre un segmento de memoria compartida

int shm_attach ( int key [, int memsize [, int perm]]) \linebreak


shm_attach() devuelve un identificador que puede usarse para acceder a la memoria compartida de
SystemV, con la llave dada, la primera llamada creará el segmento de memoria compartida con
mem_size de tamaño (por defecto: sysvshm.init_mem en el archivo de configuración, o bien de 10000
bytes) y los bits de permiso mas apropiados (por defecto: 0666).
Una segunda llamada a shm_attach() con la misma llave devolvera un id diferente de memoria
compartida, pero ambos identificadores acceden a la misma porción de memoria compartida. memsize
y perm serán ignorados.

shm_detach (PHP 3>= 3.0.6, PHP 4 )


Finaliza conexión con un segmento de memoria compartida

int shm_detach ( int shm_identifier) \linebreak


shm_detach() finaliza la conexión con la memoria compartida, especificada por el identificador
shm_identifier creado con shm_attach(). Hay que recordar que la memoria compartida aún existe
en el sistema Unix, y los datos aún están presentes.

shm_get_var (PHP 3>= 3.0.6, PHP 4 )


Devuelve una variable de la memoria compartida

mixed shm_get_var ( int id, int variable_key) \linebreak


shm_get_var() devuelve la variable con la llave variable_key dada. La variable, queda presente en
la memoria compartida.

1316
Semaphore

shm_put_var (PHP 3>= 3.0.6, PHP 4 )


Inserta o actualiza una variable en la memoria compartida

int shm_put_var ( int shm_identifier, int variable_key, mixed variable) \linebreak


Inserta o actualiza una variable con una llave variable_key. Son válidos todos los tipos de
variable (doble, entera, cadena, arreglo).

shm_remove_var (PHP 3>= 3.0.6, PHP 4 )


Elimina una variable de la memoria compartida

int shm_remove_var ( int id, int variable_key) \linebreak


Elimina la varible que se corresponde con la llave variable_key dada, liberando la memoria que
ocupaba aquella.

shm_remove (PHP 3>= 3.0.6, PHP 4 )


Elimina memoria compartida del sistma Unix

int shm_remove ( int shm_identifier) \linebreak


Elimina la memoria compartida de un sistema Unix, Todos los datos serán destruídos.

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

• the ease of use of Java-, Web- and client/server connectivity,


• the capability to work with an availability of more than 99.99%,
• the ability to manage tens and even hundreds of thousands of users.

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.

Tabla 1. SESAM Configuration 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

php3_sesam_configfile Name of SESAM application configuration file. Re-


quired for using SESAM functions. Example:
php3_sesam_configfile $SESAM.SESAM.CONF.AW
It will usually contain a configuration
like (see SESAM reference manual):
CNF=B
NAM=K
NOTYPE

php3_sesam_messagecatalog Name of SESAM message catalog file. In most cases,


this directive is not neccessary. Only if the SESAM
message file is not installed in the system’s BS2000
message file table, it can be set with this directive. Ex-
ample:
php3_sesam_messagecatalog $.SYSMES.SESAM-
SQL.030

In addition to the configuration of the PHP/SESAM interface, you have to configure the

1318
SESAM

SESAM-Database server itself on your mainframe as usual. That means:

• starting the SESAM database handler (DBH), and


• connecting the databases with the SESAM database handler

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:

Tabla 2. Scrolled Cursor Post-Processing

Scroll Type Action


SESAM_SEEK_NEXT none
SESAM_SEEK_PRIOR none
SESAM_SEEK_FIRST set scroll type to SESAM_SEEK_NEXT
SESAM_SEEK_LAST set scroll type to SESAM_SEEK_PRIOR
SESAM_SEEK_ABSOLUTE Auto-Increment internal offset value
SESAM_SEEK_RELATIVE none. (maintain global default offset value, which
allows for, e.g., fetching each 10th row backwards)

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:

• Vendor specific data types

Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT

1320
SESAM

could be replaced by VARCHAR(max. size)).

• Keywords as SQL identifiers

In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).

• Display length in data types


SESAM data types have a precision, not a display length. Instead of int(4) (intended use:
integers up to ’9999’), SESAM requires simply int for an implied size of 31 bits. Also, the only
datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).

• SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes


Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ...
VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied
auto-increment.

• int ... DEFAULT ’0000’


Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To
initialize variables of the datetime SQL data types, the initialization string must be prefixed with the
respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT
TIMESTAMP ’1970-01-01 00:00:00.000’ NOT NULL );

• $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.

• DROP TABLE thename;


In SESAM, in the DROP TABLE command, the table name must be either followed by the
keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are
dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with
the specified table.

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:

Tabla 3. SQL to PHP Type Conversions

1321
SESAM

SQL Type PHP Type


SMALLINT, INTEGER "integer"
NUMERIC, DECIMAL, FLOAT, REAL, DOUBLE "double"
DATE, TIME, TIMESTAMP "string"
VARCHAR, CHARACTER "string"

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:

Ejemplo 1. Creating a "multiple field" column

CREATE TABLE multi_field_test (


pkey CHAR(20) PRIMARY KEY,
multi(3) CHAR(12)
)

and can be filled in using:

Ejemplo 2. Filling a "multiple field" column

INSERT INTO multi_field_test (pkey, multi(2..3) )


VALUES (’Second’, <’first_val’, ’second_val’>)

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

sesam_affected_rows (PHP 3 CVS only)


Get number of rows affected by an immediate query

int sesam_affected_rows ( string result_id) \linebreak


result_id is a valid result id returned by sesam_query().
Returns the number of rows affected by a query associated with result_id.
The sesam_affected_rows() function can only return useful values when used in combination with
"immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM
does not deliver any "affected rows" information for "select type" queries. The number returned is the
number of affected rows.
See also: sesam_query() and sesam_execimm()

$result = sesam_execimm ("DELETE FROM PHONE WHERE LASTNAME = ’".strtoupper ($name)."’");


if (!$result) {
... error ...
}
print sesam_affected_rows ($result).
" entries with last name ".$name." deleted.\n"

sesam_commit (PHP 3 CVS only)


Commit pending updates to the SESAM database

bool sesam_commit ( void) \linebreak


Returns: TRUE on success, FALSE on errors
sesam_commit() commits any pending updates to the database.
Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss.
Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded
by an implied sesam_rollback() call.

See also: sesam_rollback().

Ejemplo 1. Committing an update to the SESAM database

<?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

sesam_connect (PHP 3 CVS only)


Open SESAM database connection

bool sesam_connect ( string catalog, string schema, string user) \linebreak


Returns TRUE if a connection to the SESAM database was made, or FALSE on error.
sesam_connect() establishes a connection to an SESAM database handler task. The connection is
always "persistant" in the sense that only the very first invocation will actually load the driver from the
configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use
the given catalog, schema, and user.
When creating a database, the "catalog" name is specified in the SESAM configuration directive
//ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME =
catalogname,...)
The "schema" references the desired database schema (see SESAM handbook).
The "user" argument references one of the users which are allowed to access this "catalog" /
"schema" combination. Note that "user" is completely independent from both the system’s user id’s
and from HTTP user/password protection. It appears in the SESAM configuration only.
See also sesam_disconnect().

Ejemplo 1. Connect to a SESAM database

<?php
if (!sesam_connect ("mycatalog", "myschema", "otto")
die("Unable to connect to SESAM";
?>

sesam_diagnostic (PHP 3 CVS only)


Return status information for last SESAM call

array sesam_diagnostic ( void) \linebreak


Returns an associative array of status and return codes for the last SQL query/statement/command.
Elements of the array are:

1324
SESAM

Tabla 1. Status information returned by sesam_diagnostic()

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)

In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by


including the offending SQL statement and pointing to the error location:

Ejemplo 1. Displaying SESAM error messages with error position

<?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";
}

if (!sesam_connect ("mycatalog", "phoneno", "otto"))


die ("cannot connect");

$stmt = "SELECT * FROM phone\n".


" WHERE@ LASTNAME=’KRAEMER’\n".
" ORDER BY FIRSTNAME";
if (!($result = sesam_query ($stmt)))
PrintReturncode ($stmt);
?>

See also: sesam_errormsg() for simple access to the error string only

sesam_disconnect (PHP 3 CVS only)


Detach from SESAM connection

bool sesam_disconnect ( void) \linebreak


Returns: always TRUE.
sesam_disconnect() closes the logical link to a SESAM database (without actually disconnecting and
unloading the driver).

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().

Ejemplo 1. Closing a SESAM connection

if (sesam_connect ("mycatalog", "myschema", "otto")) {


... some queries and stuff ...
sesam_disconnect();
}

sesam_errormsg (PHP 3 CVS only)


Returns error message of last SESAM call

string sesam_errormsg ( void) \linebreak


Returns the SESAM error message associated with the most recent SESAM error.

if (!sesam_execimm ($stmt))
printf ("%s<br>\n", sesam_errormsg());

See also: sesam_diagnostic() for the full set of SESAM SQL status information

sesam_execimm (PHP 3 CVS only)


Execute an "immediate" SQL-statement

string sesam_execimm ( string query) \linebreak


Returns: A SESAM "result identifier" on success, or FALSE on error.
sesam_execimm() executes an "immediate" statement (i.e., a statement like UPDATE, INSERT or
DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can
not be used with sesam_execimm(). Sets the affected_rows value for retrieval by the
sesam_affected_rows() function.

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.

$stmt = "INSERT INTO mytable VALUES (’one’, ’two’)";


$result = sesam_execimm ($stmt);
$err = sesam_diagnostic();
print ("sqlstate = ".$err["sqlstate"]."\n".
"Affected rows = ".$err["rowcount"]." == ".
sesam_affected_rows($result)."\n");

See also: sesam_query() and sesam_affected_rows().

sesam_fetch_array (PHP 3 CVS only)


Fetch one row as an associative array

array sesam_fetch_array ( string result_id [, int whence [, int offset]]) \linebreak


Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the
numeric indices of the result array, it stores the data in associative indices, using the field names as keys.
result_id is a valid result id returned by sesam_query() (select type queries only!).
For the valid values of the optional whenceand offset parameters, see the sesam_fetch_row()
function for details.
sesam_fetch_array() fetches one row of data from the result associated with the specified result
identifier. The row is returned as an associative array. Each result column is stored with an associative
index equal to its column (aka. field) name. The column names are converted to lower case.
Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in
the array. Also, if two or more columns of the result have the same column names, the later column will
take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.

SELECT TBL1.COL AS FOO, TBL2.COL AS BAR FROM TBL1, TBL2

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

CREATE TABLE ... ( ... MULTI(3) INT )

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.

Ejemplo 1. SESAM fetch array

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

See also: sesam_fetch_row() which returns an indexed array.

sesam_fetch_result (PHP 3 CVS only)


Return all or part of a query result

mixed sesam_fetch_result ( string result_id [, int max_rows]) \linebreak


Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows
rows. Note that both row and column indexes are zero-based.

Tabla 1. Mixed result set returned by sesam_fetch_result()

Array Element Contents


int $arr["count"] number of columns in result set (or zero if this was
an "immediate" query)

1329
SESAM

Array Element Contents


int $arr["rows"] number of rows in result set (between zero and
max_rows)
bool $arr["truncated"] TRUE if the number of rows was at least
max_rows, FALSE otherwise. Note that even when
this is TRUE, the next sesam_fetch_result() call
may return zero rows because there are no more
result entries.
mixed $arr[col][row] result data for all the fields at row(row) and
column(col), (where the integer index row is
between 0 and $arr["rows"]-1, and col is
between 0 and $arr["count"]-1). Fields may be
empty, so you must check for the existence of a field
by using the php isset() function. The type of the
returned fields depend on the respective SQL type
declared for its column (see SESAM overview for
the conversions applied). SESAM "multiple fields"
are "inlined" and treated like a sequence of columns.

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().

sesam_fetch_row (PHP 3 CVS only)


Fetch one row as an array

array sesam_fetch_row ( string result_id [, int whence [, int offset]]) \linebreak


Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
The number of columns in the result set is returned in an associative array element $array["count"].
Because some of the result columns may be empty, the count() function can not be used on the result row
returned by sesam_fetch_row().
result_id is a valid result id returned by sesam_query() (select type queries only!).
whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the
following predefined constants:

Tabla 1. Valid values for "whence" parameter

Value Constant Meaning

1330
SESAM

Value Constant Meaning


0 SESAM_SEEK_NEXT read sequentially (after fetch, the
internal default is set to
SESAM_SEEK_NEXT)
1 SESAM_SEEK_PRIOR read sequentially backwards (after
fetch, the internal default is set to
SESAM_SEEK_PRIOR)
2 SESAM_SEEK_FIRST rewind to first row (after fetch, the
default is set to
SESAM_SEEK_NEXT)
3 SESAM_SEEK_LAST seek to last row (after fetch, the
default is set to
SESAM_SEEK_PRIOR)
4 SESAM_SEEK_ABSOLUTE seek to absolute row number
given as offset (Zero-based.
After fetch, the internal default is
set to SESAM_SEEK_ABSOLUTE,
and the internal offset value is
auto-incremented)
5 SESAM_SEEK_RELATIVE seek relative to current scroll
position, where offset can be a
positive or negative offset value.

This parameter is only valid for "scrollable" cursors.


When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence
parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT,
and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.
offset is an optional parameter which is only evaluated (and required) if whence is either
SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable"
cursors.
sesam_fetch_row() fetches one row of data from the result associated with the specified result identifier.
The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be
empty, so you must check for the existence of a field by using the php isset() function. The type of the
returned fields depend on the respective SQL type declared for its column (see SESAM overview for the
conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.
Subsequent calls to sesam_fetch_row() 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.

Ejemplo 1. SESAM fetch rows

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

sesam_field_array (PHP 3 CVS only)


Return meta information about individual columns in a result

array sesam_field_array ( string result_id) \linebreak


result_id is a valid result id returned by sesam_query().
Returns a mixed associative/indexed array with meta information (column name, type, precision, ...)
about individual columns of the result after the query associated with result_id.

Tabla 1. Mixed result set returned by sesam_field_array()

Array Element Contents


int $arr["count"] Total number of columns in result set (or zero if this
was an "immediate" query). SESAM "multiple
fields" are "inlined" and treated like the respective
number of columns.
string $arr[col]["name"] column name for column(col), where col is
between 0 and $arr["count"]-1. The returned
value can be the empty string (for dynamically
computed columns). SESAM "multiple fields" are
"inlined" and treated like the respective number of
columns, each with the same column name.

1332
SESAM

Array Element Contents


string $arr[col]["count"] The "count" attribute describes the repetition factor
when the column has been declared as a "multiple
field". Usually, the "count" attribute is 1. The first
column of a "multiple field" column however
contains the number of repetitions (the second and
following column of the "multiple field" contain a
"count" attribute of 1). This can be used to detect
"multiple fields" in the result set. See the example
shown in the sesam_query() description for a
sample use of the "count" attribute.
string $arr[col]["type"] php variable type of the data for column(col),
where col is between 0 and $arr["count"]-1.
The returned value can be one of • "integer"
• "double"

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

Array Element Contents


string $arr[col]["sqltype"] SQL variable type of the column data for
column(col), where col is between 0 and
$arr["count"]-1. The returned value can be one
of • "CHARACTER"
• "VARCHAR"

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

Array Element Contents


string $arr[col]["scale"] The "scale" attribute of the SQL variable in
column(col), where col is between 0 and
$arr["count"]-1. The "scale" attribute is used
with numeric data types. SESAM "multiple fields"
are "inlined" and treated like the respective number
of columns, each with the same scale attribute.

See the sesam_query() function for an example of the sesam_field_array() use.

sesam_field_name (PHP 3 CVS only)


Return one column name of the result set

int sesam_field_name ( string result_id, int index) \linebreak


Returns the name of a field (i.e., the column name) in the result set, or FALSE on error.
For "immediate" queries, or for dynamic columns, an empty string is returned.

Nota: The column index is zero-based, not one-based as in 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".

sesam_free_result (PHP 3 CVS only)


Releases resources for the query

int sesam_free_result ( string result_id) \linebreak


Releases resources for the query associated with result_id. Returns FALSE on error.

sesam_num_fields (PHP 3 CVS only)


Return the number of fields/columns in a result set

int sesam_num_fields ( string result_id) \linebreak

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.

sesam_query (PHP 3 CVS only)


Perform a SESAM SQL query and prepare the result

string sesam_query ( string query [, bool scrollable]) \linebreak


Returns: A SESAM "result identifier" on success, or FALSE on error.
A "result_id" resource is used by other functions to retrieve the query results.
sesam_query() sends a query to the currently active database on the server. It can execute both
"immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no
cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an
empty result (zero columns, indicating end-of-result). For "select type" statements, a result descriptor
and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will
be allocated. If scrollable is omitted, the cursor will be 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().
For "immediate" statements, the number of affected rows is saved for retrieval by the
sesam_affected_rows() function.
See also: sesam_fetch_row() and sesam_fetch_result().

Ejemplo 1. Show all rows of the "phone" table as a html table

<?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

for ($col = 0; $col < $cols["count"]; ++$col) {


$colattr = $cols[$col];
/* Span the table head over SESAM’s "Multiple Fields": */
if ($colattr["count"] > 1) {
echo " <TH COLSPAN=".$colattr["count"].">".$colattr["name"].
"(1..".$colattr["count"].")</TH>\n";
$col += $colattr["count"] - 1;
} else
echo " <TH>" . $colattr["name"] . "</TH>\n";
}
echo " </TR>\n";
}

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

sesam_rollback (PHP 3 CVS only)


Discard any pending updates to the SESAM database

bool sesam_rollback ( void) \linebreak


Returns: TRUE on success, FALSE on errors
sesam_rollback() discards any pending updates to the database. Also affected are result cursors and
result descriptors.
At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is
executed, discarding any pending changes to the database.

1337
SESAM

See also: sesam_commit().

Ejemplo 1. Discarding an update to the SESAM database

<?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();
}
?>

sesam_seek_row (PHP 3 CVS only)


Set scrollable cursor mode for subsequent fetches

bool sesam_seek_row ( string result_id, int whence [, int offset]) \linebreak


result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested
when calling sesam_query()).
whence sets the global default value for the scrolling type, it specifies the scroll type to use in
subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined
constants:

Tabla 1. Valid values for "whence" parameter

Value Constant Meaning


0 SESAM_SEEK_NEXT read sequentially
1 SESAM_SEEK_PRIOR read sequentially backwards
2 SESAM_SEEK_FIRST fetch first row (after fetch, the
default is set to
SESAM_SEEK_NEXT)
3 SESAM_SEEK_LAST fetch last row (after fetch, the
default is set to
SESAM_SEEK_PRIOR)
4 SESAM_SEEK_ABSOLUTE fetch absolute row number given
as offset (Zero-based. After
fetch, the default is set to
SESAM_SEEK_ABSOLUTE, and the
offset value is auto-incremented)

1338
SESAM

Value Constant Meaning


5 SESAM_SEEK_RELATIVE fetch relative to current scroll
position, where offset can be a
positive or negative offset value
(this also sets the default "offset"
value for subsequent fetches).

offset is an optional parameter which is only evaluated (and required) if whence is either
SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.

sesam_settransaction (PHP 3 CVS only)


Set SESAM transaction parameters

bool sesam_settransaction ( int isolation_level, int read_only) \linebreak


Returns: TRUE if the values are valid, and the settransaction() operation was successful, FALSE
otherwise.
sesam_settransaction() overrides the default values for the "isolation level" and "read-only" transaction
parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and
guarantee database consistency. The overridden values are used for the next transaction only.
sesam_settransaction() can only be called before starting a transaction, not after the transaction has
been started already.
To simplify the use in php scripts, the following constants have been predefined in php (see SESAM
handbook for detailed explanation of the semantics):

Tabla 1. Valid values for "Isolation_Level" parameter

Value Constant Meaning


1 Read Uncommitted
SESAM_TXISOL_READ_UNCOMMITTED

2 Read Committed
SESAM_TXISOL_READ_COMMITTED

3 Repeatable Read
SESAM_TXISOL_REPEATABLE_READ

4 SESAM_TXISOL_SERIALIZABLE Serializable

Tabla 2. Valid values for "Read_Only" parameter

Value Constant Meaning


0 SESAM_TXREAD_READWRITE Read/Write
1 SESAM_TXREAD_READONLY Read-Only

1339
SESAM

The values set by sesam_settransaction() will override the default setting specified in the SESAM
configuration file.

Ejemplo 1. Setting SESAM transaction parameters

<?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.0.3, track_vars siempre está activado.

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.

Ejemplo 1. Registrar una variable con track_vars activado

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

Ejemplo 2. Registrar una variable con $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS con PHP 4.0.6 o inferior
if (!isset($_SESSION[’count’])) {
$_SESSION[’count’] = 0;
} else {
$_SESSION[’count’]++;
}
?>

Ejemplo 3. Borrar una variable con $_SESSION.

<?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

$HTTP_SESSION_VARS/$_SESSION no es necesario usar session_register().

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.

Ejemplo 4. Registrar una variable con register_globals activado

<?php
if (!session_is_registered(’count’)) {
session_register("count");
$count = 0;
}
else {
$count++;
}
?>

Si track_vars y register_globals están activados, las variables globales y las entradas de


$HTTP_SESSION_VARS/$_SESSION harán referencia al mismo valor para variables ya registradas.
Si el usuario utiliza session_register() para registrar una variable, el vector
$HTTP_SESSION_VARS/$_SESSION no contendrá esa variable hasta que se cargue de los datos de la
sesión. (p.ej. hasta la próxima petición).
Hay dos formas de propagar un "session id":

• 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

definida, si el cliente no envía la cookie adecuada. El SID puede tener la forma de


nombre_de_sesion=session_id o ser una cadena vacía.

El ejemplo siguiente demuestra cómo registrar una variable, y cómo colocar correctamente un enlace a
otra página usando la constante SID.

Ejemplo 5. Contar el número de impresiones de un usuario

<?php
if (!session_is_registered(’count’)) {
session_register(’count’);
$count = 1;
}
else {
$count++;
}
?>

Hola, visitante. Has visto esta p&aacute;gina <?php echo $count; ?> veces.

<?php
# el <?php echo SID?> (Se puede usar <?=SID?> si short tag est&aacute; activado)
# es necesario para conservar el session id
# en caso de que el usuario haya desactivado las cookies
?>

Para continuar, haga click <A HREF="nextpage.php?<?php echo SID?>">aqu&iacute;</A>.

El <?=SID?> no es necesario si se ha usado --enable-trans-sid al compilar PHP.

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

Si la profundidad de la ruta de session.save_path es mayor que 2, no se llevará a cabo la


recolección de basura.

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

• session.cookie_domain especifica el dominio a establecer en session_cookie. Por defecto no se


especifica ninguno en ningún caso.
• session.cache_limiter especifica el método de control del caché a usar en las páginas de la
sesión (none/nocache/private/private_no_expire/public). Por defecto es nocache (no guardar las

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

Nota: El manejo de sesiones fue añadido en PHP 4.0.

1346
Sesiones

session_cache_expire (PHP 4 >= 4.2.0)


Devuelve la caducidad actual del caché

int session_cache_expire ( [int nueva_caducidad_cache]) \linebreak


session_cache_expire() devuelve la caducidad actual del caché. Si se proporciona
nueva_caducidad_cache, se reemplazará la caducidad actual con nueva_caducidad_cache.

session_cache_limiter (PHP 4 >= 4.0.3)


Lee y/o cambia el limitador del caché actual

string session_cache_limiter ( [string limitador_del_cache]) \linebreak


session_cache_limiter() devuelve el nombre del limitador de caché actual. Si se especifica
limitador_del_cache, el nombre del limitador de caché actual se cambia al nuevo valor.
El limitador de caché controla las cabeceras HTTP de control del caché enviadas al cliente. Estas
cabeceras determinan las reglas por las que el contenido de la página puede ser guardado en el caché
local del cliente. Cambiando el limitador de caché a nocache, por ejemplo, impedirá cualquier tipo de
almacenamiento en el caché por parte del cliente. Un valor de public, en cambio, permitiría el
almacenamiento en el caché. Tambié se puede cambiar a private, que es un poco más restrictivo que el
public.

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.

Nota: private_no_expire fue añadida en PHP 4.2.0dev.

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()).

Ejemplo 1. Ejemplos con session_cache_limiter()

<?php

# cambia el limitador del cach&eacute; a ’private’

session_cache_limiter(’private’);
$cache_limiter = session_cache_limiter();

echo "El limitador de cach&eacute; est&aacute; puesto ahora en $cache_limiter<p>";


?>

1347
Sesiones

session_decode (PHP 4 )
Decodifica los datos de una sesión a partir de una cadena

bool session_decode ( string datos) \linebreak


session_decode() decodifica los datos de una sesión que se encuentran en datos, creando las variables
guardadas en la sesión.

session_destroy (PHP 4 )
Destruye todos los datos guardados en una sesión

bool session_destroy ( void) \linebreak


session_destroy() destruye todos los datos asociados con la sesión actual. No destruye ninguna de las
variables globales asociadas a la sesión ni la cookie.
Esta función devuelve TRUE si se ha destruido la sesión correctamente y FALSE si ha habido algún
problema al intentarlo.

Ejemplo 1. Destrucción de una sesión

<?php

// Inicializa de la sesi&oacute;n.
// Si est&aacute; usando session_name("algo"), &iexcl;no lo olvide ahora!
session_start();
// Destruye todas las variables de la sesi&oacute;n
session_unset();
// Finalmente, destruye la sesi&oacute;n
session_destroy();

?>

1348
Sesiones

Ejemplo 2. Destrucción de una sesión con $_SESSION

<?php

// Inicializa la sesi&oacute;n.
// Si est&aacute; usando session_name("algo"), &iexcl;no lo olvide ahora!
session_start();
// Destruye todas las variables de la sesi&oacute;n
$_SESSION = array();
// Finalmente, destruye la sesi&oacute;n
session_destroy();

?>

session_encode (PHP 4 )
Codifica los datos de la sesión actual en una cadena

string session_encode ( void) \linebreak


session_encode() devuelve una cadena con el contenido de la sesión actual en su interior.

session_get_cookie_params (PHP 4 )
Obtiene los parámetros de la cookie de la sesión

array session_get_cookie_params ( void) \linebreak


La función session_get_cookie_params() devuelve un vector con información sobre la cookie de la
sesión actual, conteniendo los siguientes elementos:
• "lifetime" - La duración de la cookie.
• "path" - La ruta donde se guarda la información.
• "domain" - El dominio de la cookie.
• "secure" - La cookie debe ser enviada sólo bajo conexiones seguras. (Este elemento fue añadido en
PHP 4.0.4.)

1349
Sesiones

session_id (PHP 4 )
Lee y/o cambia el session id actual

string session_id ( [string id]) \linebreak


session_id() devuelve el session id de la sesión actual. Si se especifica un id, reemplazará el session id
actual.
También se puede utilizar la constante SID para recuperar el nombre y el session id de la sesión actual
como una cadena adecuada para añadir a las URLs.

session_is_registered (PHP 4 )
Comprueba si una variable está registrada en la sesión

bool session_is_registered ( string nombre) \linebreak


session_is_registered() devuelve TRUE si hay una variable registrada en la sesión actual cuyo nombre es
nombre.

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

string session_module_name ( [string módulo]) \linebreak


session_module_name() devuelve el nombre del módulo de la sesión actual. Si se especifica módulo,
se usará ese módulo en su lugar.

session_name (PHP 4 )
Lee y/o cambia el nombre de la sesión actual

1350
Sesiones

string session_name ( [string nombre]) \linebreak


session_name() devuelve el nombre de la sesión actual. Si se especifica un nombre, el nombre de de la
sesión actual se cambia a este valor.
El nombre de la sesión hace referencia al session id utilizado en las cookies y en las URLs. Debería
contener únicamente caracteres alfanuméricos; también debería ser corto y descriptivo (p.ej. para
usuarios con los avisos de las cookies activados). El nombre de la sesión se restaura al valor guardado
por defecto en session.name al comenzar la petición. Así, pues, es necesario llamar a session_name()
en cada petición (y antes de llamar a session_start() o a session_register()).

Ejemplo 1. Ejemplos de session_name()

<?php

// Cambiar el nombre de la sesi&oacute;n a WebsiteID

$nombre_anterior = session_name("WebsiteID");

echo "El anterior nombre de la sesi&oacute;n era $nombre_anterior<p>";


?>

session_readonly (unknown)
Inicia una sesión - reinicializa las variables, pero sin guardar los cambios al terminar

void session_readonly ( void) \linebreak


Lee los datos de una sesión sin bloquearlos. No es posible cambiar los datos de la sesión, pero el
rendimiento de los framesets mejorará.

session_register (PHP 4 )
Register one or more variables with the current session

bool session_register ( mixed name [, mixed ...]) \linebreak


session_register() accepts a variable number of arguments, any of which can be either a string holding
the name of a variable or an array consisting of variable names or other arrays. For each name,
session_register() registers the global variable with that name in 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.

$barney = "A big purple dinosaur.";


session_register("barney");

$_SESSION["zim"] = "An invader from another planet.";

# The old way was to use $HTTP_SESSION_VARS


$HTTP_SESSION_VARS["spongebob"] = "He’s got square pants.";

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

See also session_is_registered() and session_unregister().

session_save_path (PHP 4 )
Lee y/o cambia la ruta donde se guardan los datos de la sesión actual

1352
Sesiones

string session_save_path ( [string path]) \linebreak


session_save_path() devuelve la ruta del directorio usado actualmente para guardar los datos de la
sesión. Si se especifica path, se cambiará la ruta donde se guardan los datos.

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.

Nota: El parámetro segura fue añadido en PHP 4.0.4.

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: Debe cambiar la opción session.save_handler en la configuración a user en su archivo


php.ini para que session_set_save_handler() tenga efecto.

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.

Ejemplo 1. Ejemplo de session_set_save_handler()

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

function leer ($id) {


global $sess_save_path, $sess_session_name;

$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&iacute;.
}

function escribir ($id, $sess_data) {


global $sess_save_path, $sess_session_name;

$sess_file = "$sess_save_path/sess_$id";
if ($fp = @fopen($sess_file, "w")) {
return(fwrite($fp, $sess_data));
} else {
return(false);
}

1354
Sesiones

function destruir ($id) {


global $sess_save_path, $sess_session_name;

$sess_file = "$sess_save_path/sess_$id";
return(@unlink($sess_file));
}

/***********************************************
* ATENCI&Oacute;N - Necesitar&aacute; implementar alg&uacute;n *
* tipo de rutinas recolectoras de basura aqu&iacute; *
***********************************************/
function rb ($maxlifetime) {
return true;
}

session_set_save_handler ("abrir", "cerrar", "leer", "escribir", "destruir", "rb");

session_start();

// proceed to use sessions normally

?>

session_start (PHP 4 )
Inicializar los datos de una sesión

bool session_start ( void) \linebreak


session_start() crea una sesió (o la continúa basandose en el session id pasado por GET o mediante una
cookie).
Si desea usar una sesión con un nombre en concreto, debe llamar a session_name() antes de llamar a
session_start().
Esta función siempre devuelve TRUE.

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.

Nota: Se recomienda utilizar zlib.output_compression en lugar de ob_gzhandler

session_unregister (PHP 4 )
Desregistrar una variable de la sesión actual

bool session_unregister ( string nombre) \linebreak


session_unregister() desregistra (olvida) la variable global llamada nombre de la sesión actual.
Esta función devuelve TRUE cuando la variable es eliminada de la sesión correctamente.

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

void session_unset ( void) \linebreak


La función session_unset() elimina y libera el espacio ocupado por todas las variables de la sesión actual
registradas.

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

session_write_close (PHP 4 >= 4.0.4)


Escribe los datos de la sesión y la finaliza

void session_write_close ( void) \linebreak


Finaliza la sesión actual y guarda sus datos
Los datos de la sesió se suelen guardar tras finalizar la ejecución de su script sin necesidad de llamar a
session_write_close(), pero como los datos de la sesió están bloqueados para evitar escrituras
concurrentes, sólo un script puede trabajar con una sesión a la vez. Cuando se usan framesets junto con
sesiones, podrá comprobar que los frames se cargan uno a uno debido a este bloqueo. Puede reducir el
tiempo necesario para cargar los frames finalizando la sesión tan pronto como haya terminado los
cambios a las variables de la sesión.

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_().

Ejemplo 1. Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id if 0xff3


$shm_id = shmop_open(0xff3, "c", 0644, 100);
if(!$shm_id) {
echo "Couldn’t create shared memory segment\n";
}

// Get shared memory block’s size


$shm_size = shmop_size($shm_id);
echo "SHM Block Size: ".$shm_size. " has been created.\n";

// Lets write a test string into shared memory


$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if($shm_bytes_written != strlen("my shared memory block")) {
echo "Couldn’t write the entire length of data\n";
}

// Now lets read the string back


$my_string = shmop_read($shm_id, 0, $shm_size);
if(!$my_string) {
echo "Couldn’t read from shared memory block\n";
}
echo "The data inside shared memory was: ".$my_string."\n";

//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

shmop_close (PHP 4 >= 4.0.4)


Close shared memory block

int shmop_close ( int shmid) \linebreak


shmop_close() is used to close a shared memory block.
shmop_close() takes the shmid, which is the shared memory block identifier created by shmop_open().

Ejemplo 1. Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

shmop_delete (PHP 4 >= 4.0.4)


Delete shared memory block

int shmop_delete ( int shmid) \linebreak


shmop_delete() is used to delete a shared memory block.
shmop_delete() takes the shmid, which is the shared memory block identifier created by shmop_open().
On success 1 is returned, on failure 0 is returned.

Ejemplo 1. Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

shmop_open (PHP 4 >= 4.0.4)


Create or open shared memory block

int shmop_open ( int key, string flags, int mode, int size) \linebreak

1359
shmop

shmop_open() can create or open a shared memory block.


shmop_open() takes 4 parameters: key, which is the system’s id for the shared memory block, this
parameter can be passed as a decimal or hex. The second parameter are the flags that you can use:

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

Ejemplo 1. Create a new shared memory block

<?php
$shm_id = shmop_open(0x0fff, "c", 0644, 100);
?>

This example opened a shared memory block with a system id of 0x0fff.

shmop_read (PHP 4 >= 4.0.4)


Read data from shared memory block

string shmop_read ( int shmid, int start, int count) \linebreak


shmop_read() will read a string from shared memory block.
shmop_read() takes 3 parameters: shmid, which is the shared memory block identifier created by
shmop_open(), offset from which to start reading and count on the number of bytes to read.

Ejemplo 1. Reading shared memory block

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

shmop_size (PHP 4 >= 4.0.4)


Get size of shared memory block

int shmop_size ( int shmid) \linebreak


shmop_size() is used to get the size, in bytes of the shared memory block.
shmop_size() takes the shmid, which is the shared memory block identifier created by shmop_open(),
the function will return and int, which represents the number of bytes the shared memory block occupies.

Ejemplo 1. Getting the size of the shared memory block

<?php
$shm_size = shmop_size($shm_id);
?>

This example will put the size of shared memory block identified by $shm_id into $shm_size.

shmop_write (PHP 4 >= 4.0.4)


Write data into shared memory block

int shmop_write ( int shmid, string data, int offset) \linebreak


shmop_write() will write a string into shared memory block.
shmop_write() takes 3 parameters: shmid, which is the shared memory block identifier created by
shmop_open(), data, a string that you want to write into shared memory block and offset, which
specifies where to start writing data inside the shared memory segment.

Ejemplo 1. Writing to shared memory block

<?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:

Ejemplo 1. SWF example

<?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_definefont (10, "Mod");


swf_fontsize (5);
swf_fontslant (10);
swf_definetext (11, "This be Flash wit PHP!", 1);

swf_pushmatrix ();
swf_translate (-50, 80, 0);
swf_placeobject (11, 60);
swf_popmatrix ();

for ($i = 0; $i < 30; $i++) {


$p = $i/(30-1);
swf_pushmatrix ();
swf_scale (1-($p*.9), 1, 1);
swf_rotate (60*$p, ’z’);
swf_translate (20+20*$p, $p/1.5, 0);
swf_rotate (270*$p, ’z’);
swf_addcolor ($p, 0, $p/1.2, -$p);
swf_placeobject (1, 50);
swf_placeobject (4, 50);
swf_placeobject (5, 50);
swf_popmatrix ();
swf_showframe ();
}

for ($i = 0; $i < 30; $i++) {


swf_removeobject (50);
if (($i%4) == 0) {
swf_showframe ();
}

1363
SWF

swf_startdoaction ();
swf_actionstop ();
swf_enddoaction ();

swf_closefile ();
?>

It will produce the animation found at the following url


(http://www.designmultimedia.com/swfphp/test.swf).

Nota: SWF support was added in PHP4 RC2.

1364
SWF

swf_actiongeturl (PHP 4 )
Get a URL from a Shockwave Flash movie

void swf_actiongeturl ( string url, string target) \linebreak


The swf_actionGetUrl() function gets the URL specified by the parameter url with the target
target.

swf_actiongotoframe (PHP 4 )
Play a frame and then stop

void swf_actiongotoframe ( int framenumber) \linebreak


The swf_actionGotoFrame() function will go to the frame specified by framenumber, play it, and
then stop.

swf_actiongotolabel (PHP 4 )
Display a frame with the specified label

void swf_actiongotolabel ( string label) \linebreak


The swf_actionGotoLabel() function displays the frame with the label given by the label parameter
and then stops.

swf_actionnextframe (PHP 4 )
Go foward one frame

void swf_actionnextframe ( void) \linebreak


Go foward one frame.

swf_actionplay (PHP 4 )
Start playing the flash movie from the current frame

void swf_actionplay ( void) \linebreak


Start playing the flash movie from the current frame.

1365
SWF

swf_actionprevframe (PHP 4 )
Go backwards one frame

void swf_actionprevframe ( void) \linebreak

swf_actionsettarget (PHP 4 )
Set the context for actions

void swf_actionsettarget ( string target) \linebreak


The swf_actionSetTarget() function sets the context for all actions. You can use this to control other
flash movies that are currently playing.

swf_actionstop (PHP 4 )
Stop playing the flash movie at the current frame

void swf_actionstop ( void) \linebreak


Stop playing the flash movie at the current frame.

swf_actiontogglequality (PHP 4 )
Toggle between low and high quality

void swf_actiontogglequality ( void) \linebreak


Toggle the flash movie between high and low quality.

swf_actionwaitforframe (PHP 4 )
Skip actions if a frame has not been loaded

void swf_actionwaitforframe ( int framenumber, int skipcount) \linebreak


The swf_actionWaitForFrame() function will check to see if the frame, specified by the
framenumber parameter has been loaded, if not it will skip the number of actions specified by the
skipcount parameter. This can be useful for "Loading..." type animations.

1366
SWF

swf_addbuttonrecord (PHP 4 )
Controls location, appearance and active area of the current button

void swf_addbuttonrecord ( int states, int shapeid, int depth) \linebreak


The swf_addbuttonrecord() function allows you to define the specifics of using a button. The first
parameter, states, defines what states the button can have, these can be any or all of the following
constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of
the button, this is usually the object id of the shape of the button. The depth parameter is the placement
of the button in the current frame.

Ejemplo 1. swf_addbuttonrecord() function example

swf_startButton ($objid, TYPE_MENUBUTTON);


swf_addButtonRecord (BSDown|BSOver, $buttonImageId, 340);
swf_onCondition (MenuEnter);
swf_actionGetUrl ("http://www.designmultimedia.com", "_level1");
swf_onCondition (MenuExit);
swf_actionGetUrl ("", "_level1");
swf_endButton ();

swf_addcolor (PHP 4 )
Set the global add color to the rgba value specified

void swf_addcolor ( float r, float g, float b, float a) \linebreak


The swf_addcolor() function sets the global add color to the rgba color specified. This color is then
used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions.
The color of the object will be add by the rgba values when the object is written to the screen.

Nota: The rgba values can be either positive or negative.

swf_closefile (PHP 4 )
Close the current Shockwave Flash file

void swf_closefile ( void) \linebreak


Close a file that was opened by the swf_openfile() function.

1367
SWF

swf_definebitmap (PHP 4 )
Define a bitmap

void swf_definebitmap ( int objid, string image_name) \linebreak


The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will
be converted into a Flash JPEG or Flash color map format.

swf_definefont (PHP 4 )
Defines a font

void swf_definefont ( int fontid, string fontname) \linebreak


The swf_definefont() function defines a font given by the fontname parameter and gives it the id
specified by the fontid parameter. It then sets the font given by fontname to the current 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

void swf_definetext ( int objid, string str, int docenter) \linebreak


Define a text string (the str parameter) using the current font and font size. The docenter is where
the word is centered, if docenter is 1, then the word is centered in x.

swf_endbutton (PHP 4 )
End the definition of the current button

void swf_endbutton ( void) \linebreak


The swf_endButton() function ends the definition of the current button.

swf_enddoaction (PHP 4 )
End the current action

void swf_enddoaction ( void) \linebreak


Ends the current action started by the swf_startdoaction() function.

swf_endshape (PHP 4 )
Completes the definition of the current shape

void swf_endshape ( void) \linebreak


The swf_endshape() completes the definition of the current shape.

1369
SWF

swf_endsymbol (PHP 4 )
End the definition of a symbol

void swf_endsymbol ( void) \linebreak


The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol()
function.

swf_fontsize (PHP 4 )
Change the font size

void swf_fontsize ( float size) \linebreak


The swf_fontsize() function changes the font size to the value given by the size parameter.

swf_fontslant (PHP 4 )
Set the font slant

void swf_fontslant ( float slant) \linebreak


Set the current font slant to the angle indicated by the slant parameter. Positive values create a foward
slant, negative values create a negative slant.

swf_fonttracking (PHP 4 )
Set the current font tracking

void swf_fonttracking ( float tracking) \linebreak


Set the font tracking to the value specified by the tracking parameter. This function is used to
increase the spacing between letters and text, positive values increase the space and negative values
decrease the space between letters.

swf_getbitmapinfo (PHP 4 )
Get information about a bitmap

array swf_getbitmapinfo ( int bitmapid) \linebreak

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

array swf_getfontinfo ( void) \linebreak


The swf_getfontinfo() function returns an associative array with the following parameters:
• Aheight - The height in pixels of a capital A.
• xheight - The height in pixels of a lowercase x.

swf_getframe (PHP 4 )
Get the frame number of the current frame

int swf_getframe ( void) \linebreak


The swf_getframe() function gets the number of the current frame.

swf_labelframe (PHP 4 )
Label the current frame

void swf_labelframe ( string name) \linebreak


Label the current frame with the name given by the name parameter.

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

void swf_modifyobject ( int depth, int how) \linebreak


Updates the position and/or color of the object at the specified depth, depth. The parameter how
determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can
be a combination of both (MOD_MATRIX|MOD_COLOR).
MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor
(specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to
position the object.

swf_mulcolor (PHP 4 )
Sets the global multiply color to the rgba value specified

void swf_mulcolor ( float r, float g, float b, float a) \linebreak


The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is
then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord()
functions. The color of the object will be multiplied by the rgba values when the object is written to the
screen.

Nota: The rgba values can be either positive or negative.

swf_nextid (PHP 4 )
Returns the next free object id

int swf_nextid ( void) \linebreak


The swf_nextid() function returns the next available object id.

1372
SWF

swf_oncondition (PHP 4 )
Describe a transition used to trigger an action list

void swf_oncondition ( int transition) \linebreak


The swf_onCondition() function describes a transition that will trigger an action list. There are several
types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:
• IdletoOverUp
• OverUptoIdle
• OverUptoOverDown
• OverDowntoOverUp
• IdletoOverDown
• OutDowntoIdle
• MenuEnter (IdletoOverUp|IdletoOverDown)
• MenuExit (OverUptoIdle|OverDowntoIdle)
For TYPE_PUSHBUTTON there are the following options:

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

swf_ortho (PHP 4 >= 4.0.1)


Defines an orthographic mapping of user coordinates onto the current viewport

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

void swf_placeobject ( int objid, int depth) \linebreak


Places the object specified by objid in the current frame at a depth of depth. The objid parameter
and the depth must be between 1 and 65535.
This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by
swf_addcolor()) to color the object and it uses the current matrix to position the object.

Nota: Full RGBA colors are supported.

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

void swf_popmatrix ( void) \linebreak


The swf_popmatrix() function pushes the current transformation matrix back onto the stack.

swf_posround (PHP 4 )
Enables or Disables the rounding of the translation when objects are placed or moved

void swf_posround ( int round) \linebreak


The swf_posround() function enables or disables the rounding of the translation when objects are placed
or moved, there are times when text becomes more readable because rounding has been enabled. The
round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0
then rounding is disabled.

1375
SWF

swf_pushmatrix (PHP 4 )
Push the current transformation matrix back unto the stack

void swf_pushmatrix ( void) \linebreak


The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.

swf_removeobject (PHP 4 )
Remove an object

void swf_removeobject ( int depth) \linebreak


Removes the object at the depth specified by depth.

swf_rotate (PHP 4 )
Rotate the current transformation

void swf_rotate ( double angle, string axis) \linebreak


The swf_rotate() rotates the current transformation by the angle given by the angle parameter around
the axis given by the axis parameter. Valid values for the axis are ’x’ (the x axis), ’y’ (the y axis) or ’z’
(the z axis).

swf_scale (PHP 4 )
Scale the current transformation

void swf_scale ( double x, double y, double z) \linebreak


The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of
the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z
parameter.

swf_setfont (PHP 4 )
Change the current font

void swf_setfont ( int fontid) \linebreak

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

void swf_setframe ( int framenumber) \linebreak


The swf_setframe() changes the active frame to the frame specified by framenumber.

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

void swf_shapefillbitmapclip ( int bitmapid) \linebreak


Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid
parameter.

swf_shapefillbitmaptile (PHP 4 )
Set current fill mode to tiled bitmap

void swf_shapefillbitmaptile ( int bitmapid) \linebreak


Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter
(tiled).

swf_shapefilloff (PHP 4 )
Turns off filling

void swf_shapefilloff ( void) \linebreak


The swf_shapeFillOff() function turns off filling for the current shape.

swf_shapefillsolid (PHP 4 )
Set the current fill style to the specified color

void swf_shapefillsolid ( float r, float g, float b, float a) \linebreak


The swf_shapeFillSolid() function sets the current fill style to solid, and then sets the fill color to the
values of the rgba parameters.

swf_shapelinesolid (PHP 4 )
Set the current line style

void swf_shapelinesolid ( float r, float g, float b, float a, float width) \linebreak

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

void swf_shapelineto ( float x, float y) \linebreak


The swf_shapeLineTo() draws a line to the x,y coordinates given by the x parameter & the y parameter.
The current position is then set to the x,y parameters.

swf_shapemoveto (PHP 4 )
Move the current position

void swf_shapemoveto ( float x, float y) \linebreak


The swf_shapeMoveTo() function moves the current position to the x coordinate given by the x
parameter and the y position given by the y parameter.

swf_showframe (PHP 4 )
Display the current frame

void swf_showframe ( void) \linebreak


The swf_showframe function will output the current frame.

swf_startbutton (PHP 4 )
Start the definition of a button

void swf_startbutton ( int objid, int type) \linebreak


The swf_startbutton() function starts off the definition of a button. The type parameter can either be
TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the
focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the
focus to travel when the mouse is down.

1379
SWF

swf_startdoaction (PHP 4 )
Start a description of an action list for the current frame

void swf_startdoaction ( void) \linebreak


The swf_startdoaction() function starts the description of an action list for the current frame. This must
be called before actions are defined for the current frame.

swf_startshape (PHP 4 )
Start a complex shape

void swf_startshape ( int objid) \linebreak


The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.

swf_startsymbol (PHP 4 )
Define a symbol

void swf_startsymbol ( int objid) \linebreak


Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The
objid parameter is the object id you want to define as a symbol.

swf_textwidth (PHP 4 )
Get the width of a string

float swf_textwidth ( string str) \linebreak


The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and
font size.

swf_translate (PHP 4 )
Translate the current transformations

void swf_translate ( double x, double y, double z) \linebreak


The swf_translate() function translates the current transformation by the x, y, and z values given.

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

snmp_get_quick_print (PHP 3>= 3.0.8, PHP 4 )


Va a buscar el valor actual de la biblioteca UCD estableciendo quick_print

boolean snmp_get_quick_print ( void ) \linebreak


Delvuele el valor actual almacenado en la biblioteca UCD para quick_print. quick_print está desactivado
por defecto.

$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 (PHP 3>= 3.0.8, PHP 4 )


Establece el valor de quick_print con el de la biblioteca UCD SNMP.

void snmp_set_quick_print ( boolean quick_print) \linebreak


Establece el valor de quick_print con la biblioteca UCD SNMP. Cuando esto está establecido (1), la
biblioteca SNMP devolverá valores ’quick printed’. De esta manera sólo el valor será impreso. Cuando
quick_print no está activada (por defecto) la biblioteca UCD SNMP imprime información extra
incluyendo el tipo del valor (p. Ej. IPAddress o OID). Adicionalmente, si quick_print no está activado, la
biblioteca imprime valores hexadecimales adicionales para todas las cadenas de 3 o menos caracteres.
El ajuste de quick_print es generalmente usado cuando usando la información devuelta con anterioridad
se muestra.

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.

snmpget (PHP 3, PHP 4 )


Va a buscar un objeto 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.

$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0")

snmprealwalk (PHP 3>= 3.0.8, PHP 4 )


Return all objects including their respective object ID within the specified one

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.

snmpset (PHP 3>= 3.0.12, PHP 4 )


Va a buscar un objeto SNMP

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.

snmpwalk (PHP 3, PHP 4 )


Busqueda por un arbol de información acerca de un entidad de red

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.

$a = snmpwalk("127.0.0.1", "public", "");

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.

for ($i=0; $i<count($a); $i++) {


echo $a[$i];
}

snmpwalkoid (PHP 3>= 3.0.8, PHP 4 )


Busqueda por un arbol de información acerca de un entidad de red

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.

$a = snmpwalkoid("127.0.0.1", "public", "");

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.

for (reset($a); $i = key($a); next($a)) {


echo "$i: $a[$i]<br>\n";
}

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.

Ejemplo 1. Socket example: Simple TCP/IP server

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

/* Allow the script to hang around waiting for connections. */


set_time_limit(0);

$address = ’192.168.1.53’;
$port = 10000;

if (($sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {


echo "socket() failed: reason: " . strerror($sock) . "\n";
}

if (($ret = bind($sock, $address, $port)) < 0) {


echo "bind() failed: reason: " . strerror($ret) . "\n";
}

if (($ret = listen($sock, 5)) < 0) {


echo "listen() failed: reason: " . strerror($ret) . "\n";
}

do {
if (($msgsock = accept_connect($sock)) < 0) {

1387
Sockets

echo "accept_connect() failed: reason: " . strerror($msgsock) . "\n";


break;
}
do {
$buf = ”;
$ret = read($msgsock, $buf, 2048);
if ($ret < 0) {
echo "read() failed: reason: " . strerror($ret) . "\n";
break 2;
}
if ($ret == 0) {
break 2;
}
$buf = trim($buf);
if ($buf == ’quit’) {
close($msgsock);
break 2;
}
$talkback = "PHP: You said ’$buf’.\n";
write($msgsock, $talkback, strlen($talkback));
echo "$buf\n";
} while (true);
close($msgsock);
} while (true);

close($sock);
?>

Ejemplo 2. Socket example: Simple TCP/IP client

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

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */


$service_port = getservbyname(’www’, ’tcp’);

/* Get the IP address for the target host. */


$address = gethostbyname(’www.php.net’);

/* Create a TCP/IP socket. */


$socket = socket(AF_INET, SOCK_STREAM, 0);
if ($socket < 0) {
echo "socket() failed: reason: " . strerror($socket) . "\n";
} else {
"socket() successful: " . strerror($socket) . "\n";

1388
Sockets

echo "Attempting to connect to ’$address’ on port ’$service_port’...";


$result = connect($socket, $address, $service_port);
if ($result < 0) {
echo "connect() failed.\nReason: ($result) " . strerror($result) . "\n";
} else {
echo "OK.\n";
}

$in = "HEAD / HTTP/1.0\r\n\r\n";


$out = ”;

echo "Sending HTTP HEAD request...";


write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";


while (read($socket, $out, 2048)) {
echo $out;
}

echo "Closing socket...";


close($socket);
echo "OK.\n\n";
?>

1389
Sockets

socket_accept (PHP 4 >= 4.1.0)


Accepts a connection on a socket

resource socket_accept ( resource socket) \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.

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().

socket_bind (PHP 4 >= 4.1.0)


Binds a name to a socket

bool socket_bind ( resource socket, string address [, 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.

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().

socket_clear_error (PHP 4 >= 4.2.0)


Clears the error on the socket or the last error code

void socket_clear_error ( [resource socket]) \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.

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().

socket_close (PHP 4 >= 4.1.0)


Closes a socket resource

void socket_close ( resource socket) \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.

socket_close() closes the socket resource given by socket.

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

See also socket_bind(), socket_listen(), socket_create() and socket_strerror().

socket_connect (PHP 4 >= 4.1.0)


Initiates a connection on a socket

bool socket_connect ( resource socket, string address [, 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.

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().

socket_create_listen (PHP 4 >= 4.1.0)


Opens a socket on port to accept connections

resource socket_create_listen ( int port [, int backlog]) \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.

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().

See also socket_create(), socket_bind(), socket_listen(), socket_last_error() and socket_strerror().

socket_create_pair (PHP 4 >= 4.1.0)


Creates a pair of indistinguishable sockets and stores them in fds.

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.

socket_create (PHP 4 >= 4.1.0)


Create a socket (endpoint for communication)

resource socket_create ( int domain, int type, int protocol) \linebreak

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.

Creates a communication endpoint (a socket), and returns a socket resource.


The domain parameter sets the domain (protocol family) to be used for communication. Currently,
AF_INET and AF_UNIX are understood. AF_INET is typical used for internet based communication.
AF_UNIX uses pathnames to identify sockets and can therefore only be used for local communication
(which is faster, on the other hand).
The type parameter selects the socket type. This is one of SOCK_STREAM, SOCK_DGRAM,
SOCK_SEQPACKET, SOCK_RAW, SOCK_RDM, or SOCK_PACKET. The two most common types are
SOCK_DGRAM for UDP (connectionless) communication and SOCK_STREAM for TCP communication.

protocol sets the protocol which is either SOL_UDP or SOL_TCP.


Returns a 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.
For more information on the usage of socket_create(), as well as on the meanings of the various
parameters, see the Unix man page socket (2).

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.

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(), and


socket_strerror().

socket_get_option (PHP 4 CVS only)


Gets socket options for the socket

mixed socket_get_option ( resource socket, int level, int optname) \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.

1394
Sockets

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

Nota: This function used to be called socket_getopt() prior to PHP 4.3.0

socket_getpeername (PHP 4 >= 4.1.0)


Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem
path, dependent on its type.

bool socket_getpeername ( resource socket, 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.

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().

socket_getsockname (PHP 4 >= 4.1.0)


Queries the local side of the given socket which may either result in host/port or in a UNIX filesystem
path, dependent on its type.

bool socket_getsockname ( resource socket, string &addr [, int &port]) \linebreak

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().

socket_iovec_add (PHP 4 >= 4.1.0)


Adds a new vector to the scatter/gather array

bool socket_iovec_add ( resource iovec, int iov_len) \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.

socket_iovec_alloc (PHP 4 >= 4.1.0)


...]) Builds a ’struct iovec’ for use with sendmsg, recvmsg, writev, and readv

1396
Sockets

resource socket_iovec_alloc ( int num_vectors [, int ]) \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.

socket_iovec_delete (PHP 4 >= 4.1.0)


Deletes a vector from an array of vectors

bool socket_iovec_delete ( resource iovec, int iov_pos) \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.

socket_iovec_fetch (PHP 4 >= 4.1.0)


Returns the data held in the iovec specified by iovec_id[iovec_position]

string socket_iovec_fetch ( resource iovec, int iovec_position) \linebreak

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.

socket_iovec_free (PHP 4 >= 4.1.0)


Frees the iovec specified by iovec_id

bool socket_iovec_free ( resource iovec) \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.

socket_iovec_set (PHP 4 >= 4.1.0)


Sets the data held in iovec_id[iovec_position] to new_val

bool socket_iovec_set ( resource iovec, int iovec_position, string new_val) \linebreak

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.

socket_last_error (PHP 4 >= 4.1.0)


Returns the last error on the socket

int socket_last_error ( [resource socket]) \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.

This function returns a socket error code.


If a socket resource is passed to this function, the last error which occured on this particular socket is
returned. If the socket resource is ommited, the error code of the last failed socket function is returned.
The latter is in particular helpful for functions like socket_create() which don’t return a socket on failure
and socket_select() which can fail for reasons not directly tied to a particular socket. The error code is
suitable to be fed to socket_strerror() which returns a string describing the given error code.

if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {


die("Couldn’t create socket, error code is: " . socket_last_error() .
",error message is: " . socket_strerror(socket_last_error()));
}

Nota: socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.

1399
Sockets

socket_listen (PHP 4 >= 4.1.0)


Listens for a connection on a socket

bool socket_listen ( resource socket [, int backlog]) \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.

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.

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.


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_accept(), socket_bind(), socket_connect(), socket_create() and socket_strerror().

socket_read (PHP 4 >= 4.1.0)


Reads a maximum of length bytes from a socket

string socket_read ( resource socket, int length [, int type]) \linebreak

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

Optional type parameter is a named constant:

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

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(),


socket_strerror() and socket_write().

socket_readv (PHP 4 >= 4.1.0)


Reads from an fd, using the scatter-gather array defined by iovec_id

bool socket_readv ( resource socket, resource iovec_id) \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.

1401
Sockets

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

socket_recv (PHP 4 >= 4.1.0)


Receives data from a connected socket

string socket_recv ( resource socket, int len, int flags) \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.

socket_recvfrom (PHP 4 >= 4.1.0)


Receives data from a socket, connected or not

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.

socket_recvmsg (PHP 4 >= 4.1.0)


Used to receive messages on a socket, whether connection-oriented or not

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.

socket_select (PHP 4 >= 4.1.0)


Runs the select() system call on the given arrays of sockets with a timeout specified by tv_sec and
tv_usec

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:

/* Prepare the read array */


$read = array($socket1, $socket2);

if (false === ($num_changed_sockets = socket_select($read, $write = NULL, $ex-


cept = NULL, 0))) {
/* Error handling */
else if ($num_changed_sockets > 0) {
/* At least at one of the sockets something interesting happened */
}

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:

socket_select($r, $w, $e = NULL, 0);

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:

if (false === socket_select($r, $w, $e = NULL, 0)) {


echo "socket_select() failed, reason: " . socket_strerror(socket_last_error()) . "\n";
}

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.

See also socket_read(), socket_write(), socket_last_error() and socket_strerror().

socket_send (PHP 4 >= 4.1.0)


Sends data to a connected 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.

socket_sendmsg (PHP 4 >= 4.1.0)


Sends a message to a socket, regardless of whether it is connection-oriented or not

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.

socket_sendto (PHP 4 >= 4.1.0)


Sends a message to a socket, whether it is connected or not

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.

socket_set_nonblock (PHP 4 >= 4.1.0)


Sets nonblocking mode for file descriptor fd

bool socket_set_nonblock ( resource socket) \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.

socket_set_option (PHP 4 CVS only)


Sets socket options for the socket

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.

Nota: This function used to be called socket_setopt() prior to PHP 4.3.0

socket_shutdown (PHP 4 >= 4.1.0)


Shuts down a socket for receiving, sending, or both.

bool socket_shutdown ( resource socket [, int how]) \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.

socket_strerror (PHP 4 >= 4.1.0)


Return a string describing a socket error

1408
Sockets

string socket_strerror ( int errno) \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.

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.

Ejemplo 1. socket_strerror() example

<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, 0))) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (false == (@socket_bind($socket, ’127.0.0.1’, 80))) {


echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n
}
?>

The expected output from the above example (assuming the script is not run with root privileges):
socket_bind() failed: reason: Permission denied

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), and socket_create().

socket_write (PHP 4 >= 4.1.0)


Write to a socket

int socket_write ( resource socket, string buffer [, int length]) \linebreak

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.

The function socket_write() writes to the socket socket from buffer.


The optional parameter length can specify an alternate length of bytes written to the socket. If this
length is greater then the buffer length, it is silently truncated to the length of the buffer.
Returns the number of bytes successfully written to the socket or FALSE one 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: 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.

See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_read() and


socket_strerror().

socket_writev (PHP 4 >= 4.1.0)


Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id

bool socket_writev ( resource socket, resource iovec_id) \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.

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

string addcslashes ( string cad, string listcar) \linebreak


Devuelve una cadena con barras invertidas antes de los caracteres listados en el parámetro listcar.
También marca \n, \r etc. Al estilo del C, los caracteres con códico ASCII inferior a 32 y superior a 126
son convertidos a representación octal. Tenga cuidado cuando marque caracteres alfanuméricos. Puede
especificar un rango en listcar como el "\0..\37", que marcaría todos los caracteres con código ASCII
entre 0 y 31.

Ejemplo 1. Ejemplo de addcslashes()

$tradformado = addcslashes ($no_transf, "\0..\37!@\177..\377");

Nota: Añadida en PHP4b3-dev.

Vea también stripcslashes(), stripslashes(), htmlspecialchars(), htmlspecialchars(), y quotemeta().

AddSlashes (PHP 3, PHP 4 )


Marca una cadena con barras

string addslashes ( string cad) \linebreak


Devuelve una cadena con barras invertidas frente a los caracteres que necesitan marcarse en consultas de
bases de datos, etc. Estos son la comilla simple (’), comilla doble ("), barra invertida (\) y NUL (el byte
nulo).
Vea también stripslashes(), htmlspecialchars(), y quotemeta().

bin2hex (PHP 3>= 3.0.9, PHP 4 )


Convierte datos binarios en su representación hexadecimal

string bin2hex ( string cad) \linebreak


Devuelve una cadena ASCII que contiene la representación hexadecimal de cad. La conversión se
realiza byte a byte, con los 4 bits superiores primero.

1413
Cadenas

chop (PHP 3, PHP 4 )


Elimina espacios sobrantes al final

string chop ( string cad) \linebreak


Devuelve la cadena argumento sin los espacios sobrantes, incluyendo los saltos de línea.

Ejemplo 1. Ejemplo de chop()

$recortada = chop ($linea);

Vea también trim().

chr (PHP 3, PHP 4 )


Devuelve un caracter específico

string chr ( int ascii) \linebreak


Devuelve una cadena de un caracter que congiene el caracter especificado por ascii.

Ejemplo 1. Ejemplo de chr()

$cad .= chr (27); /* añade un caracter de escape al final de $cad */

/* A veces esto es más útil */

$cad = sprintf ("La cadena termina en escape: %c", 27);

Esta función complementa a ord(). Vea también sprintf() con una cadena de formato %c.

chunk_split (PHP 3>= 3.0.6, PHP 4 )


Divide una cadena en trozos más pequeños

string chunk_split ( string cadena [, int tamatrozo [, string final]]) \linebreak


Se puede utilizar para trocear una cadena en pedazos más pequeños, lo que es útil, p.ej., para convertir la
salida de la función base64_encode a la semántica del RFC 2045. Inserta la cadena final cada
tamatrozo (por defecto vale 76) caracteres. Devuelve la nueva cadena y deja intacta la original.

1414
Cadenas

Ejemplo 1. Ejemplo de chunk_split()

# formatear $datos usando la semántica del RFC 2045

$nueva_cad = chunk_split (base64_encode($datos));

Esta función es notablemente más rápida que ereg_replace().

Nota: Esta función se añadió en la 3.0.6.

convert_cyr_string (PHP 3>= 3.0.6, PHP 4 )


Convierte de un juego de caracteres Cirílico a otro

string convert_cyr_string ( string cad, string desde, string hasta) \linebreak


Esta función convierte la cadena dada de un juego de caracteres Cirílico a otro. Los argumentos desde
y hasta son caracteres sencillos que representan los juegos de caracteres Cirílicos fuente y destino. Los
tipos soportados son:
• k - koi8-r
• w - windows-1251
• i - iso8859-5
• a - x-cp866
• d - x-cp866
• m - x-mac-cyrillic

count_chars (PHP 4 )
Devuelve información sobre los caracteres usados en una cadena

mixed count_chars ( string cadena [, modo]) \linebreak


Cuenta el número de apariciones de cada valor de byte (0..255) en cadena y lo devuelve de varias
maneras. El parámetro opcional modo vale por defecto 0. Dependiendo de modo, count_chars() puede
devolver:
• 0 - una matriz con el valor del byte como clave y la frecuencia de cada uno como valor.
• 1 - como el 0, pero listando únicamente los valores de byte con frecuencia superior a cero.

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.

Nota: Esta función se añadió en el PHP 4.0.

crc32 (PHP 4 >= 4.0.1)


Calcula el polinomio crc32 de una cadena

int crc32 ( string cad) \linebreak


Genera el polinomio de comprobación de reduncancia cíclica de 32 bits de cad. Se suele utilizar para
validad la integridad de los datos transmitidos.
Vea también: md5()

crypt (PHP 3, PHP 4 )


Encripta una cadena mediante DES

string crypt ( string cad [, string semilla]) \linebreak


crypt() encriptará una cadena utilizando el método estándar de encriptación del Unix DES. Los
argumentos son una cadena a encriptar y una cadena semilla de 2 caracteres en la que basar la
encriptación. Vea la página de manual de Unix sobre crypt para más información.
Si el argumento de semilla no se proporciona, será generado aleatoriamente por el PHP.
Algunos sistemas operativos soportan más de un tipo de encriptación. De hecho, algunas veces la
encriptación estándar DES es sustituída por un algoritmo de encriptación basado en MD5. El tipo de
encriptación es disparado por el argumento semilla. En tiempo de instalación, el PHP determina la
capacidad de la función de encriptación y aceptará semillas para otros tipos de encriptación. Si no se
proporciona la semilla, el PHP intentará generar una semilla estándar DES de 2 caraceres por defecto,
excepto si el tipo de encriptación estándar del sistema es el MD5, en cuyo caso se generará una semilla
aleatoria compatible con MD5. El PHP fija una constante llamada CRYPT_SALT_LENGTH que le
especifica si su sistema soporta una semilla de 2 caracteres o si se debe usar la semilla de 12 caracteres
del NDS.
La función estándar de encriptación crypt() contiene la semilla como los dos primeros caracteres de la
salida.
En los sistemas en los que la función crypt() soporta múltiples tipos de encriptación, las siguienes
constantes son fijadas a 0 ó 1 dependiendo de si está disponible el tipo dado:

1416
Cadenas

• CRYPT_STD_DES - Encriptación DES estándar con semilla de 2 caracteres


• CRYPT_EXT_DES - Encriptación DES extendida con semilla de 9 caracteres
• CRYPT_MD5 - Encriptación MD5 con semilla de 12 caracteres y comenzando por $1$
• CRYPT_BLOWFISH - Encriptación DES extendida con semilla de 16 caracteres y comenzando por
$2$
No hay función de desencriptado porque crypt() utiliza un algoritmo de una sola vía.
Vea también: md5().

echo (unknown)
Da salida a una o más cadenas

echo ( string arg1 [, string argn...]) \linebreak


Da salida a todos sus parámetros.
echo() no es realmente una función (es una sentencia del lenguaje) de modo que no se requiere el uso de
los paréntesis.

Ejemplo 1. Ejemplo de echo()

echo "Hola Mundo";

echo "Esto se extiende


por varias líneas. Los saltos de línea
también se envían";

echo "Esto se extiende\npor varias líneas. Los saltos de línea\ntambién se envían";

Nota: De hecho, si desea pasar más de un parámetro a echo no debe encerrarlos entre paréntesis.

Vea también: print(), printf(), y flush().

explode (PHP 3, PHP 4 )


Divide una cadena por otra

array explode ( string separador, string cadena [, int limite]) \linebreak

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.

Ejemplo 1. Ejemplo de explode()

$pizza = "trozo1 trozo2 trozo3 trozo4 trozo5 trozo6";


$trozos = explode (" ", $pizza);

Vea también split() e implode().

get_html_translation_table (PHP 4 )
Devuelve la tabla de traducción utilizada por htmlspecialchars() y htmlentities()

string get_html_translation_table ( int tabla) \linebreak


get_html_translation_table() devolverá la tabla de traducción que se usa internamente para
htmlspecialchars() y htmlentities(). Hay dos nuevas definiciones (HTML_ENTITIES,
HTML_SPECIALCHARS) que le permiten especificar la tabla deseada.

Ejemplo 1. Ejemplo de Tabla de Traducción

$trad = get_html_translation_table (HTML_ENTITIES);


$cad = "Hallo & <Frau> & Krämer";
$codif = strtr ($cad, $trad);

La variable $codif contendrá ahora: "Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer".


Lo interesante es usar la función array_flip() para cambiar la dirección de la traducción.

$trad = array_flip ($trad);


$original = strtr ($cad, $trad);

El contenido de $original sería: "Hallo & <Frau> & Krämer".

Nota: Esta función fue añadida en PHP 4.0.

Vea también: htmlspecialchars(), htmlentities(), strtr(), y array_flip().

1418
Cadenas

get_meta_tags (PHP 3>= 3.0.4, PHP 4 )


Extrae todas las etiquetas meta de un archivo y retorna una matriz

array get_meta_tags ( string nombrefich [, int use_ruta_include]) \linebreak


Abre el nombrefich y lo trocea línea a línea buscando etiquetas <meta> de la forma

Ejemplo 1. Ejemplo de Etiquetas Meta

<meta name="autor" content="nombre">


<meta name="etiquetas" content="documentación de php3">
</head> <!-- el proceso se detiene aquí -->

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

hebrev (PHP 3, PHP 4 )


Convierte Hebreo lógico a texto visual

string hebrev ( string texto_hebreo [, int max_cars_por_linea]) \linebreak


El parámetro opcional max_cars_por_linea indica el máximo número de caracteres que se
emitirán por línea. La función intenta evitar cortar palabras.
Vea también hebrevc()

hebrevc (PHP 3, PHP 4 )


Convierte Hebreo lógico a texto visual con conversión de saltos de línea

string hebrevc ( string texto_hebreo [, int max_cars_por_linea]) \linebreak


Esta funcion es similar a hebrev() con la diferencia que convierte las nuevas líneas (\n) a "<br>\n". El
parámetro opcional max_cars_por_linea indica el máximo número de caracteres que se emitirán
por línea. La función intenta evitar cortar palabras.
Vea también hebrev()

1419
Cadenas

htmlentities (PHP 3, PHP 4 )


Convierte todos los caracteres aplicables a entidades HTML

string htmlentities ( string cadena) \linebreak


Esta función es del todo idéntica a htmlspecialchars(), excepto que traduce todos los caracteres que
tienen equivalente como entidad HTML.
Actualmente se utiliza el juego de caracteres ISO-8859-1.
Vea también htmlspecialchars() y nl2br().

htmlspecialchars (PHP 3, PHP 4 )


Convierte caracteres especiales a entidades HTML

string htmlspecialchars ( string cadena) \linebreak


Ciertos caracteres tienen significados especiales en HTML, y deben ser representados por entidades
HTML si se desea preservar su significado. Esta función devuelve una cadena con dichas conversiones
realizadas.
Esta función es útil para evitar que el texo entrado por el usuario contenga marcas HTML, como ocurre
en aplicaciones de foros o libros de visita.
Actualmente, las traducciones hechas son:

• ’&’ (ampersand) se convierte en ’&amp;’


• ’"’ (doble comilla) se convierte en ’&quot;’
• ’<’ (menor que) se convierte en ’&lt;’
• ’>’ (mayor que) se convierte en ’&gt;’

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().

implode (PHP 3, PHP 4 )


Unir elementos de una matriz mediante una cadena

string implode ( string cola, array piezas) \linebreak


Devuelve una cadena que contiene una representación de todos los elementos de la matriz en el mismo
orden, pero con la cadena cola en medio de los mismos.

1420
Cadenas

Ejemplo 1. Ejemplo de implode()

$separada_dospuntos = implode (":", $matrizay);

Vea también explode(), join(), y split().

join (PHP 3, PHP 4 )


Une elementos de una tabla mediante una cadena

string join ( string cola, array piezas) \linebreak


join() es un alias para implode(), y es idéntica en todo.
Vea también explode(), implode(), y split().

levenshtein (PHP 3>= 3.0.17, PHP 4 >= 4.0.1)


Calcula la distancia Levenshtein entre dos cadenas

int levenshtein ( string cad1, string cad2) \linebreak


Esta función devuelve la distancia Levenshtein entre las dos cadenas argumento, ó -1 si alguna de las
cadenas tiene más de 255 caracteres.
La distancia Levenshtein se define como el mínimo número de caracteres que se tienen que sustituir,
insertar o borrar para transformar cad1 en cad2. La complejidad del algoritmo es O(m*n), donde n y m
son las longitudes de cad1 y cad2 (bastante bueno si se la compara con similar_text(), que es
O(max(n,m)**3), pero aún es cara).
Vea también soundex(), similar_text() y metaphone().

localeconv (PHP 4 >= 4.0.5)


Get numeric formatting information

array localeconv ( void) \linebreak


Returns an associative array containing localized numeric and monetary formatting information.
localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is
returned contains the following fields:

Array element Description

1421
Cadenas

Array element Description


decimal_point Decimal point character
thousands_sep Thousands separator
grouping Array containing numeric groupings
int_curr_symbol International currency symbol (i.e. USD)
currency_symbol Local currency symbol (i.e. $)
mon_decimal_point Monetary decimal point character
mon_thousands_sep Monetary thousands separator
mon_grouping Array containing monetary groupings
positive_sign Sign for positive values
negative_sign Sign for negative values
int_frac_digits International fractional digits
frac_digits Local fractional digits
p_cs_precedes TRUE if currency_symbol precedes a positive value,
FALSE if it succeeds one
p_sep_by_space TRUE if a space separates currency_symbol from a
positive value, FALSE otherwise
n_cs_precedes TRUE if currency_symbol precedes a negative
value, FALSE if it succeeds one
n_sep_by_space TRUE if a space separates currency_symbol from a
negative value, FALSE otherwise
p_sign_posn 0
Parentheses surround the quantity and
currency_symbol
1
The sign string precedes the quantity and
currency_symbol
2
The sign string succeeds the quantity and
currency_symbol
3
The sign string immediately precedes the
currency_symbol
4
The sign string immediately succeeds the
currency_symbol

1422
Cadenas

Array element Description


n_sign_posn 0
Parentheses surround the quantity and
currency_symbol
1
The sign string precedes the quantity and
currency_symbol
2
The sign string succeeds the quantity and
currency_symbol
3
The sign string immediately precedes the
currency_symbol
4
The sign string immediately succeeds the
currency_symbol

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.

Ejemplo 1. localeconv() example

setlocale(LC_ALL, "en_US");

$locale_info = localeconv();

echo "<PRE>\n";
echo "--------------------------------------------\n";
echo " Monetary information for current locale: \n";
echo "--------------------------------------------\n\n";

echo "int_curr_symbol: {$locale_info["int_curr_symbol"]}\n";


echo "currency_symbol: {$locale_info["currency_symbol"]}\n";
echo "mon_decimal_point: {$locale_info["mon_decimal_point"]}\n";
echo "mon_thousands_sep: {$locale_info["mon_thousands_sep"]}\n";
echo "positive_sign: {$locale_info["positive_sign"]}\n";
echo "negative_sign: {$locale_info["negative_sign"]}\n";
echo "int_frac_digits: {$locale_info["int_frac_digits"]}\n";
echo "frac_digits: {$locale_info["frac_digits"]}\n";
echo "p_cs_precedes: {$locale_info["p_cs_precedes"]}\n";
echo "p_sep_by_space: {$locale_info["p_sep_by_space"]}\n";
echo "n_cs_precedes: {$locale_info["n_cs_precedes"]}\n";
echo "n_sep_by_space: {$locale_info["n_sep_by_space"]}\n";
echo "p_sign_posn: {$locale_info["p_sign_posn"]}\n";
echo "n_sign_posn: {$locale_info["n_sign_posn"]}\n";
echo "</PRE>\n";

1423
Cadenas

The constant CHAR_MAX is also defined for the use mentioned above.
See also: setlocale().

ltrim (PHP 3, PHP 4 )


Elimina el espacio en blanco del principio de una cadena

string ltrim ( string cad) \linebreak


Esta función elimina el espacio en blanco del principio de una cadena y devuelve la cadena resultante.
Los caracteres de espacio que elimina realmente son: "\n", "\r", "\t", "\v", "\0", y el espacio en sí.
Vea también chop() y trim().

md5_file (PHP 4 >= 4.2.0)


Calculates the md5 hash of a given filename

string md5_file ( string filename) \linebreak


Calculates the MD5 hash of the specified filename using the RSA Data Security, Inc. MD5
Message-Digest Algorithm (http://www.faqs.org/rfcs/rfc1321.html), and returns that hash.
This function has the same purpose of the command line utility md5sum.
See also: md5() and crc32()

md5 (PHP 3, PHP 4 )


Calcula el hash md5 de una cadena

string md5 ( string cad) \linebreak


Calcula el hash (extracto) MD5 de cad usaneo el Algoritmo de Resumen de Mensajes MD5 de RSA
Data Security, Inc. (http://www.faqs.org/rfcs/rfc1321.html).
Vea también: crc32()

1424
Cadenas

metaphone (PHP 4 )
Calcula la clave "metáfona" de una cadena

string metaphone ( string cad) \linebreak


Calcula la clave "metáfona" de cad.
Similarmente a soundex(), metaphone crea la misma clave para palabras que suenan parecidas. Es más
precisa que la función soundex(), pues conoce las reglas básicas de la pronunciación del Inglés. Las
claves metafónicas generadas son de longitud variable.
Metaphone fue desarrollado por Lawrence Philips <[email protected]>. Se describe en ["Practical
Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

Nota: Esta función se añadió en PHP 4.0.

nl_langinfo (PHP 4 >= 4.1.0)


Query language and locale information

string nl_langinfo ( int item) \linebreak

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

nl2br (PHP 3, PHP 4 )


Convierte nuevas líneas a saltos de línea HTML

string nl2br ( string cadena) \linebreak


Devuelve la cadena con ’<BR>’ insertados antes de cada nueva línea.
Vea también htmlspecialchars(), htmlentities() y wordwrap().

1425
Cadenas

ord (PHP 3, PHP 4 )


Devuelve el valor ASCII de un caracter

int ord ( string cadena) \linebreak


Devuelve el valor ASCII del primer caracter de cadena. Esta función complementa a chr().

Ejemplo 1. Ejemplo de ord()

if (ord ($cad) == 10) {


echo "El primer caracter de \$cad es un salto de línea.\n";
}

Vea también chr().

parse_str (PHP 3, PHP 4 )


Divide la cadena en variables

void parse_str ( string cad) \linebreak


Divide cad como si fuera la cadena de consulta enviada por un URL y crea las variables en el ámbito
actual.

Ejemplo 1. Usando parse_str()

$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

print ( string arg) \linebreak


Emite arg.
Vea también: echo(), printf(), y flush().

1426
Cadenas

printf (PHP 3, PHP 4 )


Emite una cadena con formato

int printf ( string formato [, mixed args]) \linebreak


Produce una salida según el formato, que es descrito en la documentación para sprintf().
Vea también: print(), sprintf(), sscanf(), fscanf(), y flush().

quoted_printable_decode (PHP 3>= 3.0.6, PHP 4 )


Convierte una cadena con marcación imprimible a una cadena de 8 bits

string quoted_printable_decode ( string cad) \linebreak


Esta función devuelve una cadena binaria de 8 bit que se corresponde con la cadena con marcación
imprimible decodificada. Esta función es similar a imap_qprint(), pero sin requerir que el módulo IMAP
funcione.

quotemeta (PHP 3, PHP 4 )


Quote meta characters

string quotemeta ( string cad) \linebreak


Devuelve una versión de la cadena con una barra invertida (\) antes de cada caracter de este conjunto:

. \\ + * ? [ ^ ] ( $ )

Vea también addslashes(), htmlentities(), htmlspecialchars(), nl2br(), y stripslashes().

rtrim (PHP 3, PHP 4 )


Elimina espacios en blanco al final de la cadena.

string rtrim ( string cad) \linebreak


Devuelve la cadena argumento sin espacios en blanco ni saltos de línea al final. Es un alias para chop().

1427
Cadenas

Ejemplo 1. Ejemplo de rtrim()

$recortada = rtrim ($linea);

Vea también trim(), ltrim().

setlocale (PHP 3, PHP 4 )


Fija la información de localidad

string setlocale ( string categoria, string localidad) \linebreak


categoria es una cadena que especifica la categoría de las funciones afectadas por el ajuste de
localidad:
• LC_ALL para todas las funciones
• LC_COLLATE para la comparación de cadenas - aún no incluída en el PHP
• LC_CTYPE para la conversión y clasificación de caracteres, como por ejemplo strtoupper()
• LC_MONETARY para localeconv() - aún no incluída en el PHP
• LC_NUMERIC para el separador decimal
• LC_TIME para el formato de fecha y hora con strftime()

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.

similar_text (PHP 3>= 3.0.7, PHP 4 )


Calcula la similitud entre dos cadenas

int similar_text ( string primera, string segunda [, double porcentaje]) \linebreak


Esta función calcula la similitud entre dos cadenas según se describe en Oliver [1993]. Nótese que esta
implementación no utiliza una pila como en el pseudo-código de Oliver, sino llamadas recursivas que
pueden o no acelerar el proceso completo. Nótese también que la complejidad de este algoritmo es
O(N**3), donde N es la longitud de la cadena más larga.

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.

soundex (PHP 3, PHP 4 )


Calcula la clave soundex de una cadena

string soundex ( string cad) \linebreak


Calcula la clave soundex de cad.
Las claves soundex tienen la propiedad de que las palabras que se pronuncian de forma parecida tienen la
misma clave, de modo que se pueden usar para simplificar la búsqueda en las bases de datos cuando se
conoce la pronunciación pero no la transcripción. Esta función soundex devuelve una cadena de 4
caracteres que comienza por una letra.
Esta función soundex en particular es la descrita por Donald Knuth en "The Art Of Computer
Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.

Ejemplo 1. Ejemplos de Soundex

soundex ("Euler") == soundex ("Ellery") == ’E460’;


soundex ("Gauss") == soundex ("Ghosh") == ’G200’;
soundex ("Knuth") == soundex ("Kant") == ’H416’;
soundex ("Lloyd") == soundex ("Ladd") == ’L300’;
soundex ("Lukasiewicz") == soundex ("Lissajous") == ’L222’;

sprintf (PHP 3, PHP 4 )


Devuelve una cadena con formato

string sprintf ( string formato [, mixed args]) \linebreak


Devuelve una cadena producida de acuerdo a la cadena de formato.
La cadena de formato está compuesta por cero o más directivas: caracteres ordinarios (excepto %) que
son copiados directamente al resultado, y especificaciones de conversión, cada una de las cuales provoca
la obtención de su propio parámetro. Esto se aplica tanto a sprintf() como a printf().
Cada especificación de conversión consiste en uno de estos elementos, por orden:

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

Vea también: printf(), sscanf(), fscanf(), y number_format().

Ejemplo 1. Ejemplo de sprintf(): enteros rellenos con ceros

$fechaiso = sprintf ("%04d-%02d-%02d", $anno, $mes, $dia);

Ejemplo 2. Ejemplo de sprintf(): formateando monedas

$pelas1 = 68.75;
$pelas2 = 54.35;
$pelas = $pelas1 + $pelas2;
// echo $pelas mostrará "123.1";
$formateado = sprintf ("%01.2f", $pelas);
// echo $formateado mostrará "123.10"

sscanf (PHP 4 >= 4.0.1)


Trocea la entrada desde una cadena según un formato dado

mixed sscanf ( string cad, string formato [, string var1]) \linebreak

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.

Ejemplo 1. Ejemplo de sscanf()

// obteniendo el número de serie


$numserie = sscanf("SN/2350001","SN/%d");
// y la fecha de fabricación
$fecha = "01 Enero 2000";
list($dia, $mes, $anno) = sscanf($fecha,"%d %s %d");
echo "El objeto $numserie fue fabricado el: $anno-".substr($mes,0,3)."-$dia\n";

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.

Ejemplo 2. Ejemplo de sscanf() - usando parámetros opcionales

// obtener autor y generar la ficha DocBook


$autor = "24\tLewis Carroll";
$n = sscanf($autor,"%d\t%s %s", &$id, &$nombre, &$apell);
echo "<autor id=’$id’>
<firstname>$nombre</firstname>
<surname>$apell</surname>
</author>\n";

Vea también: fscanf(), printf(), y sprintf().

str_pad (PHP 4 >= 4.0.1)


Rellena una cadena con otra hasta una longitud dada

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

Ejemplo 1. Ejemplo de str_pad()

$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

string str_repeat ( string cad_entrada, int veces) \linebreak


Devuelve la cad_entrada repetida veces. veces debe ser mayor que 0.

Ejemplo 1. Ejemplo de str_repeat()

echo str_repeat ("-=", 10);

Esto mostrará "-=-=-=-=-=-=-=-=-=-=".

Nota: Esta función fue añadida en el PHP 4.0.

str_replace (PHP 3>= 3.0.6, PHP 4 )


Sustitiye todas las apariciones de la aguja en el pajar por la cadena

string str_replace ( string aguja, string cad, string pajar) \linebreak


Esta función sustituye todas las apariciones de la aguja en el pajar por la cad dada. Si no precisa
reglas especiales de sustitución, deberá usar siempre esta función en lugar de ereg_replace().

Ejemplo 1. Ejemplo de str_replace()

$bodytag = str_replace ("%cuerpo%", "negro", "<body text=%cuerpo%>");

Esta función tiene seguridad binaria.

1432
Cadenas

Nota: str_replace() fue añadida en PHP 3.0.6, pero tuvo errores hasta el PHP 3.0.8.

Vea también ereg_replace() y strtr().

str_rot13 (PHP 4 >= 4.2.0)


Perform the rot13 transform on a string

string str_rot13 ( string str) \linebreak


This function performs the ROT13 encoding on the str argument and returns the resulting string. The
ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha
characters untouched. Encoding and decoding are done by the same function, passing an encoded string
as argument will return the original version.

strcasecmp (PHP 3>= 3.0.2, PHP 4 )


Comparación de cadenas insensible a mayúsculas y minúsculas y segura en modo binario

int strcasecmp ( string cad1, string cad2) \linebreak


Devuelve < 0 si cad1 es menor que cad2; > 0 si cad1 es mayor que cad2, y 0 si son iguales.

Ejemplo 1. Ejemplo de strcasecmp()

$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’;
}

Vea también ereg(), strcmp(), substr(), stristr(), y strstr().

strchr (PHP 3, PHP 4 )


Encuentra la primera aparición de un caracter

string strchr ( string pajar, string aguja) \linebreak


Esta función es un alias para strstr(), y es idéntica en todo.

1433
Cadenas

strcmp (PHP 3, PHP 4 )


Comparación de cadenas con seguridad binaria

int strcmp ( string cad1, string cad2) \linebreak


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(), strncmp(), y strstr().

strcoll (PHP 4 >= 4.0.5)


Locale based string comparison

int strcoll ( string str1, string str2) \linebreak


Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this
function is equivalent to strcmp().
Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.
See also ereg(), strcmp(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), strstr(), and
setlocale().

strcspn (PHP 3>= 3.0.3, PHP 4 )


Encuentra la longitud del elemento inicial que no coincide con la máscara

int strcspn ( string cad1, string cad2) \linebreak


Devuelve la longitud del segmento inicial de cad1 que no contiene ninguno de los caracteres de cad2.
Vea también strspn().

strip_tags (PHP 3>= 3.0.8, PHP 4 )


Elimina marcas HTML y PHP de una cadena

string strip_tags ( string cad [, string etiq_permitidas]) \linebreak


Esta función intenta eliminar todas las etiquetas HTML y PHP de la cadena dada. Causa error por
precaución en caso de etiquetas incompletas o falsas. Utiliza la misma máquina de estados para eliminar
las etiquetas que la función fgetss().

1434
Cadenas

Puede usar el parámetro opcional para especificar las etiquetas que no deben eliminarse.

Nota: etiq_permitidas fue añadido en PHP 3.0.13, PHP4B3.

stripcslashes (PHP 4 )
Desmarca la cadena marcada con addcslashes()

string stripcslashes ( string cad) \linebreak


Devuelve una cadena con las barras invertidas eliminadas. Reconoce las marcas tipo C \n, \r ..., y la
representación octal y hexadecimal.

Nota: Añadida en PHP4b3-dev.

Vea también addcslashes().

stripslashes (PHP 3, PHP 4 )


Desmarca la cadena marcada con addslashes()

string stripslashes ( string cad) \linebreak


Devuelve una cadena con las barras invertidas eliminadas (\’ se convierte en ’, etc.). Las barras
invertidas dobles se convierten en sencillas.
Vea también addslashes().

stristr (PHP 3>= 3.0.6, PHP 4 )


strstr() sin tener en cuenta mayúsculas o minúsculas

string stristr ( string pajar, string aguja) \linebreak


Devuelve todo el pajar desde la primera aparición de la aguja, siendo el pajar examinado sin tener
en cuenta mayúsculas o minúsculas.
Si la aguja no se encuentra, devuelve FALSE.
Si la aguja no es una cadena, es convertida a entero y usada como código de un carácter ASCII.

1435
Cadenas

Vea también strchr(), strrchr(), substr(), y ereg().

strlen (PHP 3, PHP 4 )


Obtiene la longitud de la cadena

int strlen ( string cad) \linebreak


Devuelve la longitud de la cadena.

strnatcasecmp (PHP 4 )
Comparación de cadenas insensible a mayúsculas y minúsculas usando un algoritmo de "orden natural"

int strnatcasecmp ( string cad1, string cad2) \linebreak


Esta función implementa un algoritmo de comparación que ordena las cadenas alfanuméricas como lo
haría un ser humano. El comportamiento de esta función es similar a strnatcmp(), pero la comparación
no es sensible a mayúsculas y minúsculas. 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.
Vea también ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strnatcmp(), y strstr().

strnatcmp (PHP 4 )
Compara cadenas usando un algoritmo de "orden natural"

int strnatcmp ( string cad1, string cad2) \linebreak


Esta función implementa un algoritmo de comparación que ordena las cadenas alfanuméricas como lo
haría un ser humano, que es lo que se denomina "orden natural". A continuación se puede ver un ejemplo
de la diferencia entre este algoritmo y los algoritmos de ordenación de cadenas habituales en los
ordenadores (utilizados en strcmp()):

$matriz1 = $matriz2 = array ("img12.png","img10.png","img2.png","img1.png");


echo "Comparación de cadenas estándar\n";
usort($matriz1,"strcmp");
print_r($matriz1);
echo "\nComparación de cadenas en orden natural\n";
usort($matriz2,"strnatcmp");
print_r($matriz2);

1436
Cadenas

El código anterior generará la siguiente salida:

Comparación de cadenas estándar


Array
(
[0] => img1.png
[1] => img10.png
[2] => img12.png
[3] => img2.png
)

Comparación de cadenas en orden natural


Array
(
[0] => img1.png
[1] => img2.png
[2] => img10.png
[3] => img12.png
)

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().

strncasecmp (PHP 4 >= 4.0.2)


Binary safe case-insensitive string comparison of the first n characters

int strncasecmp ( string str1, string str2, int len) \linebreak


This function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the)
number of characters (len) from each string to be used in the comparison. If any of the strings is shorter
than len, then the length of that string will be used for the comparison.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcasecmp(), strcmp(), substr(), stristr(), and strstr().

strncmp (PHP 4 )
Comparación de los n primeros caracteres de cadenas, con seguridad binaria

1437
Cadenas

int strncmp ( string cad1, string cad2, int largo) \linebreak


Esta función es similar a strcmp(), con la diferencia que se puede especificar el (límite superior del)
número de caractares (largo) de cada cadena que se usarán en la comparación. Si alguna de las cadenas
es menor que el largo, se usará su longitud para la comparación.
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(), y strstr().

strpos (PHP 3, PHP 4 )


Encuentra la posición de la primera aparición de una cadena

int strpos ( string pajar, string aguja [, int desplazamiento]) \linebreak


Devuelve la posición numérica de la primera aparición de la aguja en la cadena pajar. A diferencia
de strrpos(), esta función puede tomar una cadena completa como aguja y se utilizará en su totalidad.
Si la aguja no es hayada, devuelve FALSE.

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:

// en PHP 4.0b3 y posteriores:


$pos = strpos ($micadena, "b");
if ($pos === false) { // nota: tres signos igual
// no encontrado ...
}

// en versiones anteriores a la 4.0b3:


$pos = strpos ($micadena, "b");
if (is_string ($pos) && !$pos) {
// no encontrado ...
}

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

strrchr (PHP 3, PHP 4 )


Encuentra la última aparición de un caracter en una cadena

string strrchr ( string pajar, string aguja) \linebreak


Esta función devuelve la porción del pajar que comienza en la última aparición de la aguja y
continúa hasta el final del pajar.
Devuelve FALSE si la aguja no es hallada.
Si la aguja contiene más de un caracter, sólo se usará el primero.
Si la aguja no es una cadena, se convierte a entero y se aplica como el valor ordinal de un caracter.

Ejemplo 1. Ejemplo de strrchr()

// obtener el último directorio de $PATH


$dir = substr (strrchr ($PATH, ":"), 1);

// obtener todo tras el último salto de línea


$texto = "Line 1\nLine 2\nLine 3";
$apell = substr (strrchr ($texto, 10), 1 );

Vea también substr(), stristr(), y strstr().

strrev (PHP 3, PHP 4 )


Invierte una cadena

string strrev ( string cadena) \linebreak


Devuele la cadena invertida.

strrpos (PHP 3, PHP 4 )


Encuentra la posición de la última aparición de un caracter en una cadena

int strrpos ( string pajar, char aguja) \linebreak


Devuele la posición numérica de la última aparición de la aguja en el pajar. Nótese que la aguja en
este caso sólo puede ser un caracter único. Si se pasa una cadena como aguja, sólo se utilizará el primer
caracter de la misma.
Si la aguja no es hayada, devuelve FALSE.
Si la aguja no es una cadena, se convierte a entero y se aplica como el valor ordinal de un caracter.

1439
Cadenas

Vea también strpos(), strrchr(), substr(), stristr(), y strstr().

strspn (PHP 3>= 3.0.3, PHP 4 )


Encuentra la longitud del segmento inicial que coincide con la máscara

int strspn ( string cad1, string cad2) \linebreak


Devuelve la longitud del segmento inicial de cad1 que consiste por entero en caracteres contenidos en
cad2.

strspn ("42 es la respuesta. ¿Cuál es la pregunta ...?", "1234567890");

devolverá 2 como resultado.

Vea también strcspn().

strstr (PHP 3, PHP 4 )


Encuentra la primera aparición de una cadena

string strstr ( string pajar, string aguja) \linebreak


Devuelve todo el pajar desde la primera aparición de la aguja hasta el final.
Si la aguja no es hayada, devuelve FALSE.
Si la aguja no es una cadena, se convierte a entero y se aplica como el valor ordinal de un caracter.

Nota: Nótese que esta función es sensible a mayúsculas y minúsculas. Para búsquedas no
sensibles, utilice stristr().

Ejemplo 1. Ejemplo de strstr()

$email = ’[email protected]’;
$dominio = strstr ($email, ’@’);
print $dominio; // imprime @designmultimedia.com

1440
Cadenas

Vea también stristr(), strrchr(), substr(), y ereg().

strtok (PHP 3, PHP 4 )


Divide una cadena en elementos

string strtok ( string arg1, string arg2) \linebreak


strtok() se usa para dividir en elementos una cadena. Es decir, que si tiene una cadena como "Esta es una
cadena de ejemplo" podría dividirla en palabras individuales utilizando el espacio como divisor.

Ejemplo 1. Ejemplo de strtok()

$cadena = "Esta es una cadena de ejemplo";


$tok = strtok ($cadena," ");
while ($tok) {
echo "Palabra=$tok<br>";
$tok = strtok (" ");
}

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().

strtolower (PHP 3, PHP 4 )


Pasa a minúsculas una cadena

string strtolower ( string cad) \linebreak


Devuelve la cadena con todas sus letras en minúsculas.
Nótese que las letras son definidad por el locale actual. Esto quiere decir que, por ejemplo, en el locale
por defecto ("C"), los caracteres como la Ñ no serán convertidos.

1441
Cadenas

Ejemplo 1. Ejemplo de strtolower()

$cad = "María Tenía Un Corderito al que QUERÍA Mucho";


$cad = strtolower($cad);
print $cad; # Visualiza maría tenía un corderito al que querÍa mucho

Vea también strtoupper() y ucfirst().

strtoupper (PHP 3, PHP 4 )


Pasa a mayúsculas una cadena

string strtoupper ( string cadena) \linebreak


Devuelve la cadena con todas sus letras en mayúsculas.
Nótese que las letras son definidad por el locale actual. Esto quiere decir que, por ejemplo, en el locale
por defecto ("C"), los caracteres como la ñ no serán convertidos.

Ejemplo 1. Ejemplo de strtoupper()

$cad = "María Tenía Un Corderito al que QUERÍA Mucho";


$cad = strtoupper ($cad);
print $cad; # Visuaiza MARíA TENíA UN CORDERITO AL QUE QUERÍA MUCHO

Vea también strtolower() and ucfirst().

strtr (PHP 3, PHP 4 )


Traduce ciertos caracteres

string strtr ( string cad, string desde, string hasta) \linebreak


Esta función trabaja sobre cad, traduciendo todas las apariciones de cada caracter en desde por el
caracter correspondiente en hasta y devolviendo el resultado.
Si desde y hasta son de distinta longitud, los caracteres extra en la más larga son ignorados.

Ejemplo 1. Ejemplo de strtr()

$addr = strtr($addr, "äåö", "aao");

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:

$trad = array ("hola" => "hey", "hey" => "hola");


echo strtr("hey a todos, dije hola", $trad) . "\n";

Mostrará: "hola a todos, dije hey",

Nota: Esta característica (2 argumentos) fue añadida en el PHP 4.0

Vea también ereg_replace().

substr_count (PHP 4 )
Cuenta el número de apariciones de la subcadena

int substr_count ( string pajar, string aguja) \linebreak


substr_count() devuelve el número de veces que la subcadena aguja se encuentra en la cadena pajar.

Ejemplo 1. Ejemplo de substr_count()

print substr_count("This is a test", "is"); // prints out 2

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

Ejemplo 1. Ejemplo de substr_replace()

<?php
$var = ’ABCDEFGH:/MNRPQR/’;
echo "Original: $var<hr>\n";

/* Estos dos ejemplos sustituyen toda $var por ’bob’. */


echo substr_replace ($var, ’bob’, 0) . "<br>\n";
echo substr_replace ($var, ’bob’, 0, strlen ($var)) . "<br>\n";

/* Inserta ’bob’ justo al inicio de $var. */


echo substr_replace ($var, ’bob’, 0, 0) . "<br>\n";

/* Los dos siguientes cambian ’MNRPQR’ en $var por ’bob’. */


echo substr_replace ($var, ’bob’, 10, -1) . "<br>\n";
echo substr_replace ($var, ’bob’, -7, -1) . "<br>\n";

/* Borrar ’MNRPQR’ de $var. */


echo substr_replace ($var, ”, 10, -1) . "<br>\n";
?>

Vea también str_replace() y substr().

Nota: substr_replace() fue añadida en el PHP 4.0.

substr (PHP 3, PHP 4 )


Devuelve parte de una cadena

string substr ( string cadena, int comienzo [, int largo]) \linebreak


substr devuelve la porción de cadena especificada por los parámetros comienzo y largo.
Si comienzo es positivo, la cadena devuelta comenzará en dicho caracter de cadena.
Ejemplos:

$resto = substr ("abcdef", 1); // devuelve "bcdef"


$resto = substr ("abcdef", 1, 3); // devuelve "bcd"

Si comienzo es negativo, la cadena devuelta comenzará en dicha posición desde el final de cadena.
Ejemplos:

1444
Cadenas

$resto = substr ("abcdef", -1); // devuelve "f"


$resto = substr ("abcdef", -2); // devuelve "ef"
$resto = substr ("abcdef", -3, 1); // devuelve "d"

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:

$resto = substr ("abcdef", 1, -1); // devuelve "bcde"

Vea también strrchr() y ereg().

trim (PHP 3, PHP 4 )


Elimina espacios del principio y final de una cadena

string trim ( string cad) \linebreak


Esta función elimina los espacios en blanco del comienzo y del final de una cadena y devuelve el
resultado. Los caracteres de espacio que elimina realmente son: "\n", "\r", "\t", "\v", "\0", y el espacio en
sí.
Vea también chop() y ltrim().

ucfirst (PHP 3, PHP 4 )


Pasar a mayúsculas el primer caracter de una cadena

string ucfirst ( string cad) \linebreak


Pone en mayúsculas el primer carácter de cad si es alfabético.
Nótese que ’alfabético’ está determinado por la localidad actual. Por ejemplo, en la localidad por defecto
"C", los caracteres como la a con diéresis (ä) no serán convertidos.

1445
Cadenas

Ejemplo 1. Ejemplo de ucfirst()

$texto = ’susanita tiene un ratón, un ratón chiquitín.’;


$texto = ucfirst ($texto); // $texto vale ahora: Susanita tiene un
// ratón, un ratón chiquitín.

Vea también strtoupper() y strtolower()

ucwords (PHP 3>= 3.0.3, PHP 4 )


Pone en mayúsculas el primer caracter de cada palabra de una cadena

string ucwords ( string cad) \linebreak


Pasa a mayúsculas la primera letra de cada palabra en cad si dicho caracter es alfabético.

Ejemplo 1. Ejemplo de ucwords()

$texto = "susanita tiene un ratón, un ratón chiquitín.";


$texto = ucwords($texto); // $texto vale ahora: Susanita Tiene Un
// Ratón, Un Ratón Chiquitín.

Vea también strtoupper(), strtolower() y ucfirst().

vprintf (PHP 4 >= 4.1.0)


Output a formatted string

void vprintf ( string format, array args) \linebreak


Display array values as a formatted string according to format (which is described in the
documentation for sprintf()).
Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.
See also: printf(), sprintf(), vsprintf()

vsprintf (PHP 4 >= 4.1.0)


Return a formatted string

1446
Cadenas

string vsprintf ( string format, array args) \linebreak


Return array values as a formatted string according to format (which is described in the documentation
for sprintf()).
Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.
See also: sprintf(), vsprintf(), vprintf()

wordwrap (PHP 4 >= 4.0.2)


Corta una cadena en un número dado de caracteres usando un caracter de ruptura de cadenas.

string wordwrap ( string cad [, int ancho [, string ruptura]]) \linebreak


Corta la cadena cad en la columna especificada por el parámetro (opcional) ancho. La línea se rompe
utilizando el parámetro (opcional) ruptura.
wordwrap() automáticamente cortará en la columna 75 y usará ’\n’ (nueva línea) si no se especifican el
ancho o la ruptura.

Ejemplo 1. Ejemplo de wordwrap()

$texto = "El veloz murciélago hindú comía feliz cardillo y kiwi.";


$textonuevo = wordwrap( $texto, 20 );

echo "$textonuevo\n";

Este ejemplo mostraría:

El veloz murciélago
hindú comía feliz cardillo y kiwi.

Vea también nl2br().

1447
XCVIII. Funciones de Sybase

1448
Sybase

sybase_affected_rows (PHP 3>= 3.0.6, PHP 4 )


obtiene el número de filas afectadas por la última consulta

int sybase_affected_rows ( [int link_identifier]) \linebreak


Devuelve: El número de filas afectadas por la última consulta.
sybase_affected_rows() devuelve el número de filas afectadas por la última acción e tipo INSERT,
UPDATE o DELETE en el servidor asociado al identificador de enlace especificado. Si no se especifica
un identificador de enlace, se asume el último enlace abierto.
Esta instrucción no es efectiva para sentencias de tipo SELECT, sólo en sentencias que modifican
registros. Para obtener el número de filas afectadas por un SELECT, use sybase_num_rows().

Nota: Esta función sólo esta disponible usando el interface de la librería CT, y no con la librería DB.

sybase_close (PHP 3, PHP 4 )


cierra una conexión Sybase

int sybase_close ( int link_identifier) \linebreak


Devuelve: TRUE si lo consigue, FALSE ante un error
sybase_close() cierra el enlace a la base de datos Sybase asociada con el identificador de enlace
especificado. Si no se especifica un identificador de enlace, se asume el último enlace abierto.
Note que esto no es necesario usualmente, ya que los enlaces no persistentes abiertos son cerrados
automaticamente al final de la ejecución del script.
sybase_close() no cerrará enlaces persistentes generados por sybase_pconnect().
Vea también: sybase_connect(), sybase_pconnect().

sybase_connect (PHP 3, PHP 4 )


abre una conexión con un servidor Sybase

int sybase_connect ( string servername, string username, string password) \linebreak


Devuelve: Un identificador de enlace Sybase positivo, o FALSE ante un error.
sybase_connect() establece una conexión son un servidor Sybase. El parámetro servername tiene que ser
un nombre de servidor válido que esta definido en el fichero ’interfaces’.

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().

sybase_data_seek (PHP 3, PHP 4 )


mueve el puntero interno de la fila

int sybase_data_seek ( int result_identifier, int row_number) \linebreak


Devuelve: TRUE si lo hace, FALSE en caso de fallo
sybase_data_seek() mueve el puntero interno de la fila del resultado asociado con el identificador de
resultado especificado hacia el número de fila introducido. La siguiente llamada a sybase_fetch_row()
devolverá esa fila.
Vea también: sybase_data_seek().

sybase_fetch_array (PHP 3, PHP 4 )


carga una fila como un array

int sybase_fetch_array ( int result) \linebreak


Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
sybase_fetch_array() es la versión extendida de sybase_fetch_row(). Además de almacenar los datos en
los indices numericos del array de resultados, también almacena los datos en indices asociativos, usando
los nombres de campo como claves.
Una cosa importante a remarcar es que el uso de sybase_fetch_array() NO es significativamente más
lento que el uso de sybase_fetch_row(), mientrás que proporciona un valor añadido significativo.
Para más detalles, vea también sybase_fetch_row()

sybase_fetch_field (PHP 3, PHP 4 )


obtiene la información del campo

object sybase_fetch_field ( int result, int field_offset) \linebreak


Devuelve un objeto conteniendo la información del campo

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

sybase_fetch_object (PHP 3, PHP 4 )


carga una fila como un objeto

int sybase_fetch_object ( int result) \linebreak


Devuelve: Un objeto con las propiedades que corresponden a la fila tomada, o FALSE si no hay más filas.
sybase_fetch_object() es similar a sybase_fetch_array(), con una diferencia - se devuelve un objeto, en
vez de un array. Indirectamente, esto significa que sólo se puede acceder a los datos por los nombres de
campo, y no por sus offsets (los números son nombres de propiedades ilegales).
En el tema de velocidad, la función es idéntica a sybase_fetch_array(), y al menos tan rápida como
sybase_fetch_row() (la diferencia es insignificante).
Vea también: sybase_fetch-array() y sybase_fetch-row().

sybase_fetch_row (PHP 3, PHP 4 )


obtiene una fila como un array enumerado

array sybase_fetch_row ( int result) \linebreak


Devuelve: Un array que corresponde a la fila obtenida, o FALSE si no hay más filas.
sybase_fetch_row() obtiene una fila de datos del resultado asociado con el identificador de resultado
especificado. La fila se devuelve como un array. Cada columna del resultado es almacenada en un offset
del arrat, comenzando en el offset 0.
Las siguientes llamadas a sybase_fetch_rows() devolverán la siguiente fila del conjunto de resultados, o
FALSE si no hay más filas.

Vea también: sybase_fetch_array(), sybase_fetch_object(), sybase_data_seek(), sybase_fetch_lengths(),


y sybase_result().

1451
Sybase

sybase_field_seek (PHP 3, PHP 4 )


establece el offset de un campo

int sybase_field_seek ( int result, int field_offset) \linebreak


Localiza el campo especificado por el offset. Si la siguiente llamada sybase_fetch_field() no incluye un
offset se devuelve este campo.

Vea también: sybase_fetch_field().

sybase_free_result (PHP 3, PHP 4 )


libera el resultado de la memoria

int sybase_free_result ( int result) \linebreak


sybase_free_result() sólo se necesita usar en el caso de que este preocupado por el uso de demasiada
memoria mientras se ejecuta su script. Todos los resultados en memoria son liberados cuando el script
finaliza, puede llamar a sybase_free_result() con el identificador de resultado como argumento y la
memoria asociada a ese resultado será liberada.

sybase_get_last_message (PHP 3, PHP 4 )


Returns the last message from the server

string sybase_get_last_message ( void) \linebreak


sybase_get_last_message() returns the last message reported by the server.

sybase_min_client_severity (PHP 3, PHP 4 )


Sets minimum client severity

void sybase_min_client_severity ( int severity) \linebreak


sybase_min_client_severity() sets the minimum client severity level.

Nota: This function is only available using the CT library interface to Sybase, and not the DB library.

See also: sybase_min_server_severity().

1452
Sybase

sybase_min_error_severity (PHP 3, PHP 4 )


Sets minimum error severity

void sybase_min_error_severity ( int severity) \linebreak


sybase_min_error_severity() sets the minimum error severity level.
See also: sybase_min_message_severity().

sybase_min_message_severity (PHP 3, PHP 4 )


Sets minimum message severity

void sybase_min_message_severity ( int severity) \linebreak


sybase_min_message_severity() sets the minimum message severity level.
See also: sybase_min_error_severity().

sybase_min_server_severity (PHP 3, PHP 4 )


Sets minimum server severity

void sybase_min_server_severity ( int severity) \linebreak


sybase_min_server_severity() sets the minimum server severity level.

Nota: This function is only available using the CT library interface to Sybase, and not the DB library.

See also: sybase_min_client_severity().

sybase_num_fields (PHP 3, PHP 4 )


obtiene el número de campos de un resultado

int sybase_num_fields ( int result) \linebreak


sybase_num_fields() devuelve el número de campos en un conjunto de resultados.
Vea también: sybase_db_query(), sybase_query(), sybase_fetch_field(), sybase_num_rows().

1453
Sybase

sybase_num_rows (PHP 3, PHP 4 )


obtiene el número de filas de un resultado

int sybase_num_rows ( string result) \linebreak


sybase_num_rows() devuelve el número de filas de un conjunto de resultados.
Vea también: sybase_db_query(), sybase_query() and, sybase_fetch_row().

sybase_pconnect (PHP 3, PHP 4 )


abre una conexión con Sybase persistente

int sybase_pconnect ( string servername, string username, string password) \linebreak


Devuelve: Un identificador de enlace persistente de Sybase positivo en caso de que pueda abrirlo, en
caso de error devuelve FALSE
sybase_pconnect() actua de una forma muy parecida a sybase_connect() con dos grandes diferencias.
Primera, cuando se conecta, esta función primero tratará de encontrar un enlace (persistente) que ya este
abierto con el mismo host, nombre de usuario y contraseña. Si encuentra uno, devolverá un identificador
para él en vez de abrir una nueva conexión.
Segunda, la conexión al servidor SQL no se cerrará cuando finalice la ejecución del script. En vez de
esto, el enlace permanecerá abierto para un futuro uso (sybase_close() no podrá cerrar enlaces
establecidos consybase_pconnect()).
Este tipo de enlaces son llamados ’persistentes’.

sybase_query (PHP 3, PHP 4 )


envía una consulta a Sybase

int sybase_query ( string query, int link_identifier) \linebreak


Devuelve: Un identificador de resultado Sybase positivo si va bien, o FALSE ante un error.
sybase_query() envía una consulta a la actual base de datos activa en el servidor que está asociada con el
identificador de enlace especificado. Si no se especifica un identificador de enlace, se asume el último
enlace abierto. Si no hay un enlace abierto, la función intentará establecer un enlace como si
sybase_connect() fuese llamada, y lo usará.
Vea también: sybase_db_query(), sybase_select_db(), y sybase_connect().

1454
Sybase

sybase_result (PHP 3, PHP 4 )


obtiene datos de un resultado

int sybase_result ( int result, int i, mixed field) \linebreak


Devuelve: El contenido de la celda en la fila y el offset especificado de un conjunto de resultados de
Sybase.
sybase_result() devuelve el contenido de una celda de un conjunto de resultados de Sybase. El parámetro
field puede ser el offset del campo, o el nombre del campo, o el nombre de la tabla, un punto y el nombre
del campo (nombre_tabla.nombre_campo). Si el nombre de la columna tiene un alias (’select foo as bar
from...’), use el alias en vez del nombre de la columna.
Cuando trabaje con conjuntos de resultados grandes, debe considerar el uso de alguna de las funciones
que cargan una fila entera (especificadas abajo). Ya que estas funciones devuelven el contenido de
multiples celdas en una única llamada, son MUCHO más rápidas que sybase_result(). Además, note que
especificar un offset númerico en el parámetro field es mucho más rápido que especificar un nombre de
campo o nombre_tabla.nombre_campo.
Alternativas recomendadas para alto rendimiento: sybase_fetch_row(), sybase_fetch_array(), y
sybase_fetch_object().

sybase_select_db (PHP 3, PHP 4 )


seleccciona una base de datos Sybase

int sybase_select_db ( string database_name, int link_identifier) \linebreak


Returns: TRUE on success, FALSE on error
sybase_select_db() establece como activa la base de datos en el servidor asociada con el identificador de
enlace especificado. Si no se especifica un identificador de enlace, se asume el último enlace abierto. Si
no hay un enlace abierto, la función intentará establecer un enlace como si sybase_connect() fuese
llamada, y lo usará.
Cada llamada subsiguiente a sybase_query() será hecha en la base de datos activa.
Vea también: sybase_connect(), sybase_pconnect(), y sybase_query()

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

token_get_all (PHP 4 >= 4.2.0)


Split given source in tokens

array token_get_all ( string source) \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.

token_name (PHP 4 >= 4.2.0)


Get the name of a given token

string token_name ( int type) \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.

1457
C. Funciones URL

1458
URLs

base64_decode (PHP 3, PHP 4 )


decodifica datos cifrados con MIME base64

string base64_decode ( string datos_cifrados) \linebreak


base64_decode() decodifica datos_cifrados y devuelve los datos originales. Los datos devueltos
pueden ser binarios.
Vea también: base64_encode(), RFC-2045 sección 6.8.

base64_encode (PHP 3, PHP 4 )


Codifica datos en MIME base64

string base64_encode ( string datos) \linebreak


base64_encode() devuelve datos cifrados en base64. Esta codificación está pensada para que los datos
binarios sobrevivan al transporte a través de capas que no son de 8 bits, como por ejemplo los cuerpos de
los mensajes de correo.
Los datos codificados con Base64 ocupan aproximadamente un 33% más de espacio que los datos
originales.
Vea también: base64_decode(), chunk_split(), RFC-2045 sección 6.8.

parse_url (PHP 3, PHP 4 )


Analiza una URL y devuelve sus componentes

array parse_url ( string url) \linebreak


Esta función devuelve una matriz que apunta a alguno de los componentes de la URL que estén
presentes. Esto incluye el "esquema", "host", "puerto", "usuario", "pass", "path", "consulta", y
"fragmento".

rawurldecode (PHP 3, PHP 4 )


Decode URL-encoded strings

string rawurldecode ( string str) \linebreak


Returns a string in which the sequences with percent (%) signs followed by two hex digits have been
replaced with literal characters. For example, the string

foo%20bar%40baz

1459
URLs

decodes into

foo bar@baz

Nota: rawurldecode() does not decode plus symbols (’+’) into spaces. urldecode() does.

See also rawurlencode(), urldecode(), urlencode().

rawurlencode (PHP 3, PHP 4 )


URL-encode according to RFC1738

string rawurlencode ( string str) \linebreak


Returns a string in which all non-alphanumeric characters except

-_.

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:

Ejemplo 1. rawurlencode() example 1

echo ’<a href="ftp://user:’, rawurlencode(’foo @+%/’),


’@ftp.my.com/x.txt">’;

Or, if you pass information in a PATH_INFO component of the URL:

Ejemplo 2. rawurlencode() example 2

echo ’<a href="http://x.com/department_list_script/’,


rawurlencode(’sales and marketing/Miami’), ’">’;

See also rawurldecode(), urldecode(), urlencode().

1460
URLs

urldecode (PHP 3, PHP 4 )


decodifica URL-cifradas en una cadena de texto

string urldecode ( string cadena) \linebreak


Decodifica cualquier %## cifrado en la cadena dada. Se devuelve la cadena decodificada.

Ejemplo 1. Ejemplo urldecode()

$a = split (’&’, $querystring);


$i = 0;
while ($i < count ($a)) {
$b = split (’=’, $a [$i]);
echo ’El valor para el parámetro ’, htmlspecialchars (urldecode ($b [0])),
’ es ’, htmlspecialchars (urldecode ($b [1])), "<BR>";
$i++;
}

Vea también urlencode()

urlencode (PHP 3, PHP 4 )


Codifica una URL en una cadena de texto

string urlencode ( string cadena) \linebreak


Devuelve una cadena en la que todos los carácteres no alfanuméricos excepto -_. han sido
reemplazados con un signo de porcentaje (%) seguido por dos dígitos hexadecimales y los espacios han
sido codificados como signos positivos (+). Está codificado de la misma manera que los datos que se
envian desde un formulario WWW, es decir de la misma forma que el tipo
application/x-www-form-urlencoded. Esto difiere del cifrado RFC1738 (vea rawurlencode() ) en
el que por razones históricas, los espacios son codificados como signos positivos (+ ). Esta función es
conveniente para codificar una cadena de texto que va a ser usada como parte de una consulta de una
URL, y es una forma adecuada de pasar variables a la página siguiente:

Ejemplo 1. Ejemplo urlencode()

echo ’<A HREF="mycgi?foo=’, urlencode ($userinput), ’">’;

Vea también urldecode()

1461
CI. Funciones sobre variables

1462
Variables

doubleval (PHP 3, PHP 4 )


Obtiene el valor double (decimal) de una variable.

double doubleval ( mixed var) \linebreak


Devuelve el valor double (decimal en punto flotante) de var.
var puede ser cualquier tipo escalar. No se puede usar doubleval() sobre arrays u objetos.
Ver también intval(), strval(), settype() y Type juggling.

empty (unknown)
Determina si una variable está definida

int empty ( mixed var) \linebreak


Devuelve FALSE si var está definida y tiene un valor no-vacío o distinto de cero; en otro caso devuelve
TRUE.

Ver también isset() y unset().

floatval (PHP 4 >= 4.2.0)


Get float value of a variable

float floatval ( mixed var) \linebreak


Returns the float value of var.
Var may be any scalar type. You cannot use floatval() on arrays or objects.

$var = ’122.34343The’;
$float_value_of_var = floatval ($var);
print $float_value_of_var; // prints 122.34343

See also intval(), strval(), settype() and Type juggling.

1463
Variables

get_defined_vars (PHP 4 >= 4.0.4)


Returns an array of all defined variables

array get_defined_vars ( void) \linebreak


This function returns an multidimensional array containing a list of all defined variables, be them
environment, server or user-defined variables.

$b = array(1,1,2,3,5,8);

$arr = get_defined_vars();

// print $b
print_r($arr["b"]);

// print path to the PHP interpreter (if used as a CGI)


// e.g. /usr/local/bin/php
echo $arr["_"];

// print the command-line paramaters if any


print_r($arr["argv"]);

// print all the server vars


print_r($arr["_SERVER"]);

// print all the available keys for the arrays of variables


print_r(array_keys(get_defined_vars()));

See also get_defined_functions() and get_defined_constants().

get_resource_type (PHP 4 >= 4.0.2)


Returns the resource type

string get_resource_type ( resource handle) \linebreak


This function returns a string representing the type of the resource passed to it. If the paramater is not a
valid resource, it generates an error.

$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

gettype (PHP 3, PHP 4 )


Obtiene el tipo de una variable.

string gettype ( mixed var) \linebreak


Devuelve el tipo de la variable PHP var.
Los valores posibles de la cadena devuelta son:

• "integer"
• "double"
• "string"
• "array"
• "object"
• "unknown type"

Ver también settype().

import_request_variables (PHP 4 >= 4.1.0)


Import GET/POST/Cookie variables into the global scope

bool import_request_variables ( string types [, string prefix]) \linebreak


Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals,
but would like to see some variables in the global scope.
Using the types parameter, you can specify which request variables to import. You can use ’G’, ’P’ and
’C’ characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you
can also use any combination of ’g’, ’p’ and ’c’. POST includes the POST uploaded file information.
Note that the order of the letters matters, as when using "gp", the POST variables will overwrite GET
variables with the same name. Any other letters than GPC are discarded.

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.

// This will import GET and POST vars


// with an "rvar_" prefix
import_request_variables("gP", "rvar_");

print $rvar_foo;

See also $_REQUEST, register_globals, Predefined Variables, and extract().

intval (PHP 3, PHP 4 )


Obtiene el valor entero de una variable.

int intval ( mixed var [, int base]) \linebreak


Devuelve el valor entero de var, usando la base de conversión especificada (por defecto es base 10).
var puede ser cualquier tipo escalar. No se puede usar intval() sobre arrays u objetos.
Ver también doubleval(), strval(), settype() y Type juggling.

is_array (PHP 3, PHP 4 )


Averigua si una variable es un array.

int is_array ( mixed var) \linebreak


Devuelve TRUE si var es un array, y FALSE en otro caso.
Ver también is_double(), is_float(), is_int(), is_integer(), is_real(), is_string(), is_long(), y is_object().

1466
Variables

is_bool (PHP 4 )
Finds out whether a variable is a boolean

bool is_bool ( mixed var) \linebreak


Returns TRUE if the var parameter is a boolean.
See also is_array(), is_float(), is_int(), is_integer(), is_string(), and is_object().

is_callable (PHP 4 >= 4.0.6)


Find out whether the argument is a valid callable construct

bool is_callable ( mixed var [, bool syntax_only [, string callable_name]]) \linebreak

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

is_double (PHP 3, PHP 4 )


Averigua si una variable es un valor double (número decimal).

int is_double ( mixed var) \linebreak


Devuelve TRUE si var es un double (número decimal), y FALSE en otro caso.
Ver también is_array(), is_float(), is_int(), is_integer(), is_real(), is_string(), is_long(), y is_object().

is_float (PHP 3, PHP 4 )


Averigua si una variable es un flotante.

int is_float ( mixed var) \linebreak


Esta función es un alias de is_double().
Ver también is_double(), is_real(), is_int(), is_integer(), is_string(), is_object(), is_array(), y is_long().

1467
Variables

is_int (PHP 3, PHP 4 )


Averigua si una variable es un valor entero.

int is_int ( mixed var) \linebreak


Esta función es un alias de is_long().
Ver también is_double(), is_float(), is_integer(), is_string(), is_real(), is_object(), is_array(), y is_long().

is_integer (PHP 3, PHP 4 )


Averigua si una variable es un valor entero.

int is_integer ( mixed var) \linebreak


Esta función es un alias de is_long().
Ver también is_double(), is_float(), is_int(), is_string(), is_real(), is_object(), is_array(), y is_long().

is_long (PHP 3, PHP 4 )


Averigua si una varible es un valor entero.

int is_long ( mixed var) \linebreak


Devuelve TRUE si var es un entero (long), y FALSE en otro caso.
Ver también is_double(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array(), y is_integer().

is_null (PHP 4 >= 4.0.4)


Finds whether a variable is NULL

bool is_null ( mixed var) \linebreak


Returns TRUE if var is null, FALSE otherwise.
See the NULL type when a variable is considered to be NULL and when not.
See also NULL, is_bool(), is_numeric(), is_float(), is_int(), is_string(), is_object(), is_array(), is_integer(),
and is_real()

1468
Variables

is_numeric (PHP 4 )
Finds whether a variable is a number or a numeric string

bool is_numeric ( mixed var) \linebreak


Returns TRUE if var is a number or a numeric string, FALSE otherwise.
See also is_bool(), is_float(), is_int(), is_string(), is_object(), is_array(), and is_integer().

is_object (PHP 3, PHP 4 )


Averigua si una varible es un objeto.

int is_object ( mixed var) \linebreak


Devuelve TRUE si var es un objeto, y FALSE en otro caso.
Ver también is_long(), is_int(), is_integer(), is_float(), is_double(), is_real(), is_string(), y is_array().

is_real (PHP 3, PHP 4 )


Averigua si una varible es un número real.

int is_real ( mixed var) \linebreak


Esta función es un alias de is_double().
Ver también is_long(), is_int(), is_integer(), is_float(), is_double(), is_object(), is_string(), y is_array().

is_resource (PHP 4 )
Finds whether a variable is a resource

bool is_resource ( mixed var) \linebreak


is_resource() returns TRUE if the variable given by the var parameter is a resource, otherwise it returns
FALSE.

See the documentation on the resource-type for more information.

is_scalar (PHP 4 >= 4.0.5)


Finds whether a variable is a scalar

1469
Variables

bool is_scalar ( mixed var) \linebreak


is_scalar() returns TRUE if the variable given by the var parameter is a scalar, otherwise it returns
FALSE.

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().

is_string (PHP 3, PHP 4 )


Averigua si una varible es una cadena de caracteres (string).

1470
Variables

int is_string ( mixed var) \linebreak


Devuelve TRUE si var es una cadena, y FALSE en otro caso.
Ver también is_long(), is_int(), is_integer(), is_float(), is_double(), is_real(), is_object(), y is_array().

isset (unknown)
Determina si una varible está definida

int isset ( mixed var) \linebreak


Devuelve TRUE si var existe; y FALSE en otro caso.
Si una variable ha sido destruida con unset(), ya no estará definida (no será isset()).

$a = "test";
echo isset($a); // true
unset($a);
echo isset($a); // false

Ver también empty() y unset().

print_r (PHP 4 )
Prints human-readable information about a variable

void print_r ( mixed expression) \linebreak


print_r() displays information about a variable in a way that’s readable by humans. If given a string,
integer or float, the value itself will be printed. If given an array, values will be presented in a format that
shows keys and elements. Similar notation is used for objects.
Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.

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>

Which will output:

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

See also ob_start(), var_dump(), and var_export().

serialize (PHP 3>= 3.0.5, PHP 4 )


Generates a storable representation of a value

string serialize ( mixed value) \linebreak


serialize() returns a string containing a byte-stream representation of value that can be stored
anywhere.
This is useful for storing or passing PHP values around without losing their type and structure.
To make the serialized string into a PHP value again, use unserialize(). serialize() handles all types,
except the resource-type. You can even serialize() arrays that contain references to itself. References
inside the array/object you are serialize()ing will also be stored.

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.

Ejemplo 1. serialize() example

// $session_data contains a multi-dimensional array with session


// information for the current user. We use serialize() to store
// it in a database at the end of the request.

$conn = odbc_connect ("webdb", "php", "chicken");


$stmt = odbc_prepare ($conn,
"UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqldata)) {
$stmt = odbc_prepare($conn,
"INSERT INTO sessions (id, data) VALUES(?, ?)");
if (!odbc_execute($stmt, &$sqldata)) {
/* Something went wrong. Bitch, whine and moan. */
}
}

See Also: unserialize().

settype (PHP 3, PHP 4 )


Establece el tipo de una variable.

int settype ( string var, string type) \linebreak


Establece el tipo de la varible var como type.
Los valores posibles para type son:

• "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().

strval (PHP 3, PHP 4 )


Obtiene una cadena de caracteres a partir de una variable.

string strval ( mixed var) \linebreak


Devuelve una cadena con el valor de var.
var puede ser cualquier tipo escalar. No se puede usar strval() sobre arrays u objetos.
Ver también doubleval(), intval(), settype() y Type juggling.

unserialize (PHP 3>= 3.0.5, PHP 4 )


Creates a PHP value from a stored representation

mixed unserialize ( string str) \linebreak


unserialize() takes a single serialized variable (see serialize()) and converts it back into a PHP value. The
converted value is returned, and can be an integer, float, string, array or object.

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.

Ejemplo 1. unserialize_callback_func example

$serialized_object=’O:1:"a":1:{s:5:"value";s:3:"100";}’;

ini_set(’unserialize_callback_func’,’mycallback’); // set your callback_function

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.

Ejemplo 2. unserialize() example

// Here, we use unserialize() to load session data to the


// $session_data array from the string selected from a database.
// This example complements the one described with serialize().

$conn = odbc_connect ("webdb", "php", "chicken");


$stmt = odbc_prepare ($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array ($PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqldata) || !odbc_fetch_into ($stmt, &$tmp)) {
// if the execute or fetch fails, initialize to empty array
$session_data = array();
} else {
// we should now have the serialized data in $tmp[0].
$session_data = unserialize ($tmp[0]);
if (!is_array ($session_data)) {
// something went wrong, initialize to empty array
$session_data = array();
}
}

See Also: serialize().

unset (unknown)
Destruye una variable dada

int unset ( mixed var) \linebreak


unset() destruye la variable especificada y devuelve TRUE.

Ejemplo 1. Ejemplo de unset()

unset( $foo );
unset( $bar[’quux’] );

1475
Variables

Ver también isset() y empty().

var_dump (PHP 3>= 3.0.5, PHP 4 )


Dumps information about a variable

void var_dump ( mixed expression [, mixed expression [, ...]]) \linebreak


This function returns structured information about one or more expressions that includes its type and
value. Arrays are explored recursively with values indented to show structure.

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.

Compare var_dump() to print_r().

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

var_export (PHP 4 >= 4.2.0)


Outputs or returns a string representation of a variable

mixed var_export ( mixed expression [, bool return]) \linebreak


This function returns structured information about the variable that is passed to this function. It is similar
to var_dump() with the exception that the returned representation is valid PHP code.
You can also return the variable representation by using TRUE as second parameter to this function.
Compare var_export() to var_dump().

<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

vpopmail_add_alias_domain_ex (PHP 4 >= 4.0.5)


Add alias to an existing virtual domain

bool vpopmail_add_alias_domain_ex ( string olddomain, string newdomain) \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.

vpopmail_add_alias_domain (PHP 4 >= 4.0.5)


Add an alias for a virtual domain

bool vpopmail_add_alias_domain ( string domain, string aliasdomain) \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.

1480
vpopmail functions

vpopmail_add_domain_ex (PHP 4 >= 4.0.5)


Add a new virtual domain

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.

vpopmail_add_domain (PHP 4 >= 4.0.5)


Add a new virtual domain

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

vpopmail_add_user (PHP 4 >= 4.0.5)


Add a new user to the specified virtual domain

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.

vpopmail_alias_add (PHP 4 >= 4.1.0)


insert a virtual alias

bool vpopmail_alias_add ( string user, string domain, string alias) \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.

1482
vpopmail functions

vpopmail_alias_del_domain (PHP 4 >= 4.1.0)


deletes all virtual aliases of a domain

bool vpopmail_alias_del_domain ( string domain) \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.

vpopmail_alias_del (PHP 4 >= 4.1.0)


deletes all virtual aliases of a user

bool vpopmail_alias_del ( string user, string domain) \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.

1483
vpopmail functions

vpopmail_alias_get_all (PHP 4 >= 4.1.0)


get all lines of an alias for a domain

array vpopmail_alias_get_all ( string domain) \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.

vpopmail_alias_get (PHP 4 >= 4.1.0)


get all lines of an alias for a domain

array vpopmail_alias_get ( string alias, string domain) \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.

1484
vpopmail functions

vpopmail_auth_user (PHP 4 >= 4.0.5)


Attempt to validate a username/domain/password. Returns true/false

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.

vpopmail_del_domain_ex (PHP 4 >= 4.0.5)


Delete a virtual domain

bool vpopmail_del_domain_ex ( string domain) \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.

1485
vpopmail functions

vpopmail_del_domain (PHP 4 >= 4.0.5)


Delete a virtual domain

bool vpopmail_del_domain ( string domain) \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.

vpopmail_del_user (PHP 4 >= 4.0.5)


Delete a user from a virtual domain

bool vpopmail_del_user ( string user, string domain) \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.

1486
vpopmail functions

vpopmail_error (PHP 4 >= 4.0.5)


Get text message for last vpopmail error. Returns string

string vpopmail_error ( void) \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.

vpopmail_passwd (PHP 4 >= 4.0.5)


Change a virtual user’s password

bool vpopmail_passwd ( string user, string domain, string password) \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.

1487
vpopmail functions

vpopmail_set_user_quota (PHP 4 >= 4.0.5)


Sets a virtual user’s quota

bool vpopmail_set_user_quota ( string user, string domain, string quota) \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.

1488
CIII. W32api functions

1489
W32api functions

w32api_deftype (PHP 4 >= 4.2.0)


Defines a type for use with other w32api_functions

int w32api_deftype ( string typename, string member1_type, string member1_name) \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.

w32api_init_dtype (PHP 4 >= 4.2.0)


Creates an instance to the data type typename and fills it with the values val1, val2, the function then
returns a DYNAPARM which can be passed when invoking a function as a parameter

resource w32api_init_dtype ( string typename, mixed val1, mixed val2) \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.

1490
W32api functions

w32api_invoke_function (PHP 4 >= 4.2.0)


Invokes function funcname with the arguments passed after the function name

mixed w32api_invoke_function ( string funcname) \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.

w32api_register_function (PHP 4 >= 4.2.0)


Registers function function_name from library with PHP

bool w32api_register_function ( string libary, string function_name) \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.

1491
W32api functions

w32api_set_call_method (PHP 4 >= 4.2.0)


Sets the calling method used

void w32api_set_call_method ( int method) \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.

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.

Ejemplo 1. Serializacion de un valor simple

<?php
print wddx_serialize_value("Ejemplo de PHP a paquete WDDX", "Paquete PHP");
?>

Este ejemplo producira:

<wddxPacket version=’0.9’><header comment=’Paquete PHP’/><data>


<string>Ejemplo de PHP a paquete WDDX</string></data></wddxPacket>

Ejemplo 2. Uso de paquetes incrementales

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suponga que $ciudades se ha obtenido de una base de datos */


$ciudades = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "ciudades");

$packet = wddx_packet_end($packet_id);
print $packet;
?>

Este ejemplo producira:

<wddxPacket version=’0.9’><header comment=’PHP’/><data><struct>


<var name=’pi’><number>3.1415926</number></var><var name=’ciudades’>
<array length=’3’><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

1493
WDDX

wddx_add_vars (PHP 3>= 3.0.7, PHP 4 )


Finaliza un paquete WDDX con el identificador dado

wddx_add_vars ( entero packet_id, varios-tipos name_var [, varios-tipos ...]) \linebreak


wddx_add_vars() se utiliza para serializar las variables dadas e incorporar el resultado al paquete
especificado por packet_id. Las variables a serializar se especifican exactamente igual que en
wddx_serialize_vars().

wddx_deserialize (PHP 3>= 3.0.7, PHP 4 )


Des-serializa un paquete WDDX

varios-tipos wddx_deserialize ( cadena packet) \linebreak


wddx_deserialized() toma una cadena packet y la desserializa. Devuelve el resultado que puede ser de
tipo cadena, numerico o array. Las estructuras son desserializadas en forma de arrays asociativos.

wddx_packet_end (PHP 3>= 3.0.7, PHP 4 )


Finaliza un paquete WDDX con el identificador dado

cadena wddx_packet_end ( entero packet_id) \linebreak


wddx_packet_end() finaliza el paquete WDDX especificado por el packet_id y devuelve la cadena
con el paquete.

wddx_packet_start (PHP 3>= 3.0.7, PHP 4 )


Comienza un nuevo paquete WDDX con una estructura dentro

entero wddx_packet_start ( [cadena comentario]) \linebreak


Utilice wddx_packet_start() para comenzar un nuevo paquete WDDX que permita la adicion sucesiva
de variables. Recibe el parametro opcional comentario y devuelve un identificador de paquete para su
uso en posteriores llamadas. Automaticamente define una estructura dentro del paquete para contener las
variables.

1494
WDDX

wddx_serialize_value (PHP 3>= 3.0.7, PHP 4 )


Serializa un valor simple en un paquete WDDX

cadena wddx_serialize_value ( varios-tipos var [, cadena comentario]) \linebreak


wddx_serialize_value() se utiliza para crear un paquete WDDX desde un valor simple dado. Toma el
valor contenido en var, y una cadena comentario opcional que aparecera en la cabecera del paquete,
y devuelve el paquete WDDX.

wddx_serialize_vars (PHP 3>= 3.0.7, PHP 4 )


Serializa variables en un paquete WDDX

cadena wddx_serialize_vars ( varios-tipos nombre_var [, varios-tipos ...]) \linebreak


wddx_serialize_vars() se utiliza para crear un paquete WDDX con una estructura que contiene la
representacion serializada de las variables pasadas como parametros.
wddx_serialize_vars() toma un numero variable de argumentos, cada uno de los cuales puede ser una
cadena con el nombre de una variable o un array con nombres de variables, o de otro array, etc.

Ejemplo 1. wddx_serialize_vars example

<?php
$a = 1;
$b = 5.5;
$c = array("azul", "naranja", "violeta");
$d = "colores";

$clvars = array("c", "d");


print wddx_serialize_vars("a", "b", $clvars);
?>

El ejemplo anterior producira:

<wddxPacket version=’0.9’><header/><data><struct><var name=’a’><number>1</number></var>


<var name=’b’><number>5.5</number></var><var name=’c’><array length=’3’>
<string>azul</string><string>naranja</string><string>violeta</string></array></var>
<var name=’d’><string>colores</string></var></struct></data></wddxPacket>

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 $@

Se puede conseguir un paquete RPM de expat en http://sourceforge.net/projects/expat/.


Nota que si se usa Apache-1.3.7 o posterior, ya tienes la biblioteca requerida expat. Simplemente,
configura PHP usando --with-xml (sin ninguna ruta adicional) y usará automáticamente la biblioteca
expat incluida en Apache.
En UNIX, ejecuta configure con la opción --with-xml. La biblioteca expat debería ser instalada en
algún lugar donde el compilador pueda encontrarlo. Si se compila PHP como un módulo para Apache
1.3.9 o posterior, PHP automáticamente usará la biblioteca integrada expat de Apache. Puede necesitar
establecer CPPFLAGS y LDFLAGS en su entorno antes de ejecutar "configure" si se ha instalado expat
en algún lugar exótico.
Compila PHP. ¡Ta-tam! Ya debería estar.

Sobre Esta Extensión


Esta extensión de PHP implementa soporte para expat de James Clarkin en PHP. Este conjunto de
herramientas permite interpretar, pero no validar, documentos XML. Soporta tres codificaciones de
caracteres fuente, también proporcionados por PHP: US-ASCII, ISO-8859-1 y UTF-8. UTF-16 no está
soportado.
Esta extensión permite crear intérpretes de XML y definir entonces gestores para diferentes eventos

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:

Tabla 1. Gestores de XML soportados

Función PHP para establecer gestor Descripción del evento


xml_set_element_handler() Los eventos de elemento ("element") se producen
cuando el intérprete XML encuentra etiquetas de
comienzo o fin. Hay gestores separados para
etiquetas de comienzo y etiquetas de fin.
xml_set_character_data_handler() La información de caracteres es, por definición,
todo el contenido no "marcado" de los documentos
XML, incluidos los espacios en blanco entre
etiquetas. Nota que el intérprete XML no añade o
elimina ningún espacio en blanco, depende de la
aplicación (de ti) decidir si el espacio en blanco es
significativo.
xml_set_processing_instruction_handler() Los programadores de PHP deberían estar ya
familiarizados con las instrucciones de procesado
(PI). <?php ?> es una instrucción de procesado,
donde php se denomina el "objetivo de procesado".
El manejo de éstos es específico a cada aplicación,
salvo que todos los objetivos PI que comienzan con
"XML" están reservados.
xml_set_default_handler() Todo lo que no va a otro gestor, va al gestor por
defecto. Se tendrán en el gestor por defecto cosas
como las declaraciones de tipos de documento y
XML.
xml_set_unparsed_entity_decl_handler() Este gestor se llamará para la declaración de una
entidad no analizada (NDATA).
xml_set_notation_decl_handler() Este gestor se llama para la declaración de una
anotación.
xml_set_external_entity_ref_handler() Este gestor se llama cuando el intérprete XML
encuentra una referencia a una entidad general
interpretada externa. Puede ser una referencia a un
archivo o URL, por ejemplo. Ver el ejemplo de
entidad externa para demostración.

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

como a los nombres de las etiquetas y a los objetivos de instrucciones de procesado.


Si el intérprete XML encuentra caracteres fuera del rango que su codificación de fuente es capaz de
representar, devolverá un error.
Si PHP encuentra caracteres en el documento XML interpretado que no pueden ser representados en la
codificación de destino elegida, los caracteres problema serán "degradados". Actualmente, esto significa
que tales caracteres se reemplazan por un signo de interrogación.

Algunos Ejemplos
Aquí hay algunos ejemplos de archivos de comandos PHP que interpretan documentos XML.

Ejemplos de Estructuras de Elementos XML


Este primer ejemplo muestra la estructura del elemento inicio en un documento con indentación.

Ejemplo 1. Muestra la Estructura del Elemento XML

$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs) {


global $depth;
for ($i = 0; $i < $depth[$parser]; $i++) {
print " ";
}
print "$name\n";
$depth[$parser]++;
}

function endElement($parser, $name) {


global $depth;
$depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}

while ($data = fread($fp, 4096)) {


if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}

1499
XML

xml_parser_free($xml_parser);

Ejemplo de Mapeo de Etiquetas XML

Ejemplo 2. Traduciendo XML a HTML

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

function startElement($parser, $name, $attrs) {


global $map_array;
if ($htmltag = $map_array[$name]) {
print "<$htmltag>";
}
}

function endElement($parser, $name) {


global $map_array;
if ($htmltag = $map_array[$name]) {
print "</$htmltag>";
}
}

function characterData($parser, $data) {


print $data;
}

$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");
}

while ($data = fread($fp, 4096)) {


if (!xml_parse($xml_parser, $data, feof($fp))) {

1500
XML

die(sprintf("XML error: %s at line %d",


xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);

Ejemplo de Entidad Externa XML


Este ejemplo resalta el código XML. Ilustra cómo usar un gestor de referencia de entidades extenas para
incluir y analizar otros documentos, así como cuúntos PIs pueden ser procesados, y un modo de
determinar "confianza" para PIs que contienen código.
Los documentos XML que se pueden usar en este ejemplo se encuentran bajo el ejemplo (xmltest.xml
y xmltest2.xml.)

Ejemplo 3. Ejemplo de Entidades Externas

$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;
}

function startElement($parser, $name, $attribs) {


print "&lt;<font color=\"#0000cc\">$name</font>";
if (sizeof($attribs)) {
while (list($k, $v) = each($attribs)) {
print " <font color=\"#009900\">$k</font>=\"<font
color=\"#990000\">$v</font>\"";
}
}
print "&gt;";
}

function endElement($parser, $name) {


print "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data) {


print "<b>$data</b>";
}

1501
XML

function PIHandler($parser, $target, $data) {


switch (strtolower($target)) {
case "php":
global $parser_file;
// Si el documento analizado es "de confianza", diremos
// que es seguro ejecutar código PHP en su interior.
// Si no, en vez de ello mostrará el código.
if (trustedFile($parser_file[$parser])) {
eval($data);
} else {
printf("Untrusted PHP code: <i>%s</i>",
htmlspecialchars($data));
}
break;
}
}

function defaultHandler($parser, $data) {


if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
printf(’<font color="#aa00aa">%s</font>’,
htmlspecialchars($data));
} else {
printf(’<font size="-1">%s</font>’,
htmlspecialchars($data));
}
}

function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,


$publicId) {
if ($systemId) {
if (!list($parser, $fp) = new_xml_parser($systemId)) {
printf("Could not open entity %s at %s\n", $openEntityNames,
$systemId);
return false;
}
while ($data = fread($fp, 4096)) {
if (!xml_parse($parser, $data, feof($fp))) {
printf("XML error: %s at line %d while parsing entity %s\n",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser), $openEntityNames);
xml_parser_free($parser);
return false;
}
}
xml_parser_free($parser);
return true;
}
return false;
}

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

if (!($fp = @fopen($file, "r"))) {


return false;
}
if (!is_array($parser_file)) {
settype($parser_file, "array");
}
$parser_file[$xml_parser] = $file;
return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {


die("could not open XML input");
}

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>

Este archivo se incluye desde xmltest.xml:

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

utf8_decode (PHP 3>= 3.0.6, PHP 4 )


Convierte una cadena codificada UTF-8 a ISO-8859-1

string utf8_decode ( string data) \linebreak


Esta función decodificadata, asume codificación UTF-8 , a ISO-8859-1.
Mira utf8_encode() para una explicación de codificación UTF-8.

utf8_encode (PHP 3>= 3.0.6, PHP 4 )


codifica una cadena ISO-8859-1 a UTF-8

string utf8_encode ( string data) \linebreak


Esta función codifica la cadena data a UTF-8, y devuelve la versión codificada. UTF-8 es un
mecanismo estándar usado por Unicodepara codificar valores de caracteres amplios en un chorro de
bytes. UTF-8 es transparente a caracteres de ASCII plano, es auto-sincronizado (significa que es posible
para un programa averiguar dónde comienzan los caracteres en el chorro de bytes) y se puede usar con
funciones de comparación de cadenas normales para ordenar y otros fines. PHP codifica caracteres
UTF-8 en hasta cuatro bytes, como esto:

Tabla 1. Codificación UTF-8

bytes bits representación


1 7 0bbbbbbb
2 11 110bbbbb 10bbbbbb
3 16 1110bbbb 10bbbbbb 10bbbbbb
4 21 11110bbb 10bbbbbb 10bbbbbb
10bbbbbb

Cada b representa un bit que puede ser usado para almacenar datos de caracteres.

xml_error_string (PHP 3>= 3.0.6, PHP 4 )


obtiene la cadena de error del analizador XML

string xml_error_string ( int code) \linebreak

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.

xml_get_current_byte_index (PHP 3>= 3.0.6, PHP 4 )


obtiene el índice del byte actual para un analizador XML

int xml_get_current_byte_index ( int parser) \linebreak

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

xml_get_current_column_number (PHP 3>= 3.0.6, PHP 4 )


Obtiene el número de columna actual para un analizador XML.

int xml_get_current_column_number ( int parser) \linebreak

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.

xml_get_current_line_number (PHP 3>= 3.0.6, PHP 4 )


obtiene el número de línea actual de un analizador XML

int xml_get_current_line_number ( int parser) \linebreak

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.

xml_get_error_code (PHP 3>= 3.0.6, PHP 4 )


obtiene el código de error del analizador XML

int xml_get_error_code ( int parser) \linebreak

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.

xml_parse_into_struct (PHP 3>= 3.0.8, PHP 4 )


Parse XML data into an array structure

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:

$simple = "<para><note>simple note</note></para>";


$p = xml_parser_create();
xml_parse_into_struct($p,$simple,$vals,$index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

When we run that code, the output will be:

1507
XML

Index array
Array
(
[PARA] => Array
(
[0] => 0
[1] => 2
)

[NOTE] => Array


(
[0] => 1
)

Vals array
Array
(
[0] => Array
(
[tag] => PARA
[type] => open
[level] => 1
)

[1] => Array


(
[tag] => NOTE
[type] => complete
[level] => 2
[value] => simple note
)

[2] => Array


(
[tag] => PARA
[type] => close
[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

Ejemplo 1. moldb.xml - small database of molecular information

<?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:

Ejemplo 2. parsemoldb.php - parses moldb.xml into and array of molecular 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 AminoAcid ($aa) {


foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}

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

// loop through the structures


foreach ($tags as $key=>$val) {
if ($key == "molecule") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}

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:

** Database of AminoAcid objects:


Array
(
[0] => aminoacid Object
(
[name] => Alanine
[symbol] => ala
[code] => A
[type] => hydrophobic
)

[1] => aminoacid Object


(
[name] => Lysine
[symbol] => lys
[code] => K

1510
XML

[type] => charged


)

xml_parse (PHP 3>= 3.0.6, PHP 4 )


comienza a analizar un documento XML

int xml_parse ( int parser, string data [, int isFinal]) \linebreak

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().

xml_parser_create_ns (PHP 4 >= 4.0.5)


Create an XML parser

resource xml_parser_create_ns ( [string encoding [, string sep]]) \linebreak

1511
XML

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

xml_parser_create (PHP 3>= 3.0.6, PHP 4 )


crea un analizador de XML

int xml_parser_create ( [string encoding]) \linebreak

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.

xml_parser_free (PHP 3>= 3.0.6, PHP 4 )


Libera un analizador XML

string xml_parser_free ( int parser) \linebreak

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.

xml_parser_get_option (PHP 3>= 3.0.6, PHP 4 )


obtiene las opciones de un analizador XML

mixed xml_parser_get_option ( int parser, int option) \linebreak

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.

xml_parser_set_option (PHP 3>= 3.0.6, PHP 4 )


establece las opciones de un analizador XML

int xml_parser_set_option ( int parser, int option, mixed value) \linebreak

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:

Tabla 1. Opciones de analizador XML

Opción constante Tipo de Datos Descripción


XML_OPTION_CASE_FOLDINGinteger Controla si case-folding se
habilita para este analizador XML.
Habilitado por defecto.

1513
XML

Opción constante Tipo de Datos Descripción


XML_OPTION_TARGET_ENCODING
string Establece qué codificación
destino se usa en este analizador
XML. Por defecto, esta puesta al
mismo que la codificación fuente
usada por xml_parser_create().
Las codificaciones de destino
soportadas son ISO-8859-1,
US-ASCII y UTF-8.

xml_set_character_data_handler (PHP 3>= 3.0.6, PHP 4 )


Establece gestores de datos de caracteres

int xml_set_character_data_handler ( int parser, string handler) \linebreak


Establece la función gestora de datos de caracteres para el analizador XML parser. handler es un
string que contiene el nombre de la función que debe existir cuando xml_parse() es llamado por
parser.
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 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.

xml_set_default_handler (PHP 3>= 3.0.6, PHP 4 )


set up default handler

int xml_set_default_handler ( int parser, string handler) \linebreak


Establece la función gestora por defecto para un analizador XML parser. handler es un string que
contiene el nombre de la función que debe existir cuando xml_parse() es llamado por parser.

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.

xml_set_element_handler (PHP 3>= 3.0.6, PHP 4 )


establece gestores de los elementos principio y fin

int xml_set_element_handler ( int parser, string startElementHandler, string endElementHandler) \linebreak


Establece las funciones de gestion de elementos para el analizador XML parser.
startElementHandler y endElementHandler son strings que contienen los nombres de las
funciones que deben existir cuando xml_parse() es llamado por parser.
La función denominada startElementHandler debe aceptar tres parámetros:
startElementHandler ( int parser, string name, string attribs) \linebreak

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

La función llamada endElementHandler debe aceptar dos parámetros: endElementHandler (


int parser, string name) \linebreak

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.

xml_set_end_namespace_decl_handler (PHP 4 >= 4.0.5)


Set up character data handler

bool xml_set_end_namespace_decl_handler ( resource pind, string hdl) \linebreak

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.

xml_set_external_entity_ref_handler (PHP 3>= 3.0.6, PHP 4 )


Establece gestores de referencia de entidades externas

int xml_set_external_entity_ref_handler ( int parser, string handler) \linebreak

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.

xml_set_notation_decl_handler (PHP 3>= 3.0.6, PHP 4 )


Establece gestores de declaraciones de notación

int xml_set_notation_decl_handler ( int parser, string handler) \linebreak


Establece las funciones gestoras 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.

1517
XML

Una declaración de notación es parte del DTD del documento y tiene el siguiente formato:

<!NOTATION name
{systemId | publicId}
>

Ver la sección 4.7 de las especificaciones XML 1.0


(http://www.w3.org/TR/1998/REC-xml-19980210#Notations) para la definición de declaraciones de
notación.
La función llamada por handler debe aceptar cinco parámetros: handler ( int parser, string
notationName, string base, string systemId, string publicId) \linebreak

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

void xml_set_object ( int parser, object &object) \linebreak


Esta función hace a parser utilizable dentro de object. Todas las funciones de callback establecidas
por xml_set_element_handler() etc se asumen como métodos de object.

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

} // end of class xml

$xml_parser = new xml();


$xml_parser->parse("<A ID=\"hallo\">PHP</A>");
?>

Nota: xml_set_object() es gestionable a partir de PHP 4.0.

xml_set_processing_instruction_handler (PHP 3>= 3.0.6, PHP 4 )


Establece el gestor de instrucciones de procesado (PI)

int xml_set_processing_instruction_handler ( int parser, string handler) \linebreak


Establece ela función de gestión de instrucciones de procesado (PI) para el analizador XML parser.
handler es un string que contiene el nombre de una función que debe existir cuando xml_parse() es
llamada por parser.
Una instrucción de procedado tiene el siguiente formato:

<?

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.

xml_set_start_namespace_decl_handler (PHP 4 >= 4.0.5)


Set up character data handler

bool xml_set_start_namespace_decl_handler ( resource pind, string hdl) \linebreak

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

xml_set_unparsed_entity_decl_handler (PHP 3>= 3.0.6, PHP 4 )


Establece un gestor de declaraciones de entidades no analizadas

int xml_set_unparsed_entity_decl_handler ( int parser, string handler) \linebreak


Establece la función gestora de declaración de entidades no analizadas para el analizador XML
parser. handler es una cadena que contiene el nombre de una función que debe existir cuando
xml_parse() es llamada por parser.
Este gestor será llamado si el analizador XML encuentra una declaración de entidades externas con una
declaración NDATA, como la siguiente:

<!ENTITY name {publicId | systemId}


NDATA notationName>

Mira la sección 4.2.2 de las especificaciones XML 1.0


(http://www.w3.org/TR/1998/REC-xml-19980210#sec-external-ent) para la definición de entidades
externas de notación declarada.
La función nombrada en handler debe aceptar seis parámetros: handler ( int parser, string
entityName, string base, string systemId, string publicId, string notationName) \linebreak

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

xmlrpc_decode_request (PHP 4 >= 4.1.0)


Decodes XML into native PHP types

array xmlrpc_decode_request ( string xml, string method [, string encoding]) \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.

xmlrpc_decode (PHP 4 >= 4.1.0)


Decodes XML into native PHP types

array xmlrpc_decode ( string xml [, string encoding]) \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.

1523
XMLRPC function

xmlrpc_encode_request (PHP 4 >= 4.1.0)


Generates XML for a method request

string xmlrpc_encode_request ( string method, mixed params) \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.

xmlrpc_encode (PHP 4 >= 4.1.0)


Generates XML for a PHP value

string xmlrpc_encode ( mixed value) \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.

1524
XMLRPC function

xmlrpc_get_type (PHP 4 >= 4.1.0)


Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings

string xmlrpc_get_type ( mixed value) \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.

xmlrpc_parse_method_descriptions (PHP 4 >= 4.1.0)


Decodes XML into a list of method descriptions

array xmlrpc_parse_method_descriptions ( string xml) \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.

1525
XMLRPC function

xmlrpc_server_add_introspection_data (PHP 4 >= 4.1.0)


Adds introspection documentation

int xmlrpc_server_add_introspection_data ( resource server, array desc) \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.

xmlrpc_server_call_method (PHP 4 >= 4.1.0)


Parses XML requests and call methods

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

xmlrpc_server_create (PHP 4 >= 4.1.0)


Creates an xmlrpc server

resource xmlrpc_server_create ( void) \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.

xmlrpc_server_destroy (PHP 4 >= 4.1.0)


Destroys server resources

void xmlrpc_server_destroy ( resource server) \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.

1527
XMLRPC function

xmlrpc_server_register_introspection_callback (PHP 4 >= 4.1.0)


Register a PHP function to generate documentation

bool xmlrpc_server_register_introspection_callback ( resource server, string function) \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.

xmlrpc_server_register_method (PHP 4 >= 4.1.0)


Register a PHP function to resource method matching method_name

bool xmlrpc_server_register_method ( resource server, string method_name, string function) \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.

1528
XMLRPC function

xmlrpc_set_type (PHP 4 >= 4.1.0)


Sets xmlrpc type, base64 or datetime, for a PHP string value

bool xmlrpc_set_type ( string value, string type) \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.

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

About XSLT and Sablotron


XSLT (Extensible Stylesheet Language (XSL) Transformations) is a language for transforming XML
documents into other XML documents. It is a standard defined by The World Wide Web consortium
(W3C). Information about XSLT and related technologies can be found at http://www.w3.org/TR/xslt.

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.

About This Extension


This PHP extension implements support Sablotron from Ginger Alliance in PHP. This toolkit lets you
transform XML documents into other documents, including new XML documents, but also into HTML
or other target formats. It basically provides a standardized and portable template mechanism, separating
content and design of a website.

1530
XSLT

xslt_create (PHP 4 >= 4.0.3)


Create a new XSL processor.

resource xslt_create ( void) \linebreak


This function returns a handle for a new XSL processor. This handle is needed in all subsequent calls to
XSL functions.

xslt_errno (PHP 4 >= 4.0.3)


Return the current error number

int xslt_errno ( [ int xh]) \linebreak


Return the current error number of the given XSL processor. If no handle is given, the last error number
that occured anywhere is returned.

xslt_error (PHP 4 >= 4.0.3)


Return the current error string

mixed xslt_error ( [ int xh]) \linebreak


Return the current error string of the given XSL processor. If no handle is given, the last error string that
occured anywhere is returned.

xslt_free (PHP 4 >= 4.0.3)


Free XSLT processor

void xslt_free ( resource xh) \linebreak


Free the XSLT processor identified by the given handle.

xslt_output_process (unknown)
unknown

unknown xslt_process ( unknown) \linebreak


This function lacks a prototype definition.

1531
XSLT

xslt_set_base (PHP 4 >= 4.0.5)


Set the base URI for all XSLT transformations

void xslt_set_base ( resource xh, string uri) \linebreak


Sets the base URI for all XSLT transformations, the base URI is used with Xpath instructions to resolve
document() and other commands which access external resources.

xslt_set_encoding (PHP 4 >= 4.0.5)


Set the encoding for the parsing of XML documents

void xslt_set_encoding ( resource xh, string encoding) \linebreak


Set the output encoding for the XSLT transformations. When using the Sablotron backend this option is
only available when you compile Sablotron with encoding support.

xslt_set_error_handler (PHP 4 >= 4.0.4)


Set an error handler for a XSLT processor

void xslt_set_error_handler ( resource xh, mixed handler) \linebreak


Set an error handler function for the XSLT processor given by xh, this function will be called whenever
an error occurs in the XSLT transformation (this function is also called for notices).

xslt_set_log (PHP 4 >= 4.0.6)


Set the log file to write log messages to

void xslt_set_log ( resource xh, mixed log) \linebreak

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:

Ejemplo 1. Using the XSLT Logging features

<?php

$xh = xslt_create();
xslt_set_log($xh, true);
xslt_set_log($xh, getcwd() . ’myfile.log’);

$result = xslt_process($xh, ’dog.xml’, ’pets.xsl’);


print($result);

xslt_free($xh);
?>

xslt_set_sax_handler (4.0.3 - 4.0.6 only)


Set SAX handlers for a XSLT processor

bool xslt_set_sax_handler ( resource xh, handlers) \linebreak


Set SAX handlers on the ressource handle given by xh.

xslt_set_sax_handlers (PHP 4 >= 4.0.6)


Set the SAX handlers to be called when the XML document gets processed

void xslt_set_sax_handlers ( resource processor, array handlers) \linebreak

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

1533
XSLT

xslt_set_scheme_handler (4.0.5 - 4.0.6 only)


Set Scheme handlers for a XSLT processor

void xslt_set_scheme_handler ( resource xh, array handlers) \linebreak


Set Scheme handlers on the resource handle given by xh. Scheme handlers should be an array with the
format (all elements are optional):

array(
[get_all] => get all handler,
[open] => open handler,
[get] => get handler,
[put] => put handler,
[close] => close handler
)

xslt_set_scheme_handlers (PHP 4 >= 4.0.6)


Set the scheme handlers for the XSLT processor

void xslt_set_scheme_handlers ( resource processor, array handlers) \linebreak

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

$num_hosts = count ($host);


if (empty($term) || count($host) == 0) {
echo ’<form method="get">
<input type="checkbox"
name="host[]" value="bagel.indexdata.dk/gils">
GILS test
<input type="checkbox"
name="host[]" value="localhost:9999/Default">
local test
<input type="checkbox" checked="1"
name="host[]" value="z3950.bell-labs.com/books">
BELL Labs Library
<br>
RPN Query:
<input type="text" size="30" name="term">
<input type="submit" name="action" value="Search">
’;
} else {

1535
YAZ

echo ’You searced for ’ . htmlspecialchars($term) . ’<br>’;


for ($i = 0; $i > $num_hosts; $i++) {
$id[] = yaz_connect($host[$i]);
yaz_syntax($id[$i],"sutrs");
yaz_search($id[$i],"rpn",$term);
}
yaz_wait();
for ($i = 0; $i < $num_hosts; $i++) {
echo ’<hr>’ . $host[$i] . ":";
$error = yaz_error($id[$i]);
if (!empty($error)) {
echo "Error: $error";
} else {
$hits = yaz_hits($id[$i]);
echo "Result Count $hits";
}
echo ’<dl>’;
for ($p = 1; $p <= 10; $p++) {
$rec = yaz_record($id[$i],$p,"string");
if (empty($rec)) continue;
echo "<dt><b>$p</b></dt><dd>";
echo ereg_replace("\n", "<br>\n",$rec);
echo "</dd>";
}
echo ’</dl>’;
}
}

1536
YAZ

yaz_addinfo (PHP 4 >= 4.0.1)


Returns additional error information

int yaz_addinfo ( int id) \linebreak


Returns additional error message for target (last request). An empty string is returned if last operation
was a success or if no additional information was provided by the target.

yaz_ccl_conf (PHP 4 >= 4.0.5)


Configure CCL parser

int yaz_ccl_conf ( int id, array config) \linebreak


This function configures the CCL query parser for a target with definitions of access points (CCL
qualifiers) and their mapping to RPN. To map a specific CCL query to RPN afterwards call the
yaz_ccl_parse() function. Each index of the array config is the name of a CCL field and the
corresponding value holds a string that specifies a mapping to RPN. The mapping is a sequence of
attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=).
Each pair is separated by white space.

Ejemplo 1. CCL configuration

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

yaz_ccl_parse (PHP 4 >= 4.0.5)


Invoke CCL Parser

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

yaz_close (PHP 4 >= 4.0.1)


Closes a YAZ connection

int yaz_close ( int id) \linebreak


Closes a connection to a target. The application can no longer refer to the target with the given id.

yaz_connect (PHP 4 >= 4.0.1)


Returns a positive association ID on success; zero on failure

int yaz_connect ( string zurl) \linebreak


yaz_connect() prepares for a connection to a Z39.50 target. The zurl argument takes the form
host[:port][/database]. If port is omitted 210 is used. If database is omitted Default is used. This function
is non-blocking and doesn’t attempt to establish a socket - it merely prepares a connect to be performed
later when yaz_wait() is called.

yaz_database (PHP 4 >= 4.0.6)


Specifies the databases within a session

int yaz_database ( int id, string databases) \linebreak


This function specifies one or more databases to be used in search, retrieval, etc. - overriding databases
specified in call to yaz_connect(). Multiple databases are separated by a plus sign +.
This function allows you to use different sets of databases within a session.
Returns TRUE on success; FALSE on error.

yaz_element (PHP 4 >= 4.0.1)


Specifies Element-Set Name for retrieval

1538
YAZ

int yaz_element ( int id, string elementset) \linebreak


This function is used in conjunction with yaz_search() and yaz_present() to specify the element set name
for records to be retrieved. Most servers support F (full) and B (brief).
Returns TRUE on success; FALSE on error.

yaz_errno (PHP 4 >= 4.0.1)


Returns error number

int yaz_errno ( int id) \linebreak


Returns error for target (last request). A positive value is returned if the target returned a diagnostic code;
a value of zero is returned if no errors occurred (success); negative value is returned for other errors
targets didn’t indicate the error in question.
yaz_errno() should be called after network activity for each target - (after yaz_wait() returns) to
determine the success or failure of the last operation (e.g. search).

yaz_error (PHP 4 >= 4.0.1)


Returns error description

int yaz_error ( int id) \linebreak


Returns error message for target (last request). An empty string is returned if last operation was a success.
yaz_error() returns a english message corresponding to the last error number as returned by yaz_errno().

yaz_hits (PHP 4 >= 4.0.1)


Returns number of hits for last search

int yaz_hits ( int id) \linebreak


yaz_hits() returns number of hits for last search.

yaz_itemorder (PHP 4 >= 4.0.5)


Prepares for Z39.50 Item Order with an ILL-Request package

int yaz_itemorder ( array args) \linebreak

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

yaz_present (PHP 4 >= 4.0.5)


Prepares for retrieval (Z39.50 present).

int yaz_present ( void) \linebreak


This function prepares for retrieval of records after a successful search. The yaz_range() should be called
prior to this function to specify the range of records to be retrieved.

yaz_range (PHP 4 >= 4.0.1)


Specifies the maximum number of records to retrieve

int yaz_range ( int id, int start, int number) \linebreak


This function is used in conjunction with yaz_search() to specify the maximum number of records to
retrieve (number) and the first record position (start). If this function is not invoked (only yaz_search())
start is set to 1 and number is set to 10.
Returns TRUE on success; FALSE on error.

yaz_record (PHP 4 >= 4.0.1)


Returns a record

int yaz_record ( int id, int pos, string type) \linebreak


Returns record at position or empty string if no record exists at given position.
The yaz_record() function inspects a record in the current result set at the position specified. If no
database record exists at the given position an empty string is returned. The argument, type, specifies the
form of the returned record. If type is "string" the record is returned in a string representation suitable for
printing (for XML and SUTRS). If type is "array" the record is returned as an array representation (for
structured records).

1542
YAZ

yaz_scan_result (PHP 4 >= 4.0.5)


Returns Scan Response result

array yaz_scan_result ( int id [, array & result]) \linebreak


Given a target ID this function returns and array with terms as received from the target in the last Scan
Response. This function returns an array (0..n-1) where n is the number of terms returned. Each value is
a pair where first item is term, second item is result-count. If the result is given it will be modified to
hold additional information taken from the Scan Response: number (number of entries returned),
stepsize (Step-size), position (position of term), status (Scan Status).

yaz_scan (PHP 4 >= 4.0.5)


Prepares for a scan

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.

Ejemplo 1. PHP function that scans titles

function scan_titles($id, $starterm) {


yaz_scan($id,"rpn", "@attr 1=4 " . $starterm);
yaz_wait();
$errno = yaz_errno($id);
if ($errno == 0) {
$ar = yaz_scan_result($id,&$options);
echo ’Scan ok; ’;
$ar = yaz_scan_result($id, &$options);
while(list($key,$val)=each($options)) {
echo "$key = $val &nbsp;";
}
echo ’<br><table><tr><td>’;
while(list($key,list($k, $term, $tcount))=each($ar)) {
if (empty($k)) continue;
echo "<tr><td>$term</td><td>";
echo $tcount;
echo "</td></tr>";

1543
YAZ

}
echo ’</table>’;
} else {
echo "Scan failed. Error: " . yaz_error($id) . "<br>";
}
}

yaz_search (PHP 4 >= 4.0.1)


Prepares for a search

int yaz_search ( int id, string type, string query) \linebreak


yaz_search() prepares for a search on the target with given id. The type represents the query type - only
"rpn" is supported now in which case the third argument is a prefix notation query as used by YAZ. Like
yaz_connect() this function is non-blocking and only prepares for a search to be executed later when
yaz_wait() is called.

yaz_sort (PHP 4 >= 4.1.0)


Sets sorting criteria

int yaz_sort ( int id, string criteria) \linebreak


This function sets sorting criteria and enables Z39.50 Sort. Use this function together with yaz_search()
or yaz_present(). Using this function alone doesn’t have any effect. If used in conjunction with
yaz_search() a Z39.50 Sort will be sent after a search response has been received and before any records
are retrieved with Z39.50 Present. The criteria takes the form
field1 flags1 field2 flags2 ...
where field1 specifies primary attributes for sort, field2 seconds, etc.. The field specifies either numerical
attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field
may specify a plain string criteria (e.g. title. The flags is a sequnce of the following characters which
may not be separated by any white space.

Sort Flags
a

Sort ascending

1544
YAZ

Sort descending

Case insensitive sorting

s
Case sensitive sorting

Ejemplo 1. Sort Criterias

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

yaz_syntax (PHP 4 >= 4.0.1)


Specifies the preferred record syntax for retrieval

int yaz_syntax ( int id, string syntax) \linebreak


This function is used in conjunction with yaz_search() to specify the preferred record syntax for retrieval.

yaz_wait (PHP 4 >= 4.0.1)


Executes queries

int yaz_wait ( int id, string syntax) \linebreak


This function carries out networked (blocked) activity for outstanding requests which have been prepared
by the functions yaz_connect(), yaz_search(). yaz_wait() returns when all targets have either completed
all requests or otherwise completed (in case of errors).

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

yp_all (PHP 4 >= 4.0.6)


Traverse the map and call a function on each entry

void yp_all ( string domain, string map, string callback) \linebreak

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

yp_cat (PHP 4 >= 4.0.6)


Return an array containing the entire map

array yp_cat ( string domain, string map) \linebreak

Aviso
Esta función no está documentada actualmente, solamente se encuentra
disponible la lista de parametros.

yp_err_string (PHP 4 >= 4.0.6)


devuelve el mensaje de error asociado con la operacion previa.Util que indica el problema exacto.

cadena yp_err_string ( void) \linebreak


yp_err_string() Retorna el mensaje de error asociado con la operacion previa.Util para indicar que salio
mal exactamente.

Ejemplo 1. Ejemplo para errores de NIS

Vea tambien: yp errno

1547
NIS

yp_errno (PHP 4 >= 4.0.6)


Retorna el codigo de error de la operacion previa.

int yp_errno ( void) \linebreak


yp_errno() retorna el codigo de error de la operacion previa.
Los errores posibles son:

1 args para funcionar son malos


2 fallo de RPC- dominio ha sido unbound
3 no puede unir a servidor en este dominio
4 ningun tal mapa en dominio de servidor
5 ninguna tal llave en
6 interno yp error de cliente o servidor
7 fallo de asignacion de recurso
8 ningunos más registros en base de datos de mapa
9 no puede comunicar wiTh portmapper
10 no puede comunicar con ypbind
11 no puede comunicar con ypserv
12 nombre de dominio local no conjunto
13 yp base de datos es malo
14 yp La version mismatch
15 violacion de acceso
16 base de datos ocupar
Ver tambien: yp_err_string

yp_first (unknown)
devuelve la primera clave emparejada con el nombrado mapa.

string[] yp_first (cadena dominio, cadena mapa)

yp_first(nombre de la funcion)() Retorna la primera clave de valor pareada del mapa nombrado en el
dominio, de otra manera FALSO.

Ejemplo 1. Ejemplo para el primer NIS

Ver tambien: yp_get_default_domain yp_errno y yp_err_string

1548
NIS

yp_get_default_domain (PHP 3>= 3.0.7, PHP 4 )


Trae el valor por omision de dominios de maquina NIS.

int yp get_default_domain ( void) \linebreak


yp_ get_default_domain() Retorna el valor por omision del dominio del nodo o FALSO. Puede ser
usado el parametro de dominio para sucesivas llamadas a NIS.
Un dominio de NIS puede ser descrito en un grupo de mapas NIS. Cada host necesita buscar uniones de
informacion en un mismo dominio. Acudir a los documentos mencionados en el comienzo para mas
informacion.

Ejemplo 1. Ejemplo para el dominio por omision

Ver tambien: yp_ errno (nombre de la funcion) y yp_err_string (nombre de la funcion)

yp_master (PHP 3>= 3.0.7, PHP 4 )


Returns the machine name of the master NIS server for a map

string yp_master ( string domain, string map) \linebreak


yp_master() returns the machine name of the master NIS server for a map.

Ejemplo 1. Example for the NIS master

<?php
$number = yp_master ($domain, $mapname);
echo "Master for this map is: " . $master;
?>

See also yp-get-default-domain().

yp_match (PHP 3>= 3.0.7, PHP 4 )


Retorna la linea compañera (pareja).

1549
NIS

cadena yp match ( cadena dominio, cadena mapa, cadena teclea) \linebreak


yp_match(nombre de la funcion)() Retorna el valor asociado con la llave pasada fuera del mapa
especificado o FALSO. esta llave tiene que ser exacta.

Ejemplo 1. Ejemplo para NIS parejo

En este caso esto puede ser: Joe:##joe:11111:100:joe usuario:/hogar/j/joe: User:/usr/local/bin/bash


Ver tambien: yp_get_default_domain yp_errno y yp_err_string

yp_next (PHP 3>= 3.0.7, PHP 4 )


Devuelve la siguiente clave tecleada en el nombre de mapa

string[] yp_next ( cadena dominio, cadena mapa, cadena teclea) \linebreak


yp_next() devuelve el siguiente par de valor tecleado en el mapa de nombres despues de la clave
especificada o FALSO.

Ejemplo 1. Ejemplo para NIS siguiente

Ver tambien: yp_get_default_domain yp_errno y yp_err_string

yp_order (PHP 3>= 3.0.7, PHP 4 )


Returns the order number for a map

int yp_order ( string domain, string map) \linebreak


yp_order() returns the order number for a map or FALSE.

Ejemplo 1. Example for the NIS order

<?php
$number = yp_order($domain,$mapname);
echo "Order number for this map is: " . $number;
?>

1550
NIS

See also yp-get-default-domain().

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.

Ejemplo 1. Zip Usage Example

<?php

$zip = zip_open("/tmp/test2.zip");

if ($zip) {

while ($zip_entry = zip_read($zip)) {


echo "Name: " . zip_entry_name($zip_entry) . "\n";
echo "Actual Filesize: " . zip_entry_filesize($zip_entry) . "\n";
echo "Compressed Size: " . zip_entry_compressedsize($zip_entry) . "\n";
echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n";

if (zip_entry_open($zip, $zip_entry, "r")) {


echo "File Contents:\n";
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
echo "$buf\n";

zip_entry_close($zip_entry);
}
echo "\n";

zip_close($zip);

1552
Zip

?>

1553
Zip

zip_close (PHP 4 >= 4.1.0)


Close a Zip File Archive

void zip_close ( resource zip) \linebreak


Closes a zip file archive. The parameter zip must be a zip archive previously opened by zip_open().
This function has no return value.
See also zip_open() and zip_read().

zip_entry_close (PHP 4 >= 4.1.0)


Close a Directory Entry

void zip_entry_close ( resource zip_entry) \linebreak


Closes a directory entry specified by zip_entry. The parameter zip_entry must be a valid
directory entry opened by zip_entry_open().
This function has no return value.
See also zip_entry_open() and zip_entry_read().

zip_entry_compressedsize (PHP 4 >= 4.1.0)


Retrieve the Compressed Size of a Directory Entry

int zip_entry_compressedsize ( resource zip_entry) \linebreak


Returns the compressed size of the directory entry specified by zip_entry. The parameter
zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().

zip_entry_compressionmethod (PHP 4 >= 4.1.0)


Retrieve the Compression Method of a Directory Entry

string zip_entry_compressionmethod ( resource zip_entry) \linebreak


Returns the compression method of the directory entry specified by zip_entry. The parameter
zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().

1554
Zip

zip_entry_filesize (PHP 4 >= 4.1.0)


Retrieve the Actual File Size of a Directory Entry

int zip_entry_filesize ( resource zip_entry) \linebreak


Returns the actual size of the directory entry specified by zip_entry. The parameter zip_entry is
a valid directory entry returned by zip_read().
See also zip_open() and zip_read().

zip_entry_name (PHP 4 >= 4.1.0)


Retrieve the Name of a Directory Entry

string zip_entry_name ( resource zip_entry) \linebreak


Returns the name of the directory entry specified by zip_entry. The parameter zip_entry is a
valid directory entry returned by zip_read().
See also zip_open() and zip_read().

zip_entry_open (PHP 4 >= 4.1.0)


Open a Directory Entry for Reading

bool zip_entry_open ( resource zip, resource zip_entry [, string mode]) \linebreak


Opens a directory entry in a zip file for reading. The parameter zip is a valid resource handle returned
by zip_open(). The parameter zip_entry is a directory entry resource returned by zip_read(). The
optional parameter mode can be any of the modes specified in the documentaion for fopen().

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

Devuelve TRUE si todo fue bien, FALSE en caso de fallo.

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.

See also zip_entry_read() and zip_entry_close().

1555
Zip

zip_entry_read (PHP 4 >= 4.1.0)


Read From an Open Directory Entry

string zip_entry_read ( resource zip_entry [, int length]) \linebreak


Reads up to length bytes from an open directory entry. If length is not specified, then
zip_entry_read() will attempt to read 1024 bytes. The parameter zip_entry is a valid directory entry
returned by zip_read().

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().

zip_open (PHP 4 >= 4.1.0)


Open a Zip File Archive

resource zip_open ( string filename) \linebreak


Opens a new zip archive for reading. The filename parameter is the filename of the zip archive to
open.
Returns a resource handle for later use with zip_read() and zip_close() or returns FALSE if filename
does not exist.
See also zip_read() and zip_close().

zip_read (PHP 4 >= 4.1.0)


Read Next Entry in a Zip File Archive

resource zip_read ( resource zip) \linebreak


Reads the next entry in a zip file archive. The parameter zip must be a zip archive previously opened by
zip_open().
Returns a directory entry resource for later use with the zip_entry_...() functions.
See also zip_open(), zip_close(), zip_entry_open(), and zip_entry_read().

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

Pequeño código de ejemlo


Abre un archivo temporal y escribe en él, una cadena de prueba, y luego presenta el cotenido del archivo
dos veces

Ejemplo 1. Ejemplo de Zlib

<?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

gzclose (PHP 3, PHP 4 )


cierra un puntero a archivo-gz abierto

int gzclose ( int zp) \linebreak


El archivo-gz al que apunta zp se cierra.
Devuelve TRUE (verdadero) si fue exitoso, si hubo errores devuelve FALSE.
El puntero al archivo-gz debe ser válido y debe apuntar a un archivo correctamente abierto con gzopen().

gzcompress (PHP 4 >= 4.0.1)


Compress a string

string gzcompress ( string data [, int level]) \linebreak


This function returns a compressed version of the input data using the ZLIB data format, or FALSE if
an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for
maximum compression.
For details on the ZLIB compression algorithm see the document "ZLIB Compressed Data Format
Specification version 3.3 (http://www.ietf.org/rfc/rfc1950.txt)" (RFC 1950).

Nota: This is not the same as gzip compression, which includes some header data. See gzencode()
for gzip compression.

See also gzdeflate(), gzinflate(), gzuncompress(), gzencode().

gzdeflate (PHP 4 >= 4.0.4)


Deflate a string

string gzdeflate ( string data [, int level]) \linebreak


This function returns a compressed version of the input data using the DEFLATE data format, or
FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression
up to 9 for maximum compression.
For details on the DEFLATE compression algorithm see the document "DEFLATE Compressed Data
Format Specification version 1.3 (http://www.ietf.org/rfc/rfc1951.txt)" (RFC 1951).
See also gzinflate(), gzcompress(), gzuncompress(), gzencode().

1558
Zlib

gzencode (PHP 4 >= 4.0.4)


Create a gzip compressed string

string gzencode ( string data [, int level [, int encoding_mode]]) \linebreak


This function returns a compressed version of the input data compatible with the output of the gzip
program, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no
compression up to 9 for maximum compression, if not given the default compression level will be the
default compression level of the zlib library.
You can also give FORCE_GZIP (the default) or FORCE_DEFLATE as optional third paramter
encoding_mode. If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib
headers) after the gzip file header but without the trailing crc32 checksum.

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

Ejemplo 1. Creating a gzip file

<?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().

gzeof (PHP 3, PHP 4 )


prueba el fin-de-archivo de un puntero de archivo-gz

int gzeof ( int zp) \linebreak

1559
Zlib

Devuelve verdadero si el puntero-a-archivo está en el fin-de-archivo, o ha ocurrido un error. De otro


modo devuelve falso.
El puntero al archivo-gz debe ser válido y debe apuntar a un archivo correctamente abierto con gzopen().

gzfile (PHP 3, PHP 4 )


lee el archivo gz completo en un arreglo

array gzfile ( string nombre_archivo [, int usar_include_path]) \linebreak


Identico a readgzfile(), solo que gzfile() devuelve el fichero en un arreglo.
Se puede usar el segundo parámetro opcional poniéndolo a "1", si se quiere que la función busque
también el archivo en la trayectoria definida como include_path.
Vea también readgzfile(), y gzopen().

gzgetc (PHP 3, PHP 4 )


toma caracteres de un archivo-gz

cadena gzgetc ( int zp) \linebreak


Devuelve una cadena conteniendo un caracter en particular (sin comprimir) leído del archivo al que
apunta zp. Devuelve FALSE cuando está al final del archivo (al igual que gzeof()).
El puntero al archivo-gz debe ser válido y debe apuntar a un archivo correctamente abierto con gzopen().
Vea también gzopen(), y gzgets().

gzgets (PHP 3, PHP 4 )


toma una linea del archivo apuntado

string gzgets ( int zp, int longitud) \linebreak


Devuelve una cadena (descomprimida) con longitud - 1 bytes de largo, leída del archivo apuntado por fp.
La lectura finaliza cuando se han leído longitud - 1 bytes, ante un salto de linea o un fin-de-archivo (lo
que ocurra primero).
Si ocurre un error, devuelve falso.
El puntero al archivo-gz debe ser válido y debe apuntar a un archivo correctamente abierto con gzopen().
Vea también gzopen(), gzgetc(), y fgets().

1560
Zlib

gzgetss (PHP 3, PHP 4 )


toma una linea del archivo-gz apuntado y le quita los tags HTML

string gzgetss ( int zp, int longitud [, string tags_permitidos]) \linebreak


Idéntica a gzgets(), excepto que gzgetss intenta quitar cualquier "tag" HTML o PHP del texto que lee.
Se puede usar el tercer parámetro para indicar qué parametros no deben ser extraídos.

Nota: tags_permitidos fue agregado en la versión de PHP 3.0.13, PHP4B3.

Véase también gzgets(), gzopen(), y strip_tags().

gzinflate (PHP 4 >= 4.0.4)


Inflate a deflated string

string gzinflate ( string data [, int length]) \linebreak


This function takes data compressed by gzdeflate() and returns the original uncompressed data or
FALSE on error. The function will return an error if the uncompressed data is more than 256 times the
length of the compressed input data or more than the optional parameter length.
See also gzcompress(). gzuncompress(), gzdeflate(), gzencode().

gzopen (PHP 3, PHP 4 )


open gz-file

int gzopen ( string nombre_fichero, string modo [, int use_include_path]) \linebreak


Abre un archivo gzip (.gz) para lectura o escritura. El parámetro modo es, como en fopen() ("rb" o "wb")
pero puede incluir tambien el nivel de compresión ("wb9") o la estrategia: ’f’ para filtrado de datos como
en "wb6f", ’h’ para comprimir solo por Huffman igual que en "wb1h". (Ver la descripción de deflateInit2
en zlib.h para más información sobre el parámetro de estrategia.)
Gzopen puede usarse para leer o escribir un fichero que no esté en formato gzip; en ese caso gzread()
leerá el archivo directamente, sin descomprimirlo.
Gzopen devuelve un puntero al archivo abierto y luego, cualquier proceso de lectura o escritura
relacionado con ese descriptor de archivo, será transparente: se comprimirá o descomprimirá los datos
según la necesidad, de manera automática.
Si la apertura fallase, se devolverá falso.

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.

Ejemplo 1. ejemplo de gzopen()

$fp = gzopen("/tmp/file.gz", "r");

Vea también gzclose().

gzpassthru (PHP 3, PHP 4 )


Devuelve el remanente de datos de un fichero-gz

int gzpassthru ( int zp) \linebreak


Lee hasta el Fin-De-Archivo del archivo gz dado, y escribe los resultados (descomprimidos) en la salida
standard.
Si ocurre un error, devuelve Falso.
El puntero al archivo-gz debe ser válido y debe apuntar a un archivo correctamente abierto con gzopen().
El archivo-gz es cerrado cuando gzpassthru() termina de leerlo (dejando zp sin utilidad).

gzputs (PHP 3, PHP 4 )


escribe al fichero-gz que se apunta

int gzputs ( int zp, string str [, int longitud]) \linebreak


gzputs() es un alias a gzwrite(), y es absolutamente idéntico.

gzread (PHP 3, PHP 4 )


Lee archivos-gz en modo Binario

string gzread ( int zp, int longitud) \linebreak


gzread() lee hasta longitud bytes del archivo-gz apuntado por el parámetro zp. La lectura termina
cuando se han leído longitud bytes (descomprimidos) o se alcanza el fin-de-archivo, lo que sucediera
primero.

// Pone los contenidos del gz, a una cadena

1562
Zlib

$filename = "/usr/local/algo.txt.gz";
$zd = gzopen( $filename, "r" );
$contents = gzread( $zd, 10000 );
gzclose( $zd );

Ver también gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), y gzpassthru().

gzrewind (PHP 3, PHP 4 )


Reposiciona al puntero de archivo-gz, al inicio de aquel

int gzrewind ( int zp) \linebreak


Reubica el indicador de posición del archivo, al comienzo del mismo.
si surge un error, devuelve 0.
El puntero al archivo-gz debe ser válido y debe apuntar a un archivo correctamente abierto con gzopen().
Ver también: gzseek() y gztell().

gzseek (PHP 3, PHP 4 )


Posiciona el puntero del archivo-gz

int gzseek ( int zp, int offset) \linebreak


Busca la posición dentro del archivo zp, indicada en bytes por el parametro de desplazamiento offset. Es
equivalente a llamar (en C) gzseek( zp, offset, SEEK_SET ).
Si el archivo se abre para lectura, la función será emulada, pero puede ponerse extremadamente lenta. Si
se trata de escritura, solo está soportada la búsqueda hacia adelante; gzseek comprime entonces una
secuencia de ceros hasta que alcanza la nueva ubicación.
Si se completa el pedido con éxito, devuelve 0; de lo contrario, devuelve -1. Note que la busqueda más
allá del fin-de-archivo no se considera un error.
Vea también gztell() y gzrewind().

gztell (PHP 3, PHP 4 )


Indica la posición de lecto-escritura en el archivo

int gztell ( int zp) \linebreak

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().

gzuncompress (PHP 4 >= 4.0.1)


Uncompress a deflated string

string gzuncompress ( string data [, int length]) \linebreak


This function takes data compressed by gzcompress() and returns the original uncompressed data or
FALSE on error. The function will return an error if the uncompressed data is more than 256 times the
length of the compressed input data or more than the optional parameter length.
See also gzdeflate(), gzinflate(), gzcompress(), gzencode().

gzwrite (PHP 3, PHP 4 )


Escritura de ficheros gz en modo Binario

int gzwrite ( int zp, string cadena [, int largo]) \linebreak


gzwrite() escribe el contenido de cadena al fichero gz referido por zp. Si el parámetro largo está
presente, se detendrá la escritura luego de escribir largo bytes (descomprimidos) o al llegar el final de
la cadena, lo que ocurriese primero.
Note que si se pasa el argumento largo, la opcion magic_quotes_runtime será ignorada y no se
quitarán barras de la cadena en cuestión.
Ver también gzread(), gzopen(), y gzputs().

readgzfile (PHP 3, PHP 4 )


devuelve el fichero-gz

int readgzfile ( string nombre_archivo [, int usar_trayectoria_include]) \linebreak


Lee el archivo, lo descomprime y lo escribe en la salida estándar.
Readgzfile() puede usarse para leer un archivo comprimido o no con gzip; en cuyo caso readgzfile() leerá
directamente el archivo, sin descomprimirlo.
Devuelve el numero de bytes (descomprimidos) leídos del archivo, si ocurre un error, se devuelve falso y
hasta que se llame como @readgzfile, se imprime un mensaje de error.

1564
Zlib

El archivo nombre_archivo se abrirá en el sistema de archivos y su contenido enviado a la salida


estándar.
Puede usarse el segundo paametro opcional dándole el valor "1", si se quiere que se busque el archivo
también dentro de la trayectoria "include": include_path.
Ver también gzpassthru(), gzfile(), y gzopen().

1565
Parte V. Extending PHP 4.0

Capítulo 25. Overview

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.

What Is Zend? and What Is PHP?


The name Zend refers to the language engine, PHP’s core. The term PHP refers to the complete system
as it appears from the outside. This might sound a bit confusing at first, but it’s not that complicated (see
Figura 25-1). To implement a Web script interpreter, you need three parts:

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.

Figura 25-1. The internal structure of PHP.

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.

The Zend Engine


Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you
need a change in the language behavior or require special functions to be built directly into the language
core. In general, however, modifications to the Zend engine should be avoided. Changes here result in
incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend
engines. Modifications can’t be detached from the main PHP sources and are overridden with the next
update using the "official" source repositories. Therefore, this method is generally considered bad
practice and, due to its rarity, is not covered in this book.

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.

Figura 27-1. Main directory layout of the PHP source tree.

The following table describes the contents of the major directories.

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.

Directory and File Functions


The following directory and file functions should be used in Zend modules. They behave exactly like
their C counterparts, but provide virtual working directory support on the thread level.

Zend Function Regular C Function


V_GETCWD() getcwd()
V_FOPEN() fopen()
V_OPEN() open()
V_CHDIR() chdir()
V_GETWD() getwd()
V_CHDIR_FILE() Takes a file path as an argument and changes the
current working directory to that file’s directory.
V_STAT() stat()
V_LSTAT() lstat()

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:

root@dev:/usr/local/src/php4/ext > ./ext_skel my_module


Creating directory
Creating basic files: config.m4 Makefile.in .cvsignore [done].
To use your new extension, you will have to execute the following steps:
$ cd ..
$ ./buildconf
$ ./configure # (your extension is automatically enabled)
$ vi ext/my_module/my_module.c
$ make
Repeat the last two steps as often as necessary.

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:

Ejemplo 28-1. The default Makefile.in.

# $Id: Extending_Zend_Build.xml,v 1.6 2002/03/25 08:13:46 hholzgra Exp $


LTLIBRARY_NAME = libmy_module.la
LTLIBRARY_SOURCES = my_module.c
LTLIBRARY_SHARED_NAME = my_module.la include
$(top_srcdir)/build/dynlib.mk

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:

Ejemplo 28-2. The default config.m4.

dnl $Id: Extending_Zend_Build.xml,v 1.6 2002/03/25 08:13:46 hholzgra Exp $


dnl config.m4 for extension my_module
dnl don’t forget to call PHP_EXTENSION(my_module)

1577
Capítulo 28. PHP’s Automatic Build System

dnl If your extension references something external, use with:


PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
[ --with-my_module Include my_module support])
dnl Otherwise use enable:
PHP_ARG_ENABLE(my_module, whether to enable my_module support,
dnl Make sure that the comment is aligned:
[ --enable-my_module Enable my_module support])
if test "$PHP_MY_MODULE" != "no"; then
dnl Action..
PHP_EXTENSION(my_module, $ext_shared)
fi

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

if test "$PHP_MY_MODULE" == "yes"; then dnl


Action.. PHP_EXTENSION(my_module, $ext_shared)
fi

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.

Ejemplo 29-1. A simple extension.

/* include standard header */


#include "php.h"

/* declaration of functions to be exported */


ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what’s in this module */


zend_function_entry firstmod_functions[] =
{
ZEND_FE(first_module, NULL)
{NULL, NULL, NULL}
};

/* compiled module information */


zend_module_entry firstmod_module_entry =
{
STANDARD_MODULE_HEADER,
"First Module",
firstmod_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */


#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */


ZEND_FUNCTION(first_module)
{
long parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAIL-


URE) {
return;
}

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:

--enable-array_experiments BOOK: Enables array experiments


--enable-call_userland BOOK: Enables userland module
--enable-cross_conversion BOOK: Enables cross-conversion module
--enable-first_module BOOK: Enables first module
--enable-infoprint BOOK: Enables infoprint module
--enable-reference_test BOOK: Enables reference test module
--enable-resource_test BOOK: Enables resource test module
--enable-variable_creation BOOK: Enables variable-creation module

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

Linking cc -shared -L/usr/local/lib -rdynamic -o <your_module_file> <your_object_file(s)>

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.

Ejemplo 30-1. A test file for first_module.so.

<?php

// remove next comment if necessary


// dl("first_module.so");

$param = 2;
$return = first_module($param);

print("We sent ’$param’ and got ’$return’");

?>

Calling this PHP file in your Web browser should give you the output shown in Figura 30-1.

Figura 30-1. Output of first_module.php.

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

Header File Inclusions


The only header file you really have to include for your modules is php.h, located in the PHP directory.
This file makes all macros and API definitions required to build new modules available to your code.
Tip: It’s good practice to create a separate header file for your module that contains module-specific
definitions. This header file should contain all the forward definitions for exported functions and include
php.h. If you created your module using ext_skel you already have such a header file prepared.

Declaring Exported Functions


To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend
provides a set of macros. A sample declaration looks like this:

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:

void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );

Expanding INTERNAL_FUNCTION_PARAMETERS results in the following:

1589
Capítulo 32. Source Discussion

void zif_my_function( int ht


, zval * return_value
, zval * this_ptr
, int return_value_used
, zend_executor_globals * executor_globals
);

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

Tabla 32-1. Zend’s Parameters to Functions Called from PHP

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

Declaration of the Zend Function Block


Now that you have declared the functions to be exported, you also have to introduce them to Zend.
Introducing the list of functions is done by using an array of zend_function_entry. This array
consecutively contains all functions that are to be made available externally, with the function’s name as
it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is
defined as shown in Ejemplo 32-1.

Ejemplo 32-1. Internal declaration of zend_function_entry.

typedef struct _zend_function_entry {


char *fname;
void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
unsigned char *func_arg_types;

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

In the example above, the declaration looks like this:

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.

Tabla 32-2. Macros for Defining Functions

Macro Name Description


ZEND_FE(name, arg_types) Defines a function entry of the name name in zend_function_en
ZEND_NAMED_FE(php_name, name, arg_types) Defines a function that will be available to PHP by the name ph
ZEND_FALIAS(name, alias, arg_types) Defines an alias named alias for name. arg_types needs to be se
PHP_FE(name, arg_types) Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types) Old PHP API equivalent of ZEND_NAMED_FE.

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

Declaration of the Zend Module Block


This block is stored in the structure zend_module_entry and contains all necessary information to
describe the contents of this module to Zend. You can see the internal definition of this module in
Ejemplo 32-2.

Ejemplo 32-2. Internal declaration of zend_module_entry.

typedef struct _zend_module_entry zend_module_entry;

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

[ Rest of the structure is not interesting here ]

};

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

In our example, this structure is implemented as follows:

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.

Tabla 32-3. Macros to Declare Startup and Shutdown Functions

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.

Implementation of All Exported Functions


Implementing the exported functions is the final step. The example function in first_module looks
like this:

ZEND_FUNCTION(first_module)
{
long parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAIL-


URE) {
return;
}

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.

Determining the Number of Arguments


Since PHP doesn’t have formal function definitions with support for call syntax checking, and since PHP
features variable arguments, sometimes you need to find out with how many arguments your function has
been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this
macro retrieved the number of arguments with which the function has been called based on the function’s
hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now
contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been
stripped down to a dummy macro (see its definition in zend_API.h). But it’s still good practice to use it,
to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this
macro is ARG_COUNT.
The following code checks for the correct number of arguments:

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

Figura 33-1. WRONG_PARAM_COUNT in action.

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:

ZEND_API void wrong_param_count(void);

1596
Capítulo 33. Accepting Arguments

#define WRONG_PARAM_COUNT { wrong_param_count(); return; }

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:

int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);

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:

Warning - ini_get_all() requires at most 1 parameter, 2 given


Warning - wddx_deserialize() expects parameter 1 to be string, array given

Of course each error message is accompanied by the filename and line number on which it occurs.

1597
Capítulo 33. Accepting Arguments

Here is the full list of type specifiers:

• 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:

/* Gets a long, a string and its length, and a zval. */


long l;
char *s;
int s_len;
zval *param;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
"lsz", &l, &s, &s_len, &param) == FAILURE) {
return;
}

/* Gets an object of class specified by my_ce, and an optional double. */


zval *obj;
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
"O|d", &obj, my_ce, &d) == FAILURE) {
return;
}

/* Gets an object or null, and an array.


If null is passed for object, obj will be set to NULL. */
zval *obj;

1598
Capítulo 33. Accepting Arguments

zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAIL-
URE) {
return;
}

/* Gets a separated array. */


zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) {
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.

int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);

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:

long l1, l2, l3;


char *s;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
ZEND_NUM_ARGS() TSRMLS_CC,
"lll", &l1, &l2, &l3) == SUCCESS) {
/* manipulate longs */
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) {
/* manipulate string */
} else {
php_error(E_WARNING, "%s() takes either three long values or a string as argument",

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.

Old way of retrieving arguments (deprecated)


Deprecated parameter parsing API: This API is deprecated and superseded by the new ZEND
parameter parsing API.

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;

if(zend_get_parameters_ex(1, &parameter) != SUCCESS)


WRONG_PARAM_COUNT;

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:

zval **param1, **param2, **param3, **param4;

if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)


WRONG_PARAM_COUNT;

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.

Dealing with a Variable Number of Arguments/Optional


Parameters
If your function is meant to accept a variable number of arguments, the snippets just described are
sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every
possible number of arguments, which is often unsatisfying.
For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of
parameters to retrieve and an array in which to store them:

zval **parameter_array[4];

/* get the number of arguments */


argument_count = ZEND_NUM_ARGS();

/* see if it satisfies our minimal request (2 arguments) */


/* and our maximal acceptance (4 arguments) */
if(argument_count < 2 || argument_count > 5)
WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */


if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
WRONG_PARAM_COUNT;

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.

Ejemplo 33-1. PHP’s implementation of variable arguments in fsockopen().

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

if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE)


CLOSE_SOCK(1);
WRONG_PARAM_COUNT;
}

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

key = emalloc(Z_STRLEN_P(args[0]) + 10);

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.

Tabla 33-1. Argument Conversion Functions

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.

Figura 33-2. Cross-conversion behavior of PHP.

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;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS))


{
WRONG_PARAM_COUNT;
}

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.

Ejemplo 33-2. PHP/Zend zval type definition.

typedef pval zval;

typedef struct _zval_struct zval;

typedef union _zvalue_value {


long lval; /* long value */
double dval; /* double value */
struct {
char *val;
int len;
} str;
HashTable *ht; /* hash table value */
struct {
zend_class_entry *ce;
HashTable *properties;
} obj;
} zvalue_value;

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.

Tabla 33-2. Zend zval Structure

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

Tabla 33-3. Zend zvalue_value Structure

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.

Tabla 33-4. Zend Variable Type Constants

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

Dealing with Arguments Passed by Reference


If your function accepts arguments passed by reference that you intend to modify, you need to take some
precautions.
What we didn’t say yet is that under the circumstances presented so far, you don’t have write access to
any zval containers designating function parameters that have been passed to you. Of course, you can
change any zval containers that you created within your function, but you mustn’t change any zvals that
refer to Zend-internal data!
We’ve only discussed the so-called *_ex() API so far. You may have noticed that the API functions
we’ve used are called zend_get_parameters_ex() instead of zend_get_parameters(),
convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new
"extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only
meant for providing read-only access.
Because Zend works internally with references, different variables may reference the same value. Write
access to a zval container requires this container to contain an isolated value, meaning a value that’s not
referenced by any other containers. If a zval container were referenced by other containers and you
changed the referenced zval, you would automatically change the contents of the other containers
referencing this zval (because they’d simply point to the changed value and thus change their own value
as well).
zend_get_parameters_ex() doesn’t care about this situation, but simply returns a pointer to the desired
zval containers, whether they consist of references or not. Its corresponding function in the traditional
API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates
a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns
a pointer to the new, isolated value.
This action is called zval separation (or pval separation). Because the *_ex() API doesn’t perform zval
separation, it’s considerably faster, while at the same time disabling write access.
To change parameters, however, write access is required. Zend deals with this situation in a special way:
Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This
means that whenever you’re calling a function like this in PHP, Zend will automatically ensure that
$parameter is being passed as an isolated value, rendering it to a write-safe state:

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.

Ejemplo 33-3. Testing for referenced parameter passing.

zval *parameter;

1606
Capítulo 33. Accepting Arguments

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)


return;

/* check for parameter being passed by reference */


if (!PZVAL_IS_REF(*parameter)) {
{
zend_error(E_WARNING, "Parameter wasn’t passed by reference");
RETURN_NULL();
}

/* make changes to the parameter */


ZVAL_LONG(*parameter, 10);

Assuring Write Safety for Other Parameters


You might run into a situation in which you need write access to a parameter that’s retrieved with
zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro
SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is
detached from internal data and has only a local scope, meaning that it can be changed or destroyed
without implying global changes in the script context:

zval **parameter;

/* retrieve parameter */
zend_get_parameters_ex(1, &parameter);

/* at this stage, <parameter> still is connected */


/* to Zend’s internal data buffers */

/* make <parameter> write-safe */


SEPARATE_ZVAL(parameter);

/* now we can safely modify <parameter> */


/* without implying global changes */

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;

/* allocate and initialize new container */


MAKE_STD_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 variable is now accessible to the script by using $new_variable_name */

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;

/* allocate and initialize new container */


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

This is actually the standard method used in most modules.


The variables generated with the snippet above will always be of local scope, so they reside in the
context in which the function has been called. To create new variables in the global scope, use the same
method but refer to another symbol table:

zval *new_variable;

// allocate and initialize new container


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

// allocate and initialize new container


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

Ejemplo 34-1. Creating variables with different scopes.

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

ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1);


ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2);

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

Ejemplo 34-2. Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long->type = IS_LONG;
new_long->value.lval = 10;

Alternatively, you can use the macro ZVAL_LONG:

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;

Alternatively, you can use the macro ZVAL_DOUBLE:

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;

Of course, there’s a macro for this as well (ZVAL_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
}

If array_init() fails to create a new array, it returns FAILURE.


To add new elements to the array, you can use numerous functions, depending on what you want to do.
Tabla 34-1, Tabla 34-2 and Tabla 34-3 describe these functions. All functions return FAILURE on failure
and SUCCESS on success.

Tabla 34-1. Zend’s API for Associative Arrays

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

add_assoc_double(zval *array, char *key, Adds a floating-point value.


double d);()
add_assoc_string(zval *array, char *key, char Adds a string to the array. The flag duplicate
*str, int duplicate);() specifies whether the string contents have to be
copied to Zend internal memory.
add_assoc_stringl(zval *array, char *key, char Adds a string with the desired length length to the
*str, uint length, int duplicate); () array. Otherwise, behaves like add_assoc_string().

Tabla 34-2. Zend’s API for Indexed Arrays, Part 1

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()().

Tabla 34-3. Zend’s API for Indexed Arrays, Part 2

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

Ejemplo 34-3. Adding an element to an associative array.

zval *new_array, *new_element;


char *key = "element_key";

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

if(zend_hash_update(new_array->value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(


{
// do error handling here
}

Ejemplo 34-4. Adding an element to an indexed array.

zval *new_array, *new_element;


int key = 2;

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

if(zend_hash_index_update(new_array->value.ht, key, (void *)&new_element, sizeof(zval *), NU


{
// do error handling here
}

To emulate the functionality of add_next_index_*(), you can use this:

zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)

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.

Tabla 34-4. Zend’s API for Object Creation

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:

ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, ch

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:

ld Normal resource destruction handler callback


pld Pesistent resource destruction handler callback
type_name A string specifying the name of your resource. It’s always a good thing to specify an unique name within
module_number The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore y

The return value is an unique integer ID for your resource type.


The resource destruction handler (either normal or persistent resources) has the following prototype:

void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);

The passed rsrc is a pointer to the following structure:

typedef struct _zend_rsrc_list_entry {

void *ptr;
int type;
int refcount;

1619
Capítulo 34. Creating Variables

} zend_rsrc_list_entry;

The member void *ptr is the actual pointer to your resource.


Now we know how to start things, we define our own resource we want register within Zend. It is only a
simple structure with two integer members:

typedef struct {

int resource_link;
int resource_type;

} my_resource;

Our resource destruction handler is probably going to look something like this:

void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

// You most likely cast the void pointer to your structure type

my_resource *my_rsrc = (my_resource *) rsrc->ptr;

// Now do whatever needs to be done with you resource. Closing


// Files, Sockets, freeing additional memory, etc.
// Also, don’t forget to actually free the memory for your resource too!

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!

Now that we have defined

1. what our resource is and


2. our resource destruction handler
we can go on and do the rest of the steps:

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

4. and finally register the handler

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

// It’s nice to define your resource name somewhere


#define le_myresource_name "My type of resource"

[...]

// Now actually define our resource destruction handler


void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

my_resource *my_rsrc = (my_resource *) rsrc->ptr;


do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}

[...]

PHP_MINIT_FUNCTION(my_extension) {

// Note that ’module_number’ is already provided through the


// PHP_MINIT_FUNCTION() function definition.

le_myresource = zend_register_resource_destructors_ex(my_destruction_handler, NULL,

// You can register additional resources, initialize


// your global vars, constants, whatever.
}

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:

int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);

rsrc_result This is an already initialized zval * container.


rsrc_pointer Your resource pointer you want to store.
rsrc_type The type which you received when you registered the resource destruction handler. If you followed the nam

The return value is an unique integer identifier for that resource.


What is really going on when you register a new resource is it gets inserted in an internal list in Zend and
the result is just stored in the given zval * container:

rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type);

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:

ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, 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

Macros for Automatic Global Variable Creation


In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables.
These are nice to know in case you want to introduce global flags, for example. This is somewhat bad
practice, but Table Tabla 34-5 describes macros that do exactly this task. They don’t need any zval
allocation; you simply have to supply a variable name and value.

Tabla 34-5. Macros for Global Variable Creation

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:

• CONST_CS - This constant’s name is to be treated as case sensitive.


• CONST_PERSISTENT - This constant is persistent and won’t be "forgotten" when the current process
carrying this constant shuts down.
To use the flags, combine them using a inary OR:

// register a new constant of type "long"


REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS |
CONST_PERSISTENT);

There are two types of macros - REGISTER_*_CONSTANT andREGISTER_MAIN_*_CONSTANT. The first


type creates constants bound to the current module. These constants are dumped from the symbol table
as soon as the module that registered the constant is unloaded from memory. The second type creates
constants that remain in the symbol table independently of the module.

Tabla 34-6. Macros for Creating Constants

Macro
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags)

1623
Capítulo 34. Creating Variables

REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flag


REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flag
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, v

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;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)


return;
}

// do modifications to the parameter here

// now we want to return the modified container:


*return_value == *parameter;
zval_copy_ctor(return_value);

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.

Tabla 36-1. Predefined Macros for Returning Values from a 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.

zend_error(E_WARNING, "This function has been called with empty arguments");

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.

Tabla 37-1. Zend’s Predefined Error Messages.

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.

Figura 37-1. Display of warning messages in the browser.

1631
Capítulo 37. Printing Information

Including Output in phpinfo()


After creating a real module, you’ll want to show information about the module in phpinfo() (in addition
to the module name, which appears in the module list by default). PHP allows you to create your own
section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the
module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().
PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function,
including the module name in the heading. Everything else must be formatted and printed by you.
Typically, you can print an HTML table header using php_info_print_table_start() and then use the
standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments,
both take the number of columns (as integers) and the column contents (as strings). Ejemplo 37-1 shows
a source example and its output. To print the table footer, use php_info_print_table_end().

Ejemplo 37-1. Source code and screenshot for output in phpinfo().

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

Ejemplo 37-2. Printing execution information.

zend_printf("The name of the current function is %s<br>", get_active_function_name(TSRMLS_C)


zend_printf("The file currently executed is %s<br>", zend_get_executed_filename(TSRMLS_C));
zend_printf("The current line being executed is %i<br>", zend_get_executed_lineno(TSRMLS_C))

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.

ZEND_API int call_user_function_ex(HashTable *function_table, zval *object,


zval *function_name, zval **retval_ptr_ptr,
int param_count, zval **params[],
int no_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.

Ejemplo 39-1. Calling user functions.

zval **function_name;
zval *retval;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS))


{
WRONG_PARAM_COUNT;
}

if((*function_name)->type != IS_STRING)
{
zend_error(E_ERROR, "Function requires string argument");

1637
Capítulo 39. Calling User Functions

TSRMSLS_FETCH();

if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != S


{
zend_error(E_ERROR, "Function call failed");
}

zend_printf("We have %i as type<br>", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);

<?php

dl("call_userland.so");

function test_function()
{

print("We are in the test function!<br>");

return("hello");

$return_value = call_userland("test_function");

print("Return value: \"$return_value\"<br>");


?>

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); // handler for ini-entry "second_ini_entry"

// specify ini-entries here

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:

#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value,


uint new_value_length, void *mh_arg1,
void *mh_arg2, void *mh_arg3)

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

argument), PHP_INI_ENTRY2 (allowing two additional arguments), and PHP_INI_ENTRY3 (allowing


three additional arguments).
The change-notification handlers should be used to cache initialization entries locally for faster access or
to perform certain tasks that are required if a value changes. For example, if a constant connection to a
certain host is required by a module and someone changes the hostname, automatically terminate the old
connection and attempt a new one.
Access to initialization entries can also be handled with the macros shown in Tabla 40-1.

Tabla 40-1. Macros to Access Initialization Entries in PHP

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.

Tabla 42-1. M4 Macros for config.m4

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

Tabla 43-1. API Macros for Accessing zval Containers

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

You might also like