Vous êtes sur la page 1sur 426

Manual de PHP XIII.

Funciones de pago electrónico


XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
Stig Sæther Bakken XVI. Character type functions
Alexander Aulbach XVII. Funciones de la capa de abstraccion de
Egon Schmid bases de datos (dbm-style)
Jim Winstead XVIII. Funciones de fecha y hora
Lars Torben Wilson XIX. Funciones para dBase
Rasmus Lerdorf XX. Funciones dbm
Andrei Zmievski XXI. dbx functions
Jouni Ahto XXII. DB++ Functions
XXIII. Direct IO functions
XXIV. Funciones con directorios
Editado por
XXV. Funciones de DOM XML
XXVI. .NET functions
Rafael Martínez (Coordinador) XXVII. Error Handling and Logging Functions
Víctor Fernández XXVIII. FrontBase Functions
Leonardo Boshell XXIX. Funciones filePro
27-01-2003 XXX. Funciones del sistema de ficheros
Copyright © 1997, 1998, 1999, 2000, 2001, 2002 por el XXXI. Funciones Forms Data Format (Formato
Grupo de documentación de PHP de Datos de Formularios)
Copyright XXXII. FriBiDi functions
Este manual es © Copyright 1997, 1998, 1999, 2000, XXXIII. Funciones FTP
2001, 2002 por el Grupo de documentación de PHP. Los XXXIV. Function Handling functions
miembros de este grupo se encuentran listados en la XXXV. GNU Gettext
primera página de este manual. XXXVI. GMP functions
Este manual puede ser redistribuido bajo los términos de XXXVII. Funciones HTTP
la "GNU General Public License" publicada por la "Free XXXVIII. Funciones para Hyperwave
Software Foundation"; tanto bajo la versión 2 de esta XXXIX. Hyperwave API functions
licencia o bajo versiones posteriores. XL. iconv functions
La sección 'Extendiendo PHP 4.0' de este manual es XLI. Funciones para imágenes
copyright © 2000 por Zend Technologies, Ltd. Este XLII. Funciones IMAP
material puede ser distribuido solamente bajo los XLIII. Funciones para Informix
terminos y condiciones de la Open Publication License, XLIV. Funciones InterBase
v1.0 ó posterior (la última versión está disponible en XLV. Ingres II functions
http://www.opencontent.org/openpub/). XLVI. IRC Gateway Functions
Tabla de contenidos XLVII. PHP / Java Integration
Prefacio XLVIII. Funciones LDAP
I. Conceptos Básicos XLIX. Funciones de Correo
1. Introducción L. mailparse functions
2. A simple tutorial LI. Funciones matemáticas
3. Instalación LII. Multi-Byte String Functions
4. Configuración LIII. MCAL functions
5. Seguridad LIV. Funciones Criptográficas
II. Referencia del Lenguaje LV. MCVE Payment Functions
6. Síntaxis básica LVI. Funciones Hash
7. Types LVII. Mimetype Functions
8. Variables LVIII. Funciones de Microsoft SQL Server
9. Constantes LIX. Ming functions for Flash
10. Expresiones LX. Miscelánea de funciones
11. Operadores LXI. mnoGoSearch Functions
12. Estructuras de Control LXII. funciones mSQL
13. Funciones LXIII. Funciones MySQL
14. Clases y Objetos LXIV. Mohawk Software session handler
15. References Explained functions
III. Características LXV. muscat functions
16. Autentificación HTTP con PHP LXVI. Funciones de Red
17. Cookies LXVII. Ncurses terminal screen control
18. Manejo de envío de ficheros functions
19. Usando archivos remotos LXVIII. Lotus Notes functions
20. Manejando conexiones LXIX. ODBC functions
21. Conexiones persistentes a bases de datos LXX. Object Aggregation/Composition
22. Modo Seguro (Safe Mode) Functions
23. Using PHP from the command line LXXI. Funciones de Oracle 8
IV. Referencia de las Funciones LXXII. OpenSSL functions
I. Funciones específicas de Apache LXXIII. Funciones Oracle
II. Funciones de matrices LXXIV. Ovrimos SQL functions
III. Funciones Aspell [deprecated] LXXV. Output Control Functions
IV. Funciones matemáticas de precisión LXXVI. Object property and method call
arbitraria BCMath overloading
V. Funciones de compresión Bzip2 LXXVII. PDF functions
VI. Funciones de calendario LXXVIII. Verisign Payflow Pro functions
VII. Funciones del API de CCVS LXXIX. opciones e información de PHP
VIII. soporte de las funciones COM para LXXX. Funciones POSIX
Windows LXXXI. Funciones de PostgreSQL
IX. Funciones de Clases/Objectos LXXXII. Process Control Functions
X. Funciones de ClibPDF LXXXIII. Funciones de ejecución de programas
XI. Crack functions LXXXIV. Printer functions
XII. CURL, Client URL Library Functions LXXXV. Pspell Functions
LXXXVI. GNU Readline D. El debugger de PHP
LXXXVII. Funciones GNU Recode E. Desarrollo en PHP
LXXXVIII. Funciones de expresiones regulares F. Lista de alias de funciones
compatibles con Perl G. List of Reserved Words
LXXXIX. qtdom functions H. List of Resource Types
XC. Funciones para expresiones regulares I. List of Supported Protocols/Wrappers
XCI. Funciones Semáforo y de memoria J. Lista de Identificadores (tokens) del
compartida Analizador
XCII. SESAM database functions K. Sobre el manual
XCIII. Funciones para el manejo de sesiones L. Materia que falta
XCIV. Shared Memory Functions
XCV. Shockwave Flash functions
XCVI. Funciones SNMP Prefacio
XCVII. Socket functions
XCVIII. Stream functions
XCIX. Funciones de cadenas PHP, acrónimo de "PHP: Hypertext
C. Funciones de Sybase Preprocessor", es un lenguaje "Open
CI. Tokenizer functions Source" interpretado de alto nivel,
CII. Funciones URL especialmente pensado para
CIII. Funciones sobre variables desarrollos web y el cual puede ser
CIV. vpopmail functions embebido en páginas HTML. La
CV. W32api functions mayoría de su sintaxis es similar a C,
CVI. Funciones WDDX Java y Perl y es fácil de aprender. La
CVII. Funciones de intérprete XML meta de este lenguaje es permitir
CVIII. XML-RPC functions escribir a los creadores de páginas
CIX. XSLT functions web, páginas dinámicas de una
CX. YAZ manera rápida y fácil, aunque se
CXI. NIS funciona pueda hacer mucho más con PHP.
CXII. Zip File Functions (Read Only Access)
CXIII. Funciones de Compresión Este manual contiene principalmente una referencia de
V. Extending PHP 4.0 funciones PHP, tambien contiene una referencia del
24. Overview lenguaje, explicaciones de caracteristicas importantes de
25. Extension Possibilities PHP y alguna información suplementaria.
26. Source Layout Este manual se puede conseguir en diferentes formatos
27. PHP's Automatic Build System en http://www.php.net/docs.php. Estos ficheros son
28. Creating Extensions actualizados a medida que el manual vaya cambiando.
29. Using Extensions Más información sobre como este manual es desarrollado
30. Troubleshooting puede encontrarse en el apéndice'Sobre este manual'
31. Source Discussion
32. Accepting Arguments
33. Creating Variables I. Conceptos Básicos
34. Duplicating Variable Contents: The Copy
Constructor
35. Returning Values Tabla de contenidos
36. Printing Information 1. Introducción
37. Startup and Shutdown Functions 2. A simple tutorial
38. Calling User Functions 3. Instalación
39. Initialization File Support 4. Configuración
40. Where to Go from Here 5. Seguridad
41. Reference: Some Configuration Macros
42. API Macros
43. Streams API for PHP Extension Authors Capítulo 1. Introducción
Overview
Streams Basics Qué es PHP?
Streams as Resources
Streams Common API Reference
Streams Dir API Reference PHP (acronimo de "PHP: Hypertext Preprocessor") es un
Streams File API Reference lenguaje "open source" interpretado de alto nivel
Streams Socket API Reference embebido en páginas HTML y ejecutado en el servidor.
Streams Structures Una respuesta corta y concisa, pero que significa
Streams Constants realmente? Un ejemplo nos aclarará las cosas:
VI. FAQ: Preguntas frecuentes Ejemplo 1-1. Un ejemplo introductorio
44. General Information
45. Mailing lists
46. Obtaining PHP <html>
47. Database issues <head>
48. Installation <title>Example</ti
49. Build Problems tle>
50. Using PHP </head>
51. PHP and HTML <body>
52. PHP and COM
53. PHP and other languages <?php
54. Migrating from PHP 2 to PHP 3 echo "Hi, I'm a PHP
55. Migrating from PHP 3 to PHP 4 script!";
56. Miscellaneous Questions ?>
VII. Apéndices
A. Historia de PHP y proyectos relacionados </body>
B. Migrating from PHP 3 to PHP 4 </html>
C. Migrando de PHP/FI 2.0 a PHP 3.0
Podemos ver que no es lo mismo que un script escrito en PHP puede ser utilizado en cualquiera de los principales
otro lenguaje de programación como Perl o C -- En vez de sistemas operativos del mercado, incluyendo Linux,
escribir un programa con muchos comandos para crear muchas variantes Unix (incluido HP-UX, Solaris y
una salida en HTML, escribimos el código HTML con OpenBSD), Microsoft Windows, Mac OS X, RISC OS y
cierto código PHP embebido (introducido) en el mismo, probablemente alguno más. PHP soporta la mayoría de
que producirá cierta salida (en nuestro ejemplo, producir servidores web de hoy en día, incluyendo Apache,
un texto). El código PHP se incluye entre etiquetas Microsoft Internet Information Server, Personal Web
especiales de comienzo y final que nos permitirán entrar Server, Netscape y iPlanet, Oreilly Website Pro server,
y salir del modo PHP. Caudium, Xitami, OmniHTTPd y muchos otros. PHP tiene
Lo que distingue a PHP de la tecnología Javascript, la cual módulos disponibles para la mayoría de los servidores,
se ejecuta en la máquina cliente, es que el código PHP es para aquellos otros que soporten el estándar CGI, PHP
ejecutado en el servidor. Si tuviesemos un script similar puede usarse como procesador CGI.
al de nuestro ejemplo en nuestro servidor, el cliente Asi que, con PHP teneis la libertad de escoger el sistema
sólamente recibiría el resultado de su ejecución en el operativo y el servidor de vuestro gusto. Tambien teneis
servidor, sin ninguna posibilidad de determinar que la posibilidad de usar programación de procediminetos ó
código ha producido el resultado recibido. El servidor programación orientada a objetos. Aunque no todas la
web puede ser incluso configurado para que procese características estándares de la programación orientada
todos los ficheros HTML con PHP. a objetos están implementadas en la versión actual de
Lo mejor de usar PHP es que es extremadamente simple PHP, muchas librerías y aplicaciones grandes (incluyendo
para el principiante, pero a su vez, ofrece muchas la libreria PEAR) están escritas íntegramente usando
caracteristicas avanzadas para los programadores programación orientada a objetos.
profesionales. No tengais miedo de leer la larga lista de Con PHP no estais limitados a resultados en HTML. Entre
caracteristicas de PHP, en poco tiempo podreis empezar las habilidades de PHP se incluyen, creación de
a escribir vuestros primeros scripts. imágenes, ficheros PDF y películas Flash (usando libswf y
Aunque el desarrollo de PHP está concentrado en la Ming) sobre la marcha. Tambien podeis presentar otros
programación de scripts en la parte del servidor, se resultados, como XHTM y ficheros XML. PHP puede
puede utilizar para muchas otras cosas. Sigue leyendo y autogenerar estos ficheros y grabarlos en el sistema de
descubre más sobre PHP en la sección Qué se puede ficheros en vez de presentarlos en la pantalla.
hacer con PHP?. Quizas la característica más potente y destacable de PHP
es su soporte para una gran cantidad de bases de datos.
Escribir un interfaz via web para una base de datos es
Qué se puede hacer con PHP? una tarea simple con PHP. Las siguientes bases de datos
están soportadas actualmente:
Oracle (OCI7 and
PHP puede hacer cualquier cosa que se pueda hacer con Adabas D Ingres
OCI8)
un script CGI, como procesar la información de
formularios, generar páginas con contenidos dinámicos, dBase InterBase Ovrimos
o mandar y recibir cookies. Y esto no es todo, se puede Empress FrontBase PostgreSQL
hacer mucho más. FilePro (read-
mSQL Solid
Existen tres campos en los que scripts escritos en PHP only)
son usados. Direct MS-
Hyperwave Sybase
SQL
IBM DB2 MySQL Velocis
• Scripts en la parte del servidor. Este es el Informix ODBC Unix dbm
campo más tradicional y el principal campo de Tambien tenemos una extensión DBX de abstracción de
trabajo. Se necesitan tres cosas para que esto
base de datos que permite usar de forma transparente
funcione. El analizador PHP (CGI ó módulo), un cualquier base de datos soportada por la extension.
servidor web y un navegador. Se necesita
Adicionalmente, PHP soporta ODBC (The Open Database
correr el servidor web con PHP instalado. El Connection standard), asi que podeis conectar a
resultado del programa PHP se puede obtener
cualquier base de datos que soporte este estandar.
a través del navegador, conectando con el PHP tambien tiene soporte para comunicarse con otros
servidor web. Consultar la sección
servicios usando protocolos tales como LDAP, IMAP,
Instrucciones de instalación para más SNMP, NNTP, POP3, HTTP, COM (en Windows) y muchos
información.
otros. Tambien se pueden crear raw sockets. PHP soporta
• Scripts en linea de comandos. Podeis crear un WDDX para intercambio de datos entre lenguajes de
script PHP y correrlo sin ningún servidor web ó programación en web. Y hablando de interconexión, PHP
navegador. Solamente necesitais el parseador puede utilizar objetos Java de forma transparente como
PHP para usarlo de esta manera. Este tipo de objetos PHP Y la extensión de CORBA puede ser utilizada
uso es ideal para scripts ejecutados para acceder a objetos remotos.
regularmente desde cron (en *nix ó Linux) ó el PHP tiene unas características muy útiles para el proceso
Planificador de tareas (en Windows). Estos de texto, desde expresiones regulares POSIX Extended ó
scripts tambien pueden ser usados para tareas Perl hasta parseador de documentos XML. Para parsear y
simples de procesado de texto. Consultar la acceder documentos XML, soportamos los estandares
sección Usos de PHP en la linea de comandos SAX y DOM. Podeis utilizar la extensión XSLT para
para más información. transformar documentos XML.
Si usais PHP en el campo del comercio electrónico,
• Escribir aplicaciones gráficas clientes. PHP no
encontrareis muy útiles las funciones Cybercash,
es probablemente el mejor lenguaje para CyberMUT, VeriSign Payflow Pro y CCVS para vuestros
escribir aplicaciones gráficas, pero si sabeis programas de pago.
bien PHP, y os gustaria utilizar algunas Para terminar, tenemos muchas otras extensiones muy
características avanzadas en programas interesantes, las funciones del motor de búsquedas
clientes, podeis utilizar PHP-GTK para escribir mnoGoSearch, funciones para pasarelas de IRC,
dichos programas. Es tambien posible escribir utilidades de compresión (gzip, bz2),, conversión de
aplicaciones independientes de una calendarios, traducción .....
plataforma. PHP-GTK es una extensión de PHP, Como podeis ver esta página no es suficiente para
no disponible en la distribución principal. Si te enumerar todas las características y beneficios que PHP
interesa PHP-GTK, puedes visitar las páginas ofrece. Consultar las secciones Instalando PHP y
web del projecto. Referencia de las funciones para una explicación de las
extensiones mencionadas aqui.
Capítulo 2. A simple tutorial
</body>
</html>
Here we would like to show the very basics of PHP in a Note that this is not like a CGI script. The file does not
short simple tutorial. This text only deals with dynamic need to be executable or special in any way. Think of it
webpage creation with PHP, though PHP is not only as a normal HTML file which happens to have a set of
capable of creating webpages. See the section titled special tags available to you that do a lot of interesting
What can PHP do for more information. things.
PHP-enabled web pages are treated just like regular This program is extremely simple and you really didn't
HTML pages and you can create and edit them the same need to use PHP to create a page like this. All it does is
way you normally create regular HTML pages. display: Hello World using the PHP echo() statement.
If you tried this example and it didn't output anything, or
it prompted for download, or you see the whole file as
What do I need? text, chances are that the server you are on does not
have PHP enabled. Ask your administrator to enable it for
In this tutorial we assume that your server has support you using the Installation chapter of the manual. If you're
developing locally, also read the installation chapter to
for PHP activated and that all files ending in .php are
handled by PHP. On most servers this is the default make sure everything is configured properly. If problems
continue to persist, don't hesitate to use one of the many
extension for PHP files, but ask your server administrator
to be sure. If your server supports PHP then you don't PHP support options.
The point of the example is to show the special PHP tag
need to do anything. Just create your .php files and put
them in your web directory and the server will magically format. In this example we used <?php to indicate the
start of a PHP tag. Then we put the PHP statement and
parse them for you. There is no need to compile anything
nor do you need to install any extra tools. Think of these left PHP mode by adding the closing tag, ?>. You may
jump in and out of PHP mode in an HTML file like this all
PHP-enabled files as simple HTML files with a whole new
family of magical tags that let you do all sorts of things. you want. For more details, read the manual section on
basic PHP syntax.
Let's say you want to save precious bandwidth and
develop locally. In this case, you'll want to install a web
server, such as Apache, and of course PHP. You'll most A Note on Text Editors: There are
likely want to install a database as well, such as MySQL. many text editors and Integrated
You can install these individually or a simpler way is to Development Environments (IDEs)
locate a pre-configured package that automatically that you can use to create, edit and
installs all of these with just a few mouse clicks. It's easy manage PHP files. A partial list of
to setup a web server with PHP support on any operating these tools is maintained at PHP
system, including Linux and Windows. In linux, you may Editor's List. If you wish to
find rpmfind helpful for locating RPMs. recommend an editor, please visit
the above page and ask the page
maintainer to add the editor to the
Your first PHP-enabled page list. Having an editor with syntax
highlighting can be helpful.
Create a file named hello.php and put it in your web
servers root directory (DOCUMENT_ROOT) with the A Note on Word Processors:
following content: Word processors such as StarOffice
Ejemplo 2-1. Our first PHP script: hello.php Writer, Microsoft Word and Abiword
are not good choices for editing PHP
files. If you wish to use one for this
<html> test script, you must ensure that you
<head> save the file as PLAIN TEXT or PHP
<title>PHP Test</title> will not be able to read and execute
</head> the script.
<body>
<?php echo "<p>Hello
World</p>"; ?> A Note on Windows Notepad: If
</body> you are writing your PHP scripts
</html> using Windows Notepad, you will
need to ensure that your files are
saved with the .php extension.
Use your browser to access the file with your web access (Notepad adds a .txt extension to
URL, ending with the "/hello.php" file reference. When files automatically unless you take
developing locally this url will be something like one of the following steps to prevent
http://localhost/hello.php or http://127.0.0.1/hello.php but it.) When you save the file and are
this depends on the web servers configuration. Although prompted to provide a name for the
this is outside the scope of this tutorial, see also the file, place the filename in quotes (i.e.
DocumentRoot and ServerName directives in your web "hello.php"). Alternately, you can
servers configuration file. (on Apache this is httpd.conf). If click on the 'Text Documents' drop-
everything is setup correctly, this file will be parsed by down menu in the save dialog box
PHP and the following output will make it to your browser: and change the setting to "All Files".
You can then enter your filename
without quotes.
<html>
<head> Now that you've successfully created a simple PHP script
<title>PHP that works, it's time to create the most famous PHP
Test</title> script! Make a call to the phpinfo() function and you'll
</head> see a lot of useful information about your system and
<body> setup such as available Predefined Variables, loaded PHP
<p>Hello modules, and configuration settings. Take some time and
World</p> review this important information.
Something Useful

A sample output of this script may be:


Let's do something a bit more useful now. We are going
to check what sort of browser the person viewing the
page is using. In order to do that we check the user You are using Internet
agent string that the browser sends as part of its HTTP Explorer<br />
request. This information is stored in a variable. Variables
always start with a dollar-sign in PHP. The variable we Here we introduce a couple of new concepts. We have an
are interested in right now is if statement. If you are familiar with the basic syntax
$_SERVER["HTTP_USER_AGENT"]. used by the C language this should look logical to you. If
you don't know enough C or some other language where
the syntax used above is used, you should probably pick
PHP Autoglobals Note: $_SERVER up any introductory PHP book and read the first couple of
is a special reserved PHP variable chapters, or read the Language Reference part of the
that contains all web server manual. You can find a list of PHP books at
information. It's known as an http://www.php.net/books.php.
Autoglobal (or Superglobal). See the The second concept we introduced was the strstr()
related manual page on Autoglobals function call. strstr() is a function built into PHP which
for more information. These special searches a string for another string. In this case we are
variables were introduced in PHP looking for "MSIE" inside
4.1.0. Before this time, we used the $_SERVER["HTTP_USER_AGENT"]. If the string is found,
older $HTTP_*_VARS arrays instead, the function returns TRUE and if it isn't, it returns
such as $HTTP_SERVER_VARS. FALSE. If it returns TRUE, the if statement evaluates to
Although deprecated, these older TRUE and the code within its {braces} is executed.
variables still exist. (See also the Otherwise, it's not. Feel free to create similar examples,
note on old code.) with if, else, and other functions such as strtoupper()
and strlen(). Each related manual page contains
examples too.
To display this variable, we can simply do: We can take this a step further and show how you can
Ejemplo 2-2. Printing a variable (Array element) jump in and out of PHP mode even in the middle of a PHP
block:
Ejemplo 2-5. Mixing both HTML and PHP modes
<?php echo
$_SERVER["HTTP_USER_AGENT"]; ?>
<?php
if (strstr($_SERVER["HTTP_USER_AGENT"],
A sample output of this script may be: "MSIE")) {
?>
<h3>strstr must have returned true</h3>
Mozilla/4.0 (compatible; MSIE 5.01; <center><b>You are using Internet
Windows NT 5.0) Explorer</b></center>
<?php
There are many types of variables available in PHP. In } else {
the above example we printed an Array element. Arrays ?>
can be very useful. <h3>strstr must have returned false</h3>
$_SERVER is just one variable that's automatically made <center><b>You are not using Internet
available to you by PHP. A list can be seen in the Explorer</b></center>
Reserved Variables section of the manual or you can get <?php
a complete list of them by creating a file that looks like }
this: ?>
Ejemplo 2-3. Show all predefined variables with
phpinfo()
A sample output of this script may be:
<?php
phpinfo(); ?>
<h3>strstr must have returned true</h3>
If you load up this file in your browser you will see a page <center><b>You are using Internet
full of information about PHP along with a list of all the Explorer</b></center>
variables available to you.
Instead of using a PHP echo statement to output
You can put multiple PHP statements inside a PHP tag
something, we jumped out of PHP mode and just sent
and create little blocks of code that do more than just a
straight HTML. The important and powerful point to note
single echo. For example, if we wanted to check for
here is that the logical flow of the script remains intact.
Internet Explorer we could do something like this:
Only one of the HTML blocks will end up getting sent to
Ejemplo 2-4. Example using control structures and
the viewer depending on if strstr() returned TRUE or
functions
FALSE In other words, if the string MSIE was found or
not.
<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], Dealing with Forms
"MSIE")) {
echo "You are using Internet
Explorer<br />"; One of the most powerful features of PHP is the way it
} handles HTML forms. The basic concept that is important
?> to understand is that any form element in a form will
automatically be available to your PHP scripts. Please
read the manual section on Variables from outside of PHP
for more information and examples on using forms with
PHP. Here's an example HTML form:
Ejemplo 2-6. A simple HTML form http://www.example.com/foo.php?id=42.
Whether on or off, $_GET['id'] is available.

<form action="action.php"
For more details on these changes, see the section on
method="POST">
predefined variables and links therein.
Your name: <input type="text"
name="name" />
Your age: <input type="text"
What's next?
name="age" />
<input type="submit">
</form> With what you know now you should be able to
There is nothing special about this form. It is a straight understand most of the manual and also the various
HTML form with no special tags of any kind. When the example scripts available in the example archives. You
user fills in this form and hits the submit button, the can also find other examples on the php.net websites in
action.php page is called. In this file you would have the links section: http://www.php.net/links.php.
something like this:
Ejemplo 2-7. Printing data from our form
Capítulo 3. Instalación

Hi <?php echo $_POST["name"]; ?>. Bajándose la última versión


You are <?php echo $_POST["age"]; ?
> years old.
El código fuente y las distribuciones binarias para
algunas plataformas (incluído Windows) se pueden
A sample output of this script may be: encontrar en http://www.php.net/.

Instalación en sistemas UNIX


Hi Joe.
You are 22
years old. Esta sección le guiará a través de la configuración e
It should be obvious what this does. There is nothing instalación del PHP. Conocimientos y software
more to it. The $_POST["name"] and $_POST["age"] necesarios:
variables are automatically set for you by PHP. Earlier we
used the $_SERVER autoglobal, now above we just
introduced the $_POST autoglobal which contains all • Habilidades básicas en UNIX (ser capaz de
POST data. Notice how the method of our form is POST. If manejar el "make" y un compilador de C)
we used the method GET then our form information • Un compilador ANSI de C
would live in the $_GET autoglobal instead. You may also
use the $_REQUEST autoglobal if you don't care the • Un servidor web
source of your request data. It contains a mix of GET,
POST, COOKIE and FILE data. See also the
import_request_variables() function.
Instrucciones Rápidas de Instalación (Versión
Using old code with new versions of PHP Módulo de Apache)

Now that PHP has grown to be a popular scripting 1. gunzip apache_1.3.x.tar.gz


language, there are more resources out there that have 2. tar xvf apache_1.3.x.tar
listings of code you can reuse in your own scripts. For the 3. gunzip php-3.0.x.tar.gz
most part the developers of the PHP language have tried 4. tar xvf php-3.0.x.tar
to be backwards compatible, so a script written for an 5. cd apache_1.3.x
older version should run (ideally) without changes in a 6. ./configure --prefix=/www
newer version of PHP, in practice some changes will 7. cd ../php-3.0.x
usually be needed. 8. ./configure --with-mysql --with-
Two of the most important recent changes that affect old apache=../apache_1.3.x --enable-track-vars
code are: 9. make
10. make install
11. cd ../apache_1.3.x
• The deprecation of the old $HTTP_*_VARS 12. ./configure --prefix=/www --activate-
arrays (which need to be indicated as global module=src/modules/php3/libphp3.a
when used inside a function or method). The 13. make
following autoglobal arrays were introduced in 14. make install
PHP 4.1.0. They are: $_GET, $_POST,
$_COOKIE, $_SERVER, $_ENV, $_REQUEST, and En lugar de este paso quizás prefiera simplemente
$_SESSION. The older $HTTP_*_VARS arrays, copiar el binario
such as $HTTP_POST_VARS, still exist and have httpd encima del binario existente. Si lo hace,
since PHP 3. asegúrese antes de
cerrar su servidor.
• External variables are no longer registered in
the global scope by default. In other words, as 15. cd ../php-3.0.x
of PHP 4.2.0 the PHP directive register_globals 16. cp php3.ini-dist /usr/local/lib/php3.ini
is off by default in php.ini. The preferred
method of accessing these values is via the Puede editar el archivo /usr/local/lib/php3.ini para
autoglobal arrays mentioned above. Older ajustar opciones
scripts, books, and tutorials may rely on this del PHP. Si prefiere tenerlo en otro sitio, utilice
directive being on. If on, for example, one --with-config-file-path=/path en el paso 8.
could use $id from the URL
distintas páginas con PHP bajo distintos identificadores
de usuario. Por favor, asegúrese de haber leído el
17. Edite su archivo httpd.conf o srm.conf y añada:
capítulo sobre Seguridad si va a ejecutar el PHP como
CGI.
AddType application/x-httpd-php3 .php3

Puede elegir la extensión que desee aquí. .php3 es


Opciones de soporte para Base de Datos
simplemente nuestra
sugerencia.
El PHP tiene soporte nativo para bastantes bases de
18. Utilice su método habitual para iniciar el servidor datos (así como para ODBC):
Apache (debe detener
y reiniciar el servidor, no solamente hacerlo
recargarse usando una Adabas D
señal HUP o USR1.)

--with-
Configuración adabas=DIR
Compila con soporte para Adabas D. El parámetro es el
Hay dos maneras de configurar el PHP. directorio de instalación de Adabas D y por defecto vale
/usr/local/adabasd.
Página de Adabas
• Utilizando el script de "setup" que viene con el
PHP. Este script le hace una serie de preguntas dBase
(casi como el script "install" del PHP/FI 2.0) y
ejecuta el "configure" al final. Para ejecutar
este script, escriba ./setup.
--with-
dbase
Este script también creará un archivo llamado Habilita el soporte integrado para DBase. No se precisan
"do-conf", que contendrá las opciones pasadas librerías externas.
a la configuración. Puede editar este archivo
para cambiar algunas opciones sin tener que
re-ejecutar el "setup". Escriba luego ./do-conf filePro
para ejecutar la configuración con las nuevas
opciones.
--with-
filepro
• Ejecutar el "configure" a mano. Para ver las
Habilita el soporte integrado de sólo lectura para filePro.
opciones de que dispone, escriba ./configure
No se precisan librerías externas.
--help.

Los detalles sobre las distintas opciones de configuración mSQL


son listados a continuación.

--with-
Módulo del Apache msql=DIR
Habilita el soporte para mSQL. El parámetro es el
Para configurar el PHP como módulo de Apache, directorio de instalación de mSQL y por defecto vale
responda "yes" a "Build as an Apache module?" (la /usr/local/Hughes. Este es el directorio por defecto de la
opción --with-apache=DIR es la que lo configura) y distribución mSQL 2.0. configure detecta
especifique el directorio base de la distribución de automáticamente qué versión de mSQL está
Apache. Si ha desempacado el Apache en ejecutándose y el PHP soporta tanto 1.0 como 2.0, pero
/usr/local/www/apache_1.2.4, este será su directorio base si compila el PHP con mSQL 1.0 sólo podrá acceder a
de la distribución de Apache. El directorio por defecto es bases de datos de esa versión y viceversa.
/usr/local/etc/httpd. Vea también Directivas de Configuración de mSQL en el
archivo de configuración.
Página de mSQL
Módulo fhttpd

MySQL
Para configurar el PHP como módulo fhttpd, responda
"yes" a "Build as an fhttpd module?" (la opción --with-
fhttpd=DIR es la que lo configura) y especifique el --with-
directorio base del fuente del fhttpd. El directorio por mysql=DIR
defecto es /usr/local/src/fhttpd. Si está ejecutando fhttpd,
configurar PHP como módulo le dará mejor rendimiento, Habilita el soporte para MySQL. El parámetro es el
más control y capacidad de ejecución remota. directorio de instalación de MySQL y por defecto vale
/usr/local. Este es el directorio de instalación de la
distribución de MySQL.
CGI version Vea también Directivas de Configuración de MySQL en el
archivo de configuración.
Página de MySQL
El valor por defecto es configurar el PHP como programa
CGI. Si está ejecutando un servidor web para el que el
PHP tiene soporte como módulo, debería elegir dicha iODBC
solución por motivos de rendimiento. Sin embargo, la
versión CGI permite a los usuarios del Apache el ejecutar
--with- ct=DIR
iodbc=DIR
Incluye soporte para Sybase-CT. El parámetro es el
Incluye soporte para iODBC. Esta característica se directorio de instalación de Sybase-CT y por defecto vale
desarrolló inicialmente para el iODBC Driver Manager, un /home/sybase.
gestor de controlador de ODBC de redistribución libre Vea también Directovas de Configuración de Sybase-CT
que ese ejecuta bajo varios sabores de UNIX. El en el archivo de configuración.
parámetro es el directorio de instalación de iODBC y por
defecto vale /usr/local.
Página de FreeODBC o página de iODBC Velocis

OpenLink ODBC --with-


velocis=DIR
Incluye soporte para Velocis. El parámetro es el
--with-
directorio de instalación de Velocis y vale por defecto
openlink=DIR
/usr/local/velocis.
Incluye soporte para OpenLink ODBC. El parámetro es el Página de Velocis
directorio de instalación de OpenLink ODBC y por defecto
vale /usr/local/openlink.
Página de OpenLink Software Una librería a medida de ODBC

Oracle --with-custom-
odbc=DIR
Incluye soporte para una librería a medida arbitraria de
--with-
ODBC. El parámetro es el directorio base y por defecto
oracle=DIR
vale /usr/local.
Incluye soporte para Oracle. Se ha probado y debería Esta opción implica que se ha definido
funcionar al menos con las versiones de la 7.0 a la 7.3. El CUSTOM_ODBC_LIBS cuando se ejecutó el script de
parámetro es el directorio ORACLE_HOME. No necesita configuración. También deberá tener una cabecera
especificar este parámetro si su entorno de Oracle ya odbc.h válida en algún lugar de su sendero (path) de
está ajustado. inclusión. Si no tiene uno, créelo e incluya su cabecera
Página de Oracle específica desde ahí. Su cabecera puede requerir algunas
definiciones extra, particularmente si es multiplataforma.
Defínalas en CFLAGS.
PostgreSQL Por ejemplo, puede usar Sybase SQL Anywhere bajo QNX
como sigue: CFLAGS=-DODBC_QNX LDFLAGS=-lunix
CUSTOM_ODBC_LIBS="-ldblib -lodbc" ./configure --with-
--with- custom-odbc=/usr/lib/sqlany50
pgsql=DIR
Incluye soporte para PostgreSQL. El parámetro es el ODBC Unificado
directorio base de la instalación de PostgreSQL y por
defecto vale /usr/local/pgsql.
Vea también Directivas de Configuración de Postgres en
--disable-unified-
el archivo de configuración.
odbc
Página de PostgreSQL
Deshabilita el módulo de ODBC Unificado, que es un
interfaz común a todas las bases de datos con interfaces
Solid basados en ODBC, tales como Solid y Adabas D. También
funciona para librerías normales de ODBC. Ha sido
probado con iODBC, Solid, Adabas D y Sybase SQL
--with- Anywhere. Requiere que uno (y sólo uno) de estos
solid=DIR módulos o el módulo de Velocis esté habilitado, o que se
especifique una librería a medida de ODBC. Esta opción
Incluye soporte para Solid. El parámetro es el directorio
sólo se puede aplicar si alguna de estas opciones es
de instalación y vale por defecto /usr/local/solid.
usada: --with-iodbc, --with-solid, --with-adabas, --with-
Página de Solid
velocis, o --with-custom-odbc.
Vea también Directivas de Configuración de ODBC
Unificado en el archivo de configuración.
Sybase

LDAP
--with-
sybase=DIR
Incluye soporte para Sybase. El parámetro es el --with-
directorio de instalación y vale por defecto ldap=DIR
/home/sybase.
Incluye soporte para LDAP (Lightweight Directory Access
Vea también Directivas de Configuración de Sybase en el
Protocol - Protocolo Ligero de Acceso a Directorios). El
archivo de configuración.
parámetro es el directorio base de instalación de LDAP, y
Página de Sybase
por defecto vale /usr/local/ldap.
Puede encontrar más información sobre LDAP en
RFC1777 y en RFC1778.
Sybase-CT

Otras opciones de configuración


--with-sybase-
--with-mcrypt=DIR --with-exec-dir

--with- --with-exec-
mcrypt dir=DIR
Incluye soporte para la librería mcrypt. Vea la Sólo permite ejecutar programas en DIR cuando está en
documentación de mcrypt para más información. Si modo seguro. Por defecto vale /usr/local/bin. Esta opción
utiliza el argumento opcional DIR, el PHP buscará sólo fija el valor por defecto. Puede ser cambiado
mcrypt.h en DIR/include. posteriormente mediante la directiva
safe_mode_exec_dir en el fichero de configuración .

--enable-sysvsem
--enable-debug

--enable-
sysvsem --enable-
debug
Incluye soporte para semáforos Sys V (soportados por
muchos derivados Unix). Vea la documentación sobre Habilita información de depuración adicional. Esto hace
Semáforos y Memoria Compartida para más información. posible obtener información más detallada cuando hay
problemas con el PHP. (Nótese que esto no tiene que ver
con las facilidades de depuración o con la información
--enable-sysvshm disponible para los script PHP).

--enable- --enable-safe-mode
sysvshm
Incluye soporte para la memoria compartida Sys V
--enable-safe-
(soportada por muchos derivados Unix). Vea la
mode
documentación sobre Semáforos y Memoria Compartida
para más información. Habilita el "modo seguro" por defecto. Esto impone
varias restricciones sobre lo que el PHP puede hacer,
tales como abrir fichero sólo en el raiz de documentos.
--with-xml Lea el capítulo de Seguridad para más información. Los
usuarios de CGI deberán siempre habilitar el modo
seguro. Esta opción sólo fija el valor por defecto. Puede
--with- ser habilitado o deshabilitado posteriormente mediante
xml la directiva safe_mode en el archivo de configuración.
Incluye soporte para un parser XML no validador que
utiliza la librería expat de James Clark. Vea la referencia --enable-track-vars
de funciones XML para más detalles.

--enable-maintainer-mode --enable-track-
vars
Hace que el PHP lleve el control de dónde proceden las
--enable- variables GET/POST/cookie usando las matrices
maintainer-mode HTTP_GET_VARS, HTTP_POST_VARS y
HTTP_COOKIE_VARS. Esta opción sólo fija el valor por
Activa avisos extra de dependencias y del compilador
defecto. Puede ser habilitado o deshabilitado
utilizados por algunos de los desarrolladores del PHP.
posteriormente mediante la directiva track_vars en el
archivo de configuración.
--with-system-regex
--enable-magic-quotes

--with-system-
regex
--enable-magic-
Utiliza la librería de expresiones regulares del sistema en quotes
lugar de la incluída. Si está compilando PHP como
Habilita las comillas mágicas por defecto. Esta opción
módulo de servidor, debe utilizar la misma librería
sólo fija el valor por defecto. Puede ser habilitada o
cuando genere el PHP y cuando lo enlace con el servidor.
deshabilitada posteriormente mediante la directiva
Active esto si la librería del sistema proporciona
magic_quotes_runtime en el archivo de configuración.
características especiales que pueda necesitar. Se
Vea también las directivas magic_quotes_gpc y
recomienda utilizar la librería incluída siempre que sea
magic_quotes_sybase.
posible.

--enable-debugger
--with-config-file-path

--enable-
--with-config-file-
debugger
path=DIR
Habilita el soporte de depuración interno del PHP. Esta
El path utilizado para buscar el archivo de configuración
característica aún está en estado experimental. Vea
cuando arranca el PHP.
también las directivas de Configuración del Depurador en
el archivo de configuración.
--enable-discard-path
--disable-
syntax-hl

--enable- Desconecta el resalte de sintáxis.


discard-path
Si está habilitado, el ejecutable CGI del PHP se puede CPPFLAGS y LDFLAGS
situar tranquilamente fuera del árbol de la web y la gente
no podrá saltarse la seguridad del .htaccess. Lea la
sección en el capítulo de seguridad sobre esta opción. Para hacer que la instalación de PHP busque los archivos
de cabecera o de librería en distintos directorios,
modifique las variables de entorno CPPFLAGS y LDFLAGS
--enable-bcmath respectivamente. Si está utilizando un shell "sensible",
podrá ejecutar LDFLAGS=-L/my/lib/dir CPPFLAGS=-
I/my/include/dir ./configure
--enable-
bcmath
Construyendo
Habilita las funciones matemáticas de precisión arbitraria
estilo bc. Vea también la opción bcmath.scale en el
archivo de configuración. Cuando el PHP está configurado, ya está listo para
construir el ejecutable CGI o la librería PERL. El comando
make debería ocuparse de esto. Si fallara y no puede
--enable-force-cgi-redirect saber el motivo, vea la sección de Problemas.

--enable-force-cgi- Probando
redirect
Habilita la comprobación de seguridad para redirecciones Si ha construído el PHP como un programa CGI, puede
internas del servidor. Deberá usar esta opción si está probar su funcionamiento tecleando make test. Siempre
ejecutando la versión CGI bajo Apache. es buena idea probar su construcción. Así puede atrapar
Cuando se utiliza el PHP como un ejecutable CGI, pronto los problemas del PHP en su plataforma sin tener
siempre comprueba primero is está siendo utilizado bajo que batallar con ellos luego.
redirección (por ejemplo bajo Apache, usando directivas
Action). Esto asegura que el ejecutable del PHP no se
puede usar para saltarse los mecanismos estánder de Comprobando la velocidad
autentificación del servidor web llamando al ejecutale
directamente, como en http://my.host/cgi-
bin/php/secret/doc.html. Este ejemplo accede al archivo Si ha construído el PHP como un programa CGI, puede
http://my.host/secret/doc.html pero sin respetar ningún comprobar la velocidad de su código escribiendo make
ajuste de seguridad del httpd para el directorio /secret. bench. Nótese que se el modo seguro está habilitado por
No habilitando esta opción se deshabilita la defecto, el test no podrá finalizar si se toma más de los
comprobación y se permite el saltarse los ajustes de 30 segundos disponibles. Esto se debe a que la función
seguridad y autenticación del httpd. Haga esto sólo si el set_time_limit() no se puede usar en modo seguro. Use
software de su servidor no puede indicar que se ha el ajuste de configuración max_execution_time para
realizado una redirección segura y que todos sus controlar este tiempo en sus propios script. make bench
archivos bajo la raiz de documentos y los directorios de ignora el archivo de configuración.
los usuarios pueden ser accedidos por cualquiera.
Lea la sección en el capítulo de seguridad acerca de esta
opción. Instalación en sistemas Windows 95/98/NT

Esta guía de instalación le ayudará a instalar y configurar


--disable-short-tags el PHP en sus servidores web bajo Windows 9x/NT. Esta
guía fue compilada por Bob Silva. La última revisión
puede encontrarse en
--disable-short- http://www.umesd.k12.or.us/php/win32install.html.
tags Esta guía proporciona soporte de instalacion para:
Deshabilita las etiquetas de PHP en formato corto <? ?>.
Debe deshabilitar el formato corto si desea usar PHP con
XML. Con el formato corto deshabilitado, la única • Personal Web Server (se recomienda la última
etiqueta de código de PHP es <?php ?>. Esta opción sólo versión)
fija el valor por defecto. Puede ser habilitada o
deshabilitada posteriormente mediante la directiva
• Internet Information Server 3 ó 4
short_open_tag en el archivo de configuración. • Apache 1.3.x
• Omni HTTPd 2.0b1
--enable-url-includes

--enable-url- Pasos Generales de Instalación


includes
Hace posible ejecutar código en otros servidores HTTP o Los siguientes pasos deben realizarse en todas las
FTP directamente desde el PHP usando include(). Vea instalaciones antes de las instrucciones específicas de
también la opción include_path en el archivo de cada servidor.
configuración.

--disable-syntax-hl
• Extraiga el archivo de distribución a un • Haga doble click en el nuevo valor de cadena y
directorio de su elección. "C:\PHP3\" es un escriba la ruta al php.exe en el campo del
buen comienzo. valor. P.ej.: c:\php3\php.exe %s %s. La parte
'%s %s' son MUY importantes, pues el PHP no
• Copie el archivo 'php3.ini-dist' a su directorio
funcionará correctamente sin ella.
'%WINDOWS%' y renómbrelo a 'php3.ini'. Su
directorio '%WINDOWS%' es típicamente: • Repita estos pasos para cada extensión que
c:\windows para Windows desee asociar con los scripts PHP.
95/98 • Ahora navegue hasta: HKEY_CLASSES_ROOT
c:\winnt o c:\winnt40 para
servidores NT • En el menú de edición elija: New->Key.

• Edite su archivo 'php3.ini': • Déle a la clave el nombre de la extensión que


preparó en la sección anterior. P.ej.: .php3
o Necesitaá cambiar la opción
'extension_dir' para que apunte a su • Marque la nueva clave y en el panel del lado
php-install-dir, o a donde quiera que derecho haga doble click en "default value" y
haya puesto sus archivos escriba phpfile.
'php3_*.dll'. P.ej.: c:\php3 • Repita el último paso para cada extensión que
o Si está utilizando Omni Httpd, no haya preparado en la sección previa.
siga el siguiente paso. Fije el • Ahora cree otra New->Key bajo
'doc_root' para que apunte a la raiz HKEY_CLASSES_ROOT y denomínela phpfile.
web de sus servidores. P.ej.:
c:\apache\htdocs o c:\webroot • Marque la nueva clave phpfile y haga doble
o Elija qué módulos desearía cargar click en el panel derecho sobre "default value"
y escriba PHP Script.
cuando comience el PHP. Puede
descomentar las líneas: • Pulse el botón derecho sobre la clave phpfile y
'extension=php3_*.dll' para cargar seleccione New->Key y llámela Shell.
estos módulos. Algunos módulos
requieren que tenga instaladas en
• Pulse el botón derecho sobre la clave Shell y
elija New->Key y llámela open.
sus sistema librerías adicionales
para que el módulo funcione • Pulse el botón derecho sobre la clave open y
correctamente. El FAQ de PHP tiene elija New->Key y llámela command.
más información sobre dónde
obtener librerías de soporte.
• Marque la nueva clave command y en el panel
derecho haga doble click sobre "default value"
También puede cargar un módulo
y entre la ruta hasta el php.exe. P.ej.:
dinámicamente en su script
c:\php3\php.exe -q %1. (no olvide el %1).
utilizando: dl("php_*.dll");
o En el PWS y el IIS puede fijar el • Salga del Regedit.
browscap.ini para que apunte a:
'c:\windows\system\inetsrv\browscap Los usuarios de PWS e IIS3 tienen ahora un sistema
.ini' bajo Windows 95/98 y a completamente operativo. Los usuarios del IIS3 también
'c:\winnt\system32\inetsrv\browscap. pueden usar una curiosa herramienta de Steven Genusa
ini' bajo NT Server. para configurar sus mapeados de script.

Las DLL para las extensiones del PHP van precedidas de


Windows NT e IIS 4
'php3_'. Esto evita confusiones entre las extensiones del
PHP y sus librerías de soporte.
Para instalar el PHP en un NT Server con IIS 4, siga estas
instrucciones:
Windows 95/98/NT y PWS/IIS 3

El método recomendado para configurar estos servidores • En el Controlador de Servicios de Internet


es usar el archivo INF incluído con la distribución (MMC), elija el sitio Web o el directorio de
(php_iis_reg.inf). Quizás desee editar este archivo y comienzo de una aplicación.
asegurarse que las extensiones y directorios de • Abra las propiedades del directorio (haciendo
instalación se ajustan a su configuración. O puede seguir click derecho y eligiendo propiedades) y luego
los pasos que siguen para hacerlo de forma manual. pulse sobre la pestaña Carpeta Inicial,
AVISO: Estos pasos conllevan el trabajar directamente Directorio Virtual o Directorio.
con el registro de windows. Un error aquí puede dejar su
sistema en un estado inestable. Le recomendamos • Pulse el botón Configuración y luego pulse
encarecidamente que haga una copia de seguridad del sobre la pestaña Mapas de Aplicación.
registro con antelación. El equipo de Desarrollo del PHP • Pulse en Añadir, y en la caja Programa,
no se hará responsable si se daña su registro. escriba: c:\path-to-php-dir\php.exe %s %s.
DEBE mantene los %s %s al final, pues el PHP
no funcionará correctamente si se equivoca al
• Ejecute Regedit. hacerlo.
• Navegue hasta: HKEY_LOCAL_MACHINE • En la caja Extensión, escriba la extensión de
/System /CurrentControlSet /Services fichero que desea asociar a los script de PHP.
/W3Svc /Parameters /ScriptMap. Debe repetir los pasos 5 y 6 para cada
• En el menú de edición elija: New->String extensión que desee asociar con los scripts
Value. PHP ( .php3 y .phtml son habituales).

• Escriba la extensión que desea usar para sus • Ajuste la seguridad apropiada (esto se realiza
script PHP. P.ej.: .php3 en el Controlador de Servicio de Internet
(ISM)), y si su NT Server usa el sistema de
archivos NTFS, añada derechos de ejecución
para I_USR_ al directorio que contenga el php3_ldap.dll Funciones de LDAP
php.exe.
php3_msql1.dll Cliente de mSQL 1
php3_msql2.dll Cliente de mSQL 2
Cliente de MSSQL client (requiere las
Windows 9x/NT y Apache 1.3.x php3_mssql.dll
librerías de MSSQL DB
php3_mysql.dll Funciones de MySQL
Debe editar sus archivos srm.conf o httpd.conf para
configurar el Apache para que trabaje con el ejecutable php3_nsmail.dl
Funciones de correo de Netscape
CGI del PHP. l
Aunque puede haber algunas variaciones al configurar php3_oci73.dll Funciones de Oracle
PHP bajo Apache, esta es lo suficientemente simple para
ser usada por el novato. Por favor, consulte la Funciones get y walk de SNMP (¡sólo en
php3_snmp.dll
Documentación del Apache para saber de las NT!)
subsiguientes directivas de configuración. php3_zlib.dll Funciones de ZLib

• ScriptAlias /php3/ "c:/ruta-al-dir-del-php/" ¿Problemas?


• AddType application/x-httpd-php3 .php3
• AddType application/x-httpd-php3 .phtml Lea las PMF (FAQ)
• Action application/x-httpd-php3
"/php3/php.exe" Algunos problemas son más comunes que otros. Los más
comunes están listados en las PMF (Preguntas Más
Frecuentes) del PHP, que están en
Para utilizar la capacidad de marcado del código fuente, http://www.php.net/FAQ.php
cree simplemente un script de PHP y pegue este código
en él: <?php show_source("script_original_php.php3"); ?
>. Sustituya script_original_php.php3 por el nombre del Informes de error
archivo del que desea visualizar el código fuente (esta es
la única forma de hacerlo). Nota: Bajo Win-Apache todas
las barras invertidas de una ruta tal como: Si cree que ha encontrado un error en el PHP, por favor
"c:\directory\file.ext", deben ser convertidas a barras infórmenos. Los desarrolladores del PHP probablemente
hacia adelante. no tengan conocimiento del mismo, y salvo si informa del
mismo, pocas probabilidades habrá de que lo solucionen.
Puede informar de los errores usando el sistema de
Omni HTTPd 2.0b1 para Windows rastreo de errores en http://bugs.php.net/.

Esta ha resultado ser la configuración más sencilla: Otros problemas


Paso 1: Instale el servidor Omni
Paso 2: Pulse el botón derecho sobre el icono azul del
OmniHTTPd que está en la barrita del sistema y elija Si aún se encuentra atascado, alguien de la lista de
Propiedades correos del PHP puede ser capaz de ayudarle. Deberá
buscar primero en los archivos, por si acaso alguien ya
Paso 3: Pulse sobre Web Server Global Settings
ha respondido a otra persona que tuvo el mismo
Paso 4: En la pestaña 'External', escriba: virtual = .php3 | problema que usted. Los archivos están disponibles
actual = c:\ruta-al-dir-del-php\php.exe desde la página de soporte en http://www.php.net/. Para
Paso 5: En la pestaña Mime, escriba: virtual = suscribirse a la lista de correo de PHP, envíe un correo
wwwserver/stdcgi | actual = .php3 vacío a php-general-subscribe@lists.php.net. La dirección
Paso 6: Pulse en OK de la lista de correo es php-general@lists.php.net.
Repita los pasos 2 a 6 para cada extensión que desee Si desea ayuda sobre la lista de correo, intente ser
asociar al PHP. preciso y de los detalles necesarios sobre su entorno
(qué sistema operativo, qué versión de PHP, qué servidor
web, si está ejecutando el PHP como CGI o como módulo
Módulos del PHP de servidor, etc.) y también código suficiente para que
otros puedan reproducir y comprobar su problema.

Tabla 3-1. Módulos del PHP


php3_calendar. Capítulo 4. Configuración
Funciones de conversión de calendario
dll
php3_crypt.dll Funciones de criptografía El archivo de configuración
php3_dbase.dll Funciones para DBase
Emulación GDBM con la librería Berkeley El archivo de configuración (llamado php3.ini en PHP 3.0,
php3_dbm.dll y simplemente php.ini a partir del PHP 4.0) es leído
DB2
cuando arranca el PHP. Para las versiones de PHP como
Acceso SÓLO LECTURA a bases de datos módulo de servidor esto sólo ocurre una vez al arrancar
php3_filepro.dll
filepro el servidor web. Para la versión CGI, esto ocurre en cada
Funciones de librería GD para manipular llamada.
php3_gd.dll Cuando se utiliza PHP como módulo Apache, también
GIF
puede cambiar los ajustes de configuración utilizando
php3_hyperwa directivas en los archivos de configuración del Apache y
Funciones de HyperWave
ve.dll en los .htaccess.
php3_imap4r2. Con el PHP 3.0 hay directivas Apache que se
Funciones de IMAP 4 corresponden a cada uno de los ajustes de configuración
dll
del php3.ini, con la excepción que su nombre va
precedido de "php3_".
Con el PHP 4.0 sólo hay unas pocas directivas de Apache los sitios apropiados del archivo httpd.conf, se
que le permiten cambiar los ajustes de configuración del puede habilitar o deshabilitar el PHP.
PHP. error_log string
php_value nombre valor Nombre del fichero para registrar los errores
Fija el valor de la variable especificada. de un script. Si se utiliza el valor especial
php_flag nombre on|off syslog, los errores se envían al registro de
Fija una opción de configuración de tipo errores del sistema. En UNIX se refiere a
Boolean. syslog(3) y en Windows NT al registro de
php_admin_value nombre valor eventos. El registro de errores del sistema no
Fija el valor de la variable especificada. Los es soportado bajo Windows 95.
ajustes de configuración de tipo "Admin" sólo error_reporting integer
se pueden fijar desde los archivos principales Fija el nivel de informe de errores. El
de configuración del Apache, y no desde los parámetro es un entero que representa un
.htaccess. campo de bits. Sume los valores de los niveles
php_admin_flag nombre on|off de informe de error que desea.
Fija una opción de configuración de tipo Tabla 4-1. Niveles de Informe de Errores
Boolean. valor de
Puede ver los ajustes de los valores de configuración en informe habilitado
bit
la salida de phpinfo(). También puede acceder a los
valores individuales de los ajustes de configuración 1 errores normales
utilizando get_cfg_var(). 2 avisos normales
errores del troceador
4
Directivas Generales de Configuración (parser)
avisos de estilo no
8
asp_tags boolean críticos
Permite el uso de las etiquetas estilo ASP <% El valor por defecto para esta directiva es 7 (se
%> además de las habituales etiquetas <? muestran los errores normales, avisos
php ?>. También se incluye el atajo para normales y errores de parser).
imprimir variables <%= $valor %>. Para más open_basedir string
información, vea Escapando del HTML. Limita los archivos que se pueden abrir por el
PHP al árbol de directorios especificado.
Cuando un script intenta abrir un archivo con,
Nota: El soporte para
por ejemplo, fopen o gzopen, se comprueba su
etiquetas estilo ASP se
localización. Si el fichero está fuera del árbol
añadió en la 3.0.4.
de directorios especificado, PHP se negará a
abrirlo. Todos los enlaces simbólicos son
auto_append_file string resueltos, de modo que no es posible evitar
Especifica el nombre de un archivo que es esta limitación usando uno de ellos.
troceado automáticamente después del El valor especial . indica que el directorio base
archivo principal. El archivo se incluye como si será aquel en el que reside el script.
fuese llamado mediante la función include(), Bajo Windows, separe los directorios mediante
así que se utiliza include_path. punto y coma. En el resto de sistemas,
El valor especial none desconecta la adición sepárelos con dos puntos ":". Como módulo de
automática de archivos. Apache, los senderos para open_basedir de los
directorios padre se heredan ahora
automáticamente.
Nota: Si el script es
terminado con exit(), no
tendrá lugar la adición Nota: El soporte para
automática. directorios múltiples se
añadió en la 3.0.7.

auto_prepend_file string
Especifica el nombre de un archivo que es El valor por defecto es permitir abrir todos los
troceado automáticamente antes del archivo archivos.
principal. Specifies the name of a file that is gpc_order string
automatically parsed before the main file. El Fija el order de troceo de variables
archivo se incluye como si fuese llamado GET/POST/COOKIE. El valor por defecto de esta
mediante la función include(), así que se directiva es "GPC". Fijándola, por ejemplo, a
utiliza include_path. "GP", hará que el PHP ignore por completo las
El valor especial none desconecta la adición cookies y que sobreescriba las variables
automática de archivos. recibidas por GET con las que tengan el mismo
cgi_ext string nombre y vengan por POST.
display_errors boolean ignore_user_abort string
Determina si los errores se visualizan en Por defecto está a on. Si se cambia a off, los
pantalla como parte de la salida en HTML o no. script terminarán tan pronto como intenten
doc_root string enviar algo después de que un cliente ha roto
"Directorio raiz" del PHP en el servidor. Sólo se la conexión. ignore_user_abort().
usa si no está vacío. Si el PHP se configura con include_path string
safe mode, no se sirven archivos fuera de este Especifica una lista de directorios en los que
directorio. las funciones require(), include() y
engine boolean fopen_with_path() buscan los archivos. El
Esta directiva sólo es realmente útil en la formato es similar a la variable de entorno de
versión de PHP como módulo Apache. Se utiliza sistema PATH: una lista de directorios
por sitios que desean habilitar la ejecución del separados por dos puntos en UNIX o por punto
PHP directorio por directorio o en base a cada y coma en Windows.
servidor virtual. Poniendo php3_engine off en Ejemplo 4-1. include_path en UNIX
El nombre base del directorio utilizado bajo el
directorio inicial de un usuario para los
archivos PHP. Por ejemplo: paginas_html.
include_path=.:/home/htt warn_plus_overloading boolean
pd/php-lib Si está activada, esta opción hace que el PHP
muestre un aviso cuando el operador suma (+)
Ejemplo 4-2. include_path en Windows se utiliza en cadenas. Así es más fácil
encontrar scripts que necesitan ser reescritos
utilizando en su lugar el concatenador de
include_path=".;c:\ww cadenas (.).
w\phplib"
El valor por defecto para esta directiva es .
(sólo el directorio actual). Directivas de Configuración de Correo
isapi_ext string
log_errors boolean SMTP string
Dice si los mensajes de error de los script Nombre DNS o dirección IP del servidor de
deben ser registrados o no en el registro del SMTP que el PHP bajo Windows deberá usar
servidor. Esta opción, por tanto, es específica para enviar correo con la función mail().
del mismo. sendmail_from string
magic_quotes_gpc boolean La dirección del remitente ("De:") para los
Fija el estado magic_quotes para operaciones correos enviados desde PHP bajo Windows.
GPC (Get/Post/Cookie). Si magic_quotes vale sendmail_path string
on, todas las ' (comilla sencilla), " (comilla Localización del programa sendmail.
doble), \ (barra invertida) y los NUL son Generalmente /usr/sbin/sendmail o
automáticamente marcados con una barra /usr/lib/sendmail. configure intenta localizarle
invertida. Si además magic_quotes_sybase este archivo lo mejor que puede y fijar un valor
vale on, la comilla sencilla es marcada con otra por defecto, pero en caso de fallo, lo puede
comilla sencilla en lugar de la barra invertida. usted fijar aquí.
magic_quotes_runtime boolean Los sistemas que no usan sendmail deberán
Si se habilita magic_quotes_runtime, muchas fijar esta directiva al nombre del programa
de las funciones que devuelven datos de algún alternativo que ofrezca su sistema de correo, si
tipo de fuente externa incluyendo bases de es que existe. Por ejemplo, los usuarios del
datos y archivos de texto devolverán las Qmail pueden fijarlo normalmente a
comillas marcadas con una barra invertida. Si /var/qmail/bin/sendmail.
también está activo magic_quotes_sybase, la
comilla simple es marcada con una comilla
simple en lugar de la barra invertida. Directivas de Configuración de Modo Seguro
magic_quotes_sybase boolean
Si magic_quotes_sybase está a on, la comilla
simple es marcada con una comilla simple en safe_mode boolean
lugar de la barra invertida cuando están Para activar el modo seguro del PHP. Lea el
habilitados magic_quotes_gpc o Capítulo de seguridad para más información.
magic_quotes_runtime. safe_mode_exec_dir string
max_execution_time integer Si el PHP se utiliza en modo seguro, la función
Fija el tiempo máximo en segundos que se le system() y el resto de funciones que ejecutan
permite usar a un script antes de ser finalizado programas del sistema se niegan a ejecutar
por el intérprete. Así se evita que scripts mal programas que no estén en este directorio.
escritos puedan bloquear el servidor.
memory_limit integer
Fija el tamaño máximo de memoria en bytes Directivas de Configuración del Debugger
que se permite reclamar a un script. Así se
evita que script mal escritos se coman toda la
memoria dispomible de un servidor. debugger.host string
nsapi_ext string Nombre DNS o dirección IP del servidor usado
short_open_tag boolean por el debugger.
Indica si se debe permitir el formato corto debugger.port string
(<? ?>) de la etiqueta de apertura del PHP. Si Número de puerto usado por el debugger.
desea utilizar PHP en combinación con XML, debugger.enabled boolean
deberá desactivar esta opción. Si está Indica si el debugger está habilitado o no.
desactivada, deberá utilizar el formato largo de
la etiqueta de apertura (<?php ?>).
Directivas de Carga de Extensiones
sql.safe_mode boolean
track_errors boolean
Si está habilitada, el último mensaje de error enable_dl boolean
estará siempre presente en la variable global Esta directiva sólo es útil en la versión del PHP
$php_errormsg. como módulo del Apache. Puede habilitar o
track_vars boolean deshabilitar para un servidor virtual o para un
Si está activada, la información de entrada de directorio la carga dinámica de extensiones de
GET, POST y de las cookies se puede encontrar PHP mediante dl().
en las matrices asociativas $HTTP_GET_VARS, La razón principal para deshabilitar la carga
$HTTP_POST_VARS y $HTTP_COOKIE_VARS dinámica es la seguridad. Con la carga
respectivamente. dinámica es posible ignorar las restricciones
upload_tmp_dir string safe_mode y open_basedir.
El directorio temporal utilizado para almacenar El valor por defecto es permitir la carga
archivos cuando se envían al servidor. Debe dinámica, excepto cuando se usa el modo
tener permiso de escritura para el usuario bajo seguro. En modo seguro, siempre es imposible
el que corra el PHP. usar dl().
user_dir string extension_dir string
En qué directorio debe buscar el PHP las
NAM=K
extensiones cargables dinámicamente.
NOTYPE
extension string
Qué extensiones dinámicas debe cargar el PHP sesam_messagecatalog string
cuando arranca. 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
Directivas de Configuración de MySQL system's BS2000 message file table, it can be
set with this directive.
The message catalog must be set
mysql.allow_persistent boolean ACCESS=READ,SHARE=YES because it must
Si permitir o no conexiones MySQL be readable by the apache server's user id.
persistentes.
mysql.default_host string
El servidor por defecto para utilizar cuando se Directivas de Configuración de Sybase
conecte al servidor de bases de datos si no se
especifica otro distinto.
mysql.default_user string sybase.allow_persistent boolean
El nombre de usuario por defecto para utilizar Si se permiten o no conexiones persistentes de
cuando se conecta al servidor de base de Sybase.
datos si no se especifica otro. sybase.max_persistent integer
mysql.default_password string El número máximo de conexiones persistentes
La clave por defecto para utilizar cuando se Sybase por proceso.
conecta al servidor de base de datos si no se sybase.max_links integer
especifica otro. El número máximo de conexiones de Sybase
mysql.max_persistent integer por proceso, incluyendo las persistentes.
El número máximo de conexiones persistentes
de MySQL por proceso.
mysql.max_links integer Directivas de Configuración de Sybase-CT
El número máximo de conexiones de MySQL
por proceso, incluyendo las persistentes.
sybct.allow_persistent boolean
Si se permiten o no conexiones persistentes de
Directivas de Configuración de mSQL Sybase-CT. El valor por defecto es on.
sybct.max_persistent integer
El número máximo de conexiones persistentes
msql.allow_persistent boolean Sybase-CT por proceso. El valor por defecto es
Si se permiten o no conexiones persistentes de -1, que significa ilimitadas.
mSQL. sybct.max_links integer
msql.max_persistent integer El número máximo de conexiones de Sybase-
El número máximo de conexiones persistentes CT por proceso, incluyendo las persistentes. El
mSQL por proceso. valor por defecto es -1, que significa ilimitadas.
msql.max_links integer sybct.min_server_severity integer
El número máximo de conexiones de mSQL por Los mensajes de servidor con gravedad mayor
proceso, incluyendo las persistentes. o igual que sybct.min_server_severity serán
reportados como avisos. Este valor también se
puede cambiar desde un script usando la
Directivas de Configuración de Postgres función sybase_min_server_severity(). El
valor por defecto es 10, que reporta los errores
de información con gravedad o mayores.
pgsql.allow_persistent boolean sybct.min_client_severity integer
Si se permiten o no conexiones persistentes de Los mensajes de librería de cliente con
Postgres. gravedad mayor o igual que
pgsql.max_persistent integer sybct.min_client_severity serán reportados
El número máximo de conexiones persistentes como avisos. Este valor también se puede
Postgres por proceso. cambiar desde un script usando la función
pgsql.max_links integer sybase_min_client_severity(). El valor por
El número máximo de conexiones de Postgres defecto es 10, que desconecta los avisos.
por proceso, incluyendo las persistentes. sybct.login_timeout integer
El número máximo de segundos de espera por
un intento de conexión con éxito antes de
SESAM Configuration Directives indicar un fallo. Nótese que si se ha excedido
max_execution_time cuando finaliza la espera
sesam_oml string de un intento de conexión, el script será
Name of BS2000 PLAM library containing the finalizado antes de que se pueda tomar una
loadable SESAM driver modules. Required for acción en caso de fallo. El valor por defecto es
using SESAM functions. The BS2000 PLAM 1 minuto.
library must be set ACCESS=READ,SHARE=YES sybct.timeout integer
because it must be readable by the apache El número máximo de segundos de espera por
server's user id. una operación de consulta o select_db con
sesam_configfile string éxito antes de indicar un fallo. Nótese que si se
Name of SESAM application configuration file. ha excedido max_execution_time cuando
Required for using SESAM functions. The finaliza la espera de un intento de conexión, el
BS2000 file must be readable by the apache script será finalizado antes de que se pueda
server's user id. tomar una acción en caso de fallo. El valor por
The application configuration file will usually defecto es sin límite.
contain a configuration like (see SESAM sybct.hostname string
reference manual): El nombre de la máquina desde la que dice
estarse conectando, para que se visualize con
CNF=B sp_who(). El valor por defecto es "none".
Directivas de Configuración de Informix uodbc.default_user string
Nombre de usuario si no se especifica uno en
odbc_connect() o en odbc_pconnect().
ifx.allow_persistent boolean uodbc.default_pw string
Si se permiten o no conexiones persistentes de Clave para usar si no se especifica una en
Informix. odbc_connect() o en odbc_pconnect().
ifx.max_persistent integer uodbc.allow_persistent boolean
El número máximo de conexiones persistentes Si se permiten o no conexiones persistentes de
de Informix por proceso. ODBC.
ifx.max_links integer uodbc.max_persistent integer
El número máximo de conexiones Informix por El número máximo de conexiones persistentes
proceso, incluyendo las persistentes. de ODBC por proceso.
ifx.default_host string uodbc.max_links integer
El servidor por defecto al que conectarse si no El número máximo de conexiones ODBC por
se especifica uno en ifx_connect() o en proceso, incluyendo las persistentes.
ifx_pconnect().
ifx.default_user string
El id de usuario por defecto para utilizar si no Capítulo 5. Seguridad
se especifica uno en ifx_connect() o en
ifx_pconnect().
ifx.default_password string PHP es un potente lenguaje y el interprete, tanto incluido
La clave por defecto para utilizar si no se en el servidor web como modulo o ejecutado como un
especifica uno en ifx_connect() o en binario CGI, puede acceder a ficheros, ejecutar
ifx_pconnect(). comandos y abrir comunicaciones de red en el servidor.
ifx.blobinfile boolean Todas estas caracteristicas hacen que lo que se ejecute
Fíjelo a TRUE si desea recibir las columnas en el servidor web sea inseguro por defecto. PHP ha sido
blob (objetos binarios grandes) en un archivo, disenado especificamente, para ser un lenguaje mas
y a FALSE si las desea en memoria. Puede seguro para escribir programas CGI, que Perl o C y con la
cambiar el ajuste en tiempo de ejecución correcta seleccion de las opciones de configuración del
utilizando ifx_blobinfile_mode(). tiempo de compilación y ejecucion se consigue la exacta
ifx.textasvarchar boolean combinación de libertad y seguridad que se necesita.
Fíjelo a TRUE si desea recibir las columnas Ya que existen diferentes modos de utilizar PHP, existen
TEXT como cadenas normales en las multitud de opciones de configuración que permiten
instrucciones select, y a FALSE si quiere usar controlar su funcionamiento. Una gran selección de
parámetros de identificador de blobs. Puede opciones garantiza que se pueda usar PHP para
cambiar el ajuste en tiempo de ejecución diferentes usos, pero tambien significa que existen
utilizando ifx_textasvarchar(). combinaciones de estas opciones y configuraciones del
ifx.byteasvarchar boolean servidor que producen instalaciones inseguras. Este
Fíjelo a TRUE si desea devolver las columnas capitulo explica las diferentes combinaciones de
BYTE como cadenas normales en las opciones de configuración y las situaciones donde
instrucciones select, y a FALSE si quiere usar pueden ser usadas de manera segura.
parámetros de identificador de blobs. Puede
cambiar el ajuste en tiempo de ejecución
utilizando ifx_byteasvarchar(). Binarios CGI
ifx.charasvarchar boolean
Fíjelo a TRUE si desea suprimir los espacios a
Posibles ataques
la derecha de las columnas CHAR cuando las
solicita.
ifx.nullformat boolean Usando PHP como un binario CGI es una opción para
Fíjelo a TRUE si desea que las columnas NULL instalaciones que por cualquier causa no quieren integrar
(nulas) se devuelvan como la cadena literal PHP como modulo en el software servidor (p.ej: Apache),
"NULL", y a FALSE si desea que se devuelvan o usaran PHP con diferentes clases de CGI wrappers para
como la cadena vacía "". Puede cambiar el crear entornos chroot y setuid seguros para los scripts.
ajuste en tiempo de ejecución utilizando Esta configuración implica generalmente el instalar el
ifx_nullformat(). binario ejecutable de PHP en el directorio cgi-bin del
servidor web. El documento del CERT CA-96.11
recomienda no instalar interpretes en cgi-bin. Aunque el
Directivas de Configuración de Matemática BC binario PHP puede ser usado como interprete
independiente, PHP esta diseñado para prevenir los
bcmath.scale integer ataques que esta configuración hace posible.
Número de dígitos decimales para todas las
funciones de bcmath.
• Accediendo a ficheros del sistema:
http://my.host/cgi-bin/php?/etc/passwd
Directivas de Configuración de Capacidades de los
Navegadores
La información introducida despues del signo
de interrogación (?) es transferida como
browscap string argumento de la línea de comando al
Nombre del archivo de capacidades del intérprete por el interfaz del CGI. Normalmente
navegador. Vea también get_browser(). los interpretes abren y ejecutan el fichero
especificado como el primer argumento en la
línea de comando.
Directivas Unificadas de Configuración de ODBC

Cuando se ejecuta como un CGI script, PHP


uodbc.default_db string rechaza interpretar los argumentos de la línea
Fuentes de datos ODBC a utilizar si no se de comando.
especifica una en odbc_connect() o en
odbc_pconnect().
peticiones de redireccionamiento. Si tu servidor web no
• Accediendo cualquier documento web en el
soporta ningun modo para informar si una peticion es
servidor: http://my.host/cgi-
directa o redireccionada, no podeis usar esta opcion y
bin/php/secret/doc.html
debereis usar alguno de los otros modos de ejecucion de
la version CGI documentados aqui.
La información con el camino (path) de la URL
despues del nombre del binario PHP,
/secret/doc.html es usada convencionalmente Caso 3: Usando doc_root or user_dir
para especificar el nombre del fichero que sera
abierto e interpretado por el programa CGI. Incluir contenidos activos, como script y ejecutables, en
Normalmente, algunas directivas del servidor el directorio de documentos del servidor web, es algunas
web (Apache:Action) son usadas para veces considerada una practica insegura. Si por algun
redireccionar peticiones de documentos como fallo de configuracion, los scripts no son ejecutados pero
http://my.host/secret/script.php3 al interprete mostrados como documentos HTML, cualquiera podra
PHP. Con esta configuración, el servidor web conseguir codigo registrado o informacion de seguridad,
comprueba primero los permisos de acceso al como p.ej: claves de acceso. Por ello, muchos
directorio /secret, y despues crea la petición administradores prefieren utilizar otra estructura de
redireccionada http://my.host/cgi- directorios que contenga solamente los scripts, los cuales
bin/php/secret/script.php3. seran solamente accesibles via PHP CGI, y por ello
Desafortunadamente, si la petición es hecha siempre seran interpretados y no mostrados.
de esta forma en un principio, el servidor web Habra que tener en cuenta que si el metodo que asegura
no comprueba los permisos de acceso del que las peticiones no son redireccionadas, como hemos
fichero /secret/script.php3, sino solamente del descrito en la seccion anterior, no esta disponible, sera
fichero /cgi-bin/php. De esta manera cualquier necesario configurar un script doc_root que sea diferente
usuario que pueda acceder /cgi-bin/php del "web document root".
tambien puede acceder a cualquier documento Podeis definir el script PHP "document root" con la
protegido en el servidor web. directiva de configuracion doc_root en el fichero de
configuracion, o definir la variable de entorno
En PHP, a la hora de compilar, la opción de PHP_DOCUMENT_ROOT. Si esta definida, la version CGI
configuracion --enable-force-cgi-redirect y las de PHP siempre obtendra el nombre del fichero a abrir
directivas de configuracion a la hora de con doc_root y el camino (path) utilizado en la peticion,
ejecutar doc_root y user_dir pueden ser usadas asi podeis estar seguros que ningun script sera ejecutado
para prevenir este ataque, si el arbol de fuera de este directorio (excepto para user_dir, ver a
documentos del servidor tiene cualquier continuacion)
directorio con acceso restringido. Ver mas Otra opcion que se puede usar aqui es user_dir. Cuando
adelante la explicacion de las diferentes user_dir no esta definido, lo unico que controla la
combinaciones. apertura del fichero es doc_root. Si intentamos abrir una
url tal como esta http://my.host/~user/doc.php3 no se
abrira un fichero en el directorio de usuarios, en su lugar
se abrira un fichero llamado ~user/doc.php3 en el
directorio doc_root. (si, un directorio que empieza por
Caso 1: solamente se sirven ficheros publicos tilde [~]).
Si user_dir esta definido por ejemplo como public_php,
una peticion tal como http://my.host/~user/doc.php3,
Si tu servidor no contiene informacion que este protegida abrira un fichero llamado doc.php3 en el directorio
con clave o acceso de control de IPs, no se necesitan llamado public_php del directorio "home" del usuario. Si
estas opciones de configuracion. Si tu servidor web no el directorio del usuario es /home/user, el fichero
permite realizar redireccionamientos, o el servidor no ejecutado sera /home/user/public_php/doc.php3.
tiene modo de comunicar al binario PHP que la peticion La expansion de user_dir ocurre sin tener en cuenta la
es una peticion segura redireccionada, podeis especificar configuracion de doc_root, de este modo se puede
la opcion --disable-force-cgi-redirect en el script de controlar los accesos al directorio principal (document
configuracion. De todas maneras, teneis que aseguraros root) y al directorio de usuario separadamente.
que vuestros scripts PHP no confíen en la manera al
llamar al script, ni de forma directa http://my.host/cgi-
bin/php/dir/script.php3 o por redireccion Caso 4: Analizador PHP fuera del arbol web.
http://my.host/dir/script.php3.
Redireccionamiento puede ser configurado en Apache
usando las directivas AddHandler y Action (ver mas Una opcion muy segura es poner el analizador binario
abajo). PHP, en algun lugar fuera del arbol de ficheros web. Por
ejemplo en /usr/local/bin. La unica pega real de esta
opcion es que habra que poner una linea similar a:
Caso 2: usando --enable-force-cgi-redirect
#!/usr/local/bi
n/php
Esta opcion a la hora de compilar previene que alguien como primera linea en cualquier fichero que contenga
llame PHP directamente con una url como la siguiente codigo PHP. Tambien sera necesario asignar al fichero
http://my.host/cgi-bin/php/secretdir/script.php3. PHP permisos de ejecucion. De esta manera, es tratado de la
solamente analizara en este modo si ha pasado por una misma manera que cualquier otro CGI script escrito en
regla de redireccionamiento en el servidor. Perl o sh o otro lenguaje utilizado para scripts y que
Normalmente la redireccion en la configuracion de utilicen el mecanismo #! para ejecutarse.
Apache es hecha con la siguientes directivas: Para conseguir que PHP maneje correctamente con esta
Action php3-script /cgi- configuracion, la informacion de PATH_INFO y
bin/php PATH_TRANSLATED, el analizador PHP deberia ser
AddHandler php3- compilado con la opcion de configuracion --enable-
script .php3 discard-path.
Esta opcion ha sido solo comprobada con el servidor web
Apache, y depende de Apache para fijar la variable de Modulo Apache
entorno CGI no estandar REDIRECT_STATUS en las
Cuando PHP es usado como modulo Apache, hereda los php.ini-dist, se desaconseja el uso del formato de
permisos de usuario de Apache (normalmente "nobody") etiquetas corto.
El método cuarto sólo está disponible si se han activado
las etiquetas ASP en el fichero de configuración:
II. Referencia del Lenguaje asp_tags.

Tabla de contenidos Nota: El soporte de etiquetas ASP se


6. Síntaxis básica añadió en la versión 3.0.4.
7. Types
8. Variables
9. Constantes Nota: No se debe usar el formato
10. Expresiones corto de etiquetas cuando se
11. Operadores desarrollen aplicaciones o librerías
12. Estructuras de Control con intención de redistribuirlas, o
13. Funciones cuando se desarrolle para servidores
14. Clases y Objetos que no están bajo nuestro control,
15. References Explained porque puede ser que el formato
corto de etiquetas no esté soportado
en el servidor. Para generar código
Capítulo 6. Síntaxis básica portable y redistribuíble, asegúrate
de no usar el formato corto de
etiquetas.
Saliendo de HTML

La etiqueta de fin de bloque incluirá tras ella la siguiente


Para interpretar un archivo, php símplemente interpreta línea si hay alguna presente. Además, la etiqueta de fin
el texto del archivo hasta que encuentra uno de los de bloque lleva implícito el punto y coma; no necesitas
carácteres especiales que delimitan el inicio de código por lo tanto añadir el punto y coma final de la última
PHP. El intérprete ejecuta entonces todo el código que línea del bloque PHP.
encuentra, hasta que encuentra una etiqueta de fin de PHP permite estructurar bloques como:
código, que le dice al intérprete que siga ignorando el Ejemplo 6-2. Métodos avanzados de escape
código siguiente. Este mecanismo permite embeber
código PHP dentro de HTML: todo lo que está fuera de las
etiquetas PHP se deja tal como está, mientras que el
<?php
resto se interpreta como código.
if ($expression) {
Hay cuatro conjuntos de etiquetas que pueden ser
?>
usadas para denotar bloques de código PHP. De estas
<strong>This is
cuatro, sólo 2 (<?php. . .?> y <script
true.</strong>
language="php">. . .</script>) están siempre
<?php
disponibles; el resto pueden ser configuradas en el
} else {
fichero de php.ini para ser o no aceptadas por el
?>
intérprete. Mientras que el formato corto de etiquetas
<strong>This is
(short-form tags) y el estilo ASP (ASP-style tags) pueden
false.</strong>
ser convenientes, no son portables como la versión de
<?php
formato largo de etiquetas. Además, si se pretende
}
embeber código PHP en XML o XHTML, será obligatorio el
?>
uso del formato <?php. . .?> para la compatibilidad con
XML. Este ejemplo realiza lo esperado, ya que cuando PHP
Las etiquetas soportadas por PHP son: encuentra las etiquetas ?> de fin de bloque, empieza a
Ejemplo 6-1. Formas de escapar de HTML escribir lo que encuentra tal cual hasta que encuentra
otra etiqueta de inicio de bloque. El ejemplo anterior es,
por supuesto, inventado. Para escribir bloques grandes
1. <?php echo("si quieres servir documentos XHTML o de texto generamente es más eficiente separalos del
XML, haz como aqu&iacute;\n"); ?> código PHP que enviar todo el texto mediante las
funciones echo(), print() o similares.
2. <? echo ("esta es la m&aacute;s simple, una
instrucci&oacute;n de procesado SGML \n"); ?>
<?= expression ?> Esto es una abreviatura de "<? Separación de instrucciones
echo expression ?>"
Las separación de instrucciones se hace de la misma
3. <script language="php">
manera que en C o Perl - terminando cada declaración
echo ("muchos editores (como FrontPage) no
con un punto y coma.
aceptan instrucciones de procesado");
La etiqueta de fin de bloque (?>) implica el fin de la
</script>
declaración, por lo tanto lo siguiente es equivalente:
4. <% echo ("Opcionalmente, puedes usar las <?php
etiquetas ASP"); %> echo "This is a
<%= $variable; # Esto es una abreviatura de "<% test";
echo . . ." %> ?>
El método primero, <?php. . .?>, es el más conveniente,
<?php echo "This is a
ya que permite el uso de PHP en código XML como
test" ?>
XHTML.
El método segundo no siempre está disponible. El
formato corto de etiquetas está disponible con la función
short_tags() (sólo PHP 3), activando el parámetro del Comentarios
fichero de configuración de PHP short_open_tag, o
compilando PHP con la opción --enable-short-tags del
PHP soporta el estilo de comentarios de 'C', 'C++' y de la
comando configure. Aunque esté activa por defecto en
interfaz de comandos de Unix. Por ejemplo:
Los números en punto flotante ("double") se pueden
<?php
especificar utilizando cualquiera de las siguientes
echo "This is a test"; // This is a one-line c+
sintaxis:
+ style comment
/* This is a multi line comment $a = 1.234; $a =
yet another line of comment */ 1.2e3;
echo "This is yet another test";
echo "One Final Test"; # This is shell-style
style comment Cadenas
?>
Los estilos de comentarios de una linea actualmente sólo
comentan hasta el final de la linea o el bloque actual de Las cadenas de caracteres se pueden especificar usando
código PHP, lo primero que ocurra. uno de dos tipos de delimitadores.
Si la cadena está encerrada entre dobles comillas ("), las
<h1>This is an <?php # echo "simple";? variables que estén dentro de la cadena serán
> example.</h1> expandidas (sujetas a ciertas limitaciones de
<p>The header above will say 'This is an interpretación). Como en C y en Perl, el carácter de barra
example'. invertida ("\") se puede usar para especificar caracteres
Hay que tener cuidado con no anidar comentarios de especiales:
estilo 'C', algo que puede ocurrir al comentar bloques Tabla 7-1. Caracteres protegidos
largos de código. secuencia significado
<?php \n Nueva línea
/*
echo "This is a test"; /* This comment will \r Retorno de carro
cause a problem */ \t Tabulación horizontal
*/
?> \\ Barra invertida

Los estilos de comentarios de una linea actualmente sólo \$ Signo del dólar
comentan hasta el final de la linea o del bloque actual de \" Comillas dobles
código PHP, lo primero que ocurra. Esto implica que el
código HTML tras // ?> seráa impreso: ?> sale del modo la secuencia de caracteres que coincida con la
PHP, retornando al modo HTML, el comentario // no le \[0-7]{1,3} expresión regular es un carácter en notación
influye. octal
la secuencia de caracteres que coincida con la
\x[0-9A-Fa-
expresión regular es un carácter en notación
Capítulo 7. Types f]{1,2}
hexadecimal
Se puede proteger cualquier otro carácter, pero se
PHP soporta los siguientes tipos: producirá una advertencia en el nivel de depuración más
alto.
La segunda forma de delimitar una cadena de caracteres
• array usa el carácter de comilla simple ("'"). Cuando una
cadena va encerrada entre comillas simples, los únicos
• números en punto flotante caracteres de escape que serán comprendidos son "\\" y
• entero "\'". Esto es por convenio, así que se pueden tener
comillas simples y barras invertidas en una cadena entre
• objeto comillas simples. Las variables no se expandirán dentro
• cadena de una cadena entre comillas simples.
Otra forma de delimitar cadenas es usando la sintaxis de
documento incrustado ("<<<"). Se debe proporcionar un
El tipo de una variable normalmente no lo indica el identificador después de <<<, después la cadena, y
programador; en su lugar, lo decide PHP en tiempo de después el mismo identificador para cerrar el
ejecución dependiendo del contexto en el que se utilice entrecomillado.
esa variable. Ejemplo 7-1. He aquí un ejemplo de entrecomillado
Si se quisiese obligar a que una variable se convierta a de cadenas con sintaxis de documento incrustado
un tipo concreto, se podría forzar la variable o usar la
función settype() para ello.
Nótese que una variable se puede comportar de formas $str = <<<EOD
diferentes en ciertas situaciones, dependiendo de qué Ejemplo de cadena
tipo sea en ese momento. Para más información, vea la Expandiendo múltiples líneas
sección Conversión de Tipos. usando sintaxis de documento
incrustado.
EOD;
Enteros

Los enteros se puede especificar usando una de las Nota: La sintaxis de documento
siguientes sintaxis: incristado fue añadida en PHP 4.
$a = 1234; # número decimal
$a = -123; # un número negativo Las cadenas se pueden concatenar usando el operador '.'
$a = 0123; # número octal (equivalente al (punto). Nótese que el operador '+' (suma) no sirve para
83 decimal) esto. Por favor mire Operadores de cadena para más
$a = 0x12; # número hexadecimal información.
(equivalente al 18 decimal) Se puede acceder a los caracteres dentro de una cadena
tratándola como un array de caracteres indexado
numéricamente, usando una sintaxis similar a la de C.
Números en punto flotante Vea un ejemplo más abajo.
Ejemplo 7-2. Algumos ejemplos de cadenas
Arrays

Los arrays actualmente actúan tanto como tablas hash


<?php
(arrays asociativos) como arrays indexados (vectores).
/* Asignando una cadena. */
$str = "Esto es una cadena";
Arrays unidimensionales
/* Añadiendo a la cadena. */
$str = $str . " con algo más de texto";
PHP soporta tanto arrays escalares como asociativos. De
/* Otra forma de añadir, incluye un carácter de hecho, no hay diferencias entre los dos. Se puede crear
nueva línea protegido. */ una array usando las funciones list() o array(), o se
$str .= " Y un carácter de nueva línea al final.\n"; puede asignar el valor de cada elemento del array de
manera explícita.
/* Esta cadena terminará siendo '<p>Número:
9</p>' */ $a[0] =
$num = 9; "abc";
$str = "<p>Número: $num</p>"; $a[1] =
"def";
/* Esta será '<p>Número: $num</p>' */ $b["foo"] =
$num = 9; 13;
$str = '<p>Número: $num</p>'; También se puede crear un array simplemente
añadiendo valores al array. Cuando se asigna un valor a
/* Obtener el primer carácter de una cadena */ una variable array usando corchetes vacíos, el valor se
$str = 'Esto es una prueba.'; añadirá al final del array.
$first = $str[0];
$a[] = "hola"; // $a[2] ==
"hola"
/* Obtener el último carácter de una cadena. */
$a[] = "mundo"; // $a[3]
$str = 'Esto es aún una prueba.';
== "mundo"
$last = $str[strlen($str)-1];
?> Los arrays se pueden ordenar usando las funciones
asort(), arsort(), ksort(), rsort(), sort(), uasort(),
usort(), y uksort() dependiendo del tipo de ordenación
Conversión de cadenas que se desee.
Se puede contar el número de elementos de un array
usando la función count().
Cuando una cadena se evalúa como un valor numérico, Se puede recorrer un array usando las funciones next()
el valor resultante y el tipo se determinan como sigue. y prev(). Otra forma habitual de recorrer un array es
La cadena se evaluará como un doble si contiene usando la función each().
cualquiera de los caracteres '.', 'e', o 'E'. En caso
contrario, se evaluará como un entero.
El valor viene dado por la porción inicial de la cadena. Si Arrays Multidimensionales
la cadena comienza con datos de valor numérico, este
será el valor usado. En caso contrario, el valor será 0
Los arrays multidimensionales son bastante simples
(cero). Los datos numéricos válidos son un signo
actualmente. Para cada dimensión del array, se puede
opcional, seguido por uno o más dígitos (que
añadir otro valor [clave] al final:
opcionalmente contengan un punto decimal), seguidos
por un exponente opcional. El exponente es una 'e' o una $a[1] = $f; # ejemplos de una sola dimensión
'E' seguidos por uno o más dígitos. $a["foo"] = $f;
Cuando la primera expresión es una cadena, el tipo de la
variable dependerá de la segunda expresión. $a[1][0] = $f; # bidimensional
$a["foo"][2] = $f; # (se pueden mezclar índices
$foo = 1 + "10.5"; // $foo es
numéricos y asociativos)
doble (11.5)
$a[3]["bar"] = $f; # (se pueden mezclar índices
$foo = 1 + "-1.3e3"; // $foo es
numéricos y asociativos)
doble (-1299)
$foo = 1 + "bob-1.3e3"; // $foo es
$a["foo"][4]["bar"][0] = $f; # tetradimensional!
entero (1)
$foo = 1 + "bob3"; // $foo es En PHP3 no es posible referirse a arrays
entero (1) multidimensionales directamente dentro de cadenas. Por
$foo = 1 + "10 Cerditos"; // $foo es ejemplo, lo siguiente no tendrá el resultado deseado:
entero (11)
$a[3]['bar'] = 'Bob';
$foo = 1 + "10 Cerditos"; // $foo es
echo "Esto no va a funcionar:
entero (11)
$a[3][bar]";
$foo = "10.0 cerdos " + 1; // $foo
es entero (11) En PHP3, lo anterior tendrá la salida Esto no va a
$foo = "10.0 cerdos " + 1.0; // $foo funcionar: Array[bar]. De todas formas, el operador de
es double (11) concatenación de cadenas se puede usar para solucionar
esto:
Para más información sobre esta conversión, mire en la
página del manual de Unix strtod(3). $a[3]['bar'] = 'Bob';
Si quisiera probar cualquiera de los ejemplos de esta echo "Esto no va a funcionar: " .
sección, puede cortar y pegar los ejemplos e insertar la $a[3][bar];
siguiente línea para ver por sí mismo lo que va En PHP4, sin embargo, todo el problema se puede
ocurriendo: circunvenir encerrando la referencia al array (dentro de
echo "\$foo==$foo; el tipo es " . la cadena) entre llaves:
gettype( $foo ) . "<br>\n"; $a[3]['bar'] = 'Bob';
echo "Esto va a funcionar:
{$a[3][bar]}";
Se pueden "rellenar" arrays multidimensionales de cadena. Si después se asigna un valor entero a la
muchas formas, pero la más difícil de comprender es variable var, se convierte en una variable entera.
cómo usar el comando array() para arrays asociativos. Un ejemplo de conversión de tipo automática en PHP3 es
Estos dos trozos de código rellenarán el array el operador suma '+'. Si cualquiera de los operandos es
unidimensional de la misma manera: un doble, entonces todos los operandos se evalúan como
dobles, y el resultado será un doble. En caso contrario,
# Ejemplo 1:
los operandos se interpretarán como enteros, y el
resultado será también un entero. Nótese que esto NO
$a["color"] = "rojo";
cambia los tipos de los operandos propiamente dichos; el
$a["sabor"] = "dulce";
único cambio está en cómo se evalúan los operandos.
$a["forma"] = "redondeada";
$a["nombre"] = $foo = "0"; // $foo es una cadena (ASCII
"manzana"; 48)
$a[3] = $foo++; // $foo es la cadena "1" (ASCII
4; 49)
$foo += 1; // $foo ahora es un entero (2)
# Example 2: $foo = $foo + 1.3; // $foo ahora es un
$a = array( doble (3.3)
"color" => "rojo", $foo = 5 + "10 Cerditos Pequeñitos"; //
"sabor" => "dulce", $foo es entero (15)
"forma" => "redondeada", $foo = 5 + "10 Cerditos"; // $foo es
"nombre" => "manzana", entero (15)
3 => 4
Si los últimos dos ejemplos anteriores parecen confusos,
);
vea Conversión de cadenas.
La función array() se puede anidar para arrays Si se desea obligar a que una variable sea evaluada con
multidimensionales: un tipo concreto, mire la sección Forzado de tipos. Si se
desea cambiar el tipo de una variable, vea la función
<?
settype().
$a = array(
Si quisiese probar cualquiera de los ejemplos de esta
"manzana" => array(
sección, puede cortar y pegar los ejemplos e insertar la
"color" => "rojo",
siguiente línea para ver por sí mismo lo que va
"sabor" => "dulce",
ocurriendo:
"forma" => "redondeada"
), echo "\$foo==$foo; el tipo es " .
"naranja" => array( gettype( $foo ) . "<br>\n";
"color" => "naranja",
"sabor" => "ácido",
"forma" => "redondeada" Nota: La posibilidad de una
), conversión automática a array no
"plátano" => array( está definida actualmente.
"color" => "amarillo",
"sabor" => "paste-y",
"forma" => "aplatanada" $a = 1; // $a es un entero
) $a[0] = "f"; // $a se convierte en un array, en
); el que $a[0] vale "f"
echo $a["manzana"]["sabor"]; #
devolverá "dulce"
Aunque el ejemplo anterior puede
?>
parecer que claramente debería
resultar en que $a se convierta en
un array, el primer elemento del cual
Objetos es 'f', consideremos esto:

Inicialización de Objetos
$a = "1"; // $a es una cadena
$a[0] = "f"; // ¿Qué pasa con los índices de las
Para inicializar un objeto, se usa la sentencia new para cadenas? ¿Qué ocurre?
instanciar el objeto a una variable.
class foo {
function do_foo Dado que PHP soporta indexación en
() { las cadenas vía offsets usando la
echo "Doing misma sintaxis que la indexación de
foo."; arrays, el ejemplo anterior nos
} conduce a un problema: ¿debería
} convertirse $a en un array cuyo
primer elemento sea "f", o debería
$bar = new foo; convertirse "f" en el primer carácter
$bar->do_foo(); de la cadena $a?

Por esta razón, tanto en PHP 3.0.12


Type juggling como en PHP 4.0b3-RC4, el resultado
de esta conversión automática se
considera que no está definido. Los
PHP no requiere (o soporta) la declaración explícita del parches se están discutiendo, de
tipo en la declaración de variables; el tipo de una todas formas.
variable se determina por el contexto en el que se usa
esa variable. Esto quiere decir que si se asigna un valor
de cadena a la variable var, var se convierte en una
Forzado de tipos ocurre más rápidamente. De cualquier forma, cualquier
incremento de velocidad se notará sólo en los bucles
críticos cuando se asignen grandes arrays u objetos.
El forzado de tipos en PHP funciona como en C: el Para asignar por referencia, simplemente se antepone un
nombre del tipo deseado se escribe entre paréntesis ampersand (&) al comienzo de la variable cuyo valor se
antes de la variable a la que se pretende forzar. está asignando (la variable fuente). Por ejemplo, el
$foo = 10; // $foo es un siguiente trozo de código produce la salida 'Mi nombre es
entero Bob' dos veces:
$bar = (double) $foo; // $bar <?php
es un doble $foo = 'Bob'; // Asigna el
Los forzados de tipo permitidos son: valor 'Bob' a $foo
$bar = &$foo; // Referencia
$foo vía $bar.
• (int), (integer) - fuerza a entero (integer) $bar = "Mi nombre es $bar"; //
Modifica $bar...
• (real), (double), (float) - fuerza a doble (double) echo $foo; // $foo también
• (string) - fuerza a cadena (string) se modifica.
echo $bar;
• (array) - fuerza a array (array) ?>
• (object) - fuerza a objeto (object) Algo importante a tener en cuenta es que sólo las
variables con nombre pueden ser asignadas por
referencia.
Nótese que las tabulaciones y espacios se permiten
dentro de los paréntesis, así que los siguientes ejemplos <?php
son funcionalmente equivalentes: $foo = 25;
$bar = &$foo; // Esta es una asignación
$foo = (int) válida.
$bar; $bar = &(24 * 7); // Inválida; referencia una
$foo = ( int ) expresión sin nombre.
$bar;
Puede no ser obvio que ocurrirá cuando se fuerce entre function test() {
ciertos tipos. Por ejemplo, lo siguiente debería ser tenido return 25;
en cuenta. }
Cuando se fuerza el cambio de un escalar o una variable
de cadena a un array, la variable se convertirá en el $bar = &test(); // Inválida.
primer elemento del array: ?>
$var = 'ciao';
$arr = (array) $var;
echo $arr[0]; // produce la Variables predefinidas
salida 'ciao'
Cuando se fuerza el tipo de una variable escalar o de una PHP proporciona una gran cantidad de variables
cadena a un objeto, la variable se convertirá en un predefinidas a cualquier script que se ejecute. De todas
atributo del objeto; el nombre del atributo será 'scalar': formas, muchas de esas variables no pueden estar
completamente documentadas ya que dependen de
$var = 'ciao';
sobre qué servidor se esté ejecutando, la versión y
$obj = (object) $var;
configuración de dicho servidor, y otros factores. Algunas
echo $obj->scalar; // produce la
de estas variables no estarán disponibles cuando se
salida 'ciao'
ejecute PHP desde la línea de comandos.
A pesar de estos factores, aquí tenemos una lista de
variables predefinidas disponibles en una instalación por
Capítulo 8. Variables defecto de PHP 3 corriendo como modulo de un Apache
1.3.6 con su configuración también por defecto.
Para una lista de variables predefinidas (y muchas más
Conceptos Básicos
información útil), por favor, vea (y use) phpinfo().

En PHP las variables se representan como un signo de


Nota: Esta lista no es exhaustiva ni
dólar seguido por el nombre de la variable. El nombre de
pretende serlo. Simplemente es una
la variable es sensible a minúsculas y mayúsculas.
guía de qué tipo de variables
$var = "Bob"; predefinidas se puede esperar tener
$Var = "Joe"; disponibles en un script.
echo "$var, $Var"; // produce la
salida "Bob, Joe"
En PHP3, las variables siempre se asignan por valor. Esto
significa que cuando se asigna una expresión a una Variables de Apache
variable, el valor íntegro de la expresión original se copia
en la variable de destino. Esto quiere decir que, por
ejemplo, después e asignar el valor de una variable a Estas variables son creadas por el servidor web Apache.
otra, los cambios que se efectúen a una de esas Si se está utilizando otro servidor web, no hay garantía
variables no afectará a la otra. Para más información de que proporcione las mismas variables; pueden faltar
sobre este tipo de asignación, vea Expresiones. algunas, o proporcionar otras no listadas aquí. Dicho
PHP4 ofrece otra forma de asignar valores a las esto, también están presentes las variables de la
variables: asignar por referencia. Esto significa que la especificación CGI 1.1, por lo que también se deben
nueva variable simplemente referencia (en otras tener en cuenta.
palabras, "se convierte en un alias de" o "apunta a") la Tenga en cuenta que unas pocas, como mucho, de estas
variable original. Los cambios a la nueva variable afectan variables van a estar disponibles (o simplemente tener
a la original, y viceversa. Esto también significa que no sentido) si se ejecuta PHP desde la línea de comandos.
se produce una copia de valores; por tanto, la asignación GATEWAY_INTERFACE
Qué revisión de la especificación CGI está configuraciones por defecto, será '80'; al usar
usando el servidor; por ejemplo 'CGI/1.1'. SSL, por ejemplo, cambiará al puerto que se
SERVER_NAME haya definido como seguro para HTTP.
El nombre del equipo servidor en el que se SERVER_SIGNATURE
está ejecutando el script. Si el script se está Una cadena que contiene la versión del
ejecutando en un servidor virtual, este será el servidor y el nombre del servidor virtual que es
valor definido para dicho servidor virtual. añadida a las páginas generadas por el
SERVER_SOFTWARE servidor, si está característica está activa.
Una cadena de identificación del servidor, que PATH_TRANSLATED
aparece en las cabeceras al responderse a las Vía de acceso basada en el sistema de
peticiones. ficheros- (no el directorio raíz del documento-)
SERVER_PROTOCOL del script en cuestión, después de que el
Nombre y revisión del protocolo a través del servidor haya hecho la conversión virtual-a-
que se solicitó la página; p.ej. 'HTTP/1.0'; real.
REQUEST_METHOD SCRIPT_NAME
Qué método de petición se usó para acceder a Contiene la vía de acceso del script actual. Es
la página; p.ej. 'GET', 'HEAD', 'POST', 'PUT'. útil para páginas que necesitan apuntar a sí
QUERY_STRING mismas.
La cadena de la petición, si la hubo, mediante REQUEST_URI
la que se accedió a la página. La URI que se dió para acceder a esta página;
DOCUMENT_ROOT por ejemplo, '/index.html'.
El directorio raíz del documento bajo el que se
ejecuta el script, tal y como está definido en el
fichero de configuración del servidor. Variables de entorno
HTTP_ACCEPT
Los contenidos de la cabecera Accept: de la
petición actual, si hay alguna. Estas variables se importan en el espacio de nombres
HTTP_ACCEPT_CHARSET global de PHP desde el entorno en el que se esté
Los contenidos de la cabecera Accept-Charset: ejecutando el intérprete PHP. Muchas son proporcionadas
de la petición actual, si hay alguna. Por por el intérprete de comandos en el que se está
ejemplo: 'iso-8859-1,*,utf-8'. ejecutando PHP, y dado que a sistemas diferentes les
HTTP_ACCEPT_ENCODING gusta ejecutar diferentes tipos de intérpretes de
Los contenidos de la cabecera Accept- comandos, es imposible hacer una lista definitiva. Por
Encoding: de la petición actual, si la hay. Por favor, mire la documentación de su intérprete de
ejemplo: 'gzip'. comandos para ver una lista de las variables de entorno
HTTP_ACCEPT_LANGUAGE definidas.
Los contenidos de la cabecera Accept- Otras variables de entorno son las de CGI, que están ahí
Language: de la petición actual, si hay alguna. sin importar si PHP se está ejecutando como un módulo
Por ejemplo: 'en'. del servidor o como un intérprete CGI.
HTTP_CONNECTION
Los contenidos de la cabecera Connection: de
Variables de PHP
la petición actual, si hay alguna. Por ejemplo:
'Keep-Alive'.
HTTP_HOST Estas variables son creadas por el propio PHP.
Los contenidos de la cabecera Host: de la argv
petición actual, si hay alguna. Array de argumentos pasados al script. Cuando
HTTP_REFERER el script se ejecuta desde la línea de
La dirección de la página (si la hay) desde la comandos, esto da un acceso, al estilo de C, a
que el navegador saltó a la página actual. Esto los parámetros pasados en línea de comandos.
lo establece el navegador del usuario; no todos Cuando se le llama mediante el método GET,
los navegadores lo hacen. contendrá la cadena de la petición.
HTTP_USER_AGENT argc
Los contenidos de la cabecera User_Agent: de Contiene el número de parámetros de la línea
la petición actual, si hay alguna. Indica el de comandos pasados al script (si se ejecuta
navegador que se está utilizando para ver la desde la línea de comandos).
página actual; p.ej. Mozilla/4.5 [en] (X11; U; PHP_SELF
Linux 2.2.9 i586). Entre otras cosas, se puede El nombre del fichero que contiene el script
usar este valor con get_browser() para que se esta ejecutando, relativo al directorio
adaptar la funcionalidad de la página a las raíz de los documentos. Si PHP se está
posibilidades del navegador del usuario. ejecutando como intérprete de línea de
REMOTE_ADDR comandos, esta variable no está disponible.
La dirección IP desde la que el usuario está HTTP_COOKIE_VARS
viendo la página actual. Un array asociativo de variables pasadas al
REMOTE_PORT script actual mediante cookies HTTP. Sólo está
El puerto que se está utilizando en la máquina disponible si el seguimiento de variables ha
del usuario para comunicarse con el servidor sido activado mediante la directiva de
web. configuración track_vars o la directiva <?
SCRIPT_FILENAME php_track_vars?>.
La vía de acceso absoluta del script que se HTTP_GET_VARS
está ejecutando. Un array asociativo de variables pasadas al
SERVER_ADMIN script actual mediante el método HTTP GET.
El valor que se haya dado a la directiva Sólo está disponible si --variable tracking-- ha
SERVER_ADMIN (en Apache) en el fichero de sido activado mediante la directiva de
configuración del servidor web. Si el script se configuración track_vars o la directiva <?
está ejecutando en un servidor virtual, será el php_track_vars?>.
valor definido para dicho servidor virtual. HTTP_POST_VARS
SERVER_PORT Un array asociativo de variables pasadas al
El puerto del equipo servidor que está usando script actual mediante el método HTTP POST.
el servidor web para la comunicación. Para Sólo está disponible si --variable tracking-- ha
sido activado mediante la directiva de El array $GLOBALS es un array asociativo con el nombre
configuración track_vars o la directiva <? de la variable global como clave y los contenidos de
php_track_vars?>. dicha variable como el valor del elemento del array.
Otra característica importante del ámbito de las variables
es la variable static. Una variable estática existe sólo en
Ambito de las variables el ámbito local de la función, pero no pierde su valor
cuando la ejecución del programa abandona este ámbito.
Consideremos el siguiente ejemplo:
El ámbito de una variable es el contexto dentro del que
la variable está definida. La mayor parte de las variables Function Test
PHP sólo tienen un ámbito simple. Este ámbito simple () {
también abarca los ficheros incluidos y los requeridos. $a = 0;
Por ejemplo: echo $a;
$a++;
$a = 1; }
include
"b.inc"; Esta función tiene poca utilidad ya que cada vez que es
llamada asigna a $a el valor 0 y representa un "0". La
Aquí, la variable $a dentro del script incluido b.inc. De sentencia $a++, que incrementa la variable, no sirve
todas formas, dentro de las funciones definidas por el para nada, ya que en cuanto la función termina la
usuario aparece un ámbito local a la función. Cualquier variable $a desaparece. Para hacer una función útil para
variables que se use dentro de una función está, por contar, que no pierda la pista del valor actual del conteo,
defecto, limitada al ámbito local de la función. Por la variable $a debe declararse como estática:
ejemplo:
Function Test
$a = 1; /* ámbito global */ () {
static $a =
Function Test () { 0;
echo $a; /* referencia a una variable de echo $a;
ámbito local */ $a++;
} }
Test (); Ahora, cada vez que se llame a la función Test(), se
representará el valor de $a y se incrementará.
Este script no producirá salida, ya que la orden echo Las variables estáticas también proporcionan una forma
utiliza una versión local de la variable $a, a la que no se de manejar funciones recursivas. Una función recursiva
ha asignado ningún valor en su ámbito. Puede que usted es la que se llama a sí misma. Se debe tener cuidado al
note que hay una pequeña diferencia con el lenguaje C, escribir una función recursiva, ya que puede ocurrir que
en el que las variables globales están disponibles se llame a sí misma indefinidamente. Hay que
automáticamente dentro de la función a menos que sean asegurarse de implementar una forma adecuada de
expresamente sobreescritas por una definición local. terminar la recursión. La siguiente función cuenta
Esto puede causar algunos problemas, ya que la gente recursivamente hasta 10, usando la variable estática
puede cambiar variables globales inadvertidamente. En $count para saber cuándo parar:
PHP, las variables globales deben ser declaradas globales
dentro de la función si van a ser utilizadas dentro de Function Test
dicha función. Veamos un ejemplo: () {
static
$a = 1; $count = 0;
$b = 2;
$count++;
Function Sum echo
() { $count;
global $a, if ($count <
$b; 10) {
Test ();
$b = $a + }
$b; $count--;
} }
Sum ();
echo $b;
Variables variables
El script anterior producirá la salida "3". Al declarar $a y
$b globales dentro de la función, todas las referencias a
tales variables se referirán a la versión global. No hay A veces es conveniente tener nombres de variables
límite al número de variables globales que se pueden variables. Dicho de otro modo, son nombres de variables
manipular dentro de una función. que se pueden establecer y usar dinámicamente. Una
Un segundo método para acceder a las variables desde variable normal se establece con una sentencia como:
un ámbito global es usando el array $GLOBALS propio de
$a =
PHP3. El ejemplo anterior se puede reescribir así:
"hello";
$a = 1;
Una variable variable toma el valor de una variable y lo
$b = 2;
trata como el nombre de una variable. En el ejemplo
anterior, hello, se puede usar como el nombre de una
Function Sum () {
variable utilizando dos signos de dólar. p.ej.
$GLOBALS["b"] = $GLOBALS["a"] +
$GLOBALS["b"]; $$a =
} "world";
En este momento se han definido y almacenado dos
Sum (); variables en el árbol de símbolos de PHP: $a, que
echo $b; contiene "hello", y $hello, que contiene "world". Es más,
esta sentencia:
echo "$a $ name="sub">
{$a}";
Cuando el usuario hace click en cualquier parte de la
produce el mismo resultado que: imagen, el formulario que la acompaña se transmitirá al
servidor con dos variables adicionales, sub_x y sub_y.
echo "$a
Estas contienen las coordenadas del click del usuario
$hello";
dentro de la imagen. Los más experimentados puede
p.ej. ambas producen el resultado: hello world. notar que los nombres de variable enviados por el
Para usar variables variables con arrays, hay que navegador contienen un guión en vez de un subrayado
resolver un problema de ambigüedad. Si se escribe $ (guión bajo), pero PHP convierte el guión en subrayado
$a[1] el intérprete necesita saber si nos referimos a automáticamente.
utilizar $a[1] como una variable, o si se pretendía utilizar
$$a como variable y el índice [1] como índice de dicha
variable. La sintaxis para resolver esta ambiguedad es: $ Cookies HTTP
{$a[1]} para el primer caso y ${$a}[1] para el segundo.
PHP soporta cookies de HTTP de forma transparente tal y
Variables externas a PHP como están definidas en en las Netscape's Spec. Las
cookies son un mecanismo para almacenar datos en el
navegador y así rastrear o identificar a usuarios que
Formularios HTML (GET y POST) vuelven. Se pueden crear cookies usando la función
SetCookie(). Las cookies son parte de la cabecera HTTP,
así que se debe llamar a la función SetCookie antes de
Cuando se envía un formulario a un script PHP, las que se envíe cualquier salida al navegador. Es la misma
variables de dicho formulario pasan a estar restricción que para la función header(). Cualquier
automáticamente disponibles en el script gracias a PHP. cookie que se reciba procedente del cliente será
Por ejemplo, consideremos el siguiente formulario: convertida automáticamente en una variable de PHP
Ejemplo 8-1. Variables de formulario simples como con los datos en los métodos GET y POST.
Si se quieren asignar múltiples valores a una sola cookie,
basta con añadir [] al nombre de la. Por ejemplo:
<form action="foo.php3"
method="post"> SetCookie ("MyCookie[]", "Testing",
Name: <input type="text" time()+3600);
name="name"><br> Nótese que una cookie reemplazará a una cookie
<input type="submit"> anterior que tuviese el mismo nombre en el navegador a
</form> menos que el camino (path) o el dominio fuesen
Cuando es enviado, PHP creará la variable $name, que diferentes. Así, para una aplicación de carro de la compra
contendrá lo que sea que se introdujo en el campo se podría querer mantener un contador e ir pasándolo.
Name: del formulario. P.ej.
PHP también maneja arrays en el contexto de variables Ejemplo 8-3. SetCookie Example
de formularios, pero sólo en una dimensión. Se puede,
por ejemplo, agrupar juntas variables relacionadas, o
usar esta característica para recuperar valores de un $Count++;
campo select input múltiple: SetCookie ("Count", $Count, time()
Ejemplo 8-2. Variables de formulario más +3600);
complejas SetCookie ("Cart[$Count]", $item,
time()+3600);

<form action="array.php" method="post">


Name: <input type="text" Variables de entorno
name="personal[name]"><br>
Email: <input type="text"
name="personal[email]"><br> PHP hace accesibles las variables de entorno
Beer: <br> automáticamente tratándolas como variables normales.
<select multiple name="beer[]"> echo $HOME; /* Shows the HOME environment
<option value="warthog">Warthog variable, if set. */
<option value="guinness">Guinness
<option Dado que la información que llega vía mecanismos GET,
value="stuttgarter">Stuttgarter POST y Cookie crean automáticamente variables de PHP,
Schwabenbräu algunas veces es mejor leer variables del entorno
</select> explícitamente para asegurarse de que se está
<input type="submit"> trabajando con la versión correcta. La función getenv()
</form> se puede usar para ello. También se puede asignar un
valor a una variable de entorno con la función putenv().
Si la posibilidad de PHP de track_vars está activada, ya
sea mediante la opción de configuración track_vars o
mediante la directiva <?php_track_vars?>, las variables Puntos en los nombres de variables de entrada
enviadas con los métodos POST o GET también se
encontrarán en los arrays asociativos globales
$HTTP_POST_VARS y $HTTP_GET_VARS. Típicamente, PHP no altera los nombres de las variables
cuando se pasan a un script. De todas formas, hay que
notar que el punto no es un carácter válido en el nombre
IMAGE SUBMIT variable names de una variable PHP. Por esta razón, mire esto:
$varname.ext; /* nombre de
Cuando se envía un formulario, es posible usar una variable no válido */
imagen en vez del botón submit estándar con una Lo que el intérprete ve es el nombre de una variable
etiqueta como: $varname, seguido por el operador de concatenación, y
<input type=image src="image.gif" seguido por la prueba (es decir, una cadena sin
entrecomillar que no coincide con ninguna palabra clave
o reservada conocida) 'ext'. Obviamente, no se pretendía
que fuese este el resultado.
• Las constantes no son precedidas por un
símbolo de dolar ($)
Por esta razón, es importante hacer notar que PHP
reemplazará automáticamente cualquier punto en los • Las contantes solo pueden ser definidas
nombres de variables de entrada por guiones bajos usando la función() define , nunca por simple
(subrayados). asignación
• Las constantes pueden ser definidas y
Determinando los tipos de variables accedidas sin tener en cuenta las reglas de
alcanze del ámbito.
• Las constantes no pueden ser redefinidas o
Dado que PHP determina los tipos de las variables y los eliminadas despues de establecerse; y
convierte (generalmente) según necesita, no siempre
resulta obvio de qué tipo es una variable dada en un • Las constantes solo puede albergar valores
momento concreto. PHP incluye varias funciones que escalares
descubren de qué tipo es una variable. Son gettype(),
is_long(), is_double(), is_string(), is_array(), y
is_object(). Ejemplo 9-1. Definiendo constantes

Capítulo 9. Constantes <?php


define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
Una constante es un identificador para expresar un valor echo Constant; // outputs "Constant" and
simple. Como el nombre sugiere, este valor no puede issues a notice.
variar durante la ejecución del script. (Las constantes ?>
especiales __FILE__ y __LINE__ son una excepción a
esto, ya que actualmente no lo soin). Una constante es
sensible a mayúsculas por defecto. Por convención, los
Constantes predefinidas
identificadores de constantes suelen declararse en
mayúsculas
El nombre de una constante sigue las mismas reglas que PHP ofrece un largo número de constantes predefinidas a
cualquier etiqueta en PHP. Un nombre de constante cualquier script en ejecución. Muchas de estas
válido empieza con una letra o un caracter de subrayado, constantes, sin embargo, son creadas por diferentes
seguido por cualquier número de letras, números, o extensiones, y solo estarán presentes si dichas
subrayados. Se podrían expresar mediante la siguiente extensiones están disponibles, bien por carga dinámica o
expresión regular: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* porque has sido compiladas.
Se puede encontrar una lista de constantes predefinidas
en la seccion Constantes predefinidas.
Nota: Para nuestros propósitos ,
entenderemos como letra los
carácteres a-z, A-Z, y los ASCII del
Capítulo 10. Expresiones
127 hasta el 255 (0x7f-0xff).

Las expresiones son la piedra angular de PHP. En PHP,


El alcanze de una constante es global, Es decir, es
casi cualquier cosa que escribes es una expresión. La
posible acceder a ellas sin preocuparse por el ámbito de
forma más simple y ajustada de definir una expresión es
alcance.
"cualquier cosa que tiene un valor".
Las formas más básicas de expresiones son las
constantes y las variables. Cuando escribes "$a = 5",
Sintaxis
estás asignando '5' a $a. '5', obviamente, tiene el valor 5
o, en otras palabras '5' es una expresión con el valor 5
Se puede definir una constante usando la función (en este caso, '5' es una constante entera).
define(). Una vez definida, no puede ser modificada ni Después de esta asignación, esperarás que el valor de $a
eliminada . sea 5 también, de manera que si escribes $b = $a,
Solo se puede definir como constantes valores escalares esperas que se comporte igual que si escribieses $b = 5.
(boolean, integer, float y string ). En otras palabras, $a es una expresión también con el
Para obtener el valor de una constante solo es necesario valor 5. Si todo va bien, eso es exactamente lo que
especificar su nombre. A diferencia de las variables, no pasará.
se tiene que especificar el prefijo $. Tambien se puede Las funciones son un ejemplo algo más complejo de
utilizar la función constant(), para obtener el valor de expresiones. Por ejemplo, considera la siguiente función:
una constante, en el caso de que queramos expresarla function foo
de forma dinámica Usa la función () {
get_defined_constants() parar obtener una lista de return 5;
todas las constantes definidas. }
Suponiendo que estés familiarizado con el concepto de
Nota: Las contantes y las variables funciones (si no lo estás échale un vistazo al capítulo
(globales) se encuentran en un sobre funciones), asumirás que teclear $c = foo() es
espacio de nombres distinto. Esto esencialmente lo mismo que escribir $c = 5, y has
implica que por ejemplo TRUE y acertado. Las funciones son expresiones que valen el
$TRUE son diferentes. valor que retornan. Como foo() devuelve 5, el valor de la
expresión 'foo()' es 5. Normalmente las funciones no
devuelven un valor fijo, sino que suele ser calculado.
Si usas una constante todavia no definida, PHP asume Desde luego, los valores en PHP no se limitan a enteros,
que estás refiriéndote al nombre de la constante en si. y lo más normal es que no lo sean. PHP soporta tres tipos
Se lanzará un aviso si esto sucede. Usa la función escalares: enteros, punto flotante y cadenas (los tipos
defined() para comprobar la existencia de dicha escalares son aquellos cuyos valores no pueden
constante. 'dividirse' en partes menores, no como los arrays, por
Estas son las diferencias entre constantes y variables: ejemplo). PHP también soporta dos tipos compuestos (no
escalares): arrays y objetos. Se puede asignar cada uno Si el valor de la primera subexpresión es verdadero
de estos tipos de valor a variables o bien retornarse de (distinto de cero), entonces se evalúa la segunda
funciones, sin ningún tipo de limitación. subexpresión, si no, se evalúa la tercera y ése es el
Hasta aquí, los usuarios de PHP/FI 2 no deberían haber valor.
notado ningún cambio. Sin embargo, PHP lleva las El siguiente ejemplo te ayudará a comprender un poco
expresiones mucho más allá, al igual que otros mejor el pre y post incremento y las expresiones en
lenguajes. PHP es un lenguaje orientado a expresiones, general:
en el sentido de que casi todo es una expresión.
function double($i) {
Considera el ejemplo anterior '$a = 5'. Es sencillo ver
return $i*2;
que hay dos valores involucrados, el valor de la
}
constante entera '5', y el valor de $a que está siendo
$b = $a = 5; /* asignar el valor cinco a las variables
actualizado también a 5. Pero la verdad es que hay un
$a y $b */
valor adicional implicado aquí, y es el valor de la propia
$c = $a++; /* postincremento, asignar el valor
asignación. La asignación misma se evalúa al valor
original de $a (5) a $c */
asignado, en este caso 5. En la práctica, quiere decir que
$e = $d = ++$b; /* preincremento, asignar el valor
'$a = 5', independientemente de lo que hace, es una
incrementado de $b (6) a
expresión con el valor 5. De esta manera, escribir algo
$d y a $e */
como '$b = ($a = 5)' es como escribir '$a = 5; $b = 5;'
(un punto y coma marca el final de una instrucción).
/* en este punto, tanto $d como $e son iguales a 6 */
Como las asignaciones se evalúan de derecha a
izquierda, puedes escribir también '$b = $a = 5'.
$f = double($d++); /* asignar el doble del valor de $d
Otro buen ejemplo de orientación a expresiones es el pre
antes
y post incremento y decremento. Los usuarios de PHP/FI
del incremento, 2*6 = 12 a $f */
2 y los de otros muchos lenguajes les sonará la notación
$g = double(++$e); /* asignar el doble del valor de $e
variable++ y variable--. Esto son las operaciones de
después
incremento y decremento. En PHP/FI 2, la instrucción
del incremento, 2*7 = 14 a $g */
'$a++' no tiene valor (no es una expresión), y no puedes
$h = $g += 10; /* primero, $g es incrementado en 10
asignarla o usarla de ningún otro modo. PHP mejora las
y termina valiendo 24.
características del incremento/decremento haciéndolos
después el valor de la asignación (24) se
también expresiones, como en C. En PHP, como en C,
asigna a $h,
hay dos tipos de incremento - pre-incremento y post-
y $h también acaba valiendo 24. */
incremento. Ambos, en esencia, incrementan la variable
y el efecto en la variable es idéntico. La diferencia radica Al principio del capítulo hemos dicho que describiríamos
en el valor de la propia expresion incremento. El los distintos tipos de instrucciones y, como prometimos,
preincremento , escrito '++$variable', se evalúa al valor las expresiones pueden ser instrucciones. Sin embargo,
incrementado (PHP incrementa la variable antes de leer no todas las expresiones son instrucciones. En este caso,
su valor, de ahí el nombre 'preincremento'). El una instrucción tiene la forma 'expr' ';', es decir, una
postincremento, escrito '$variable++', se evalúa al valor expresión seguida de un punto y coma. En '$b=$a=5;',
original de $variable antes de realizar el incremento (PHP $a=5 es una expresión válida, pero no es una instrucción
incrementa la variable después de leer su valor, de ahí el en sí misma. Por otro lado '$b=$a=5:' sí es una
nombre 'postincremento'). instrucción válida.
Un tipo muy corriente de expresiones son las Una última cosa que vale la pena mencionar, es el valor
expresiones de comparación. Estas expresiones se booleano de las expresiones. En muchas ocasiones,
evalúan a 0 o 1, significando FALSO (FALSE) o CIERTO principalmente en condicionales y bucles, no estás
(TRUE), respectivamente. PHP soporta > (mayor que), interesado en el valor exacto de la expresión, sino
>= (mayor o igual que), == (igual que), != (distinto), < únicamente si es CIERTA (TRUE) o FALSA (FALSE) (PHP
(menor que) y <= (menor o igual que). Estas no tiene un tipo booleano específico). El valor de verdad
expresiones se usan frecuentemente dentro de la de las expresiones en PHP se calcula de forma similar a
ejecución condicional como la instrucción if. perl. Cualquier valor numérico distinto de cero es CIERTO
El último tipo de expresiones que trataremos, es la (TRUE), cero es FALSO (FALSE). Fíjate en que los valores
combinación operador-asignación. Ya sabes que si negativos son distinto de cero y considerados CIERTO
quieres incrementar $a en 1, basta con escribir '$a++' o (TRUE)! La cadena vacía y la cadena "0" son FALSO
++$a'. Pero qué pasa si quieres añadir más de 1, por (FALSE); todas las demás cadenas son TRUE. Con los
ejemplo 3? Podrías escribir '$a++' múltiples veces, pero tipos no escalares (arrays y objetos) - si el valor no
no es una forma de hacerlo ni eficiente ni cómoda. Una contiene elementos se considera FALSO (FALSE), en
práctica mucho más corriente es escribir '$a = $a + 3'. caso contrario se considera CIERTO (TRUE).
'$a + 3' se evalúa al valor de $a más 3, y se asigna de PHP te brinda una completa y potente implementación
nuevo a $a, lo que resulta en incrementar $a en 3. En de expresiones, y documentarla enteramente está más
PHP, como en otros lenguajes como C, puedes escribir allá del objetivo de ete manual. Los ejemplos anteriores,
esto de una forma más concisa, que con el tiempo será deberían darte una buena idea de qué son las
más clara y también fácil de entender. Añadir 3 al valor expresiones y cómo construir expresiones útiles. A lo
actual de $a se puede escribir como '$a += 3'. Esto largo del resto del manual, escribiremos expr para
quiere decir exactamente "toma el valor de $a, súmale 3, indicar una expresión PHP válida.
y asígnalo otra vez a $a". Además de ser más corto y
claro, también resulta en una ejecución más rápida. El
valor de '$a += 3', como el valor de una asignación Capítulo 11. Operadores
normal y corriente, es el valor asignado. Ten en cuenta
que NO es 3, sino el valor combinado de $a más 3 (ése
es el valor asignado a $a). Cualquier operación binaria
puede ser usada en forma de operador-asignación, por
Operadores Aritméticos
ejemplo '$a -= 5' (restar 5 del valor de $a), '$b *= 7'
(multiplicar el valor de $b por 5), etc.
Hay otra expresión que puede parecer extraña si no la ¿Recuerdas la aritmética básica del colegio? Pues estos
has visto en otros lenguaes, el operador condicional operadores funcionan exactamente igual.
ternario: Tabla 11-1. Operadores Aritméticos
$first ? $second : ejemp
$third nombre resultado
lo
$a + Adición Suma de $a y $b.
ejemp ejemp
nombre resultado nombre resultado
lo lo
$b por dos el valor de $a)
Substracci Diferencia entre $a y Desplaza los bits de $a, $b
$a - $b
ón $b. posiciones hacia la derecha (por
$a >> Desplazamient
aritmética binaria, cada posición
$a * Multiplicac $b o a la derecha
Producto de $a and $b. desplazada equivale a dividir entre
$b ión
dos el valor de $a)
Cociente de $a entre
$a / $b División
$b.
$a % Resto de $a dividido Operadores de Comparación
Módulo
$b entre $b.
Los operadores de comparación, como su nombre indica,
permiten comparar dos valores.
Operadores de Asignación Tabla 11-3. Operadores de Comparación
ejempl
nombre resultado
El operador básico de asignación es "=". A primera vista o
podrías pensar que es el operador de comparación "igual $a ==
que". Pero no. Realmente significa que el operando de la Igualdad Cierto si $a es igual a $b.
$b
izquierda toma el valor de la expresión a la derecha,
(esto es, "toma el valor de"). $a === Cierto si $a es igual a $b y si son del
Identidad
El valor de una expresión de asignación es el propio valor $b mismo tipo (sólo PHP4)
asignado. Esto es, el valor de "$a = 3" es 3. Esto permite $a !=
hacer cosas curiosas como Desigualdad Cierto si $a no es igual a $b.
$b
$a = ($b = 4) + 5; // ahora $a es igual
Cierto si $a es estrictamente menor
a 9, y $b vale 4. $a < $b Menor que
que $b.
Además del operador básico de asignación, existen los
Cierto si $a es estrictamente mayor
"operadores combinados" para todas las operaciones $a > $b Mayor que
que $b.
aritméticas y de cadenas que sean binarias. Este
operador combinado te permite, de una sola vez, usar $a <= Menor o
Cierto si $a es menor o igual que $b.
una variable en una expresión y luego establecer el valor $b igual que
de esa variable al resultado de la expresión. Por ejemplo:
$a >= Mayor o
Cierto si $a es mayor o igual que $b.
$a = 3; $b igual que
$a += 5; // establece $a a 8, como si hubiésemos escrito:
Otro operador condicional es el operador "?:" (o ternario),
$a = $a + 5;
que funciona como en C y otros muchos lenguajes.
$b = "Hola ";
$b .= "Ahí!"; // establece $b a "Hola Ahí!", igual que si (expr1) ? (expr2) :
hiciésemos $b = $b . "Ahí!"; (expr3);
Fíjate en que la asignación realiza una nueva copia de la La expresión toma el valor expr2 si expr1 se evalúa a
variable original (asignación por valor), por lo que cierto, y expr3 si expr1 se evalúa a falso.
cambios a la variable original no afectan a la copia. Esto
puede tener interés si necesitas copiar algo como un
array con muchos elementos dentro de un bucle que se Operador de ejecución
repita muchas veces (cada vez se realizará una nueva
copia del array). PHP4 soporta asignación por referencia,
PHP soporta un operador de ejecución: el apóstrofe
usando la sintaxis $var = &$othervar;, pero esto no es
invertido (``). ¡Fíjate que no son apostrofes normales!
posible en PHP3. 'Asignación por referencia' quiere decir
PHP intentará ejecutar la instrucción contenida dentro de
que ambas variables acabarán apuntando al mismo dato
los apóstrofes invertidos como si fuera un comando del
y que nada es realmente copiado.
shell; y su salida devuelta como el valor de esta
expresión (i.e., no tiene por qué ser simplemente volcada
Operadores Bit a bit como salida; puede asignarse a una variable).
$output = `ls -al`;
echo
Los operadores bit a bit te permiten activar o desactivar "<pre>$output</pre
bits individuales de un entero. >";
Tabla 11-2. Operadores Bit a bit
Ver también system(), passthru(), exec(), popen(), y
ejemp escapeshellcmd().
nombre resultado
lo
$a & Se activan los bits que están activos
Y Operadores de Incremento/decremento
$b tanto en $a como $b.
Se activan los bits que están activos
$a | $b O
en $a o que lo están en $b. PHP soporta los operadores de predecremento y post
incremento al estilo de C.
Se activan los bits que están activos
$a ^ Xor ("o Tabla 11-4. Operadores de Incremento/decremento
en $a o en $b pero no en ambos a
$b exclusiva")
la vez. ejemp
nombre efecto
lo
Se activan los bits que no están
~ $a No
activos en $a. Preincremen Incrementa $a en uno y después
++$a
to devuelve $a.
$a << Desplazamient Desplaza los bits de $a, $b
$b o a la posiciones hacia la izquierda (por Postincreme Devuelve $a y después incrementa
$a++
izquierda aritmética binaria, cada posición nto $a en uno.
desplazada equivale a multiplicar
ejemp + 5 * 3, la respuesta es 16 y no 18 porque el operador de
nombre efecto multiplicación ("*") tiene una mayor precedencia que el
lo
de adición ("+").
Predecreme Decrementa $a en uno y después La siguiente tabla lista la precedencia de operadores,
--$a
nto devuelve $a. indicándose primero los de menor precedencia.
Postdecrem Devuelve $a y después decrementa Tabla 11-6. Precedencia de Operadores
$a--
ento $a en uno. Asociativi
Operadores
He aquí un listado de ejemplo: dad

<?php izquierda ,
echo izquierda or
"<h3>Postincremento</h3>"
; izquierda xor
$a = 5; izquierda and
echo "Debería ser 5: " . $a++
. "<br>\n"; derecha print
echo "Debería ser 6: " . $a . = += -= *= /= .= %= &= |= ^=
"<br>\n"; izquierda
~= <<= >>=

echo izquierda ?:
"<h3>Preincremento</h3>"; izquierda ||
$a = 5;
echo "Debería ser 6: " . ++$a izquierda &&
. "<br>\n"; izquierda |
echo "Debería ser 6: " . $a .
"<br>\n"; izquierda ^
izquierda &
echo
"<h3>Postdecremento</h3> no
== != ===
"; asociativo
$a = 5; no
echo "Debería ser 5: " . $a-- . < <= > >=
asociativo
"<br>\n";
echo "Debería ser 4: " . $a . izquierda << >>
"<br>\n"; izquierda +-.

echo izquierda */%


"<h3>Predecremento</h3>" ! ~ ++ -- (int) (double) (string)
; derecha
(array) (object) @
$a = 5;
echo "Debería ser 4: " . --$a . derecha [
"<br>\n"; no
echo "Debería ser 4: " . $a . new
asociativo
"<br>\n";
?>
Operadores de Cadenas

Operadores Lógicos
Hay dos operadores de cadenas. El primero es el
operador de concatenación ('.'), que devuelve el
Tabla 11-5. Operadores Lógicos resultado de concatenar sus operandos izquierdo y
ejempl derecho. El segundo es el operador de concatenación y
nombre resultado asignación ('.='). Consulta Operadores de Asignación
o
para más información.
$a and
Y Cierto si tanto $a como $b son ciertos. $a = "Hola ";
$b
$b = $a . "Mundo!"; // ahora $b contiene
$a or "Hola Mundo!"
O Cierto si $a o $b son ciertos.
$b
O $a = "Hola ";
$a xor Cierto si $a es cierto o $b es cierto, pero $a .= "Mundo!"; // ahora $a contiene
exclusiv
$b no ambos a la vez. "Hola Mundo!"
a
Negació
! $a Cierto si $a no es cierto.
n
Capítulo 12. Estructuras de Control
$a &&
Y Cierto si tanto $a como $b son ciertos.
$b
Todo archivo de comandos PHP se compone de una serie
$a || $b O Cierto si $a o $b son ciertos. de sentencias. Una sentencia puede ser una asignación,
La razón de las dos variaciones de "y" y "o" es que una llamada a función, un bucle, una sentencia
operan con distinta precedencia (ver Precedencia de condicional e incluso una sentencia que no haga nada
Operadores.) (una sentencia vacía). Las sentencias normalmente
acaban con punto y coma. Además, las sentencias se
pueden agrupar en grupos de sentencias encapsulando
Precedencia de Operadores un grupo de sentencias con llaves. Un grupo de
sentencias es también una sentencia. En este capítulo se
describen los diferentes tipos de sentencias.
La precedencia de operadores especifica cómo se
agrupan las expresiones. Por ejemplo, en la expresión 1
if
{
print "a es igual
La construcción if es una de las más importantes que b";
características de muchos lenguajes, incluido PHP. } else {
Permite la ejecución condicional de fragmentos de print "a es mayor
código. PHP caracteriza una estructura if que es similar a que b";
la de C: }

if (expr) Puede haber varios elseifs dentro de la misma sentencia


senten if. La primera expresión elseif (si hay alguna) que se
cia evalúe como TRUE se ejecutaría. En PHP, también se
puede escribir 'else if' (con dos palabras) y el
Como se describe en la sección sobre expresiones, expr comportamiento sería idéntico al de un 'elseif' (una sola
se evalúa a su valor condicional. Si expr se evalúa como palabra). El significado sintáctico es ligeramente distinto
TRUE, PHP ejecutará la sentencia, y si se evalúa como (si estas familiarizado con C, es el mismo
FALSE - la ignorará. comportamiento) pero la línea básica es que ambos
El siguiente ejemplo mostraría a es mayor que b si $a resultarían tener exactamente el mismo
fuera mayor que $b: comportamiento.
if ($a > $b) La sentencia elseif se ejecuta sólo si la expresión if
print "a es mayor precedente y cualquier expresión elseif precedente se
que b"; evalúan como FALSE, y la expresión elseif actual se
evalúa como TRUE.
A menudo, se desea tener más de una sentencia
ejecutada de forma condicional. Por supuesto, no hay
necesidad de encerrar cada sentencia con una cláusula Sintaxis Alternativa de Estructuras de Control
if. En vez de eso, se pueden agrupar varias sentencias en
un grupo de sentencias. Por ejemplo, este código
mostraría a es mayor que b si $a fuera mayor que $b, y PHP ofrece una sintaxis altenativa para alguna de sus
entonces asignaría el valor de $a a $b: estructuras de control; a saber, if, while, for, y switch. En
cada caso, la forma básica de la sintaxis alternativa es
if ($a > $b) {
cambiar abrir-llave por dos puntos (:) y cerrar-llave por
print "a es mayor
endif;, endwhile;, endfor;, or endswitch;,
que b";
respectivamente.
$b = $a;
} <?php if
($a==5): ?>
Las sentencias if se pueden anidar indefinidamente
A es igual a 5
dentro de otras sentencias if, lo cual proporciona una
<?php endif; ?
flexibilidad completa para ejecuciones condicionales en
>
las diferentes partes de tu programa.
En el ejemplo de arriba, el bloque HTML "A = 5" se anida
dentro de una sentencia if escrita en la sintaxis
else alternativa. El bloque HTML se mostraría solamente si $a
fuera igual a 5.
La sintaxis alternativa se aplica a else y también a elseif.
A menudo queremos ejecutar una sentencia si se cumple La siguiente es una estructura if con elseif y else en el
una cierta condicion, y una sentencia distinta si la formato alternativo:
condición no se cumple. Esto es para lo que sirve else.
else extiende una sentencia if para ejecutar una if ($a == 5):
sentencia en caso de que la expresión en la sentencia if print "a es igual
se evalúe como FALSE. Por ejemplo, el siguiente código a 5";
mostraría a es mayor que b si $a fuera mayor que $b, y a print "...";
NO es mayor que b en cualquier otro caso: elseif ($a == 6):
print "a es igual
if ($a > $b) { a 6";
print "a es mayor print "!!!";
que b"; else:
} else { print "a no es ni
print "a NO es mayor 5 ni 6";
que b"; endif;
}
Mirar también while, for, e if para más ejemplos.
La sentencia else se ejecuta solamente si la expresión if
se evalúa como FALSE, y si hubiera alguna expresión
elseif - sólo si se evaluaron también a FALSE (Ver elseif). while

elseif Los bucles while son los tipos de bucle más simples en
PHP. Se comportan como su contrapartida en C. La forma
básica de una sentencia while es:
elseif, como su nombre sugiere, es una combinación de if
y else. Como else, extiende una sentencia if para while (expr)
ejecutar una sentencia diferente en caso de que la sentencia
expresión if original se evalúa como FALSE. No obstante, El significado de una sentencia while es simple. Le dice a
a diferencia de else, ejecutará esa expresión alternativa PHP que ejecute la(s) sentencia(s) anidada(s)
solamente si la expresión condicional elseif se evalúa repetidamente, mientras la expresión while se evalúe
como TRUE. Por ejemplo, el siguiente código mostraría a como TRUE. El valor de la expresión es comprobado
es mayor que b, a es igual a b o a es menor que b: cada vez al principio del bucle, así que incluso si este
if ($a > $b) { valor cambia durante la ejecución de la(s) sentencia(s)
print "a es mayor anidada(s), la ejecución no parará hasta el fin de la
que b"; iteración (cada vez que PHP ejecuta las sentencias en el
} elseif ($a == $b) bucle es una iteración). A veces, si la expresión while se
evalúa como FALSE desde el principio de todo, la(s) incluso archivos de comandos potentes sin usar esta
sentencia(s) anidada(s) no se ejecutarán ni siquiera una 'propiedad'.
vez.
Como con la sentencia if, se pueden agrupar multiples
sentencias dentro del mismo bucle while encerrando un for
grupo de sentencias con llaves, o usando la sintaxis
alternativa:
Los bucles for son los bucles más complejos en PHP. Se
while (expr): sentencia ... comportan como su contrapartida en C. La sintaxis de un
endwhile; bucle for es:
Los siguientes ejemplos son idénticos, y ambos imprimen for (expr1; expr2; expr3)
números del 1 al 10: sentencia
/* ejemplo 1 */ La primera expresión (expr1) se evalúa (ejecuta)
incondicionalmente una vez al principio del bucle.
$i = 1; Al comienzo de cada iteración, se evalúa expr2 . Si se
while ($i <= 10) { evalúa como TRUE, el bucle continúa y las sentencias
print $i++; /* el valor anidadas se ejecutan. Si se evalúa como FALSE, la
impreso sería ejecución del bucle finaliza.
$i antes del Al final de cada iteración, se evalúa (ejecuta) expr3.
incremento Cada una de las expresiones puede estar vacía. Que
(post- expr2 esté vacía significa que el bucle debería correr
incremento) */ indefinidamente (PHP implicitamente lo considera como
} TRUE, al igual que C). Esto puede que no sea tan inútil
como se podría pensar, puesto que a menudo se quiere
/* ejemplo 2 */ salir de un bucle usando una sentencia break condicional
en vez de usar la condición de for.
$i = 1; Considera los siguientes ejemplos. Todos ellos muestran
while ($i <= 10): números del 1 al 10:
print $i;
$i++; /* ejemplo 1 */
endwhile;
for ($i = 1; $i <= 10; $i+
+) {
print $i;
do..while }

/* ejemplo 2 */
Los bucles do..while son muy similares a los bucles while,
excepto que las condiciones se comprueban al final de
for ($i = 1;;$i++) {
cada iteración en vez de al principio. La principal
if ($i > 10) {
diferencia frente a los bucles regulares while es que se
break;
garantiza la ejecución de la primera iteración de un bucle
}
do..while (la condición se comprueba sólo al final de la
print $i;
iteración), mientras que puede no ser necesariamente
}
ejecutada con un bucle while regular (la condición se
comprueba al principio de cada iteración, si esta se
/* ejemplo 3 */
evalúa como FALSE desde el principio la ejecución del
bucle finalizará inmediatamente).
$i = 1;
Hay una sola sintaxis para los bucles do..while:
for (;;) {
$i = 0; if ($i > 10) {
do { break;
print $i; }
} while print $i;
($i>0); $i++;
El bucle de arriba se ejecutaría exactamente una sola }
vez, después de la primera iteración, cuando la condición
se comprueba, se evalúa como FALSE ($i no es más /* ejemplo 4 */
grande que 0) y la ejecución del bucle finaliza.
Los usuarios avanzados de C pueden estar familiarizados for ($i = 1; $i <= 10;
con un uso distinto del bucle do..while, para permitir print $i, $i++) ;
parar la ejecución en medio de los bloques de código, Por supuesto, el primer ejemplo parece ser el mas
encapsulandolos con do..while(0), y usando la sentencia elegante (o quizás el cuarto), pero uno puede descubrir
break. El siguiente fragmento de código demuestra esto: que ser capaz de usar expresiones vacías en bucles for
do { resulta útil en muchas ocasiones.
if ($i < 5) { PHP también soporta la "sintaxis de dos puntos"
print "i no es lo alternativa para bucles for.
suficientemente grande"; for (expr1; expr2; expr3):
break; sentencia; ...; endfor;
}
Otros lenguajes poseen una sentencia foreach para
$i *= $factor;
traducir un array o una tabla hash. PHP3 no posee tal
if ($i < $minimum_limit) {
construcción; PHP4 sí (ver foreach). En PHP3, se puede
break;
combinar while con las funciones list() y each() para
}
conseguir el mismo efecto. Mirar la documentación de
print "i es correcto";
estas funciones para ver un ejemplo.
...procesa i...
} while(0);
No se preocupes si no entiende esto completamente o en foreach
absoluto. Se pueden codificar archivos de comandos e
PHP4 (PHP3 no) incluye una construcción foreach, tal
como perl y algunos otros lenguajes. Esto simplemente
foreach($a as $v) {
da un modo fácil de iterar sobre arrays. Hay dos sintaxis;
print "\$a[$i] => $k.\n";
la segunda es una extensión menor, pero útil de la
}
primera:
foreach(expresion_array as $value) /* foreach ejemplo 3: clave y valor */
sentencia $a = array(
foreach(expresion_array as $key => "uno" => 1,
$value) sentencia "dos" => 2,
"tres" => 3,
La primera forma recorre el array dado por
"diecisiete" => 17
expresion_array. En cada iteración, el valor del elemento
);
actual se asigna a $value y el puntero interno del array
se avanza en una unidad (así en el siguiente paso, se
foreach($a as $k => $v) {
estará mirando el elemento siguiente).
print "\$a[$k] => $v.\n";
La segunda manera hace lo mismo, salvo que la clave
}
del elemento actual será asignada a la variable $key en
cada iteración.

break
Nota: Cuando foreach comienza su
primera ejecución, el puntero interno
a la lista (array) se reinicia break escapa de la estructuras de control iterante (bucle)
automáticamente al primer actuales for, while, o switch.
elemento del array. Esto significa break accepta un parámetro opcional, el cual determina
que no se necesita llamar a reset() cuantas estructuras de control hay que escapar.
antes de un bucle foreach. $arr = array ('one', 'two', 'three', 'four',
'stop', 'five');
Nota: Hay que tener en cuanta while (list (, $val) = each ($arr)) {
queforeach con una copia de la lista if ($val == 'stop') {
(array) especificada y no la lista en break; /* You could also write
si, por ello el puntero de la lista no 'break 1;' here. */
es modificado como en la }
construcción each. echo "$val<br>\n";
}

Puede haber observado que las siguientes son /* Using the optional argument. */
funcionalidades idénticas:
$i = 0;
reset( $arr );
while (++$i) {
while( list( , $value ) =
switch ($i) {
each( $arr ) ) {
case 5:
echo "Valor:
echo "At 5<br>\n";
$value<br>\n";
break 1; /* Exit only the switch. */
}
case 10:
echo "At 10; quitting<br>\n";
foreach( $arr as $value ) {
break 2; /* Exit the switch and the
echo "Valor:
while. */
$value<br>\n";
default:
}
break;
Las siguientes también son funcionalidades idénticas: }
}
reset( $arr );
while( list( $key, $value ) =
each( $arr ) ) {
echo "Key: $key; Valor: continue
$value<br>\n";
}
continue se usa dentro de la estructura del bucle para
foreach( $arr as $key => saltar el resto de la iteración actual del bucle y continuar
$value ) { la ejecución al comienzo de la siguiente iteración.
echo "Key: $key; Valor: continue accepta un parámetro opcional, el cual
$value<br>\n"; determina cuantos niveles (bluces) hay que saltar antes
} de continuar con la ejecución.

Algunos ejemplos más para demostrar su uso: while (list($key,$value) =


each($arr)) {
/* foreach ejemplo 1: sólo valor*/ if ($key % 2) { // salta los
$a = array(1, 2, 3, 17); miembros impares
continue;
foreach($a as $v) { }
print "Valor actual de \$a: $v.\n"; do_something_odd ($value);
} }
$i = 0;
/* foreach ejemplo 2: valor (con clave while ($i++ < 5) {
impresa para ilustrar) */ echo "Outer<br>\n";
$a = array(1, 2, 3, 17); while (1) {
echo " Middle<br>\n";
$i = 0; /* sólo para propósitos demostrativos while (1) {
*/ echo " Inner<br>\n";
sentencias break (incluso aunque pueda querer evitar
continue 3;
escribirlas intencionadamente en ciertas circunstancias).
}
En una sentencia switch, la condición se evalúa sólo una
echo "This never gets
vez y el resultado se compara a cada sentencia case. En
output.<br>\n";
una sentencia elseif, la condición se evalúa otra vez. Si
}
tu condición es más complicada que una comparación
echo "Neither does
simple y/o está en un bucle estrecho, un switch puede
this.<br>\n";
ser más rápido.
}
La lista de sentencias de un case puede también estar
vacía, lo cual simplemente pasa el control a la lista de
sentencias del siguiente case.
switch
switch ($i) {
case 0:
La sentencia switch es similar a una serie de sentencias case 1:
IF en la misma expresión. En muchas ocasiones, se case 2:
quiere comparar la misma variable (o expresión) con print "i es menor que 3, pero
nuchos valores diferentes, y ejecutar una parte de código no negativo";
distinta dependiendo de a qué valor es igual. Para ello break;
sirve la sentencia switch. case 3:
Los siguientes dos ejemplos son dos modos distintos de print "i es 3";
escribir la misma cosa, uno usa una serie de sentencias }
if, y el otro usa la sentencia switch: Un case especial es el default case. Este case coincide
if ($i == 0) { con todo lo que no coincidan los otros case. Por ejemplo:
print "i es igual switch ($i) {
a 0"; case 0:
} print "i es igual a 0";
if ($i == 1) { break;
print "i es igual case 1:
a 1"; print "i es igual a 1";
} break;
if ($i == 2) { case 2:
print "i es igual print "i es igual a 2";
a 2"; break;
} default:
print "i no es igual a
switch ($i) { 0, 1 o 2";
case 0: }
print "i es
igual a 0"; La expresión case puede ser cualquier expresión que se
break; evalúe a un tipo simple, es decir, números enteros o de
case 1: punto flotante y cadenas de texto. No se pueden usar
print "i es aquí ni arrays ni objetos a menos que se conviertan a un
igual a 1"; tipo simple.
break; La sintaxis alternativa para las estructuras de control
case 2: está también soportada con switch. Para más
print "i es información, ver Sintaxis alternativa para estructuras de
igual a 2"; control.
break; switch ($i):
} case 0:
Es importante entender cómo se ejecuta la sentencia print "i es igual 0";
switch para evitar errores. La sentencia switch ejecuta break;
línea por línea (realmente, sentencia a sentencia). Al case 1:
comienzo, no se ejecuta código. Sólo cuando se print "i es igual a 1";
encuentra una sentencia case con un valor que coincide break;
con el valor de la expresión switch PHP comienza a case 2:
ejecutar las sentencias. PHP continúa ejecutando las print "i es igual a 2";
sentencias hasta el final del bloque switch, o la primera break;
vez que vea una sentencia break. Si no se escribe una default:
sentencia break al final de una lista de sentencias case, print "i no es igual a
PHP seguirá ejecutando las sentencias del siguiente case. 0, 1 o 2";
Por ejemplo: endswitch;
switch ($i) {
case 0:
print "i es require()
igual a 0";
case 1:
La sentencia require() se sustituye a sí misma con el
print "i es
archivo especificado, tal y como funciona la directiva
igual a 1";
#include de C.
case 2:
Un punto importante sobre su funcionamiento es que
print "i es
cuando un archivo se incluye con include() o se requiere
igual a 2";
con require()), el intérprete sale del modo PHP y entra
}
en modo HTML al principio del archivo referenciado, y
Aquí, si $i es igual a 0, ¡PHP ejecutaría todas las vuelve de nuevo al modo PHP al final. Por esta razón,
sentecias print! Si $i es igual a 1, PHP ejecutaría las cualquier código dentro del archivo referenciado que
últimas dos sentencias print y sólo si $i es igual a 2, se debiera ser ejecutado como código PHP debe ser
obtendría la conducta 'esperada' y solamente se encerrado dentro de etiquetas válidas de comienzo y fin
mostraría 'i es igual a 2'. Así, es importante no olvidar las de PHP.
require() no es en realidad una función de PHP; es más La sentencia include() incluye y evalúa el archivo
una construcción del lenguaje. Está sujeta a algunas especificado.
reglas distintas de las de funciones. Por ejemplo, Si "URL fopen wrappers" esta activada en PHP (como
require() no esta sujeto a ninguna estructura de control está en la configuración inicial), se puede especificar el
contenedora. Por otro lado, no devuelve ningún valor; fichero que se va a incluir usando una URL en vez de un
intentar leer un valor de retorno de una llamada a un fichero local (con su Path) Ver Ficheros remotos y
require() resulta en un error del intérprete. fopen() para más información.
A diferencia de include(), require() siempre leerá el Un punto importante sobre su funcionamiento es que
archivo referenciado, incluso si la línea en que está no se cuando un archivo se incluye con include() o se requiere
ejecuta nunca. Si se quiere incluir condicionalmente un con require(), el intérprete sale del modo PHP y entra
archivo, se usa include(). La sentencia conditional no en modo HTML al principio del archivo referenciado, y
afecta a require(). No obstante, si la línea en la cual vuelve de nuevo al modo PHP al final. Por esta razón,
aparece el require() no se ejecuta, tampoco se cualquier código dentro del archivo referenciado que
ejecutará el código del archivo referenciado. debiera ser ejecutado como código PHP debe ser
De forma similar, las estructuras de bucle no afectan la encerrado dentro de etiquetas válidas de comienzo y fin
conducta de require(). Aunque el código contenido en el de PHP.
archivo referenciado está todavía sujeto al bucle, el Esto sucede cada vez que se encuentra la sentencia
propio require() sólo ocurre una vez. include(), así que se puede usar una sentencia
Esto significa que no se puede poner una sentencia include() dentro de una estructura de bucle para incluir
require() dentro de una estructura de bucle y esperar un número de archivos diferentes.
que incluya el contenido de un archivo distinto en cada
$archivos = array ('primero.inc',
iteración. Para hacer esto, usa una sentencia include().
'segundo.inc', 'tercero.inc');
require( 'header. for ($i = 0; $i < count($archivos); $i++) {
inc' ); include $archivos[$i];
}
When a file is require()ed, the code it contains inherits
the variable scope of the line on which the require() include() difiere de require() en que la sentencia
occurs. Any variables available at that line in the calling include se re-evalúa cada vez que se encuentra (y sólo
file will be available within the called file. If the require() cuando está siendo ejecutada), mientras que la
occurs inside a function within the calling file, then all of sentencia require() se reemplaza por el archivo
the code contained in the called file will behave as referenciado cuando se encuentra por primera vez, se
though it had been defined inside that function. vaya a evaluar el contenido del archivo o no (por
If the require()ed file is called via HTTP using the fopen ejemplo, si está dentro de una sentencia if cuya
wrappers, and if the target server interprets the target condición evaluada es falsa).
file as PHP code, variables may be passed to the Debido a que include() es una construcción especial del
require()ed file using an URL request string as used with lenguaje, se debe encerrar dentro de un bloque de
HTTP GET. This is not strictly speaking the same thing as sentencias si está dentro de un bloque condicional.
require()ing the file and having it inherit the parent file's
/* Esto es ERRÓNEO y no funcionará
variable scope; the script is actually being run on the
como se desea. */
remote server and the result is then being included into
the local script.
if ($condicion)
/* This example assumes that someserver is include($archivo);
configured to parse .php else
* files and not .txt files. Also, 'works' here means include($otro);
that the variables
* $varone and $vartwo are available within the /* Esto es CORRECTO. */
require()ed file. */
if ($condicion) {
/* Won't work; file.txt wasn't handled by include($archivo);
someserver. */ } else {
require ("http://someserver/file.txt? include($otro);
varone=1&vartwo=2"); }
En ambos, PHP3 y PHP4, es posible ejecutar una
/* Won't work; looks for a file named 'file.php?
sentencia return dentro de un archivo incluido con
varone=1&vartwo=2'
include(), para terminar el procesado de ese archivo y
* on the local filesystem. */
volver al archivo de comandos que lo llamó. Existen
require ("file.php?varone=1&vartwo=2");
algunas diferencias en el modo en que esto funciona, no
obstante. La primera es que en PHP3, return no puede
/* Works. */
aparecer dentro de un bloque a menos que sea un
require ("http://someserver/file.php?
bloque de función, en el cual return se aplica a esa
varone=1&vartwo=2");
función y no al archivo completo. En PHP4, no obstante,
esta restricción no existe. También, PHP4 permite
$varone = 1;
devolver valores desde archivos incluidos con include().
$vartwo = 2;
Se puede capturar el valor de la llamada a include()
require ("file.txt"); /* Works. */
como se haría con una función normal. Esto genera un
require ("file.php"); /* Works. */
error de intérprete en PHP3.
En PHP3, es posible ejecutar una sentencia return dentro
de un archivo referenciado con require(), en tanto en
cuanto esa sentencia aparezca en el ámbito global del
archivo requerido (require()). No puede aparecer dentro
de ningún bloque (lo que siginifica dentro de llaves({})).
En PHP4, no obstante, esta capacidad ha sido
desestimada. Si se necesita esta funcionalidad, véase
include().
Ver tambien include(), require_once(),
include_once(), readfile(), y virtual().

include()
Ejemplo 12-1. include() en PHP3 y PHP4
main.html

Asumamos la existencia del siguiente archivo (llamado


test.inc) en el mismo directorio que el archivo principal: El '27' espúreo se debe al hecho de que PHP3 no soporta
devolver valores con return desde archivos como ese.
When a file is include()ed, the code it contains inherits
<?php the variable scope of the line on which the include()
echo "Antes del return occurs. Any variables available at that line in the calling
<br>\n"; file will be available within the called file. If the include()
if ( 1 ) { occurs inside a function within the calling file, then all of
return 27; the code contained in the called file will behave as
} though it had been defined inside that function.
echo "Después del return If the include()ed file is called via HTTP using the fopen
<br>\n"; wrappers, and if the target server interprets the target
?> file as PHP code, variables may be passed to the
include()ed file using an URL request string as used with
HTTP GET. This is not strictly speaking the same thing as
include()ing the file and having it inherit the parent file's
Asumamos que el archivo principal (main.html) contiene
variable scope; the script is actually being run on the
lo siguiente:
remote server and the result is then being included into
the local script.
<?php /* This example assumes that someserver is
$retval = include( 'test.inc' ); configured to parse .php
echo "El archivo devolvió: * files and not .txt files. Also, 'works' here means
'$retval'<br>\n"; that the variables
?> * $varone and $vartwo are available within the
include()ed file. */

Cuando se llama a main.html en PHP3, generará un error /* Won't work; file.txt wasn't handled by
del intérprete en la linea 2; no se puede capturar el valor someserver. */
de un include() en PHP3. En PHP4, no obstante, el include ("http://someserver/file.txt?
resultado será: varone=1&vartwo=2");

/* Won't work; looks for a file named 'file.php?


varone=1&vartwo=2'
Antes del return
* on the local filesystem. */
El archivo
include ("file.php?varone=1&vartwo=2");
devolvió: '27'
/* Works. */
include ("http://someserver/file.php?
Ahora, asumamos que se ha modificado main.html para varone=1&vartwo=2");
que contenga lo siguiente:
$varone = 1;
$vartwo = 2;
<?php include ("file.txt"); /* Works. */
include( 'test.inc' ); include ("file.php"); /* Works. */
echo "De vuelta en
main.html<br>\n"; See also require(), require_once(), include_once(),
?> readfile(), and virtual().

require_once()
En PHP4, la salida será:

The require_once() statement replaces itself with the


Antes del return specified file, much like the C preprocessor's #include
De vuelta en works, and in that respect is similar to the require()
main.html statement. The main difference is that in an inclusion
chain, the use of require_once() will assure that the
code is added to your script only once, and avoid clashes
No obstante, PHP3 dará la siguiente salida: with variable values or function names that can happen.
For example, if you create the following 2 include files
utils.inc and foolib.inc
Ejemplo 12-2. utils.inc
Antes del return
27De vuelta en main.html

Parse error: parse error in <?php


/home/torben/public_html/phptest/main.html on line 5 define(PHPVERSION,
floor(phpversion()));
echo "GLOBALS ARE NICE\n";
function goodTea() {
El error del intérprete es resultado del hecho de que la
return "Oolong tea tastes
sentencia return está encerrada en un bloque de no-
good!";
función dentro de test.inc. Cuando el return se mueve
}
fuera del bloque, la salida es:
?>
Ejemplo 12-3. foolib.inc
Antes del return
27De vuelta en
<?php Array
require ("utils.inc"); (
function [0] => 1
showVar($var) { [1] => Array
if (PHPVERSION (
== 4) { [0] => complex
print_r($var) [1] => quaternion
; )
} else {
dump_var($ )
var);
Also note that, analogous to the behavior of the #include
}
of the C preprocessor, this statement acts at "compile
}
time", e.g. when the script is parsed and before it is
executed, and should not be used for parts of the script
// bunch of other
that need to be inserted dynamically during its
functions ...
execution. You should use include_once() or include()
?>
for that purpose.
And then you write a script cause_error_require.php For more examples on using require_once() and
Ejemplo 12-4. cause_error_require.php include_once(), look at the PEAR code included in the
latest PHP source code distributions.
See also: require(), include(), include_once(),
<?php get_required_files(), get_included_files(), readfile(),
require("foolib.inc"); and virtual().
/* the following will generate an error
*/
require("utils.inc"); include_once()
$foo =
array("1",array("complex","quaternion
The include_once() statement includes and evaluates
"));
the specified file during the execution of the script. This
echo "this is requiring utils.inc again
is a behavior similar to the include() statement, with the
which is also\n";
important difference that if the code from a file has
echo "required in foolib.inc\n";
already been included, it will not be included again.
echo "Running goodTea:
As mentioned in the require_once() description, the
".goodTea()."\n";
include_once() should be used in the cases in which the
echo "Printing foo: \n";
same file might be included and evaluated more than
showVar($foo);
once during a particular execution of a script, and you
?>
want to be sure that it is included exactly once to avoid
When you try running the latter one, the resulting ouptut problems with function redefinitions, variable value
will be (using PHP 4.01pl2): reassignments, etc.
For more examples on using require_once() and
GLOBALS ARE NICE
include_once(), look at the PEAR code included in the
GLOBALS ARE NICE
latest PHP source code distributions.
See also: require(), include(), require_once(),
Fatal error: Cannot redeclare causeerror() in
get_required_files(), get_included_files(), readfile(),
utils.inc on line 5
and virtual().
By modifying foolib.inc and cause_errror_require.php to
use require_once() instead of require() and renaming
the last one to avoid_error_require_once.php, we have: Capítulo 13. Funciones
Ejemplo 12-5. foolib.inc (fixed)
Funciones definidas por el usuario
...
require_once("utils Una función se define con la siguiente sintaxis:
.inc");
function function foo ($arg_1,
showVar($var) { $arg_2, ..., $arg_n) {
... echo "Función de
ejemplo.\n";
Ejemplo 12-6. avoid_error_require_once.php return $retval;
}
Cualquier instrucción válida de PHP puede aparecer en el
...
cuerpo de la función, incluso otras funiones y
require_once("foolib.inc");
definiciones de clases.
require_once("utils.inc");
En PHP3, las funciones deben definirse antes de que se
$foo =
referencien. En PHP4 no existe tal requerimiento.
array("1",array("complex","quatern
PHP no soporta la sobrecarga de funciones, y tampoco es
ion"));
posible redefinir u ocultar funciones previamente
...
declaradas.
And when running the latter, the output will be (using PHP3 no soporta un número variable de parámetros,
PHP 4.0.1pl2): aunque sí soporta parámetros por defecto (ver Valores
GLOBALS ARE NICE por defecto de de los parámetros para más información).
this is requiring globals.inc again PHP4 soporta ambos: ver Listas de longitud variable de
which is also parámetros y las referencias de las funciones
required in foolib.inc func_num_args(), func_get_arg(), y func_get_args()
Running goodTea: Oolong tea para más información.
tastes good!
Printing foo:
Parámetros de las funciones
La información puede suministrarse a las funciones Destacar que cuando se usan parámetros por defecto,
mediante la lista de parámetros, una lista de variables estos tienen que estar a la derecha de cualquier
y/o constantes separadas por comas. parámetro sin valor por defecto; de otra manera las
PHP soporta pasar parámetros por valor (el cosas no funcionarán de la forma esperada. Considera el
comportamiento por defecto), por referencia, y siguiente fragmento de código:
parámetros por defecto. Listas de longitud variable de
function makeyogurt ($type = "acidophilus",
parámetros sólo están soportadas en PHP4 y posteriores;
$flavour) {
ver Listas de longitud variable de parámetros y la
return "Haciendo un bol de $type $flavour.\n";
referencia de las funciones func_num_args(),
}
func_get_arg(), y func_get_args() para más
información. Un efecto similar puede conseguirse en
echo makeyogurt ("mora"); // No funcionará de la
PHP3 pasando un array de parámetros a la función:
manera esperada
function takes_array($input) {
La salida del ejemplo anterior es:
echo "$input[0] + $input[1] = ",
$input[0]+$input[1]; Warning: Missing argument 2 in call to
} makeyogurt() in
/
usr/local/etc/httpd/htdocs/php3test/functes
t.html on line 41
Pasar parámetros por referencia
Haciendo un bol de mora.
Y ahora, compáralo con:
Por defecto, los parámetros de una función se pasan por
valor (de manera que si cambias el valor del argumento function makeyogurt ($flavour, $type =
dentro de la función, no se ve modificado fuera de ella). "acidophilus") {
Si deseas permitir a una función modificar sus return "Haciendo un bol de $type
parámetros, debes pasarlos por referencia. $flavour.\n";
Si quieres que un parámetro de una función siempre se }
pase por referencia, puedes anteponer un ampersand (&)
al nombre del parámetro en la definición de la función: echo makeyogurt ("mora"); // funciona
como se esperaba
function add_some_extra(&$string) {
$string .= ' y algo más.'; La salida de este ejemplo es:
} Haciendo un bol de
$str = 'Esto es una cadena, '; acidophilus mora.
add_some_extra($str);
echo $str; // Saca 'Esto es una
cadena, y algo más.'
Lista de longitud variable de parámetros
Si deseas pasar una variable por referencia a una función
que no toma el parámetro por referencia por defecto,
puedes anteponer un ampersand al nombre del PHP4 soporta las listas de longitud variable de
parámetro en la llamada a la función: parámetros en las funciones definidas por el usuario. Es
realmente fácil, usando las funciones func_num_args(),
function foo ($bar) { func_get_arg(), y func_get_args().
$bar .= ' y algo más.'; No necesita de ninguna sintaxis especial, y las listas de
} parámetros pueden ser escritas en la llamada a la
$str = 'Esto es una cadena, '; función y se comportarán de la manera esperada.
foo ($str);
echo $str; // Saca 'Esto es una
cadena, ' Devolver valores
foo (&$str);
echo $str; // Saca 'Esto es una
cadena, y algo más.' Los valores se retornan usando la instrucción opcional
return. Puede devolverse cualquier tipo de valor,
incluyendo listas y objetos.
Parámetros por defecto function square
($num) {
return $num *
Una función puede definir valores por defecto para los $num;
parámetros escalares estilo C++: }
function makecoffee ($type = echo square (4); //
"cappucino") { saca '16'.
return "Hacer una taza de No puedes devolver múltiples valores desde una función,
$type.\n"; pero un efecto similar se puede conseguir devolviendo
} una lista.
echo makecoffee ();
echo makecoffee ("espresso"); function small_numbers() {
return array (0, 1, 2);
La salida del fragmento anterior es: }
Hacer una taza de list ($zero, $one, $two) =
cappucino. small_numbers();
Hacer una taza de
espresso.
El valor por defecto tiene que ser una expresión old_function
constante, y no una variable o miembro de una clase.
En PHP 4.0 también es posible especificar unset como
La instrucción old_function permite declarar una función
parámetro por defecto. Esto significa que el argumento
usando una sintaxis idéntica a la de PHP/FI2 (excepto
no tomará ningún valor en absoluto si el valor no es
que debes reemplazar 'function' por 'old_function').
suministrado.
Es una característica obsoleta, y debería ser usada
?>
únicamente por el conversor PHP/FI2->PHP3.
El ejemplo define una clase llamada Cart que consiste en
Aviso
un array asociativo de artículos en el carro y dos
Las funciones declaradas como old_function no pueden funciones para meter y sacar ítems del carro
llamarse desde el código interno de PHP. Entre otras cosas, Las clases son tipos, es decir, son plantillas para
esto significa que no puedes usarlas en funciones como variables. Tienes que crear una variable del tipo deseado
usort(), array_walk(), y register_shutdown_function(). con el operador new.
Puedes solventar esta limitación escribiendo un "wrapper"
$cart = new Cart;
(en PHP3 normal) que a su vez llame a la función declarada
$cart-
como old_function.
>add_item("10",
1);

Funciones variable Este ejemplo crea un objeto $cart de clase Cart. La


función add_item() de ese objeto se llama para añadir un
item del artículo número 10 al carro.
PHP soporta el concepto de funciones variable, esto Las Clases pueden ser extensiones de otras clases. Las
significa que si una variable tiene unos paréntesis clases extendidas o derivadas tienen todas las variables
añadidos al final, PHP buscará una función con el mismo y funciones de la clase base y lo que les añadas al
nombre que la evaluación de la variable, e intentará extender la definición. La herencia múltiple no está
ejecutarla. Entre otras cosas, esto te permite soportada.
implementar retrollamadas (callbacks), tablas de class Named_Cart
funciones y demás. extends Cart {
Ejemplo 13-1. Ejemplo de función variable var $owner;

function set_owner
<?php ($name) {
function foo() { $this->owner =
echo "Dentro de foo()<br>\n"; $name;
} }
}
function bar( $arg = '' ) {
echo "Dentro de bar(); el parámetro Ese ejemplo define una clase Named_Cart (carro con
fue '$arg'.<br>\n"; nombre o dueño) que tiene todas las variables y
} funciones de Cart, y además añade la variable $owner y
una función adicional set_owner(). Un carro con nombre
$func = 'foo'; se crea de la forma habitual y, una vez hecho, puedes
$func(); acceder al propietario del carro. En los carros con
$func = 'bar'; nombre también puedes acceder a las funciones
$func( 'test' ); normales del carro:
?> $ncart = new Named_Cart; // Creamos un
carro con nombre
$ncart->set_owner ("kris"); // Nombramos el
Capítulo 14. Clases y Objetos carro
print $ncart->owner; // Imprimimos el
nombre del propietario
class $ncart->add_item ("10", 1); // Funcionalidad
heredada de Cart

Una clase es una colección de variables y de funciones Entre funciones de una clase, la variable $this hace
que acceden a esas variables. Una clase se define con la referencia al propio objeto. Tienes que usar $this-
siguiente sintaxis: >loquesea para acceder a una variable o función llamada
loquesea del objeto actual.
<?php Los constructores son funciones de una clase que se
class Cart { llaman automáticamente al crear una nueva instancia
var $items; // Items en nuestro (objeto) de una clase. Una función se convierte en
carro de la compra constructor cuando tiene el mismo nombre que la clase.
// Añadir $num artículos de tipo class Auto_Cart
$artnr al carro extends Cart {
function Auto_Cart ()
function add_item ($artnr, $num) { {
$this->items[$artnr] += $num; $this->add_item
} ("10", 1);
}
// Sacar $num artículos del tipo }
$artnr del carro Este ejemplo define una clase Auto_Cart que es un Cart
junto con un constructor que inicializa el carro con un
function remove_item ($artnr, item del tipo de artículo "10" cada vez que se crea un
$num) { nuevo Auto_Cart con "new". Los constructores también
if ($this->items[$artnr] > $num) pueden recibir parámetros y estos parámetros pueden
{ ser opcionales, lo que los hace más útiles.
$this->items[$artnr] -= $num;
return true; class Constructor_Cart extends Cart {
} else { function Constructor_Cart ($item =
return false; "10", $num = 1) {
} $this->add_item ($item, $num);
} }
} }
Zend Engine and will therefore result
// Compramos las mismas cosas
in a parser error.
aburridas de siempre

$default_cart = new Constructor_Cart; The second thing references do is to pass variables by-
reference. This is done by making a local variable in a
// Compramos las cosas interesantes function and a variable in the calling scope reference to
the same content. Example:
$different_cart = new Constructor_Cart
("20", 17); function foo
(&$var)
Atención {
$var++;
Para las clases derivadas, el constructor de la clase padre }
no es llamado automáticamente cuando se llama al
constructor de la clase derivada. $a=5;
foo ($a);
will make $a to be 6. This happens because in the
Capítulo 15. References Explained
function foo the variable $var refers to the same content
as $a. See also more detailed explanations about passing
What References Are by reference.
The third thing reference can do is return by reference.

References in PHP are a means to access the same


variable content by different names. They are not like C What References Are Not
pointers, they are symbol table aliases. Note that in PHP,
variable name and variable content are different, so the
same content can have different names. The most close As said before, references aren't pointers. That means,
analogy is with Unix filenames and files - variable names the following construct won't do what you expect:
are directory entries, while variable contents is the file function foo (&$var)
itself. References can be thought of as hardlinking in {
Unix filesystem. $var =&
$GLOBALS["baz"];
}
What References Do foo($bar);
What happens is that $var in foo will be bound with $bar
PHP references allow you to make two variables to refer in caller, but then it will be re-bound with
to the same content. Meaning, when you do: $GLOBALS["baz"]. There's no way to bind $bar in the
calling scope to something else using the reference
$a =&
mechanism, since $bar is not available in the function foo
$b
(it is represented by $var, but $var has only variable
it means that $a and $b point to the same variable. contents and not name-to-value binding in the calling
symbol table).
Nota: $a and $b are completely
equal here, that's not $a is pointing Passing by Reference
to $b or vice versa, that's $a and $b
pointing to the same place.
You can pass variable to function by reference, so that
function could modify its arguments. The syntax is as
The same syntax can be used with functions, that return follows:
references, and with new operator (in PHP 4.0.4 and
later): function foo
(&$var)
$bar =& new {
fooclass(); $var++;
$foo =& find_var }
($bar);
$a=5;
foo ($a);
Nota: Not using the & operator // $a is 6 here
causes a copy of the object to be
Note that there's no reference sign on function call - only
made. If you use $this in the class it
on function definition. Function definition alone is enough
will operate on the current instance
to correctly pass the argument by reference.
of the class. The assignment without
Following things can be passed by reference:
& will copy the instance (i.e. the
object) and $this will operate on the
copy, which is not always what is
desired. Usually you want to have a • Variable, i.e. foo($a)
single instance to work with, due to • New statement, i.e. foo(new foobar())
performance and memory
consumption issues. • Reference, returned from a function, i.e.:

While you can use the @ operator to function


mute any errors in the constructor &bar()
when using it as @new, this does not {
work when using the &new $a = 5;
statement. This is a limitation of the return
$a;
Many syntax constructs in PHP are implemented via
}
referencing mechanisms, so everything told above about
foo(bar());
reference binding also apply to these constructs. Some
constructs, like passing and returning by-reference, are
mentioned above. Other constructs that use references
• See also explanations about returning by are:
reference.

global References
Any other expression should not be passed by reference,
as the result is undefined. For example, the following
examples of passing by reference are invalid: When you declare variable as global $var you are in
fact creating reference to a global variable. That means,
function bar() // Note the this is the same as:
missing &
{ $var =&
$a = 5; $GLOBALS["var"];
return $a; That means, for example, that unsetting $var won't unset
} global variable.
foo(bar());

foo($a = 5) // Expression, $this


not variable
foo(5) // Constant, not
variable In an object method, $this is always reference to the
caller object.
These requirements are for PHP 4.0.4 and later.

III. Características
Returning References

Tabla de contenidos
Returning by-reference is useful when you want to use a 16. Autentificación HTTP con PHP
function to find which variable a reference should be 17. Cookies
bound to. When returning references, use this syntax: 18. Manejo de envío de ficheros
function &find_var 19. Usando archivos remotos
($param) 20. Manejando conexiones
{ 21. Conexiones persistentes a bases de datos
...code... 22. Modo Seguro (Safe Mode)
return $found_var; 23. Using PHP from the command line
}

$foo =& find_var Capítulo 16. Autentificación HTTP con PHP


($bar);
$foo->x = 2; Las caracteríticas de autentificación HTTP en PHP solo
In this example, the property of the object returned by estan disponibles cuando se está ejecutando como un
the find_var function would be set, not the copy, as it módulo en Apache y hasta ahora no lo estan en la
would be without using reference syntax. versión CGI. En un script PHP como módulo de Apache,
se puede usar la función header() para enviar un
mensaje de "Autentificación requerida" al navegador
Nota: Unlike parameter passing, cliente haciendo que muestre una ventana de entrada
here you have to use & in both emergente con nombre de usuario y contraseña. Una vez
places - to indicate that you return que el usuario ha rellenado el nombre y la contraseña, la
by-reference, not a copy as usual, URL que contiene el script PHP vuelve a ser llamada con
and to indicate that reference las variables $PHP_AUTH_USER, $PHP_AUTH_PW y
binding, rather than usual $PHP_AUTH_TYPE rellenas con el nombre de usuario, la
assignment, should be done for $foo. contraseña y el tipo de autentificación respectivamente.
Sólo autentificación "Básica" esta soportada en este
momento. Consulte la función header() para más
información.
Un fragmento de script de ejmplo que fuerce la
Unsetting References
autentificación del cliente en una página sería como el
siguiente:
When you unset the reference, you just break the binding Ejemplo 16-1. Ejemplo de autentificación HTTP
between variable name and variable content. This does
not mean that variable content will be destroyed. For
example: <?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
$a = 1;
header("WWW-Authenticate: Basic realm=\"My
$b =&
Realm\"");
$a;
header("HTTP/1.0 401 Unauthorized");
unset
echo "Text to send if user hits Cancel button\n";
($a);
exit;
won't unset $b, just $a. } else {
Again, it might be useful to think about this as analogous echo "<p>Hello
to Unix unlink call. {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered
{$_SERVER['$PHP_AUTH_PW']} as your
Spotting References password.</p>";
} {$_SERVER['$PHP_AUTH_USER']}<br>";
?> echo "Old: {$_REQUEST['$OldAuth']}";
echo "<form action='{$_SERVER['$PHP_SELF']}'
METHOD='POST'>\n";
Nota: Por favor tener cuidado echo "<input type='hidden' name='SeenBefore'
cuando esteis programando las lines value='1'>\n";
de cabecera HTTP. Para garantizar la echo "<input type='hidden' name='OldAuth'
maxima compatibilidad con todos los value='{$_SERVER['$PHP_AUTH_USER']}'
clientes, la palabra clave "Basic" >\n";
debe de ser escrita con "B" echo "<input type='submit' value='Re
mayúscula, la cadena de texto debe Authenticate'>\n";
estar incluida entre comillas dobles echo "</form></p>\n";
(no simples) y un espacio debe }
preceder el código "401" en la linea ?>
de cabecera "HTTP/1.0 401" Este comportamiento no es requerido por el estándar de
autentificación básica de HTTP, por lo que nunca debe
depender de esto. Pruebas con Lynx han demostrado que
En vez de, sencillamente, mostrar $PHP_AUTH_USER y
Lynx no borra las credenciales de autentificación con una
$PHP_AUTH_PW, seguramente querais comprobar la
respuesta 401 del servidor, por lo que pulsando atrás y
validez del nombre de usuario y la contraseña. Tal vez
después adelante abriría el recurso de nuevo (siempre
enviando una consulta a una base de datos o buscando
que los requerimientos de contraseña no hayan
el usuario en un fichero dbm.
cambiado).
Vigilar aquí los navegadores Interner Explorer con bugs.
Además tener en cuanta que esto no funciona usando el
Parecen muy quisquillosos con el orden de las cabeceras.
servidor IIS de Microsoft y la versión CGI de PHP debido a
Enviar la cabecera WWW-Autentificación antes que la
una limitación del IIS
cabecera HTTP/1.0 401 parece ser el truco por ahora.
Para prevenir que alguien escriba un script que revele la
contraseña de una página que ha sido autentificada a
Capítulo 17. Cookies
través de algún mecanismo externo tradicional, las
variables PHP_AUTH no serán rellenadas si algún tipo de
autentificación externo ha sido activado para una página PHP soporta transparentemente cookies HTTP. Las
en particular. En este caso, la variable $REMOTE_USER Cookies son un mecanismo que sirve para almacenar
puede ser usada para identificar al usuario autentificado datos en el navegador del usuario remoto, para así poder
externamente. identificar al usuario cuando vuelva. Se pueden poner
cookies usando la función setcookies(). Las Cookies son
parte de la cabecera HTTP, por tanto la función
Configuration Note: PHP usa la
setcookie() debe ser llamada antes de que se produzca
directiva AuthType para determinar
cualquier salida al navegador. Esta limitación es la
si una autentificación externa esta
misma a la de la función header(). Se pueden usar las
en uso. Recordar no usar esta
funciones de almacenamiento intermedio del resultado
directiva cuando querais usar la
para retrasar el resultado del script hasta que hayas
autentificación de PHP (si no todo
decidido mandar o no una cookie o cabecera.
intentento de autentificación fallará)
Cualquier cookie enviada a ti desde el cliente,
automáticamente se convertirá en una variable PHP igual
Nota, a pesar de todo, lo ya dicho no proteje de que como ocurre con los métodos de datos GET y POST,
alguien que controle una URL no autentificada robe dependiendo de las variables de configuración
contraseñas de URLs autentificadas en el mismo register_globals y variables_order. Si deseas asignar
servidor. multiples valores a una cookie simple, añade
Tanto Netscape como Internet Explorer borrarán la caché simplemente [] a el nombre de la cookie.
de la ventana de autentificación en el navegador local En PHP 4.1.0 y posteriores, la array auto-global $_COOKIE
después de recibir una respuesta 401 del servidor. Esto será siempre actualizada con cualquier cookie mandada
puede usarse, de forma efectiva, para "desconectar" a por el cliente. $HTTP_COOKIE_VARS es tambien
un usuario, forzandole a reintroducir su nombre y actualizada en versiones anteriores de PHP cuando la
contraseña. Algunas personas usan esto para "hacer variable de configuración track_vars esté activada.
caducar" entradas, o para proveer un botón de Para más detalles ver la función setcookie().
"desconectar".
Ejemplo 16-2. Ejemplo de autentificación HTTP
forzando una reentrada Capítulo 18. Manejo de envío de ficheros

Envío de archivos con el método POST


<?php
function authenticate() {
header( "WWW-Authenticate: Basic realm=\"Test PHP es capaz de recibir envíos de archivo de cualquier
Authentication System\""); navegador que cumpla la norma RFC-1867 (entre los que
header( "HTTP/1.0 401 Unauthorized"); se incluyen Netscape Navigator 3 o posterior, Microsoft
echo "You must enter a valid login ID and password Internet Explorer 3 con un parche o posterior sin éste).
to access this resource\n" Ésta característica permite que los usuarios envien
; archivos de texto y binarios. Mediante la autentificación
exit; y funciones de manejo de archivos de PHP, es posible un
} control total de quién puede enviar archivos y que se
hace con éstos una vez recibidos.
if (!isset($_SERVER['PHP_AUTH_USER']) || Es importante destacar que PHP también soporta el
($SeenBefore == 1 && $OldAuth == $_SER método PUT para envío de archivos tal y como lo utiliza
VER['$PHP_AUTH_USER']))) { Netscape Composer y el cliente Amaya de W3C. Consulte
authenticate(); Soporte del método PUT para más detalles.
} Una página de envío de archivos se puede crear
else { mediante un formulario parecido a éste:
echo "<p>Welcome: Ejemplo 18-1. Formulario de envío de archivo
• $userfile_name - El nombre original del fichero
en la máquina cliente.
<form enctype="multipart/form-data" • $userfile_size - El tamaño en bytes del fichero
action="_URL_" method="post"> recibido.
<input type="hidden" name="MAX_FILE_SIZE" • $userfile_type - El tipo mime del fichero (si el
value="1000"> navegador lo proporciona). Un ejemplo podría
Send this file: <input name="userfile" type="file"> ser "image/gif".
<input type="submit" value="Send File">
</form>
La _URL_ debe tener como destino un script PHP. El input Se puede ver que "$userfile" (en las variables anteriores)
oculto MAX_FILE_SIZE debe encontrarse antes del input toma el valor del atributo "name" que contenga el campo
de tipo "file" para indicar el tamaño máximo de archivo <input> de tipo "file" del formulario de envio. En el
que se puede enviar en bytes ejemplo anterior, elegimos llamarlo "userfile".

Aviso
Nota: register_globals = On se
MAX_FILE_SIZE debe ser consultado por el navegador; aun desaconseja por razones de
así es sencillo saltarse este máximo por lo tanto no se debe seguridad y rendimiento.
presuponer que el navegador siempre lo respetará. En
contrapartida, la configuracion de PHP relativa al tamaño
maximo no puede ser obviada. Por defecto, los ficheros serán almacenados en el
Las variables definidas para los archivos enviados varian directorio temporal por defecto del servidor a no ser que
en función de la versión y configuración de PHP que se se especifique otra localizacion con la directiva
utilice. Las variables de las que hablamos a continuación upload_tmp_dir en php.ini. El directorio temporal por
serán definidas en la página destino despues de una defecto del servidor puede ser modificado cambiando el
recepción de fichero correcta. Cuando track_vars este valor de la variable de entorno TMPDIR en el contexto en
activado, el array $HTTP_POST_FILES/$_FILES se que se ejecuta PHP La configuración de las variables de
inicializará. Por ultimo, las variables relacionadas seran entorno no se puede realizar en PHP a través de la
inicializadas como globales cuando register_globals esté función putenv(). Esta variable de entorio puede ser
habilitado. Cabe señalar que el uso de las variables utilizada también para asegurarnos que otras
globales no esta recomendado en ningún caso. operaciones con archivos recibidos están funcionando
correctamente.
Ejemplo 18-2. Verificando los archivos recibidos
Nota: track_vars esta activado
siempre desde PHP 4.0.3. A partir de
PHP 4.1.0 , $_FILES puede ser Los siguientes ejemplos son validos para versiones de
utilizado alternativamente a PHP 4 superiores a la 4.0.2. Veanse las funciones
$HTTP_POST_FILES. $_FILES es is_uploaded_file() y move_uploaded_file().
siempre global asi que global no
debe ser usado con $_FILES en el
ámbito de función. <?php
// In PHP 4.1.0 or later, $_FILES should be used instead
of $HTTP_POST_FILES.
$HTTP_POST_FILES/$_FILES contienen la información if (is_uploaded_file($HTTP_POST_FILES['userfile']
sobre el fichero recibido. ['tmp_name'])) {
A continuación se describe el contenido de copy($HTTP_POST_FILES['userfile']['tmp_name'],
$HTTP_POST_FILES. Se ha tomado el nombre 'userfile' "/place/to/put/uploaded/file");
para el fichero recibido tal y como se usaba en el script } else {
de ejemplo anterior: echo "Possible file upload attack. Filename: " .
$HTTP_POST_FILES['userfile']['name'] $HTTP_POST_FILES['userfile']['name'];
El nombre original del fichero en la máquina }
cliente. /* ...or... */
$HTTP_POST_FILES['userfile']['type'] move_uploaded_file($HTTP_POST_FILES['userfile']
El tipo mime del fichero (si el navegador lo ['tmp_name'], "/place/to/put/uploaded/file");
proporciona). Un ejemplo podría ser ?>
"image/gif".
$HTTP_POST_FILES['userfile']['size'] El script PHP que recibe el fichero, debe implementar la
El tamaño en bytes del fichero recibido. lógica necesaria para determinar que debe ser realizado
$HTTP_POST_FILES['userfile']['tmp_name'] con el fichero. Se puede utilizar, por ejemplo, la variable
El nombre del fichero temporal que se utiliza $HTTP_POST_FILES['userfile']['size'] para descartar los
para almacenar en el servidor el archivo ficheros demasiado chicos o demasiado grandes; por otro
recibido. lado, se puede usar la variable
$HTTP_POST_FILES['userfile']['type'] para descartar los
que no se ajusten a algun criterio de tipo. Cualquiera que
Nota: A partir de PHP 4.1.0 se sea la logica que utilicemos, se debe borrar o mover el
puede utilizar el variable corta archivo del directorio temporal.
$_FILES. PHP 3 no soporta El archivo será borrado del directorio temporal al final de
$HTTP_POST_FILES. la petición si no se ha movido o renombrado.

Cuando register_globals se activa en el php.ini las Errores comunes


siguientes variables son accesibles. Se ha tomado el
nombre 'userfile' para el fichero recibido tal y como se
usaba en el script de ejemplo del principio: A MAX_FILE_SIZE no se le puede dar un valor mayor que
el valor que se haya especificado en la
directivaupload_max_filesize. Por defecto se tiene un
• $userfile - El nombre del fichero temporal que límite de 2 MegaBytes.
se utiliza para almacenar en el servidor el Si se ha activado el límite de memoria, se deben
archivo recibido. especificar un valor alto para memory_limit. En cualquier
caso, se debe asegurar un valor suficientemente grande
PUT /path/filename.html
para memory_limit.
HTTP/1.1
Si max_execution_time tiene un valor muy pequeño, la
ejecución del script puede exceder este valor. De esta Esto normalmente significaría que el cliente remoto
forma, se debe asegurar un valor suficientemente grande quiere salvar el contenido como: /path/filename.html en
para max_execution_time. tu árbol web. Lógicamente no una buena idea que la
Si post_max_size< tiene un valor muy pequeño, los gente pueda escribir en tu árbol web. Para manipular
ficheros mas grandes a este valor, no podrán ser esta petición debes decirle al servidor que esta petición
enviados. Por ello, se debe asegurar un valor sea atendida por un script PHP. En Apache, por ejemplo,
suficientemente grande para post_max_size. se utiliza para esto la directiva Script en los alguno de los
No verificar que ficheros se estan manipulando puede archivos de configuración del servidor. Un sitio típico de
tener como consecuencia que los usuarios puedan uso es dentro del bloque &lt;Directory&gt; o quizás en el
acceder a información sensible en otros directorios. bloque &lt;Virtualhost&gt;. Una linia así deberia hacer
Cabe señalar que el httpd de CERN parece cortar todo a ésta función:
partir del primer espacio en blanco en el "content-type" Script PUT
de la cabecera mime que obtiene del cliente. Si este es el /put.php
caso, con el httpd de CERN no se soporta la funcionalidad
de envío de ficheros. Ésto le dice a Apache que envíe todas peticiones PUT
para URIs que contengan esta linia al script put.php. Se
asume que PHP se encuentra activo y con la extensión
Envío de multiples ficheros .php enlazada a él.
Dentro del script put.php3 se podría implementar algo
así:
Se pueden enviar multiples ficheros usando diferentes
nombres (name) para los input. <?php copy($PHP_UPLOADED_FILE_NAME,
Así mismo, es posible enviar varios archivos $DOCUMENT_ROOT.$REQUEST_URI); ?>
simultaneamente y tener organizada en arrays la Esto copiaría el archivo a la localización requerida por el
información. Para hacer esto, se utiliza la misma sintáxis cliente remoto. Aqui se pueden ejecutar funciones de
que cuando tenemos multiples "selects" o "checkboxes" autentificación de usuario o cualquier otro tipo de
en el formulario HTML: chequeo. El archivo se guarda en el archivo temporal del
sistema servidor de la misma manera que el Método
POST. Cuando la petición finaliza, el archivo temporal es
Nota: El soporte para envío multiple eliminado. En consequencia el script dede proceder al
de ficheros fue añadido en la versión trato de éste inmediatamente, ya sea para copiarlo,
3.0.10. renombrarlo, etc. El archivo se encuentra en la variable
$PHP_PUT_FILENAME, y el destino sugerido por el cliente
Ejemplo 18-3. Envío de multiples ficheros en la variable $REQUEST_URI (puede variar en servidores
web que no sean Apache). No es necesario hacer caso al
destino sugerido por el cliente. Por ejemplo se podrían
copiar los archivos enviados a directorios especialmente
<form action="file-upload.php" method="post"
designados para esta tarea.
enctype="multipart/form-data">
Send these files:<br>
<input name="userfile[]" type="file"><br> Capítulo 19. Usando archivos remotos
<input name="userfile[]" type="file"><br>
<input type="submit" value="Send files">
</form> Siempre que el soporte para la "envoltura URL fopen"
Cuando el formulario del ejemplo es enviado, los arrays esté habilitado cuando se configura PHP (lo cual ocurre a
$HTTP_POST_FILES['userfile'], menos que se pasa explícitamente la opción --disable-url-
$HTTP_POST_FILES['userfile']['name'] y fopen-wrapper a configure (para versiones hasta la
$HTTP_POST_FILES['userfile']['size'] son inicializados. Así 4.0.3), ó configurar como "off" el parámetro
mismo pasa con $_FILES en PHP 4.1.0 o superiores y allow_url_fopen en php.ini (para las nuevas versiones))
$HTTP_POST_VARS en PHP 3. Cuando register_globals se pueden usar URLs HTTP y FTP con la mayoría de las
esta activa, las variables globales para los archivos funciones que toman un archivo como parámetro,
recibidos también son inicializadas. Cada uno de estos incluyendo las sentencias require() e include().
arrays tendrá en los índices numericos correspondientes
los valores para cada fichero recibido. Nota: La versión actual de PHP para
Por ejemplo, si tomamos como nombres de archivo Windows no soporta el acceso
enviados /home/test/review.html y /home/test/xwp.out. remoto a ficheros en las siguientes
Tendríamos en $HTTP_POST_FILES['userfile']['name'][0] funciones: include(),
el valor de review.html, y en include_once(), require() y
$HTTP_POST_FILES['userfile']['name'][1] tendríamos require_once().
xwp.out; analogamente, $HTTP_POST_FILES['userfile']
['size'][0] contendría el tamaño del fichero review.html, y
asi sucesivamente... Por ejemplo, se puede usar este para abrir un archivo en
$HTTP_POST_FILES['userfile']['name'][0], un servidor web remoto, analizar en la salida la
$HTTP_POST_FILES['userfile']['tmp_name'][0], información que se quiera, y entonces, usar la
$HTTP_POST_FILES['userfile']['size'][0] y información en una consulta a base de datos, o
$HTTP_POST_FILES['userfile']['type'][0] tambien son simplemente para sacarlas en un estilo que coincida con
asignadas. el resto de su sitio web.
Ejemplo 19-1. Obtener el título de una página
remota
Soporte del método PUT

PHP soporta el metodo HTTP PUT que usan aplicaciones <?php


como Netscape Composer y Amaya del W3C. Las $file = fopen ("http://www.example.com/",
peticiones PUT son más sencillas que el método POST. Un "r");
ejemplo: if (!$file) {
echo "<p>Unable to open remote file.\n";
alcanza el límite de tiempo impuesto por PHP (ver
exit;
set_time_limit()), se pasa al estado TIMEOUT.
}
Puedes decidir si quieres que la desconexión de un
while (!feof ($file)) {
cliente cause que tu script sea abortado. Algunas veces
$line = fgets ($file, 1024);
es cómodo que tus scripts se ejecuten por completo,
/* This only works if the title and its tags
incluso si no existe ya un navegador remoto que reciba
are on one line */
la salida. El comportamiento por defecto es sin embargo,
if (eregi ("<title>(.*)</title>", $line,
que tu script se aborte cuando el cliente remoto se
$out)) {
desconecta. Este comportamiento puede ser configurado
$title = $out[1];
vía la directiva ignore_user_abort en el fichero php3.ini, o
break;
también con la función ignore_user_abort(). Si no le
}
espeficicas al PHP que cuando un usuario aborte lo
}
ignore, tu script terminará su ejecución. La única
fclose($file);
excepción es si tienes registrada un función de
?>
desconexión usando la función
También se puede escribir a archivos en un FTP siempre register_shutdown_function(). Con una función de
que se conecte como un usuario con los correctos desconexión, cuando un usuario remoto pulsa en el
derechos de acceso, y el archivo no exista ya.Para botón STOP, la próxima vez que tu script intenta mostrar
conectar como un usuario distinto de 'anonymous', se algo, PHP detecta que la conexión ha sido abortada y se
necesita especificar el nombre de usuario (y llama a la función de desconexión. Esta función de
posiblemente contraseña) dentro de la URL, tales como desconexión también se llama al final de la ejecución de
'ftp://usuario:clave@ftp.ejemplo.com/camino/a/archivo'. tu script cuando se ha ejecutado normalmente, de
(Se puede usar la misma clase de sintaxis para acceder a manera que si quieres hacer algo diferente en caso de
archivos via HTTP cuando se requería una autenticació que un cliente se haya desconectado, puedes usar la
de same sort of syntax to access files via HTTP when función connection_aborted(). Esta función devuelve
they require Basic authentication.) TRUE si la conexión fue abortada.
Ejemplo 19-2. Almacenando datos en un servidor Vuestro script también se puede terminar por un
remoto temporizador interno. El timeout por defecto es de 30
segundos. Se puede cambiar usando la directiva
max_execution_time en el fichero php.ini o la
<?php correspondiente directiva php_max_execution_time en la
$file = fopen configuración del servidor de páginas Apache, como
("ftp://ftp.example.com/incoming/outputfile", "w"); también con la función set_time_limit(). Cuando el
if (!$file) { temporizador expira, el script se aborta como en el caso
echo "<p>Unable to open remote file for de la desconexión del cliente, de manera que si se ha
writing.\n"; definido una función de desconexión, esta se llamará.
exit; Dentro de esta función de desconexión, puedes
} comprobar si fue el timeout el que causó que se llamara
/* Write the data here. */ a la función de desconexión, llamando a la función
fputs ($file, connection_timeout(). Esta función devolverá
$HTTP_SERVER_VARS['HTTP_USER_AGENT'] . verdadero si el timeout causa que se llame a la función
"\n"); de desconexión.
fclose ($file); Hay que destacar que ambos, el estado ABORTED y el
?> TIMEOUT, se pueden activar al mismo tiempo. Esto es
posible si le dices a PHP que ignore las desconexiones
intencionadas de los usuarios. PHP aún notará el hecho
Nota: Podeis captar la idea en el de que el usuario puede haberse desconectado, pero el
ejemplo anterior de como escribir en script continuará ejecutándose. Si se alcanza el tiempo
un registro remoto, pero como ya límite de ejecución será abortado y, si se ha definido una
hemos comentado antes, solamente función de desconexión, esta será llamada. En este
se puede escribir a un fichero nuevo punto, encontrarás que las funciones
usando la "envoltura URL fopen" connection_timeout() y connection_aborted()
Para registros distribuidos, consultar devuelven verdadero. Puedes comprobar ambos estados
la función syslog(). de una manera simple usando la función
connection_status(). Esta función devuelve un campo
de bit de los estados activos. De este modo, si ambos
estados están activos devolvería por ejemplo un valor 3.

Capítulo 20. Manejando conexiones


Capítulo 21. Conexiones persistentes a bases de
datos
Nota: Todo lo siguiente se aplica a
partir de la versión 3.0.7 y posterior.
Las conexiones persistentes son enlaces SQL que no se
cierran cuando termina la ejecución del archivo de
Internamente en PHP se mantiene el estado de la comandos. Cuando se pide una conexión persistente,
conexión. Hay 3 posibles estados: PHP comprueba si hay ya una conexión persistente
idéntica (que permanecía abierta desde antes) - y si
existe, la usa. Si no existe, crea un enlace. Una conexión
• 0 - NORMAL 'idéntica' es una conexión que se abrió hacia el mismo
• 1 - ABORTED (Abortado) "host", con el mismo nombre de usuario y la misma
contraseña (donde sea aplicable).
• 2 - TIMEOUT (Fuera de tiempo)

Nota: Existen otras extensiones que


Cuando un script PHP se está ejecutando se activa el proporcionan conexiones
estado NORMAL. Si el cliente remoto se desconecta, se persistentes, tal como la extensión
pasa al estado ABORTED. Esto suele ocurrir cuando el IMAP
usuario pulsa en el botón STOP del navegador. Si se
La gente que no está familiarizada con el modo como datos tiene un límite de 16 conexiones simultaneas y en
trabajan y distribuyen la carga los servidores "web" el curso de una sesión de servidor, 17 procesos hijo
puede confundir que significa conexiones persistentes. intentan conectarse, uno de ellos no podrá hacerlo. Si
En particular, no te dan la habilidad de abrir 'sesiones de existen errores en los scripts, que no permitan terminar
usuario' en el mismo enlace SQL, no dan la habilidad de la conexion (p.ej.bucles infinitos), una base de datos con
construir una transacción de forma eficiente, y no hacen solo 32 conexiones puede ser rápidamente hundida.
un montón de otras cosas. De hecho, para ser Comprobar la documentacion de vuestra base de datos
extremadamente claros sobre el tema las conexiones para obtener información sobre que hacer con
persistentes no te dan ninguna functionalidad que no conexiones abandonadas ó libres.
fuera posible con sus hermanas no-persistentes. Aviso
¿Por qué?
Esto tiene que ver con el modo como funcionan los Un par de advertencias más a tener en cuenta cuando
servidores "web". Hay tres modos en que un servidor utiliceis conexiones persistentes. La primera, si utilizais
"web" puede utilizar PHP para generar páginas web. bloqueos en una tabla desde una conexión persistente y
El primer método es usar PHP como una capa CGI. por cualquier causa el script no puede desbloquear la
Cuando corre de este modo, se crea y destruye una tabla, todos los scripts posteriores que usen esta conexión,
instancia del intérprete PHP por cada página solicitada quedarán bloqueados indefinídamente y se requerirá que,
(para una página PHP) a tu servidor. Debido a que se ó bien el servidor httpd ó la base de datos sean arrancados
destruye después de cada petición, cualquier recurso de nuevo. La segunda, cuando utiliceis transacciones, un
que adquiera (como un enlace a un servidor de base de bloqueo por transacción será heredado por el próximo
datos SQL) se cierra cuando es destruido. En este caso, script usando la conexión, si la ejecución del primer script
no se gana nada si se intentan usar conexiones termina antes que el bloqueo. en ambos caso podeis
persistentes, ya que simplemente no persisten. utilizar register_shutdown_function() para registrar una
El segundo, y más popular, método es correr PHP como funcion simple de limpieza que desbloquee las tablas ó
un módulo en un servidor web multiproceso, lo cual deshaga la transacción. Lo mejor para evitar problemas es
actualmente sólo incluye Apache. Un servidor no usar conexiones persistentes en scripts que usen
multiproceso tiene típicamente un proceso (el padre) que bloqueos de tablas ó transacciones (para todolo demás
coordina un conjunto de procesos (sus hijos) que pueden ser usadas sin problemas)
realmente hacen el trabajo se servir las páginas web. Un resumen importante. Las conexiones persistentes
Cuando entra cada petición de un cliente, es entregada a fueron diseñadas para tener una equivalencia uno-a-uno
uno de los hijos que no esté ya sirviendo a otro cliente. con las conexiones normales. Eso significa que deberíais
Esto significa que cuando el mismo cliente hace una siempre ser capaz de reemplazar las conexiones
segunda petción al servidor, puede ser atendido por un persistentes por conexiones no persistentes y no
proceso hijo distinto del de la primera vez. Lo que una cambiará, el modo como se comporta el archivo de
conexión persistente hace por ti en este caso es hacerlo comandos. Puede cambiar la eficiencia del archivo de
de tal modo que cada proceso hijo sólo necesita conectar comandos (y probablemete lo hará), ¡pero no su
a tu SQL server la primera vez que sirve una página que comportamiento!
hace uso de una conexión así. Cuando otra página
solicita una conexión a SQL server, puede reutilizar la
conexión que el hijo estableció previamente. Capítulo 22. Modo Seguro (Safe Mode)
El último método es usar PHP como un "plug-in" para un
servidor web multihilo. En la actualidad es solamente
teórico -- PHP no funciona aún como "plug-in" para El Modo Seguro de PHP es un intento para resolver el
ningún servidor web multihilo. Actualmente PHP 4 problema de la seguridad en un servidor compartido.
soporta ISAPI, WSAPI y NSAPI (en Windows), lo cual Tratar de resolver este problema al nivel de PHP es
permite a PHP ser utilizado como "plug-in" para arquitectónicamente incorrecto, pero ya que las
servidores web multihilo como Netscape FastTrack, alternativas en un servidor web y a niveles de sistemas
Internet Information Server (IIS) de Microsoft, y O'Reilly's operativos no son tan realistas, mucha gente,
WebSite Pro. El comportamiento es exactamente el especialmente la de proveedores de Internet (ISP), usa el
mismo que para el modelo de multiprocesador descrito Modo Seguro por ahora.
anteriormente. Tener en cuanta que el soporte para SAPI Tabla 22-1. Las directivas de Configuración que
no está disponible en PHP 3. controlan el Modo Seguro son:
Si las conexiones persistentes no aportan ninguna Valor por
funcionalidad añadida, ¿para qué son buenas? Directiva
Omisión
La respuesta aqui es extremadamente simple --
eficiencia. Las conexiones persistentes son buenas si las safe_mode Off
cabeceras de control para crear un enlace a tu servidor safe_mode_gid 0
SQL es alta. Que estas cabeceras sean o no realmente
altas depende de muchos factores. Como, qué clase de safe_mode_include_dir ""
base de datos es, si esta o no situada en el mismo safe_mode_exec_dir 1
ordenador que el servidor web, cómo está de cargada la
máquina donde se encuentre el servidor SQL, y otras así. open_basedir ""
El hecho fundamental es que si la cabecera de conexión safe_mode_allowed_env
es alta, las conexiones persistentes te ayudan PHP_
_vars
considerablemente . Ellas hacen que el proceso hijo
simplemente conecte solamente una vez durante todo su safe_mode_protected_e LD_LIBRARY_PAT
intervalo de vida, en vez de cada vez que procesa una nv_vars H
pagina que requiere conectar al servidor SQL. Esto disable_functions ""
significa que por cada hijo que abrió una conexión
persistente tendrá su propia conexión persistente al Cuando safe_mode está en On, el PHP verifica si el dueño
servidor. Por ejemplo, si tienes 20 procesos hijos del script actual coincide con el dueño del fichero a ser
distintos que corran un archivo de comandos que cree operado por una función de fichero. Por ejemplo:
una conexión persistente a tu servidor SQL, tendrías 20 -rw-rw-r-- 1 rasmus rasmus 33 Jul 1
conexiones diferentes a ti servidor SQL, una por cada 19:20 script.php
hijo. -rw-r--r-- 1 root root 1116 May 26
No obstante, hay que tener en cuenta que esto puede 18:01 /etc/passwd
tener desventajas si estais utilizando una base de datos
con límites de conexión, por debajo del numero de Corriendo este script.php
procesos hijo con conexiones persistentes. Si tu base de <?php
readfile('/etc/pas Función Limitaciones
swd');
comprueba si
?>
el
resulta in este error cuando Modo Seguro está habilitado: fichero(s)/direc
torios que vas
Warning: SAFE MODE Restriction in effect. The script
a utilizar,
whose uid is 500 is not
tienen la
allowed to access /etc/passwd owned by uid 0 in
misma UID que
/docroot/script.php on line 2
el script que
Sin embargo, pueden haber ambientes donde una está siendo
estricta verificación del UID no es apropiada, y una ejecutado.
relajada verificación del GID es suficiente. Esto es
soportado por medio del switch safe_mode_gid. Nota: Cuando
safe-mode
Seteándolo a On hace la verificación relajada GID,
seteándolo a Off (el valor por omisión) hace la (modo-seguro)
está activado,
verificación del UID.
Si en vez del safe_mode, Ud. setea un directorio PHP
comprueba si
open_basedir, entonces todas las operaciones de fichero
estarán limitadas a los ficheros bajo ese directorio el
filepro() fichero(s)/direc
especificado. Por ejemplo (ejemplo de httpd.conf de
Apache): torios que vas
a utilizar,
<Directory /docroot> tienen la
php_admin_value misma UID que
open_basedir /docroot el script que
</Directory> está siendo
Si Ud. corre el mismo script.php con este seteo ejecutado.
open_basedir, entonces este es el resultado: Nota: Cuando
Warning: open_basedir restriction in effect. File is in safe-mode
wrong directory in (modo-seguro)
/docroot/script.php on line 2 está activado,
PHP
Ud. también puede inhabilitar funciones individuales. comprueba si
Note que la directiva disable_functions no puede ser el
usada fuera del fichero php.ini lo que significa que Ud. no filepro_rowcount() fichero(s)/direc
puede inhabilitar funciones en los principios per- torios que vas
virtualhost o per-directory en su fichero httpd.conf. Si a utilizar,
agregamos esto a nuestro fichero php.ini: tienen la
disable_functions misma UID que
readfile,system el script que
está siendo
Entonces obtenemos esta salida: ejecutado.
Warning: readfile() has been disabled for Nota: Cuando
security reasons in safe-mode
/docroot/script.php on line 2 (modo-seguro)
está activado,
PHP
Funciones restringidas/inhabilitadas por Modo comprueba si
Seguro el
filepro_retrieve() fichero(s)/direc
torios que vas
Esta es una lista probablemente incompleta y a utilizar,
posiblemente incorrecta de las funciones limitadas por tienen la
safe mode. misma UID que
Tabla 22-2. Funciones limitadas por Modo Seguro el script que
Función Limitaciones está siendo
ejecutado.
Nota: Cuando
safe-mode restricciones sql_safe_mode, (!=
ifx_*()
(modo-seguro) safe mode)
está activado, restricciones sql_safe_mode, (!=
PHP ingres_*()
safe mode)
comprueba si
el restricciones sql_safe_mode, (!=
mysql_*()
dbmopen() fichero(s)/direc safe mode)
torios que vas pg_loimport() Nota: Cuando
a utilizar, safe-mode
tienen la (modo-seguro)
misma UID que está activado,
el script que PHP
está siendo comprueba si
ejecutado. el
dbase_open() Nota: Cuando fichero(s)/direc
safe-mode torios que vas
(modo-seguro) a utilizar,
está activado, tienen la
PHP misma UID que
Función Limitaciones Función Limitaciones
el script que razones prácticas, no está
está siendo actualmente permitido tener
ejecutado. componentes .. en la ruta del
fichero ejecutable.
Nota: Cuando
safe-mode Ud. puede correr sólo ejecutatables
(modo-seguro) dentro delsafe_mode_exec_dir. Por
está activado, razones prácticas, no está
popen()
PHP actualmente permitido tener
comprueba si componentes .. en la ruta del
los directorios fichero ejecutable.
posix_mkfifo()
que vas a
Nota: Cuando
utilizar, tienen
safe-mode
la misma UID
(modo-seguro)
que el script
está activado,
que está
PHP
siendo
comprueba si
ejecutado.
los directorios
mkdir()
Obecede las ini-directivas que vas a
safe_mode_protected_env_vars y utilizar, tienen
putenv() safe_mode_allowed_env_vars. Vea la misma UID
también la documentación de que el script
putenv() que está
siendo
Nota: Cuando
ejecutado.
safe-mode
(modo-seguro) Nota: Cuando
está activado, safe-mode
PHP (modo-seguro)
comprueba si está activado,
el PHP
move_uploaded_file(
fichero(s)/direc comprueba si
)
torios que vas el
a utilizar, rmdir() fichero(s)/direc
tienen la torios que vas
misma UID que a utilizar,
el script que tienen la
está siendo misma UID que
ejecutado. el script que
está siendo
Nota: Cuando
ejecutado.
safe-mode
(modo-seguro) Nota: Cuando
está activado, safe-mode
PHP (modo-seguro)
comprueba si está activado,
los directorios PHP
chdir()
que vas a comprueba si
utilizar, tienen el
la misma UID fichero(s)/direc
que el script torios que vas
que está a utilizar,
siendo tienen la
ejecutado. misma UID que
el script que
Esta función no está activada en
dl() está siendo
safe-mode (modo-seguro)
ejecutado.
Esta función no está activada en rename()
backtick operator
safe-mode (modo-seguro)
Nota: Cuando
shell_exec() safe-mode
Esta función no está activada en
(equivalencia funcional (modo-seguro)
safe-mode (modo-seguro)
de backticks) está activado,
Ud. puede correr sólo ejecutables PHP
dentro delsafe_mode_exec_dir. Por comprueba si
razones prácticas, no está los directorios
exec() que vas a
actualmente permitido tener
componentes .. en la ruta del utilizar, tienen
fichero ejecutable. la misma UID
que el script
Ud. puede correr sólo ejecutatables que está
dentro delsafe_mode_exec_dir. Por siendo
razones prácticas, no está ejecutado.
system()
actualmente permitido tener
componentes .. en la ruta del unlink() Nota: Cuando
fichero ejecutable. safe-mode
(modo-seguro)
passthru() Ud. puede correr sólo ejecutatables está activado,
dentro delsafe_mode_exec_dir. Por PHP
Función Limitaciones Función Limitaciones
comprueba si safe-mode
el (modo-seguro)
fichero(s)/direc está activado,
torios que vas PHP
a utilizar, comprueba si
tienen la el
misma UID que fichero(s)/direc
el script que torios que vas
está siendo a utilizar,
ejecutado. tienen la
misma UID que
el script que
Nota: Cuando está siendo
safe-mode ejecutado.
(modo-seguro)
está activado, Nota: Cuando
PHP safe-mode
comprueba si (modo-seguro)
los directorios está activado,
que vas a PHP
utilizar, tienen comprueba si
la misma UID el
que el script fichero(s)/direc
que está torios que vas
siendo chmod() a utilizar,
ejecutado. tienen la
misma UID que
Nota: Cuando el script que
safe-mode está siendo
(modo-seguro) ejecutado.
está activado,
PHP
comprueba si Además, Ud. no puede setear los
el bits de SUID, SGID y sticky
fichero(s)/direc
Nota: Cuando
torios que vas
safe-mode
a utilizar,
(modo-seguro)
tienen la
está activado,
misma UID que
PHP
el script que
comprueba si
está siendo
el
ejecutado.
fichero(s)/direc
torios que vas
copy() a utilizar,
Nota: Cuando
safe-mode tienen la
(modo-seguro) misma UID que
está activado, el script que
PHP está siendo
comprueba si ejecutado.
los directorios touch()
que vas a
Nota: Cuando
utilizar, tienen
safe-mode
la misma UID
(modo-seguro)
que el script
está activado,
que está
PHP
siendo
comprueba si
ejecutado.
los directorios
que vas a
(en source y target) utilizar, tienen
la misma UID
Nota: Cuando que el script
safe-mode que está
(modo-seguro) siendo
está activado, ejecutado.
PHP
comprueba si symlink() Nota: Cuando
el safe-mode
chgrp() fichero(s)/direc (modo-seguro)
torios que vas está activado,
a utilizar, PHP
tienen la comprueba si
misma UID que el
el script que fichero(s)/direc
está siendo torios que vas
ejecutado. a utilizar,
tienen la
chown() Nota: Cuando misma UID que
Función Limitaciones Función Limitaciones
el script que fichero(s)/direc
está siendo torios que vas
ejecutado. a utilizar,
tienen la
misma UID que
Nota: Cuando el script que
safe-mode está siendo
(modo-seguro) ejecutado.
está activado,
PHP
comprueba si Nota: Cuando
los directorios safe-mode
que vas a (modo-seguro)
utilizar, tienen está activado,
la misma UID PHP
que el script comprueba si
que está los directorios
siendo que vas a
ejecutado. utilizar, tienen
la misma UID
que el script
(Nota: sólo el target es que está
comprobado) siendo
Nota: Cuando ejecutado.
safe-mode
(modo-seguro)
(Nota: sólo afectado desde PHP
está activado,
4.2.1)
PHP
comprueba si Nota: Cuando
el safe-mode
fichero(s)/direc (modo-seguro)
torios que vas está activado,
a utilizar, PHP
tienen la comprueba si
misma UID que el
el script que fichero(s)/direc
está siendo torios que vas
ejecutado. a utilizar,
tienen la
misma UID que
link() Nota: Cuando el script que
safe-mode está siendo
(modo-seguro) ejecutado.
está activado,
PHP
comprueba si parse_ini_file() Nota: Cuando
los directorios safe-mode
que vas a (modo-seguro)
utilizar, tienen está activado,
la misma UID PHP
que el script comprueba si
que está los directorios
siendo que vas a
ejecutado. utilizar, tienen
la misma UID
que el script
(Nota: sólo the target es que está
comprobado) siendo
En Modo Seguro, las cabeceras que ejecutado.
empiezan con 'authorization'
(insensitivo al tipo de letra) no
getallheaders() (Nota: sólo afectado desde PHP
serán retornadas. Advertencia: esto
4.2.1)
está roto por la implementación de
aol-server de getallheaders()! Cualquier función que
usa
En Modo Seguro, el UID del script ??
php4/main/fopen_wrap
está agregado a la parte realm de
pers.c
header() la cabecera WWW-Authenticate si
Ud. setea esta cabecera (usado por
HTTP Authentication).
Capítulo 23. Using PHP from the command line
highlight_file(), Nota: Cuando
show_source() safe-mode
(modo-seguro) As of version 4.3.0, PHP supports a new SAPI type (Server
está activado, Application Programming Interface) named CLI which
PHP means Command Line Interface. As the name implies,
comprueba si this SAPI type main focus is on developing shell (or
el desktop as well) applications with PHP. There are quite a
few differences between the CLI SAPI and other SAPIs CLI
which are explained in this chapter. It's worth mentioning SAPI
that CLI and CGI are different SAPI's although they do Directive Comment
default
share many of the same behaviors. value
The CLI SAPI was released for the first time with PHP
4.2.0, but was still experimental and had to be explicitly It can be quite hard to
enabled with --enable-cli when running ./configure. Since read the error message
PHP 4.3.0 the CLI SAPI is no longer experimental and the in your shell when it's
option --enable-cli is on by default. You may use cluttered with all those
html_errors FALSE
--disable-cli to disable it. meaningless HTML
As of PHP 4.3.0, the name, location and existence of the tags, therefore this
CLI/CGI binaries will differ depending on how PHP is directive defaults to
installed on your system. By default when executing FALSE.
make, both the CGI and CLI are built and placed as It is desired that any
sapi/cgi/php and sapi/cli/php respectively, in your php output coming from
source directory. You will note that both are named php. print(), echo() and
What happens during make install depends on your friends is immediately
configure line. If a module SAPI is chosen during written to the output
configure, such as apxs, or the --disable-cgi option is implicit_flush TRUE and not cached in any
used, the CLI is copied to {PREFIX}/bin/php during make buffer. You still can use
install otherwise the CGI is placed there. So, for example, output buffering if you
if --with--apxs is in your configure line then the CLI is want to defer or
copied to {PREFIX}/bin/php during make install. If you manipulate standard
want to override the installation of the CGI binary, use output.
make install-cli after make install. Alternatively you can
specify --disable-cgi in your configure line. Due to endless
possibilities of using
PHP in shell
Nota: Because both --enable-cli and environments, the
--enable-cgi are enabled by default, maximum execution
simply having --enable-cli in your 0 time has been set to
configure line does not necessarily max_execution
(unlimit unlimited. Whereas
mean the CLI will be copied as _time
ed) applications written for
{PREFIX}/bin/php during make the web are often
install. executed very quickly,
shell application tend to
have a much longer
The windows package distributes the CGI as php.exe and
execution time.
has a folder named cli with the CLI in it, so: cli/php.exe.
Because this setting is
TRUE you will always
What SAPI do I have?: From a have access to argc
shell, typing php -v will tell you (number of arguments
whether php is CGI or CLI. See also passed to the
the function php_sapi_name() and application) and argv
the constant PHP_SAPI. (array of the actual
arguments) in the CLI
SAPI.
Remarkable differences of the CLI SAPI compared to
other SAPIs:
As of PHP 4.3.0, the
PHP variables $argc
• Unlike the CGI SAPI, no headers are written to and $argv are
the output. registered and filled in
with the appropriate
register_argc_a values when using the
Though the CGI SAPI provides a way to TRUE CLI SAPI. Prior to this
rgv
suppress HTTP headers, there's no equivalent version, the creation of
switch to enable them in the CLI SAPI. these variables
behaved as they do in
CLI is started up in quiet mode by default, CGI and MODULE
though the -q switch is kept for compatibility versions which requires
so that you can use older CGI scripts. the PHP directive
register_globals to be
on. Regardless of
It does not change the working directory to version or
that of the script. (-C switch kept for register_globals setting,
compatibility) you can always go
through either
$_SERVER or
Plain text error messages (no HTML $HTTP_SERVER_VARS.
formatting). Example:
$_SERVER['argv']

• There are certain php.ini directives which are


overriden by the CLI SAPI because they do not Nota: These directives
make sense in shell environments: cannot be initialized with
another value from the
configuration file php.ini or
Tabla 23-1. Overriden php.ini directives a custom one (if
specified). This is a
/tmp/another_directory
limitation because those
default values are applied
after all configuration files
have been parsed. This clearly shows that PHP changes its current
However, their value can directory to the one of the executed script.
be changed during
runtime (which does not Using the CLI SAPI yields:
make sense for all of those
directives, e.g.
register_argc_argv).
$ pwd
/tmp
• To ease working in the shell environment, the $ php -f
following constants are defined: another_directory/test.ph
p
Tabla 23-2. CLI specific Constants /tmp

Consta This allows greater flexibility when writing shell


Description tools in PHP.
nt
An already opened stream to stdin. This
saves opening it with Nota: The CGI SAPI
STDIN supports the CLI SAPI
$stdin = behaviour by means of the
fopen('php://stdin', 'r'); -C switch when run from
the command line.
An already opened stream to stdout.
This saves opening it with
STDOU
T $stdout = The list of command line options provided by the PHP
fopen('php://stdout', 'w'); binary can be queried anytime by running PHP with the
-h switch:
An already opened stream to stderr. This Usage: php [options] [-f] <file> [args...]
saves opening it with php [options] -r <code> [args...]
STDER
R $stderr = php [options] [-- args...]
fopen('php://stderr', 'w'); -s Display colour syntax highlighted source.
-w Display source with stripped comments
and whitespace.
-f <file> Parse <file>.
Given the above, you don't need to open e.g. a -v Version number
stream for stderr yourself but simply use the -c <path>|<file> Look for php.ini file in this directory
constant instead of the stream resource: -a Run interactively
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for
php -r 'fwrite(STDERR, debugger/profiler
"stderr\n");' -z <file> Load Zend extension <file>.
-l Syntax check only (lint)
-m Show compiled in modules
You do not need to explicitly close these -i PHP information
streams, as they are closed automatically by -r <code> Run PHP <code> without using script
PHP when your script ends. tags <?..?>
-h This help

• The CLI SAPI does not change the current args... Arguments passed to script. Use -- args
when first argument
directory to the directory of the executed
starts with - or script is read from stdin
script!
The CLI SAPI has three different ways of getting the PHP
code you want to execute:
Example showing the difference to the CGI
SAPI:
1. Telling PHP to execute a certain file.
<?php
/* Our simple test application
named test.php*/ php
echo getcwd(), "\n"; my_script.php
?>
php -f
my_script.php
When using the CGI version, the output is:

2. Both ways (whether using the -f switch or not)


$ pwd execute the file my_script.php. You can choose
/tmp any file to execute - your PHP scripts do not
have to end with the .php extension but can
$ php -q have any name or extension you wish.
another_directory/test.php
3. Pass the PHP code to execute directly on the rgv);
command line. ?>

php -r Assuming this file is named test in the current directory,


'print_r(get_defined_constants we can now do the following:
());' $ chmod 755
4. Special care has to be taken in regards of shell test
variable substitution and quoting usage. $ ./test -h --
foo
5. Nota: Read the array(4) {
example carefully, there [0]=>
are no beginning or ending string(6)
tags! The -r switch simply "./test"
does not need them. Using [1]=>
them will lead to a parser string(2) "-
error. h"
6. Provide the PHP code to execute via standard
[2]=>
string(2) "--"
input (stdin). [3]=>
string(3)
This gives the powerful ability to dynamically "foo"
create PHP code and feed it to the binary, as }
shown in this (fictional) example: As you see, in this case no care needs to be taken when
passing parameters which start with - to your script.
Tabla 23-3. Command line options
$ some_application | some_filter | php | sort -u Optio
>final_output.txt Description
n
You cannot combine any of the three ways to execute Display colour syntax highlighted source.
code.
Like every shell application, the PHP binary accepts a
number of arguments but your PHP script can also This option uses the internal mechanism to parse
receive arguments. The number of arguments which can the file and produces a HTML highlighted version of
be passed to your script is not limited by PHP (the shell it and writes it to standard output. Note that all it
-s
has a certain size limit in the number of characters which does it to generate a block of <code> [...] </code>
can be passed; usually you won't hit this limit). The HTML tags, no HTML headers.
arguments passed to your script are available in the
global array $argv. The zero index always contains the
script name (which is - in case the PHP code is coming Nota: This option does not work
from either standard input or from the command line together with the -r option.
switch -r). The second registered global variable is $argc Display source with stripped comments and
which contains the number of elements in the $argv whitespace.
array (not the number of arguments passed to the
script). -w
As long as the arguments you want to pass to your script Nota: This option does not work
do not start with the - character, there's nothing special together with the -r option.
to watch out for. Passing an argument to your script
Parses and executed the given filename to the -f
which starts with a - will cause trouble because PHP itself
-f option. This switch is optional and can be left out.
thinks it has to handle it. To prevent this, use the
Only providing the filename to execute is sufficient.
argument list separator --. After this separator has been
parsed by PHP, every argument following it is passed Writes the PHP, PHP SAPI, and Zend version to
untouched to your script. standard output, e.g.
# This will not execute the given code but will show the $ php -v
PHP usage -v PHP 4.3.0 (cli), Copyright (c) 1997-2002 The
$ php -r 'var_dump($argv);' -h PHP Group
Usage: php [options] [-f] <file> [args...] Zend Engine v1.3.0, Copyright (c) 1998-2002
[...] Zend Technologies

# This will pass the '-h' argument to your script and With this option one can either specify a directory
prevent PHP from showing it's usage where to look for php.ini or you can specify a custom
$ php -r 'var_dump($argv);' -- -h INI file directly (which does not need to be named
array(2) { php.ini), e.g.:
[0]=> -c $ php -c /custom/directory/
string(1) "-" my_script.php
[1]=>
string(2) "-h" $ php -c /custom/directory/custom-
} file.ini my_script.php
However, there's another way of using PHP for shell
scripting. You can write a script where the first line starts -a Runs PHP interactively.
with #!/usr/bin/php. Following this you can place normal This option allows you to set a custom value for any
PHP code included within the PHP starting and end tags. of the configuration directives allowed in php.ini.
Once you have set the execution attributes of the file The syntax is:
appropriately (e.g. chmod +x test) your script can be
executed like a normal shell or perl script: -d -d
configuration_directive[
#!/usr/bin/php =value]
<?php
var_dump($a Examples:
Optio Optio
Description Description
n n
the information tables. Beware that the output is in
# Omitting the value part will set the given
HTML and therefore quite huge.
configuration directive to "1"
$ php -d max_execution_time -r '$foo = -r This option allows execution of PHP right from within
ini_get("max_execution_time"); the command line. The PHP start and end tags (<?
var_dump($foo);' php and ?>) are not needed and will cause a
string(1) "1" parser error if present.

# Passing an empty value part will set the


configuration directive to "" Nota: Care has to be taken
php -d max_execution_time= -r '$foo = when using this form of PHP to
ini_get("max_execution_time"); not collide with command line
var_dump($foo);' variable substitution done by
string(0) "" the shell.

# The configuration directive will be set to


Example showing a parser error
anything passed after the '=' character
$ php -d max_execution_time=20 -r '$foo =
ini_get("max_execution_time");
var_dump($foo);' $ php -r "$foo =
string(2) "20" get_defined_constants();"
$ php -d Command line code(1) : Parse error -
max_execution_time=doesntmakesense -r '$foo parse error, unexpected '='
= ini_get("max_execution_time");
var_dump($foo);'
string(15) "doesntmakesense" The problem here is that the
sh/bash performs variable
Generate extended information for substitution even when using
-e double quotes ". Since the
debugger/profiler.
variable $foo is unlikely to be
Load Zend extension. If only a filename is given, PHP defined, it expands to nothing
tries to load this extension from the current default which results in the code passed
library path on your system (usually specified to PHP for execution actually
/etc/ld.so.conf on Linux systems). Passing a filename reading:
-z
with an absolute path information will not use the
systems library search path. A relative filename with
a directory information will tell PHP only to try to
$ php -r " =
load the extension relative to the current directory.
get_defined_constants();"
This option provides a convenient way to only
perform a syntax check on the given PHP code. On
succes, the text No syntax errors detected in The correct way would be to use
<filename> is written to standard output and the single quotes '. Variables in
shell return code is 0. On failure, the text Errors single-quoted strings are not
parsing <filename> in addition to the internal expanded by sh/bash.
parser error message is written to standard output
-l and the shell return code is set to 255.
This option won't find fatal errors (like undefined $ php -r '$foo =
functions). Use -f if you would like to test for fatal get_defined_constants();
errors too. var_dump($foo);'
array(370) {
Nota: This option does not work ["E_ERROR"]=>
together with the -r option. int(1)
["E_WARNING"]=>
Using this option, PHP prints out the built in (and int(2)
loaded) PHP and Zend modules: ["E_PARSE"]=>
$ php -m int(4)
[PHP ["E_NOTICE"]=>
Modules] int(8)
xml ["E_CORE_ERROR"]=>
tokenizer [...]
standard
session
-m If you are using a shell different
posix
pcre from sh/bash, you might
overload experience further issues. Feel
mysql free to open a bug report or
mbstring send a mail to
ctype phpdoc@lists.php.net. One can
still easily run into troubles
[Zend when trying to get shell
Modules] variables into the code or using
backslashes for escaping.
-i This command line option calls phpinfo(), and You've been warned.
prints out the results. If PHP is not working correctly,
it is advisable to use php -i and see whether any
error messages are printed out before or in place of Nota: -r is available in the CLI
Optio See also the Readline extension documentation for more
Description functions you can use to enhance your command line
n
applications in PHP.

SAPI and not in the CGI SAPI. IV. Referencia de las Funciones
With this option, you can get information about the
-h actual list of command line options and some one Tabla de contenidos
line descriptions about what they do. I. Funciones específicas de Apache
The PHP executable can be used to run PHP scripts II. Funciones de matrices
absolutely independent from the web server. If you are III. Funciones Aspell [deprecated]
on a Unix system, you should add a special first line to IV. Funciones matemáticas de precisión arbitraria
your PHP script, and make it executable, so the system BCMath
will know, what program should run the script. On a V. Funciones de compresión Bzip2
Windows platform you can associate php.exe with the VI. Funciones de calendario
double click option of the .php files, or you can make a VII. Funciones del API de CCVS
batch file to run the script through PHP. The first line VIII. soporte de las funciones COM para Windows
added to the script to work on Unix won't hurt on IX. Funciones de Clases/Objectos
Windows, so you can write cross platform programs this X. Funciones de ClibPDF
way. A simple example of writing a command line PHP XI. Crack functions
program can be found below. XII. CURL, Client URL Library Functions
Ejemplo 23-1. Script intended to be run from XIII. Funciones de pago electrónico
command line (script.php) XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
XVI. Character type functions
#!/usr/bin/php XVII. Funciones de la capa de abstraccion de bases de
<?php datos (dbm-style)
XVIII. Funciones de fecha y hora
if ($argc != 2 || in_array($argv[1], array('--help', XIX. Funciones para dBase
'-help', '-h', '-?'))) { XX. Funciones dbm
?> XXI. dbx functions
XXII. DB++ Functions
This is a command line PHP script with one XXIII. Direct IO functions
option. XXIV. Funciones con directorios
XXV. Funciones de DOM XML
Usage: XXVI. .NET functions
<?php echo $argv[0]; ?> <option> XXVII. Error Handling and Logging Functions
XXVIII. FrontBase Functions
<option> can be some word you would like XXIX. Funciones filePro
to print out. With the --help, -help, -h, XXX. Funciones del sistema de ficheros
or -? options, you can get this help. XXXI. Funciones Forms Data Format (Formato de Datos
de Formularios)
<?php XXXII. FriBiDi functions
} else { XXXIII. Funciones FTP
echo $argv[1]; XXXIV. Function Handling functions
} XXXV. GNU Gettext
?> XXXVI. GMP functions
XXXVII. Funciones HTTP
In the script above, we used the special first line to XXXVIII. Funciones para Hyperwave
indicate that this file should be run by PHP. We work with XXXIX. Hyperwave API functions
a CLI version here, so there will be no HTTP header XL. iconv functions
printouts. There are two variables you can use while XLI. Funciones para imágenes
writing command line applications with PHP: $argc and XLII. Funciones IMAP
$argv. The first is the number of arguments plus one (the XLIII. Funciones para Informix
name of the script running). The second is an array XLIV. Funciones InterBase
containing the arguments, starting with the script name XLV. Ingres II functions
as number zero ($argv[0]). XLVI. IRC Gateway Functions
In the program above we checked if there are less or XLVII. PHP / Java Integration
more than one arguments. Also if the argument was XLVIII. Funciones LDAP
--help, -help, -h or -?, we printed out the help message, XLIX. Funciones de Correo
printing the script name dynamically. If we received L. mailparse functions
some other argument we echoed that out. LI. Funciones matemáticas
If you would like to run the above script on Unix, you LII. Multi-Byte String Functions
need to make it executable, and simply call it as LIII. MCAL functions
script.php echothis or script.php -h. On Windows, you can LIV. Funciones Criptográficas
make a batch file for this task: LV. MCVE Payment Functions
Ejemplo 23-2. Batch file to run a command line PHP LVI. Funciones Hash
script (script.bat) LVII. Mimetype Functions
LVIII. Funciones de Microsoft SQL Server
LIX. Ming functions for Flash
@c:\php\cli\php.exe script.php %1 LX. Miscelánea de funciones
%2 %3 %4 LXI. mnoGoSearch Functions
Assuming you named the above program script.php, and LXII. funciones mSQL
you have your CLI php.exe in c:\php\cli\php.exe this LXIII. Funciones MySQL
batch file will run it for you with your added options: LXIV. Mohawk Software session handler functions
script.bat echothis or script.bat -h. LXV. muscat functions
LXVI. Funciones de Red
LXVII. Ncurses terminal screen control functions
LXVIII. Lotus Notes functions
LXIX. ODBC functions Description
LXX. Object Aggregation/Composition Functions
LXXI. Funciones de Oracle 8
LXXII. OpenSSL functions bool apache_child_terminate ( void)
LXXIII. Funciones Oracle
LXXIV. Ovrimos SQL functions apache_child_terminate() will register the Apache
LXXV. Output Control Functions process executing the current PHP request for
LXXVI. Object property and method call overloading termination once execution of PHP code it is completed.
LXXVII. PDF functions It may be used to terminate a process after a script with
LXXVIII. Verisign Payflow Pro functions high memory consumption has been run as memory will
LXXIX. opciones e información de PHP usually only be freed internally but not given back to the
LXXX. Funciones POSIX operating system.
LXXXI. Funciones de PostgreSQL
LXXXII. Process Control Functions
LXXXIII. Funciones de ejecución de programas Nota: The availability of this feature
LXXXIV. Printer functions is controlled by the php.ini directive
LXXXV. Pspell Functions apache.child_terminate, which is set
LXXXVI. GNU Readline to off by default.
LXXXVII. Funciones GNU Recode
LXXXVIII. Funciones de expresiones regulares
compatibles con Perl This feature is also not available on
LXXXIX. qtdom functions multithreaded versions of apache
XC. Funciones para expresiones regulares like the win32 version.
XCI. Funciones Semáforo y de memoria compartida
XCII. SESAM database functions See also exit().
XCIII. Funciones para el manejo de sesiones
XCIV. Shared Memory Functions
XCV. Shockwave Flash functions apache_lookup_uri
XCVI. Funciones SNMP
XCVII. Socket functions
XCVIII. Stream functions (PHP 3>= 3.0.4, PHP 4 )
XCIX. Funciones de cadenas apache_lookup_uri -- Efectua una petición parcial a la
C. Funciones de Sybase URI especificada y devuelve toda la información sobre
CI. Tokenizer functions ella.
CII. Funciones URL
CIII. Funciones sobre variables
Descripción
CIV. vpopmail functions
CV. W32api functions
CVI. Funciones WDDX class apache_lookup_uri ( string filename)
CVII. Funciones de intérprete XML
CVIII. XML-RPC functions
CIX. XSLT functions Esta función efectua una llamada parcial a URI. Esta
CX. YAZ llamada no hace sino obtener toda la información
CXI. NIS funciona importante sobre el recurso pedido y la devuelve en un
CXII. Zip File Functions (Read Only Access) tipo clase .Las propiedades de esa clase son:
CXIII. Funciones de Compresión status
the_reques
t
I. Funciones específicas de Apache status_line
method
Estas funciones están disponibles solamente si content_ty
ejecutamos PHP como módulo de Apache. pe
Tabla de contenidos handler
apache_child_terminate -- Terminate apache process
uri
after this request
apache_lookup_uri -- Efectua una petición parcial a la filename
URI especificada y devuelve toda la información sobre path_info
ella. args
apache_note -- Recibe y establece los valores de una boundary
petición en una tabla de notas del Apache no_cache
apache_request_headers -- Fetch all HTTP request
no_local_co
headers
py
apache_response_headers -- Fetch all HTTP response
headers allowed
apache_setenv -- Set an Apache subprocess_env variable send_body
ascii2ebcdic -- Translate string from ASCII to EBCDIC ct
ebcdic2ascii -- Translate string from EBCDIC to ASCII bytes_sent
getallheaders -- Recibe todas las cabeceras de una byterange
petición HTTP
clength
virtual -- Ejecuta una sub-petición al Apache
unparsed_u
ri
apache_child_terminate mtime
request_ti
(PHP 4 >= 4.0.5) me
apache_child_terminate -- Terminate apache process
after this request
Nota: Nota: apache_lookup_uri solo apache_response_headers -- Fetch all HTTP response
funciona cuando el PHP está headers
instalado como módule del Apache.

Description
apache_note

array apache_response_headers ( void)


(PHP 3>= 3.0.2, PHP 4 )
apache_note -- Recibe y establece los valores de una
Returns an array of all Apache response headers. This
petición en una tabla de notas del Apache
functionality is only available in PHP version 4.3.0 and
greater.
Descripción See also getallheaders() and headers_sent().

string apache_note ( string note_name [, string apache_setenv


note_value])
(PHP 4 >= 4.2.0)
apache_note() es una función específica del Apache apache_setenv -- Set an Apache subprocess_env variable
que recibe y establece valores de la petición en una tabla
de notas. Si se llama con un solo parámetro,devuelve el
valor de note_name. Si se llama con dos parámetros, Description
establece el valor de note_value en note_value y
devuelve el valor que había en note_name.
int apache_setenv ( string variable, string value [, bool
walk_to_top])
apache_request_headers
Aviso
(PHP 4 >= 4.3.0) Esta función no está documentada actualmente, solamente
apache_request_headers -- Fetch all HTTP request se encuentra disponible la lista de parametros.
headers

Description ascii2ebcdic

array apache_request_headers ( void) (PHP 3>= 3.0.17)


ascii2ebcdic -- Translate string from ASCII to EBCDIC
apache_request_headers() returns an associative
array of all the HTTP headers in the current request. This Description
is only supported when PHP runs as an Apache module.

int ascii2ebcdic ( string ascii_str)


Nota: Prior to PHP 4.3.0,
apache_request_headers() was
ascii2ebcdic() is an Apache-specific function which is
called getallheaders(). After PHP
available only on EBCDIC based operating systems
4.3.0, getallheaders() is an alias
(OS/390, BS2000). It translates the ASCII encoded string
for apache_request_headers().
ascii_str to its equivalent EBCDIC representation (binary
safe), and returns the result.
Ejemplo 1. apache_request_headers() Example See also the reverse function ebcdic2ascii()

ebcdic2ascii
<?php
$headers =
apache_request_headers(); (PHP 3>= 3.0.17)
ebcdic2ascii -- Translate string from EBCDIC to ASCII
foreach ($headers as $header
=> $value) {
echo "$header: $value Description
<br />\n";
}
int ebcdic2ascii ( string ebcdic_str)
?>

ebcdic2ascii() is an Apache-specific function which is


Nota: You can also get at the value available only on EBCDIC based operating systems
of the common CGI variables by (OS/390, BS2000). It translates the EBCDIC encoded
reading them from the environment, string ebcdic_str to its equivalent ASCII representation
which works whether or not you are (binary safe), and returns the result.
using PHP as an Apache module. Use See also the reverse function ascii2ebcdic()
phpinfo() to see a list of all of the
available environment variables.
getallheaders

apache_response_headers
(PHP 3, PHP 4 )
getallheaders -- Recibe todas las cabeceras de una
(PHP 4 >= 4.3.0) petición HTTP
Descripción Requerimientos

array getallheaders ( void) Estas funciones están disponibles como parte del módulo
estandar, el cual está siempre disponible.
Esta función devuelve asociados en un vector todas las
cabeceras de la actual petición HTTP.
Instalación

Nota: También puedes obtener los No se necesita ninguna instalación para usar estas
valores de las variables de los CGIs
funciones, son parte del núcleo de PHP.
mediante variables de entorno, que
funcionan, esté o no el PHP
funcionando como módulo del Configuración en tiempo de ejecución
Apache. Utiliza phpinfo()para ver
una lista de todas las variables de
entorno definidas de esta forma. Esta extensión no define ninguna directiva de
configuración.
Ejemplo 1. ObtenerTodaslasCabeceras() Ejemplo
Tipos de recursos

$cabeceras = getallheaders();
while (list($cabecera, $valor) = Esta extensión no define ningún tipo de recurso.
each($cabeceras)) {
echo "$cabecera: $valor<br>\n";
} Constantes predefinidas

Este ejemplo visualiza todas las cabeceras de la petición


actual. CASE_UPPER y CASE_LOWER son usadas con la
función array_change_key_case(). Son usadas
respectivamente para cambiar una cadena literal de
Nota: mayúsculas a minúsculas.
ObtenerTodaslasCabeceras()
actualmente solo funcionará si el
PHP es cargado como módulo del Ver tambien
Apache .

Ver tambien is_array(), explode(), implode(), split(),


virtual y join().
Tabla de contenidos
array_change_key_case -- Returns an array with all string
(PHP 3, PHP 4 ) keys lowercased or uppercased
virtual -- Ejecuta una sub-petición al Apache array_chunk -- Split an array into chunks
array_count_values -- Cuenta todos los valores de una
Descripción matriz
array_diff_assoc -- Computes the difference of arrays
with additional index check
int virtual ( string filename) array_diff -- Computes the difference of arrays
array_fill -- Fill an array with values
array_filter -- Filters elements of an array using a
virtual() es una función específica del Apache que es
callback function
equivalente a <!--#include virtual...--> en mod_include.
array_flip -- Intercambia los valores de una matriz
Esto ejecuta una sup-petición al Apache .Esto, es util
array_intersect_assoc -- Computes the intersection of
para incluir CGI-scripts o páginas .shtml o cualquier tipo
arrays with additional index check
de fichero que puedas procesar mediante el Apache. Los
array_intersect -- Computes the intersection of arrays
CGI-scripts deberán generar cabeceras válidas. Esto,
array_key_exists -- Checks if the given key or index exists
implica como mínimo un include() ó un require(); La
in the array
función virtual() no puede ser usada para incluir un
array_keys -- Devuelve todas las claves de una matriz
documento que sea por si mismo un documento PHP.
array_map -- Applies the callback to the elements of the
given arrays
II. Funciones de matrices array_merge_recursive -- Merge two or more arrays
recursively
array_merge -- Combina dos o más matrices
Introducción array_multisort -- Sort multiple or multi-dimensional
arrays
array_pad -- Rellena una matriz con un valor hasta el
Estas funciones permiten trabajar y manipular matrices tamaño especificado
(arrays) de diferentes maneras. Las matrices se utilizan array_pop -- Extrae el último elemento de la matriz
para guardar, manejar y operar grupos de variables. array_push -- Inserta uno o más elementos al final de la
Matrices simples y multi-dimensionales están soportadas matriz
y pueden ser creadas por el usuario u otras funciones. array_rand -- Pick one or more random entries out of an
Existen funciones específicas de manejo de bases de array
datos que actualizan matrices con el resultado devuelto array_reduce -- Iteratively reduce the array to a single
por la base de datos, numerosas otras funciones value using a callback function
devuelven matrices como resultado. array_reverse -- Devuelve una matriz con los elementos
Consultar la sección del manual Matrices si quereis una en orden inverso
explicación detallada de como las matrices están array_search -- Searches the array for a given value and
implementadas en PHP. returns the corresponding key if successful
array_shift -- Extrae un elemento del comienzo de la
print_r(array_change_key_case($input_array,
matriz
CASE_UPPER));
array_slice -- Extrae una porción de la matriz
array_splice -- Suprime una porción de la matriz y la
sustituye por otra cosa
array_sum -- Calculate the sum of values in an array. The printout of the above program will be:
array_unique -- Removes duplicate values from an array
array_unshift -- Introduce uno o más elementos al
principio de la matriz Array
array_values -- Devuelve todos los valores de una matriz (
array_walk -- Aplica una función del usuario a cada [FIRST] =>
elemento de una matriz. 1
array -- Crear una matriz [SECOND]
arsort -- Ordena una matriz en orden inverso y mantiene => 2
la asociación de índices )
asort -- Ordena una matriz y mantiene la asociación de
índices
compact -- Crea una matriz que contiene variables y sus array_chunk
valores
count -- Cuenta los elementos de una variable
current -- Devuelve el elemento actual de una matriz (PHP 4 >= 4.2.0)
each -- Devuelve el siguiente par clave/valor de una array_chunk -- Split an array into chunks
matriz
end -- Mueve el puntero interno de una tabla al último Description
elemento
extract -- Importa variables a la tabla de símbolos desde
una matriz array array_chunk ( array input, int size [, bool
in_array -- Devuelve TRUE si un valor está en una matriz preserve_keys])
key -- Obtiene una clave de una matriz asociativa
krsort -- Ordena una matriz por clave en orden inverso
ksort -- Ordena una matriz por clave array_chunk() splits the array into several arrays with
list -- Asigna variables como si fueran una matriz size values in them. You may also have an array with less
natcasesort -- Sort an array using a case insensitive values at the end. You get the arrays as members of a
"natural order" algorithm multidimensional array indexed with numbers starting
natsort -- Sort an array using a "natural order" algorithm from zero.
next -- Avanza el puntero interno de una matriz By setting the optional preserve_keys parameter to
pos -- Obtiene el elemento actual de una matriz TRUE, you can force PHP to preserve the original keys
prev -- Rebobina el puntero interno de una matriz from the input array. If you specify FALSE new number
rango -- Crea una matriz que contiene un rango de indices will be used in each resulting array with indices
enteros starting from zero. The default is FALSE.
reset -- Fija el puntero interno de una matriz a su primer Ejemplo 1. array_chunk() example
elemento
rsort -- Ordena una matriz en orden inverso
shuffle -- Mezcla una matriz $input_array = array('a', 'b', 'c',
sizeof -- Obtiene el número de elementos de una matriz 'd', 'e');
sort -- Ordena una matriz print_r(array_chunk($input_array,
uasort -- Ordena una matriz mediante una función de 2));
comparación definida por el usuario y mantiene la print_r(array_chunk($input_array,
asociación de índices 2, TRUE));
uksort -- Ordena una matriz por claves mediante una
función definida por el usuario
usort -- Ordena una matriz por valores mediante una The printout of the above program will be:
funcion definida por el usuario

Array
array_change_key_case
(
[0] =>
(PHP 4 >= 4.2.0) Array
array_change_key_case -- Returns an array with all string (
keys lowercased or uppercased [0]
=> a
[1]
Description => b
)

array array_change_key_case ( array input [, int case]) [1] =>


Array
array_change_key_case() changes the keys in the (
input array to be all lowercase or uppercase. The change [0]
depends on the last optional case parameter. You can => c
pass two constants there, CASE_UPPER and [1]
CASE_LOWER. The default is CASE_LOWER. The => d
function will leave number indices as is. )
Ejemplo 1. array_change_key_case() example
[2] =>
Array
$input_array = array("FirSt" => 1, "SecOnd" (
=> 4); [0]
=> e
Ejemplo 1. array_diff_assoc() example
)

)
Array <?php
( $array1 = array ("a" => "green", "b" => "brown",
[0] => "c" => "blue", "red");
Array $array2 = array ("a" => "green", "yellow", "red");
( $result = array_diff_assoc ($array1, $array2);
[0]
=> a /* The result is:
[1] Array
=> b (
) [b] => brown
[c] => blue
[1] => [0] => red
Array )
( */
[2] ?>
=> c In our example above you see the "a" => "green" pair is
[3] present in both arrays and thus it is not in the ouput from
=> d the function. Unlike this, the pair 0 => "red" is in the
) ouput because in the second argument "red" has key
which is 1.
[2] => Two values from key => value pairs are considered
Array equal only if (string) $elem1 === (string) $elem2 . In
( other words a strict check takes place so the string
[4] representations must be the same.
=> e
)
Nota: Please note that this function
) only checks one dimension of a n-
dimensional array. Of course you can
check deeper dimensions by using,
array_count_values for example,
array_diff_assoc($array1[0],
$array2[0]);.
(PHP 4 )
array_count_values -- Cuenta todos los valores de una
matriz See also array_diff(), array_intersect(), and
array_intersect_assoc().

Descripción
array_diff

array array_count_values ( array entrada)


(PHP 4 >= 4.0.1)
array_diff -- Computes the difference of arrays
array_count_values() devuelve una matriz usando los
valores de la matriz entrada como claves y su frecuencia
de aparición en la entrada como valores. Description
Ejemplo 1. Ejemplo de array_count_values()
array array_diff ( array array1, array array2 [, array ...])
$matriz = array(1, "hola", 1, "mundo", "hola");
array_count_values($matriz); // devuelve array(1=>2, array_diff() returns an array containing all the values of
"hola"=>2, "mundo"=>1) array1 that are not present in any of the other
arguments. Note that keys are preserved.
Ejemplo 1. array_diff() example
Nota: Esta función fue añadida en el
PHP 4.0.
$array1 = array ("a" => "green",
"red", "blue", "red");
array_diff_assoc $array2 = array ("b" => "green",
"yellow", "red");
$result = array_diff ($array1,
(PHP 4 >= 4.3.0)
$array2);
array_diff_assoc -- Computes the difference of arrays
with additional index check This makes $result have array ("blue");. Multiple
occurrences in $array1 are all treated the same way.

Description
Nota: Two elements are considered
equal if and only if (string) $elem1
array array_diff_assoc ( array array1, array array2 [, === (string) $elem2. In words:
array ...]) when the string representation is the
same.
array_diff_assoc() returns an array containing all the
values from array1 that are not present in any of the
Nota: Please note that this function
other arguments. Note that the keys are used in the
only checks one dimension of a n-
comparison unlike array_diff().
dimensional array. Of course you can
check deeper dimensions by using
array_diff($array1[0], $array2[0]);.
$array1 = array ("a"=>1, "b"=>2,
"c"=>3, "d"=>4, "e"=>5);
$array2 = array (6, 7, 8, 9, 10, 11, 12);
Aviso
This was broken in PHP 4.0.4! echo "Odd :\n";
print_r(array_filter($array1, "odd"));
See also array_diff_assoc(), array_intersect() and echo "Even:\n";
array_intersect_assoc(). print_r(array_filter($array2, "even"));

array_fill
The printout of the program above will be:

(PHP 4 >= 4.2.0)


array_fill -- Fill an array with values Odd :
Array
Description (
[a] =>
1
array array_fill ( int start_index, int num, mixed value) [c] =>
3
[e] =>
array_fill() fills an array with num entries of the value of 5
the value parameter, keys starting at the start_index )
parameter. Even:
Ejemplo 1. array_fill() example Array
(
[0] =>
$a = array_fill(5, 6, 6
'banana'); [2] =>
8
[4] =>
$a now has the following entries using print_r(): 10
[6] =>
12
Array )
( Users may not change the array itself from the callback
[5] => function. e.g. Add/delete an element, unset the array
banana that array_filter() is applied to. If the array is changed,
[6] => the behavior of this function is undefined.
banana See also array_map() and array_reduce().
[7] =>
banana
[8] => array_flip
banana
[9] =>
banana (PHP 4 )
[10] => array_flip -- Intercambia los valores de una matriz
banana
)
Descripción

array_filter array array_flip ( array trans)

(PHP 4 >= 4.0.6) array_flip() devuelve una matriz con los valores
array_filter -- Filters elements of an array using a intercambiados.
callback function Ejemplo 1. Ejemplo de array_flip()

Description $trans = array_flip


($trans);
$original = strtr ($str,
array array_filter ( array input [, callback function])
$trans);

array_filter() returns an array containing all the


elements of input filtered according a callback function. If Nota: Esta función fue añadida en el
the input is an associative array the keys are preserved. PHP 4.0.
Ejemplo 1. array_filter() example

array_intersect_assoc
function odd($var) {
return ($var % 2 == 1);
(PHP 4 >= 4.3.0)
}
array_intersect_assoc -- Computes the intersection of
arrays with additional index check
function even($var) {
return ($var % 2 == 0);
} Description
array array_intersect_assoc ( array array1, array Nota: Two elements are considered
array2 [, array ...]) equal if and only if (string) $elem1
=== (string) $elem2. In words:
when the string representation is the
array_intersect_assoc() returns an array containing all
same.
the values of array1 that are present in all the
arguments. Note that the keys are used in the
comparison unlike in array_intersect().
Ejemplo 1. array_intersect_assoc() example Aviso
This was broken in PHP 4.0.4!
See also array_intersect_assoc(), array_diff(),
<?php array_diff_assoc().
$array1 = array ("a" => "green", "b" => "brown",
"c" => "blue", "red");
$array2 = array ("a" => "green", "yellow", "red"); array_key_exists
$result_array = array_intersect_assoc ($array1,
$array2);
(PHP 4 >= 4.1.0)
/* $result_array will look like: array_key_exists -- Checks if the given key or index exists
in the array
Array
(
Description
[a] => green
)
bool array_key_exists ( mixed key, array search)
*/
?>
array_key_exists() returns TRUE if the given key is set
In our example you see that only the pair "a" => "green" in the array. key can be any value possible for an array
is present in both arrays and thus is returned. The value index.
"red" is not returned because in $array1 it's key is 2 Ejemplo 1. array_key_exists() example
while the key of "red" in $array2 it is 1.
The two values from the key => value pairs are
considered equal only if (string) $elem1 === (string)
$search_array = array("first" => 1,
$elem2 . In otherwords a strict type check is executed so
"second" => 4);
the string representation must be the same.
if (array_key_exists("first",
See also array_intersect(), array_diff() and
$search_array)) {
array_diff_assoc().
echo "The 'first' element is in the
array";
array_intersect }

(PHP 4 >= 4.0.1) Nota: The name of this function is


array_intersect -- Computes the intersection of arrays key_exists() in PHP version 4.0.6.

Description See also isset().

array array_intersect ( array array1, array array2 [, array_keys


array ...])

(PHP 4 )
array_intersect() returns an array containing all the
array_keys -- Devuelve todas las claves de una matriz
values of array1 that are present in all the arguments.
Note that keys are preserved.
Ejemplo 1. array_intersect() example Descripción

$array1 = array ("a" => "green", array array_keys ( array entrada [, mixed val_a_buscar])
"red", "blue");
$array2 = array ("b" => "green", array_keys() devuelve las claves, numéricas y de
"yellow", "red"); cadena, de la matriz entrada.
$result = array_intersect ($array1, Si se especifica el parámetro opcional val_a_buscar, sólo
$array2); se devuelven las claves para dicho valor. De otro modo,
se devuelven todas las claves de la entrada.
Ejemplo 1. Ejemplo de array_keys()
This makes $result have

$matriz = array(0 => 100, "color" =>


Array "rojo");
( array_keys ($matriz); // devuelve
[a] => array (0, "color")
green
[0] => $matriz = array(1, 100, 2, 100);
red array_keys ($matriz, 100); // devuelve
) array (0, 2)
Vea también: array_values().
Nota: Esta función fue añadida en el
$b);
PHP 4.0.
print_r($d);
?>
array_map

This results:
(PHP 4 >= 4.0.6)
array_map -- Applies the callback to the elements of the
given arrays // printout of $c
Array
Description (
[0] => The number 1 is called uno
in Spanish
array array_map ( callback function, array arr1 [, array [1] => The number 2 is called dos
arr2...]) in Spanish
[2] => The number 3 is called tres
in Spanish
array_map() returns an array containing all the
[3] => The number 4 is called
elements of arr1 after applying the callback function to
cuatro in Spanish
each one. The number of parameters that the callback
[4] => The number 5 is called
function accepts should match the number of arrays
cinco in Spanish
passed to the array_map()
)
Ejemplo 1. array_map() example
// printout of $d
Array
<?php (
function cube($n) { [0] => Array
return $n*$n*$n; (
} [1] => uno
)
$a = array(1, 2, 3, 4,
5); [1] => Array
$b = (
array_map("cube", [2] => dos
$a); )
print_r($b);
?> [2] => Array
(
[3] => tres
This makes $b have: )

[3] => Array


Array (
( [4] => cuatro
[0] => )
1
[1] => [4] => Array
8 (
[2] => [5] => cinco
27 )
[3] =>
64 )
[4] => Usually when using two or more arrays, they should be of
125 equal length because the callback function is applied in
) parallel to the corresponding elements. If the arrays are
Ejemplo 2. array_map() - using more arrays of unequal length, the shortest one will be extended with
empty elements.
An interesting use of this function is to construct an array
<?php of arrays, which can be easily performed by using NULL
function show_Spanish($n, $m) { as the name of the callback function
return "The number $n is called Ejemplo 3. Creating an array of arrays
$m in Spanish";
}
<?php
function map_Spanish($n, $m) { $a = array(1, 2, 3, 4, 5);
return array ($n => $m); $b = array("one", "two", "three",
} "four", "five");
$c = array("uno", "dos", "tres",
$a = array(1, 2, 3, 4, 5); "cuatro", "cinco");
$b = array("uno", "dos", "tres",
"cuatro", "cinco"); $d = array_map(null, $a, $b, $c);
print_r($d);
$c = array_map("show_Spanish", $a, ?>
$b); The printout of the program above will be:
print_r($c);
Array
$d = array_map("map_Spanish", $a , (
arrays have the same numeric key, the later value will
[0] => Array
not overwrite the original value, but will be appended.
(
Ejemplo 1. array_merge_recursive() example
[0] =>
1
[1] =>
one $ar1 = array ("color" => array ("favorite" =>
[2] => "red"), 5);
uno $ar2 = array (10, "color" => array ("favorite"
) => "green", "blue"));
$result = array_merge_recursive ($ar1, $ar2);
[1] => Array
(
[0] => The $result will be:
2
[1] =>
two Array
[2] => (
dos [color] => Array
) (
[favorite]
[2] => Array => Array
( (
[0] => [0] =>
3 red
[1] => [1] =>
three green
[2] => )
tres
) [0] => blue
)
[3] => Array
( [0] => 5
[0] => [1] => 10
4 )
[1] =>
See also array_merge().
four
[2] =>
cuatro array_merge
)

[4] => Array (PHP 4 )


( array_merge -- Combina dos o más matrices
[0] =>
5
[1] => Descripción
five
[2] => array array_merge ( array matriz1, array matriz2 [, ...])
cinco
)
array_merge() combina los elementos de dos o más
) matrices conjuntamente de modo que los valores de una
son agregados al final de los valores de la anterior.
See also array_filter(), array_reduce(), and Devuelve la matriz resultante.
array_walk(). Si las matrices de entrada tienen las mismas claves de
cadena, el último valor para cada clave reemplazará el
array_merge_recursive valor previo de la misma. Si, por el contrario, las matrices
tienen la misma clave numérica, esto no pasa y los
valores son simplemente agregados.
(PHP 4 >= 4.0.1) Ejemplo 1. Ejemplo de array_merge()
array_merge_recursive -- Merge two or more arrays
recursively
$matriz1 = array ("color" => "rojo", 2, 4);
$matriz2 = array ("a", "b", "color" => "verde",
Description
"forma" => "trapezoide");
array_merge ($matriz1, $matriz2);
array array_merge_recursive ( array array1, array
array2 [, array ...])
La matriz resultante sería array("color" => "verde", 2, 4,
"a", "b", "forma" => "trapezoide").
array_merge_recursive() merges the elements of two
or more arrays together so that the values of one are
appended to the end of the previous one. It returns the Nota: Esta función fue añadida en el
resulting array. PHP 4.0.
If the input arrays have the same string keys, then the
values for these keys are merged together into an array,
and this is done recursively, so that if one of the values is array_multisort
an array itself, the function will merge it with a
corresponding entry in another array too. If, however, the
(PHP 4 )
array_multisort -- Sort multiple or multi-dimensional array_pad -- Rellena una matriz con un valor hasta el
arrays tamaño especificado

Description Descripción

bool array_multisort ( array ar1 [, mixed arg [, mixed ... array array_pad ( array entrada, int tama_relleno, mixed
[, array ...]]]) valor_relleno)

array_multisort() can be used to sort several arrays at array_pad() Devuelve una copia de la entrada rellenada
once or a multi-dimensional array according by one of hasta el tamaño tama_relleno con el valor valor_relleno.
more dimensions. It maintains key association when Si tama_relleno es positivo, entonces la matriz es
sorting. rellenada por la derecha, y si es negativo, por la
The input arrays are treated as columns of a table to be izquierda. Si el valor absoluto de tama_relleno es menor
sorted by rows - this resembles the functionality of SQL o igual que el tamaño de la entrada no se produce
ORDER BY clause. The first array is the primary one to relleno alguno.
sort by. The rows (values) in that array that compare the Ejemplo 1. Ejemplo de array_pad()
same are sorted by the next input array, and so on.
The argument structure of this function is a bit unusual,
but flexible. The very first argument has to be an array. $entrada = array (12, 10, 9);
Subsequently, each argument can be either an array or a
sorting flag from the following lists. $resultado = array_pad ($entrada,
Sorting order flags: 5, 0);
// el resultado es array (12, 10, 9,
0, 0)
• SORT_ASC - sort in ascending order
$resultado = array_pad ($entrada,
• SORT_DESC - sort in descending order
-7, -1);
// el resultado es array (-1, -1, -1,
Sorting type flags: -1, 12, 10, 9)

$resultado = array_pad ($entrada,


2, "no");
• SORT_REGULAR - compare items normally
// no rellenado
• SORT_NUMERIC - compare items numerically
• SORT_STRING - compare items as strings
array_pop

No two sorting flags of the same type can be specified


after each array. The sorting flags specified after an (PHP 4 )
array argument apply only to that array - they are reset array_pop -- Extrae el último elemento de la matriz
to default SORT_ASC and SORT_REGULAR before each
new array argument. Descripción
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
Ejemplo 1. Sorting multiple arrays
mixed array_pop ( array matriz)

$ar1 = array ("10", 100, array_pop() extrae y devuelve el último valor de la


100, "a"); matriz, acortando la matriz en un elemento.
$ar2 = array (1, 3, "2", Ejemplo 1. Ejemplo de array_pop()
1);
array_multisort ($ar1,
$ar2);
$pila = array ("naranja", "manzana",
In this example, after sorting, the first array will contain "frambuesa");
10, "a", 100, 100. The second array will contain 1, 1, "2", $fruta = array_pop ($pila);
3. The entries in the second array corresponding to the
identical entries in the first array (100 and 100) were
sorted as well. Tras esto, $pila contiene sólo 2 elementos: "naranja" y
Ejemplo 2. Sorting multi-dimensional array "manzana", y $fruta contiene "frambuesa".
Vea también: array_push(), array_shift(), y
array_unshift().
$ar = array (array ("10", 100, 100, "a"),
array (1, 3, "2", 1));
array_multisort ($ar[0], SORT_ASC, Nota: Esta función fue añadida en el
SORT_STRING, PHP 4.0.
$ar[1], SORT_NUMERIC,
SORT_DESC);
array_push
In this example, after sorting, the first array will contain
10, 100, 100, "a" (it was sorted as strings in ascending
order), and the second one will contain 1, 3, "2", 1 (PHP 4 )
(sorted as numbers, in descending order). array_push -- Inserta uno o más elementos al final de la
matriz

array_pad
Descripción

(PHP 4 )
int array_push ( array matriz, mixed var [, ...]) array to a single value. If the optional initial is available,
it will be used at the beginning of the process, or as a
final result in case the array is empty.
array_push() considera a la matriz como una pila, e
Ejemplo 1. array_reduce() example
inserta las variables que se le pasan al final de la matriz.
La longitud de la matriz se incrementa en el número de
variables insertadas. Tiene el mismo efecto que ejecutar:
function rsum($v, $w) {
$matriz[] = $v += $w;
$var; return $v;
para cada var. }
Devuelve el nuevo número de elementos de la matriz.
Ejemplo 1. Ejemplo de array_push() function rmul($v, $w) {
$v *= $w;
return $v;
$pila = array (1, }
2);
array_push($pila, $a = array(1, 2, 3, 4, 5);
"+", 3); $x = array();
$b = array_reduce($a,
Este ejemplo dejará $pila conteniendo 4 elementos: 1, 2, "rsum");
"+", y 3. $c = array_reduce($a,
Vea también: array_pop(), array_shift(), y "rmul", 10);
array_unshift(). $d = array_reduce($x,
"rsum", 1);
Nota: Esta función fue añadida en el This will result in $b containing 15, $c containing 1200 (=
PHP 4.0. 1*2*3*4*5*10), and $d containing 1.
See also array_filter() and array_map().

array_rand
array_reverse

(PHP 4 )
array_rand -- Pick one or more random entries out of an (PHP 4 )
array array_reverse -- Devuelve una matriz con los elementos
en orden inverso

Description
Descripción

mixed array_rand ( array input [, int num_req])


array array_reverse ( array matriz)
array_rand() is rather useful when you want to pick one
or more random entries out of an array. It takes an input array_reverse() toma la matriz de entrada y devuelve
array and an optional argument num_req which specifies una nueva matriz con los elementos en orden inverso.
how many entries you want to pick - if not specified, it Ejemplo 1. Ejemplo de array_reverse()
defaults to 1.
If you are picking only one entry, array_rand() returns
the key for a random entry. Otherwise, it returns an array $entrada = array ("php", 4.0, array
of keys for the random entries. This is done so that you ("verde", "rojo"));
can pick random keys as well as values out of the array. $resultado = array_reverse
Don't forget to call srand() to seed the random number ($entrada);
generator.
Esto hace que $resultado contenga array (array ("verde",
Ejemplo 1. array_rand() example
"rojo"), 4.0, "php").

srand ((float) microtime() * 10000000); Nota: Esta función fue añadida en


$input = array ("Neo", "Morpheus", "Trinity", PHP 4.0 Beta 3.
"Cypher", "Tank");
$rand_keys = array_rand ($input, 2);
print $input[$rand_keys[0]]."\n"; array_search
print $input[$rand_keys[1]]."\n";
(PHP 4 >= 4.0.5)
array_search -- Searches the array for a given value and
array_reduce returns the corresponding key if successful

(PHP 4 >= 4.0.5) Description


array_reduce -- Iteratively reduce the array to a single
value using a callback function
mixed array_search ( mixed needle, array haystack [,
bool strict])
Description

Searches haystack for needle and returns the key if it is


mixed array_reduce ( array input, callback function [, found in the array, FALSE otherwise.
int initial])

Nota: Prior to PHP 4.2.0,


array_reduce() applies iteratively the function function array_search() returns NULL on
to the elements of the array input, so as to reduce the failure instead of FALSE.
If the optional third parameter strict is set to TRUE then
$salida = array_slice ($entrada, 2, -1); //
the array_search() will also check the types of the
devuelve "c", "d"
needle in the haystack.
$salida = array_slice ($entrada, -2, 1); //
Aviso devuelve "d"
$salida = array_slice ($entrada, 0, 3); //
Esta función puede devolver el Boolean FALSE, pero
devuelve "a", "b", y "c"
también puede devolver un valor no-Boolean que será
evaluado FALSE, como por ejemplo 0 o "". Por favor, lea la Vea también: array_splice().
sección Booleans para más información. Utilice el operador
=== para comprobar el valor devuelto por esta función.
Nota: Esta función fue añadida en el
See also array_keys() and in_array(). PHP 4.0.

array_shift array_splice

(PHP 4 ) (PHP 4 )
array_shift -- Extrae un elemento del comienzo de la array_splice -- Suprime una porción de la matriz y la
matriz sustituye por otra cosa

Descripción Descripción

mixed array_shift ( array matriz) array array_splice ( array entrada, int desplazamiento [,
int tamano [, array sustitucion]])
array_shift() extrae el primer valor de la matriz y lo
devuele, acortando la matriz en un elemnto y moviendo array_splice() suprime los elementos designados por el
todo hacia arriba. desplazamiento y el tamano de la matriz entrada, y los
Ejemplo 1. Ejemplo de array_shift() sustituye con los elementos de la matriz de sustitucion si
se especifica.
Si el desplazamiento es positivo, el comienzo de la parte
$args = array ("-v", "- suprimida sería en esa posición desde el comienzo de la
f"); matriz de entrada. Si el desplazamiento es negativo, se
$opcion = array_shift cuenta la posición desde el final de la matriz de entrada.
($args); Si se omite tamano, se suprime todo desde el
Esto da como resultado que $args tenga como elemento desplazamiento hasta el final de la matriz. Si se
restante "-f" y que $opcion valga "-v". especifica el tamano y es positivo, se suprimirán tantos
Vea también: array_unshift(), array_push(), y elementos como se especifica. Si fuera negativo, el final
array_pop(). de la porción eliminada estará a tantos elementos del
final de la matriz. Truco: para eliminar todo desde el
desplazamiento hasta el final de la matriz cuando
Nota: Esta función fue añadida en el también se especifica sustitucion, utilice count($entrada)
PHP 4.0. como tamano.
Si se especifia la matriz de sustitucion, entonces los
elementos suprimidos son reemplazados con los
array_slice elementos de dicha matriz. Si los valores de
desplazamiento y tamano son tales que nada es borrado,
los elementos de la matriz sustitucion se insertarán en la
(PHP 4 )
posición indicada por el desplazamiento. Truco: si sólo se
array_slice -- Extrae una porción de la matriz
va a sustituir algo por un elemento nada más, no hace
falta poner array() alrededor del mismo, salvo que dicho
Descripción elemento sea una matriz en sí mismo.
Las siguientes funciones son equivalentes:
array_push($entrada, $x, $y) array_splice($entrada,
array array_slice ( array matriz, int desplazamiento [, int
count($entrada), 0, array($x, $y))
tamano])
array_pop($entrada) array_splice($entrada, -1)
array_shift($entrada) array_splice($entrada, 0, 1)
array_slice() devuelve una secuencia de elementos de array_unshift($entrada, $x, $y) array_splice($entrada, 0,
la matriz especificada por los parámetros 0, array($x, $y))
desplazamiento y tamano. $a[$x] = $y array_splice($entrada, $x, 1, $y)
Si el desplazamiento es positivo, la secuencia comenzará
Devuelve una matriz que tiene los elementos eliminados
en dicha posición de la matriz. Si el desplazamiento es
Ejemplo 1. Ejemplos de array_splice()
negativo, la secuencia comenzará en esa posición desde
el final de la matriz.
Si se especifica el tamano y éste es positivo, la secuencia
contendrá tantos elementos como se diga en él. Si fuese $entrada = array("rojo", "verde", "azul", "amarillo");
negativo, la secuencia se detendrá a tantos elementos
del final de la matriz. Si se omite, la secuencia contendrá array_splice($entrada, 2); // $entrada vale ahora
todos los elementos desde el desplazamiento hasta el array("rojo", "verde")
final de la matriz. array_splice($entrada, 1, -1); // $entrada vale ahora
Ejemplo 1. Ejemplo de array_slice() examples array("rojo", "amarillo")
array_splice($entrada, 1, count($entrada), "naranja");
// $entrada vale ahora array("rojo",
"naranja")
$entrada = array ("a", "b", "c", "d", "e");
array_splice($entrada, -1, 1, array("negro", "marrón"));
// $entrada vale ahora array("rojo",
$salida = array_slice ($entrada, 2); //
"verde",
devuelve "c", "d", y "e"
// "azul", "negro", "marrón")
Vea también: array_slice(). Aviso
This was broken in PHP 4.0.4!
Nota: Esta función fue añadida en el
PHP 4.0. Ejemplo 1. array_unique() example

array_sum $input = array ("a" => "green", "red", "b" =>


"green", "blue", "red");
$result = array_unique ($input);
(PHP 4 >= 4.0.4) print_r($result);
array_sum -- Calculate the sum of values in an array.

Description This will output:

mixed array_sum ( array array) Array


(
array_sum() returns the sum of values in an array as an [b] =>
integer or float. green
Ejemplo 1. array_sum() examples [1] =>
blue
[2] =>
$a = array(2, 4, 6, 8); red
echo "sum(a) = )
".array_sum($a)."\n"; Ejemplo 2. array_unique() and types

$b =
array("a"=>1.2,"b"=>2.3,"c" $input = array
=>3.4); (4,"4","3",4,3,"3");
echo "sum(b) = $result = array_unique
".array_sum($b)."\n"; ($input);
var_dump($result);

The printout of the program above will be:


The printout of the program above will be (PHP 4.0.6):

sum(a) =
20 array(2
sum(b) = ){
6.9 [3]=>
int(4)
[4]=>
Nota: PHP versions prior to 4.0.6 int(3)
modified the passed array itself and }
converted strings to numbers (which
most of the time converted them to
zero, depending on their value). array_unshift

array_unique (PHP 4 )
array_unshift -- Introduce uno o más elementos al
principio de la matriz
(PHP 4 >= 4.0.1)
array_unique -- Removes duplicate values from an array
Descripción
Description
int array_unshift ( array matriz, mixed var [, ...])
array array_unique ( array array)
array_unshift() añade los elementos que se le pasan al
principio de la matriz. Nótese que la lista de elementos
array_unique() takes input array and returns a new
es añadida como un todo, de modo que los elementos
array without duplicate values.
añadidos mantienen su orden.
Note that keys are preserved. array_unique() sorts the
Devuelve el número de elementos en la matriz.
values treated as string at first, then will keep the first
Ejemplo 1. Ejemplo de array_unshift()
key encountered for every value, and ignore all following
keys. It does not mean that the key of the first related
value from the unsorted array will be kept.
$cola = array("p1", "p3");
array_unshift($cola, "p4",
Nota: Two elements are considered "p5", "p6");
equal if and only if (string) $elem1
Esto hará que $cola contenga 5 elementos: "p4", "p5",
=== (string) $elem2. In words:
"p6", "p1", y "p3".
when the string representation is the
Vea también: array_shift(), array_push(), y
same.
array_pop().

The first element will be used.


Nota: Esta función fue añadida en el
$frutas = array ("d"=>"limón", "a"=>"naranja",
PHP 4.0.
"b"=>"plátano", "c"=>"manzana");

array_values function test_alterar (&$item1, $clave, $prefix) {


$item1 = "$prefix: $item1";
}
(PHP 4 )
array_values -- Devuelve todos los valores de una matriz function test_ver ($item2, $clave) {
echo "$clave. $item2<br>\n";
}
Descripción
array_walk ($frutas, 'test_ver');
array array_values ( array entrada) reset ($frutas);
array_walk ($frutas, 'test_alterar', 'fruta');
reset ($frutas);
array_values() devuelve todos los valores de la matriz array_walk ($frutas, 'test_ver');
entrada.
Ejemplo 1. Ejemplo de array_values() Vea también: each() y list().

array
$matriz = array("talla" => "XL", "color"
=> "dorado");
array_values($matriz); // devuelve (PHP 3, PHP 4 )
array("XL", "dorado") array -- Crear una matriz

Descripción
Nota: Esta función fue añadida en el
PHP 4.0.
array array ( mixed ...)
array_walk
Devuelve una matriz con los parámetros que se le pasan.
A dichos parámetros se les puede dar un índice usando el
(PHP 3>= 3.0.3, PHP 4 ) operador =>.
array_walk -- Aplica una función del usuario a cada
elemento de una matriz.
Nota: array() es una construcción
del lenguaje que se utiliza para
Descripción representar matrices literales, no
una función regular.
int array_walk ( array matriz, string func, mixed
datosvarios) El siguiente ejemplo demuestra cómo crear una matriz
bidimensional, cómo especificar claves para matrices
Aplica la función llamada func a cada elemento de la asociativas, y cómo especificar índices no consecutivos
matriz. La función func recibirá el valor de la matriz como en matrices normales.
primer parámetro y la clave como segundo. Si se Ejemplo 1. Ejemplo de array()
proporciona el parámetro datosvarios será pasado como
tercer parámetro a la función de usuario.
Si func necesita más de dos o 3 argumentos, $frutas = array (
dependiendo de datosvarios, se generará un aviso cada "frutas" => array("a"=>"naranja",
vez que array_walk() llama a func. Estos avisos pueden "b"=>"plátano", "c"=>"manzana"),
suprimirse si se pone '@' antes de la llamada a "números" => array(1, 2, 3, 4, 5, 6),
array_walk(), o usando la función error_reporting(). "hoyos" => array("primero", 5 => "segundo",
"tercero")
);
Nota: Si func precisa trabajar con
Vea también: list().
los valores reales de la matriz,
especifique que el valor del primer
parámetro de func debe pasarse por arsort
referencia. Desde ese instante, los
cambios realizados sobre dichos
elementos también serán realizados (PHP 3, PHP 4 )
en la propia matriz. arsort -- Ordena una matriz en orden inverso y mantiene
la asociación de índices
Nota: El pasar la clave y los datos
de usuario a func fue una Descripción
característica añadida en PHP 4.0.

void arsort ( array matriz)


En PHP 4 se debe llamar reset() las
veces necesarias, pues
Esta función ordena una matriz de modo que los índices
array_walk() no reajusta la matriz
mantengan su correlación con los elementos de la misma
por defecto.
a los que están asociados. Esto se utiliza principalmente
para ordenar matrices asociativas en las que el orden de
Ejemplo 1. Ejemplo de array_walk() los elementos es importante.
Ejemplo 1. Ejemplo de arsort()
$frutas = array ("d"=>"limón", "a"=>"naranja", $ciudad = "San Francisco";
"b"=>"plátano", "c"=>"manzana"); $estado = "CA";
arsort ($frutas); $evento = "SIGGRAPH";
for (reset ($frutas); $clave = key ($frutas); next
($frutas)) { $location_vars = array ("ciudad",
echo "frutas[$clave] = ".$frutas[$clave]."\n"; "estado");
}
$resultado = compact ("evento",
Este ejemplo mostraría: frutas[b] = plátano frutas[a] =
$location_vars);
naranja frutas[c] = manzana frutas[d] = limón Las frutas
han sido ordenadas en orden alfabético inverso y los
índices asociados con cada elemento se han mantenido.
Vea también: asort(), rsort(), ksort(), y sort(). Tras esto, $resultado valdrá array ("evento" =>
"SIGGRAPH", "ciudad" => "San Francisco", "estado" =>
"CA").
asort Vea también: extract().

(PHP 3, PHP 4 ) Nota: Esta función fue añadida en el


asort -- Ordena una matriz y mantiene la asociación de PHP 4.0.
índices

count
Descripción

(PHP 3, PHP 4 )
void asort ( array matriz) count -- Cuenta los elementos de una variable

Esta función ordena una matriz de modo que los índices Descripción
mantengan su correlación con los elementos de la misma
a los que están asociados. Esto se utiliza principalmente
para ordenar matrices asociativas en las que el orden de int count ( mixed var)
los elementos es importante.
Ejemplo 1. Ejemplo de asort()
Devuelve el número de elementos en var, que
típicamente es una matriz (porque cualquier otra cosa
tendría sólo un elemento).
$frutas = array ("d"=>"limón", "a"=>"naranja", Devuele 1 si la variable no es una matriz.
"b"=>"plátano", "c"=>"manzana"); Devuelve 0 si la variable no tiene valor.
asort ($frutas);
for (reset ($frutas); $clave = key ($frutas); next Aviso
($frutas)) { count() puede devolver 0 para una variable sin valor, pero
echo "frutas[$clave] = ".$frutas[$clave]."\n"; también puede devolver 0 para una variable ya inicializada
} pero con una matriz vacía. Utilice isset() para comprobar
Este ejemplo mostrará: frutas[d] = limón frutas[a] = si una variable está inicializada.
naranja frutas[c] = manzana frutas[d] = plátano Las Vea también: sizeof(), isset(), y is_array().
frutas han sido ordenadas en orden alfabético y los
índices asociados con cada elemento se han mantenido.
Vea también: arsort(), rsort(), ksort(), y sort(). current

compact (PHP 3, PHP 4 )


current -- Devuelve el elemento actual de una matriz

(PHP 4 )
compact -- Crea una matriz que contiene variables y sus Descripción
valores
mixed current ( array matriz)
Descripción
Cada matriz tiene un puntero interno al elemento
array compact ( string nombrevar | array nombrevars "actual", que se inicializa al primer elemento insertado
[, ...]) en la misma.
La función current() simplemente devuelve el elemento
de la tabla al que apunta el puntero interno. No mueve el
compact() toma un número variable de parámetros. puntero de ninguna manera. Si el puntero interno apunta
Cada uno puede ser tanto una cadena que contiene el fuera del final de la lista de elementos, current()
nombre de la variable, como una matriz de nombres de devuelve FALSE.
variable. La matriz puede contener otras matrices de
Aviso
nombres de variable en su interior; compact() los
procesa recursivamente. Si la matriz contiene elementos vacíos (0 ó "", la cadena
Para cada uno de estos, compact() busca una variable vacía) esta función devolverá FALSE también para dichos
con dicho nombre en la tabla de símbolos y la añade a la elementos. Esto hace imposible determinar si se está
matriz de salida de modo que el nombre de la variable es realmente al final de la lista en tales matrices usando
la clave y el contenido de ésta es el valor para dicha current(). Para recorrer adecuadamente una matriz que
clave. Para resumir, hace lo contrario de extract(). pueda contener elementos vacíos, utilice la función each().
Devuelve la matriz de salida con las variables añadidas a
Vea también: end(), next(), prev() y reset().
la misma.
Ejemplo 1. Ejemplo de compact()
each
(PHP 3, PHP 4 ) Descripción
each -- Devuelve el siguiente par clave/valor de una
matriz
end ( array matriz)

Descripción
end() avanza el puntero interno de la matriz al último
elemento.
array each ( array matriz) Vea también: current(), each(), end(), next(), y
reset().

Devuelve el par clave/valor actual para la matriz y


avanza el cursor de la misma. Esta pareja se devuele en extract
una matriz de 4 elementos, con las claves 0, 1, key, y
value. Los elementos 0 y key contienen el nombre de
clave del elemento de la matriz, y 1 y value contienen los (PHP 3>= 3.0.7, PHP 4 )
datos. extract -- Importa variables a la tabla de símbolos desde
Si el puntero interno para la matriz apunta pasado el una matriz
final del contenido de la matriz, each() devuelve FALSE.
Ejemplo 1. Ejemplos de each()
Descripción

$chorrada = array ("bob", "fred", "jussi", "jouni", void extract ( array matriz_vars [, int tipo_extraccion [,
"egon", "marliese"); string prefijo]])
$tonteria = each ($chorrada);
Esta función se utiliza para importar variables desde una
matriz a la tabla de símbolos actual. Toma la matriz
$tonteria contiene ahora los siguientes pares clave/valor: asoiativa matriz_vars y trata las claves como nombres de
variable y los valores como los valores de éstas. Para
cada par clave/valor creará una variable en la tabla de
• 0 => 0 símbolos actual, sujeto a los parámetros tipo_extraccion
• 1 => 'bob' y prefijo.
extract() controla las colisiones con las variables que ya
• key => 0 existen. La forma de tratar éstas se determina por el
• value => 'bob'
tipo_extraccion. Puede tener únicamente uno de los
siguientes valores:
EXTR_OVERWRITE
Si hay colisión, sobreescribe la variable
$chorrada = array ("Robert" => "Bob", existente.
"Seppo" => "Sepi"); EXTR_SKIP
$tonteria = each ($chorrada); Si hay colisión, no sobreescribas la variable
$tonteria contiene ahora los siguientes pares clave/valor: existente.
EXTR_PREFIX_SAME
Si hay una colisión, añade el prefijo a la nueva
• 0 => 'Robert' variable.
EXTR_PREFIX_ALL
• 1 => 'Bob' Añade el prefijo a todas las variables.
• key => 'Robert' Si no se especifica tipo_extraccion, se asume que vale
EXTR_OVERWRITE.
Nótese que el prefijo sólo se necisita si tipo_extraccion
vale EXTR_PREFIX_SAME o EXTR_PREFIX_ALL.
• value => 'Bob' extract() comprueba si cada clave es un nombre válido
each() se usa normalmente de forma conjunta a list() de variable, y sólo lo importa si lo es.
para recorrer una matriz; por ejemplo,
$HTTP_POST_VARS:
Ejemplo 2. Recorriendo $HTTP_POST_VARS con Nota: N.T.: En el caso español, no
each() valdría "año" como nombre variable
(pero sí como clave en una matriz
cualquiera).
echo "Valores enviados con el método
POST:<br>";
reset ($HTTP_POST_VARS); Un uso posible para extract sería importar en la tabla de
while (list ($clave, $val) = each símbolos las variables contenidas en la matriz asociativa
($HTTP_POST_VARS)) { que devuelve wddx_deserialize().
echo "$clave => $val<br>"; Ejemplo 1. Ejemplo de extract()
}
Cuando se ha ejecutado each(), el cursor de la matriz <php?
quedará en el siguiente elemento de la misma, o en el
último si llega al final de ésta. /* Suponemos que $matriz_var es una
Vea también: key(), list(), current(), reset(), next(), y matriz devuelta por
prev(). wddx_deserialize */

end $tamano = "grande";


$matriz_var = array ("color" => "azul",
"tamano" => "media",
(PHP 3, PHP 4 ) "forma" => "esfera");
end -- Mueve el puntero interno de una tabla al último extract ($matriz_var, EXTR_PREFIX_SAME,
elemento "wddx");
print "$color, $tamano, $forma, $frutas = array ("d"=>"limón", "a"=>"naranja",
$wddx_tamano\n"; "b"=>"plátano", "c"=>"manzana");
krsort ($frutas);
?> for (reset ($frutas); $clave = key ($frutas); next
($frutas)) {
El programa anterior producirá:
echo "frutas[$clave] = ".$frutas[$clave]."\n";
azul, grande, esfera, }
media
Este ejemplo mostrará: frutas[d] = limón frutas[c] =
La variable $tamano no fue sobreescrita porque manzana frutas[b] = plátano frutas[a] = naranja
especificamos EXTR_PREFIX_SAME, que provocó la Vea también: asort(), arsort(), ksort() sort(), y
creación de $wddx_tamano. Si se hubiera especificado rsort().
EXTR_SKIP, $wddx_tamano ni siquiera habría sido
creada. EXTR_OVERWRITE habría provocado que
$tamano tuviera el valor "media", y EXTR_PREFIX_ALL ksort
habría provocado que aparecieran nuevas variables
llamadas $wddx_color, $wddx_tamano, y $wddx_forma.
(PHP 3, PHP 4 )
ksort -- Ordena una matriz por clave
in_array
Descripción
(PHP 4 )
in_array -- Devuelve TRUE si un valor está en una matriz
int ksort ( array matriz)

Descripción Ordena una matriz por clave, manteniendo las


correlaciones clave a dato. Esto es útil principalmente en
matrices asociativas.
bool in_array ( mixed aguja, array pajar)
Ejemplo 1. Ejemplo de ksort()

Busca la aguja en el pajar, y devuelve TRUE si se


encuentra y FALSE en caso contrario. $frutas = array ("d"=>"limón", "a"=>"naranja",
Ejemplo 1. Ejemplo de in_array() "b"=>"plátano", "c"=>"manzana");
ksort ($frutas);
for (reset ($frutas); $clave = key ($frutas); next
$os = array ("Mac", "NT", ($frutas)) {
"Irix", "Linux"); echo "frutas[$clave] = ".$frutas[$clave]."\n";
if (in_array ("Irix", $os)) }
print "Encontrado Irix";
Este ejemplo mostrará: frutas[a] = naranja frutas[b] =
plátano frutas[c] = manzana frutas[d] = limón
Vea también: asort(), arsort(), sort(), y rsort().
Nota: Esta función fue añadida en el
PHP 4.0.
list
key
(PHP 3, PHP 4 )
list -- Asigna variables como si fueran una matriz
(PHP 3, PHP 4 )
key -- Obtiene una clave de una matriz asociativa
Descripción
Descripción
void list ( mixed ...)
mixed key ( array matriz)
Como array(), esta no es realmente una función, sino
una construcción del lenguaje. list() se usa para asignar
key() devuelve el elemento índice de la posición actual una lista de variables en una sola operación.
en la matriz. Ejemplo 1. Ejemplo de list()
Vea también: current(), next()

krsort <table>
<tr>
<th>Nombre empleado</th>
(PHP 3>= 3.0.13, PHP 4 ) <th>Sueldo</th>
krsort -- Ordena una matriz por clave en orden inverso </tr>

<?php
Descripción
$resultado = mysql($conn, "SELECT id, nombre,
int krsort ( array matriz) salario FROM empleados");
while (list($id, $nombre, $salario) =
mysql_fetch_row($resultado)) {
Ordena una matriz por clave en orden inverso, print(" <tr>\n".
manteniendo las correlaciones clave a dato. Esto es útil " <td><a href=\"info.php3?
principalmente en matrices asociativas. id=$id\">$nombre</a></td>\n".
Ejemplo 1. Ejemplo de krsort() " <td>$salario</td>\n".
" </tr>\n");
} [3] =>
img2.png
?> )

</table> Natural order


sorting
Vea también: each(), array().
Array
(
natcasesort [3] =>
img1.png
[2] =>
(PHP 4 ) img2.png
natcasesort -- Sort an array using a case insensitive [1] =>
"natural order" algorithm img10.png
[0] =>
img12.png
Description )
For more information see: Martin Pool's Natural Order
void natcasesort ( array array) String Comparison page.

This function implements a sort algorithm that orders Nota: If you're wanting to maintain
alphanumeric strings in the way a human being would. index/value associations, consider
This is described as a "natural ordering". using usort($arr, 'strnatcmp').
natcasesort() is a case insensitive version of natsort().
See natsort() for an example of the difference between
this algorithm and the regular computer string sorting See also natcasesort(), strnatcmp(), and
algorithms. strnatcasecmp().
For more information see: Martin Pool's Natural Order
String Comparison page.
See also sort(), natsort(), strnatcmp(), and next
strnatcasecmp().
(PHP 3, PHP 4 )
natsort next -- Avanza el puntero interno de una matriz

(PHP 4 ) Descripción
natsort -- Sort an array using a "natural order" algorithm
mixed next ( array matriz)
Description
Devuelve el elemento de la matriz que ocupa el lugar
siguiente al apuntado por el puntero interno, o FALSE si
void natsort ( array array)
no hay más elementos.
next() se comporta como current(), con una diferencia.
This function implements a sort algorithm that orders Avanza el puntero interno de la matriz en una posición
alphanumeric strings in the way a human being would. antes de devolver el elemento. Eso significa que
This is described as a "natural ordering". An example of devuelve el siguiente elemento de la matriz y que
the difference between this algorithm and the regular avanza el puntero interno en uno. Si al avanzar se pasa
computer string sorting algorithms (used in sort()) can del final de la lista de elementos, next() devuelve
be seen below: FALSE.
Ejemplo 1. natsort() example
Aviso
Si la matriz contiene elementos vacíos, esta función
<?php también devolverá FALSE para dichos elementos. Para
$array1 = $array2 = array ("img12.png", "img10.png", recorrer adecuadamente una matriz que pueda contener
"img2.png", "img1.png"); elementos vacíos, vea la función each().
Vea también: current(), end() prev() y reset()
sort($array1);
echo "Standard sorting\n";
print_r($array1); pos

natsort($array2);
echo "\nNatural order sorting\n"; (PHP 3, PHP 4 )
print_r($array2); pos -- Obtiene el elemento actual de una matriz
?>
The code above will generate the following output: Descripción
Standard
sorting mixed pos ( array matriz)
Array
(
[0] => Este es un alias para current().
img1.png Vea también: end(), next(), prev() y reset().
[1] =>
img10.png prev
[2] =>
img12.png
(PHP 3, PHP 4 )
$frutas = array ("limón", "naranja",
prev -- Rebobina el puntero interno de una matriz
"plátano", "manzana");
rsort ($frutas);
Descripción for (reset ($frutas); list ($clave, $valor) =
each ($frutas); ) {
echo "frutas[$clave] = ", $valor, "\n";
mixed prev ( array matriz) }
Este ejemplo mostrará: frutas[0] = plátano frutas[1] =
Devuelve el elemento de la matriz que está en la naranja frutas[2] = manzana frutas[3] = limón Las frutas
posición anterior a la que apuntaba previamente el han sido ordenadas en orden alfabético inverso.
puntero interno, o FALSE si no hay más elementos. Vea también: arsort(), asort(), ksort(), sort(), y
Aviso usort().

Si la matriz contiene elementos vacíos, esta función


también devolverá FALSE para dichos elementos. Para shuffle
recorrer adecuadamente una matriz que puede contener
elementos vacíos, vea la función each().
(PHP 3>= 3.0.8, PHP 4 )
prev() se comporta igual que next(), excepto que shuffle -- Mezcla una matriz
rebobina el puntero interno una posición en lugar de
avanzarlo.
Vea también: current(), end() next() y reset() Descripción

rango void shuffle ( array matriz)

(no version information, might be only in CVS) Esta función mezcla (cambia aleatoriamente el orden de
rango -- Crea una matriz que contiene un rango de los elementos de) una matriz.
enteros Ejemplo 1. Ejemplo de shuffle()

Descripción $numeros = range (1,20);


srand (time());
shuffle ($numeros);
array rango ( int bajo, int alto) while (list(, $numero) = each
($numeros)) {
rango() devuelve una matriz de enteros desde bajo echo "$numero ";
hasta alto, ambos inclusive. }
Vea un ejemplo de su uso en la función shuffle(). Vea también: arsort(), asort(), ksort(), rsort(), sort()
y usort().
reset
sizeof
(PHP 3, PHP 4 )
reset -- Fija el puntero interno de una matriz a su primer (PHP 3, PHP 4 )
elemento sizeof -- Obtiene el número de elementos de una matriz

Descripción Descripción

mixed reset ( array matriz) int sizeof ( array matriz)

reset() rebobina el puntero interno de la matriz a su Devueve el número de elementos de la matriz.


primer elemento. Vea también: count()
reset() devuelve el valor del primer elemento de la
matriz.
Vea también: current(), each(), next(), prev(), y sort
reset().

(PHP 3, PHP 4 )
rsort sort -- Ordena una matriz

(PHP 3, PHP 4 ) Descripción


rsort -- Ordena una matriz en orden inverso

void sort ( array matriz)


Descripción
Esta función ordena una matriz. Los elementos estarán
void rsort ( array matriz) ordenados de menor a mayor cuando la función termine.
Ejemplo 1. Ejemplo de sort()
Esta función ordena una matriz en orden inverso (mayor
a menor).
$frutas = array ("limón", "naranja",
Ejemplo 1. Ejemplo de rsort()
"plátano", "manzana");
sort ($frutas);
for (reset ($frutas); $clave = key ($frutas);
void usort ( array matriz, function func_comparar)
next ($frutas)) {
echo "frutas[$clave] = ".
$frutas[$clave]."\n"; Esta función ordenará una matriz por sus valores
} utilizando una función suministrada por el usuario. Si la
matriz que desea ordenar necesita utilizar un criterio
Este ejemplo mostrará: frutas[0] = limón frutas[1] =
poco trivial, esta es la función que deberá usar.
manzana frutas[2] = naranja frutas[3] = plátano Las
La función de comparación deberá devolver un entero
frutas han sido ordenadas en orden alfabético.
menor, igual, o mayor que cero, si el primer argumento
Vea también: arsort(), asort(), ksort(), rsort(), y
se considera respectivamente menor que, igual que, o
usort().
mayor que el segundo. Si dos miembros resultan ser
iguales, su orden en la matriz ordenada será cualquiera.
uasort Ejemplo 1. Ejemplo de usort()

(PHP 3>= 3.0.4, PHP 4 ) function cmp ($a, $b) {


uasort -- Ordena una matriz mediante una función de if ($a == $b) return 0;
comparación definida por el usuario y mantiene la return ($a > $b) ? -1 : 1;
asociación de índices }
$a = array (3, 2, 5, 6, 1);
usort ($a, cmp);
Descripción
while (list ($clave, $valor) =
each ($a)) {
void uasort ( array matriz, function func_comparar) echo "$clave: $valor\n";
}
Esta función ordena una matriz de modo que los índices Este ejemplo mostrará: 0: 6 1: 5 2: 3 3: 2 4: 1
de la misma mantengan su correlación con los elementos
a los que están asociados. Esto se utiliza principalmente
Nota: Obviamente en este caso
para ordenar matrices asociativas en las que el orden de
trivial la función rsort() habría sido
los elementos es importante. La función de comparación
más apropiada.
viene definida por el usuario.

uksort Aviso
La función quicksort subyacente en ciertas librerías de C
(PHP 3>= 3.0.4, PHP 4 ) (tales como las de Solaris) pueden hacer que el PHP falle si
uksort -- Ordena una matriz por claves mediante una la función de comparación no devuelve valores
función definida por el usuario consistentes.
Vea también: arsort(), asort(), ksort(), rsort() y
sort().
Descripción

III. Funciones Aspell [deprecated]


void uksort ( array matriz, function func_comparar)

Esta función ordenará las claves de una matriz utilizando Introducción


una función de comparación suministrada por el usuario.
Si la matriz a ordenar necesita utilizar un criterio poco La función aspell() permite comprobar la ortografía de
trivial, esta es la función que deberá usar. una palabra y ofrece alternativas a la misma.
Ejemplo 1. Ejemplo de uksort()

Requerimientos
function micomparar ($a, $b) {
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1; aspell funciona solamente con versiones muy antiguas
} (hasta la .27.* mas ó menos) de la biblioteca aspell. Ni
$a = array (4 => "cuatro", 3 => "tres", 20 => este módulo ni las versiones de la biblioteca aspell se
"veinte", 10 => "diez"); soportan actualmente. Si quereis utilizar capacidades de
uksort ($a, micomparar); comprobación ortográfica en php, usar pspell. Utiliza la
while (list ($clave, $valor) = each ($a)) { biblioteca pspell y funciona con versiones recientes de
echo "$clave: $valor\n"; aspell.
}
Este ejemplo mostrará: 20: veinte 10: diez 4: cuatro 3: Instalación
tres
Vea también: arsort(), asort(), uasort(), ksort(),
rsort(), y sort(). Necesitais la biblioteca aspell disponible en:
http://aspell.sourceforge.net/.
usort
Ver tambien
(PHP 3>= 3.0.3, PHP 4 )
usort -- Ordena una matriz por valores mediante una Ver tambien pspell.
funcion definida por el usuario Tabla de contenidos
aspell_check-raw -- Comprueba una palabra sin
cambiarla ó intentar arreglarla [deprecated]
Descripción
aspell_check -- Comprueba una palabra[deprecated]
aspell_new -- Lee un nuevo diccionario [deprecated]
aspell_suggest -- Sugiere la ortografía para una palabra aspell_new() Abre un nuevo diccionario devolviendo el
[deprecated] identificador de este para ser utilizado en otras funciones
ortográficas.
Ejemplo 1. Nuevo_diccionario
aspell_check-raw

(PHP 3>= 3.0.7, PHP 4 <= 4.2.3) $aspell_link =


aspell_check-raw -- Comprueba una palabra sin aspell_new("english");
cambiarla ó intentar arreglarla [deprecated]

aspell_suggest
Descripción

(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)


boolean aspell_check_raw ( int dictionary_link, string aspell_suggest -- Sugiere la ortografía para una palabra
word) [deprecated]

aspell_check_raw() comprueba la ortografía de una


Descripción
palabra,sin cambiarla ni intentar arreglarla esté bien o
mal. Si está bien, devuelve cierto (TRUE), si no lo está,
devuelve falso(FALSE). array aspell_suggest ( int dictionary_link, string word)
Ejemplo 1. aspell_check_raw
aspell_suggest() devuelve una matriz con posibles
correciones ortográficas para la palabra dada.
$aspell_link =
Ejemplo 1. aspell_suggest
aspell_new("english");

if
(aspell_check_raw($aspell_link, $aspell_link = aspell_new("english");
"test")) {
echo "This is a valid if (!aspell_check($aspell_link, "test")) {
spelling"; $suggestions =
} else { aspell_suggest($aspell_link, "test");
echo "Sorry, wrong spelling";
} foreach ($suggestions as
$suggestion) {
echo "Possible spelling:
$suggestion<br>\n";
aspell_check
}
}
(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)
aspell_check -- Comprueba una palabra[deprecated]
IV. Funciones matemáticas de precisión arbitraria
BCMath
Descripción

Introducción
boolean aspell_check ( int dictionary_link, string word)

Para operaciones matemáticas de precisión arbitraria,


aspell_check() comprueba la ortografía de una palabra,
PHP tiene disponible la Calculadora Binaria que soporta
y devuelve cierto(TRUE) si la ortografía es correcta ,falso
números de cualquier tamaño y precisión, representados
(FALSE) si no lo es .
como cadenas de texto.
Ejemplo 1. aspell_check

Requerimientos
$aspell_link =
aspell_new("english");
Desde PHP 4.0.4, libbcmath se encuentra incorporada en
if (aspell_check($aspell_link, PHP. No se necesitan bibliotecas externas para esta
"testt")) { extensión.
echo "This is a valid
spelling";
} else { Instalación
echo "Sorry, wrong
spelling";
En PHP 4, estas funciones están disponibles solamente si
}
PHP ha sido configurado con --enable-bcmath en PHP 3,
estas funciones están disponibles solamente si PHP no ha
sido configurado con --disable-bcmath.
aspell_new

Configuración en tiempo de ejecución


(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)
aspell_new -- Lee un nuevo diccionario [deprecated]
Esta extensión no define ninguna directiva de
configuración.
Descripción

int aspell_new ( string master, string personal) Tipos de recursos


Esta extensión no define ningún tipo de recurso. Divide el operando izq por el operando der y devuelve el
resultado. El parámetro opcional escala fija el número de
dígitos tras el punto decimal a usar en el resultado.
Constantes predefinidas Ver también bcmul().

Esta extensión no define ninguna constante. bcmod


Tabla de contenidos
bcadd -- Suma dos números de precisión arbitriaria.
bccomp -- Compara dos números de precisión arbitraria. (PHP 3, PHP 4 )
bcdiv -- Divide dos números de precisión arbitraria. bcmod -- Obtiene el módulo de un número de precisión
bcmod -- Obtiene el módulo de un número de precisión arbitraria.
arbitraria.
bcmul -- Multiplica dos números de precisión arbitraria.
Descripción
bcpow -- Eleva un número de precisión arbitraria a otro.
bcpowmod -- Raise an arbitrary precision number to
another, reduced by a specified modulus. string bcmod ( string operando izq, string modulo)
bcscale -- Fija el parámetro de escala por defecto para
todas las funciones matemáticas bc.
bcsqrt -- Obtiene la raíz cuadrada de un número de Obtiene el módulo del operando izq usando modulo.
precisión arbitraria. Ver también bcdiv().
bcsub -- Resta un número de precisión arbitraria de otro.
bcmul
bcadd
(PHP 3, PHP 4 )
(PHP 3, PHP 4 ) bcmul -- Multiplica dos números de precisión arbitraria.
bcadd -- Suma dos números de precisión arbitriaria.
Descripción
Descripción
string bcmul ( string operando izq, string operando der [,
string bcadd ( string operando izq, string operando der [, int escala])
int escala])
Multiplica el operando izq por el operando der y devuelve
Suma el operando izq con el operando der y devuelve la el resultado. El parámetro opcional escala fija el número
suma en una cadena de texto. El parámetro opcional de dígitos tras el punto decimal del resultado.
escala se usa para fijar el número de dígitos tras el punto Ver también bcdiv().
decimal que aparecerán en el resultado.
Vea también bcsub().
bcpow

bccomp (PHP 3, PHP 4 )


bcpow -- Eleva un número de precisión arbitraria a otro.
(PHP 3, PHP 4 )
bccomp -- Compara dos números de precisión arbitraria. Descripción

Descripción
string bcpow ( string x, string y [, int escala])

int bccomp ( string operando izq, string operando der [, Eleva x a la potencia de y. El parámetro opcional escala
int escala]) se puede usar para fijar el número de dígitos tras el
punto decimal del resultado.
Compara el operando izq con el operando der y devuelve Ver también bcsqrt().
el resultado como un entero. El parámetro opcional
escala se usa para fijar el número de dígitos tras el punto bcpowmod
decimal que se utilizarán en la comparación. El valor
devuelto es 0 si los dos operandos son iguales. Si el
operando izq es mayor que el operando der el valor (PHP 5 CVS only)
devuelto es +1 y si el operando izq es menor que el bcpowmod -- Raise an arbitrary precision number to
operando der el valor devuelto es -1. another, reduced by a specified modulus.

bcdiv Description

(PHP 3, PHP 4 ) string bcpowmod ( string x, string y, string modulus [,


bcdiv -- Divide dos números de precisión arbitraria. int scale])

Descripción Use the fast-exponentiation method to raise x to the


power y with respect to the modulus modulus. The
optional scale can be used to set the number of digits
string bcdiv ( string operando izq, string operando der [, after the decimal place in the result.
int escala]) The following two statements are functionally identical.
The bcpowmod() version however, executes in less time
and can accept larger parameters.
Introducción
<?php
$a = bcpowmod($x,$y,
$mod); Las funciones bzip2 son usadas para leer y escribir de
forma transparente, ficheros comprimidos bzip2 (.bz2)
$b = bcmod(bcpow($x,$y),
$mod);
Requerimientos
/* $a and $b are equal to
each other. */
?> Este módulo usa las funciones de la biblioteca bzip2 de
Julian Seward.

Nota: Because this method uses the


modulus operation, non-natural Instalación
numbers may give unexpected
results. A natural number is any El soporte Bzip2 en PHP no está activado por defecto.
positive non-zero integer. Necesitais usar la opción de configuración --with-bz2
cuando vayais a compilar PHP, si quereis soporte bzip2.
See also bcpow(), and bcmod(). Este módulo requiere bzip2/libbzip2 versión >= 1.0.x.

bcscale Configuración en tiempo de ejecución

(PHP 3, PHP 4 ) Esta extensión no define ninguna directiva de


bcscale -- Fija el parámetro de escala por defecto para configuración.
todas las funciones matemáticas bc.

Tipos de recursos
Descripción
Esta extensión define un tipo de recurso: un puntero de
string bcscale ( int escala) fichero que identifica el fichero bz2 con el que se va a
trabajar.
Esta función fija el parámetro de escala por defecto para
las subsiguientes funciones matemáticas bc que no Constantes predefinidas
especifican dicho parámetro explícitamente.

Esta extensión no define ninguna constante.


bcsqrt

(PHP 3, PHP 4 ) Ejemplos


bcsqrt -- Obtiene la raíz cuadrada de un número de
precisión arbitraria. Este ejemplo abre un fichero temporal, escribe una
cadena literal en el y presenta el contenido de dicho
Descripción fichero.
Ejemplo 1. Ejemplo simple de bzip2

string bcsqrt ( string operando, int escala)


<?php
Devuelve la raíz cuadrada del operando. El parámetro
opcional escala fija el número de dígitos tras el punto $filename = "/tmp/testfile.bz2";
decimal del resultado. $str = "This is a test string.\n";
Ver también bcpow().
// open file for writing
$bz = bzopen($filename, "w");
bcsub
// write string to file
bzwrite($bz, $str);
(PHP 3, PHP 4 )
bcsub -- Resta un número de precisión arbitraria de otro. // close file
bzclose($bz);
Descripción
// open file for reading
$bz = bzopen($filename, "r");
string bcsub ( string operando izq, string operando der [,
int escala]) // read 10 characters
print bzread($bz, 10);

Resta el operando der del operando izq y devuelve el // output until end of the file (or the next 1024
resultado en una cadena. El parámetro opcional escala char) and close it.
se utiliza para fijar el número de dígitos tras el punto print bzread($bz);
decimal del resultado.
Ver también bcadd(). bzclose($bz);

?>
V. Funciones de compresión Bzip2
Tabla de contenidos
bzclose -- Close a bzip2 file pointer bzdecompress() decompresses the source string
bzcompress -- Compress a string into bzip2 encoded data containing bzip2 encoded data and returns it. If the
bzdecompress -- Decompresses bzip2 encoded data optional parameter small is TRUE, an alternative
bzerrno -- Returns a bzip2 error number decompression algorithm will be used which uses less
bzerror -- Returns the bzip2 error number and error string memory (the maximum memory requirement drops to
in an array around 2300K) but works at roughly half the speed. See
bzerrstr -- Returns a bzip2 error string the bzip2 documentation for more information about this
bzflush -- Force a write of all buffered data feature.
bzopen -- Open a bzip2 compressed file Ejemplo 1. bzdecompress()
bzread -- Binary safe bzip2 file read
bzwrite -- Binary safe bzip2 file write
<?php
$start_str = "This is not an
bzclose
honest face?";
$bzstr =
(PHP 4 >= 4.0.4) bzcompress($start_str);
bzclose -- Close a bzip2 file pointer
print( "Compressed String: " );
print( $bzstr );
Description print( "\n<br>\n" );

$str = bzdecompress($bzstr);
int bzclose ( resource bz) print( "Decompressed String: "
);
Closes the bzip2 file referenced by the pointer bz. print( $str );
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. print( "\n<br>\n" );
The file pointer must be valid, and must point to a file ?>
successfully opened by bzopen(). See also bzcompress().
See also bzopen().

bzerrno
bzcompress

(PHP 4 >= 4.0.4)


(PHP 4 >= 4.0.4) bzerrno -- Returns a bzip2 error number
bzcompress -- Compress a string into bzip2 encoded data

Description
Description

int bzerrno ( resource bz)


string bzcompress ( string source [, int blocksize [, int
workfactor]])
Returns the error number of any bzip2 error returned by
the file pointer bz.
bzcompress() compresses the source string and returns See also bzerror() and bzerrstr().
it as bzip2 encoded data.
The optional parameter blocksize specifies the blocksize
used during compression and should be a number from 1 bzerror
to 9 with 9 giving the best compression, but using more
resources to do so. blocksize defaults to 4.
The optional parameter workfactor controls how the (PHP 4 >= 4.0.4)
compression phase behaves when presented with worst bzerror -- Returns the bzip2 error number and error string
case, highly repetitive, input data. The value can be in an array
between 0 and 250 with 0 being a special case and 30
being the default value. Regardless of the workfactor, the
Description
generated output is the same.
Ejemplo 1. bzcompress() Example
array bzerror ( resource bz)

<?php
Returns the error number and error string, in an
$str = "sample data";
associative array, of any bzip2 error returned by the file
$bzstr =
pointer bz.
bzcompress($str, 9);
Ejemplo 1. bzerror() Example
print( $bzstr );
?>
See also bzdecompress(). <?php
$error =
bzerror($bz);
bzdecompress
echo
(PHP 4 >= 4.0.4) $error["errno"];
bzdecompress -- Decompresses bzip2 encoded data echo
$error["errstr"];
?>
Description
See also bzerrno() and bzerrstr().

string bzdecompress ( string source [, int small])


bzerrstr
(PHP 4 >= 4.0.4) not specified, bzread() will read 1024 (uncompressed)
bzerrstr -- Returns a bzip2 error string bytes at a time.
Ejemplo 1. bzread() Example

Description
<?php
string bzerrstr ( resource bz) $bz =
bzopen("/tmp/foo.bz2",
"r");
Returns the error string of any bzip2 error returned by $str = bzread($bz,
the file pointer bz. 2048);
See also bzerrno() and bzerror(). print( $str );
?>
bzflush See also bzwrite() and bzopen().

(PHP 4 >= 4.0.4) bzwrite


bzflush -- Force a write of all buffered data

(PHP 4 >= 4.0.4)


Description bzwrite -- Binary safe bzip2 file write

int bzflush ( resource bz) Description

Forces a write of all buffered bzip2 data for the file int bzwrite ( resource bz, string data [, int length])
pointer bz.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
See also bzread() and bzwrite(). bzwrite() writes the contents of the string data to the
bzip2 file stream pointed to by bz. If the optional length
argument is given, writing will stop after length
bzopen (uncompressed) bytes have been written or the end of
string is reached, whichever comes first.
Ejemplo 1. bzwrite() Example
(PHP 4 >= 4.0.4)
bzopen -- Open a bzip2 compressed file
<?php
Description $str = "uncompressed
data";
$bz =
resource bzopen ( string filename, string mode) bzopen("/tmp/foo.bz2",
"w");
bzwrite($bz, $str,
Opens a bzip2 (.bz2) file for reading or writing. filename
strlen($str));
is the name of the file to open. mode is similar to the
bzclose($bz);
fopen() function (`r' for read, `w' for write, etc.).
?>
If the open fails, the function returns FALSE, otherwise it
returns a pointer to the newly opened file. See also bzread() and bzopen().
Ejemplo 1. bzopen() Example

VI. Funciones de calendario


<?php
$bz = bzopen("/tmp/foo.bz2", "r"); Introducción
$decompressed_file = bzread($bz,
filesize("/tmp/foo.bz2"));
bzclose($bz); La extensión calendar pone a disposición una serie de
funciones para simplificar la conversión entre los
print( "The contents of /tmp/foo.bz2 are: " ); distintos formatos de calendario. El intermediario ó
print( "\n<br>\n" ); estándar en que se basa es la Cuenta de Días Juliana. La
print( $decompressed_file ); Cuenta de Días Juliana es una cuenta que comienza
?> mucho antes que lo que mucha gente podría necesitar
contar (como alrededor del 4000 AC). Para convertir
See also bzclose().
entre sistemas de calendario, primero deberá convertir a
la Cuenta de Días Juliana y luego al sistema de su
bzread elección. ¡La Cuenta de Días es muy diferente del
Calendario Juliano! Para más información sobre la Cuenta
de Días Juliana visitar
(PHP 4 >= 4.0.4) http://serendipity.magnet.ch/hermetic/cal_stud/jdn.htm.
bzread -- Binary safe bzip2 file read Para más información sobre sistemas de calendario,
visitar http://genealogy.org/~scottlee/cal-overview.html.
En estas instrucciones se han incluído extractos
Description entrecomillados de dicha página.

string bzread ( resource bz [, int length])


Instalación

bzread() reads up to length bytes from the bzip2 file


pointer referenced by bz. Reading stops when length Para que estas funciones funcionen, hay que compilar
(uncompressed) bytes have been read or EOF is reached, PHP con la opción --enable-calendar.
whichever comes first. If the optional parameter length is
Configuración en tiempo de ejecución Descripción

Esta extensión no define ninguna directiva de int cal_days_in_month ( int calendario, int mes, int año)
configuración.
Esta función devuelve el numero de dias en el mes del
año para el calendario especificado calendario.
Tipos de recursos
Ver también jdtounix().

Esta extensión no define ningún tipo de recurso.


cal_from_jd

Constantes predefinidas (PHP 4 >= 4.1.0)


cal_from_jd -- Convierte de Cuenta de Días Juliana a un
Estas constantes están definidas por esta extensión y calendario soportado y devuelve información adicional.
estarán disponibles solamente cuando la extensión ha
sido o bien compilada dentro de PHP o grabada Descripción
dinamicamente en tiempo de ejecución.
CAL_GREGORIAN (entero)
CAL_JULIAN (entero) array cal_from_jd ( int jd, int calendario)
CAL_JEWISH (entero)
CAL_FRENCH (entero)
CAL_NUM_CALS (entero) cal_info
CAL_DOW_DAYNO (entero)
CAL_DOW_SHORT (entero)
(PHP 4 >= 4.1.0)
CAL_DOW_LONG (entero)
cal_info -- Devuelve información sobre un calendario den
CAL_MONTH_GREGORIAN_SHORT (entero)
particular.
CAL_MONTH_GREGORIAN_LONG (entero)
CAL_MONTH_JULIAN_SHORT (entero)
CAL_MONTH_JULIAN_LONG (entero) Descripción
CAL_MONTH_JEWISH (entero)
CAL_MONTH_FRENCH (entero)
Las siguientes constantes se pueden utilizar desde PHP array cal_info ( int calendario)
4.3.0 :
CAL_EASTER_DEFAULT (entero)
CAL_EASTER_ROMAN (entero) cal_to_jd
CAL_EASTER_ALWAYS_GREGORIAN (entero)
CAL_EASTER_ALWAYS_JULIAN (entero) (PHP 4 >= 4.1.0)
Tabla de contenidos cal_to_jd -- Convierte de un calendario soportado a
cal_days_in_month -- Devuelve el número de dias en un Cuenta de Días Juliana.
mes para un determinado año y calendario
cal_from_jd -- Convierte de Cuenta de Días Juliana a un
calendario soportado y devuelve información adicional. Descripción
cal_info -- Devuelve información sobre un calendario den
particular.
cal_to_jd -- Convierte de un calendario soportado a int cal_to_jd ( int calendario, int mes, int dia, int año)
Cuenta de Días Juliana.
easter_date -- devuelve la marca de tiempo UNIX para la
easter_date
medianoche de Pascua de un año dado
easter_days -- Obtiene el número de días tras el 21 de
marzo en que cae la Pascua en un año dado (PHP 3>= 3.0.9, PHP 4 )
FrenchToJD -- Convierte del Calendario Republicano easter_date -- devuelve la marca de tiempo UNIX para la
Francés a la Cuenta de Días Juliana medianoche de Pascua de un año dado
GregorianToJD -- Convierte de fecha Gregoriana a la
Cuenta de Días Juliana
JDDayOfWeek -- Devuelve el día de la semana Descripción
JDMonthName -- Devuelve el nombre de un mes
JDToFrench -- Convierte de Cuenta de Días al Calendario
Republicano Francés int easter_date ( [int anno])
JDToGregorian -- Convierte de Cuenta de Días a fecha
Gregoriana Devuelve la marca de tiempo UNIX que corresponde a la
JDToJewish -- Convierte de Cuenta de Días Juliana a medianoche de Pascua del año dado.
Calendario Judío A partir de PHP 4.3.0, el parametro anno es opcional y si
JDToJulian -- Convierte de Cuenta de Días Juliana a se omite, usa por defecto el año en curso según
Calendario Juliano "localtime".
jdtounix -- Convierte un dia Juliano a UNIX timestamp Aviso: Esta función generará un aviso si el año está fuera
JewishToJD -- Convierte del Calendario Judío a la Cuenta del rango para las marcas de tiempo del UNIX (es decir,
de Días Juliana antes de 1970 o después del 2037).
JulianToJD -- Convierte de Calendario Juliano a Cuenta de Ejemplo 1. ejemplo de easter_date()
Días Juliana
unixtojd -- Convierte de UNIX timestamp a dia Juliano
echo date ("M-d-Y", easter_date(1999)); /*
cal_days_in_month "Apr-04-1999" */
echo date ("M-d-Y", easter_date(2000)); /*
"Apr-23-2000" */
(PHP 4 >= 4.1.0) echo date ("M-d-Y", easter_date(2001)); /*
cal_days_in_month -- Devuelve el número de dias en un "Apr-15-2001" */
mes para un determinado año y calendario
La fecha del Día de Pascua fue definida por el Concilio de (PHP 3, PHP 4 )
Nicea en el 325 D.C. como el domingo tras la primera FrenchToJD -- Convierte del Calendario Republicano
luna llena que cayera en ó después del equinoccio de Francés a la Cuenta de Días Juliana
Primavera. El equinoccio se supone que siempre cae en
el 21 de marzo, de modo que el cálculo se reduce a
determinar la fecha de la luna llena y la del domingo Descripción
siguiente. El algoritmo usado aquí fue introducido en el
año 532 por Dionisio Exiguo. Bajo el Calendario Juliano
int frenchtojd ( int mes, int dia, int anno)
(para años anteriores al 1753), se usa un ciclo simple de
19 años para calcular las fases de la luna. Bajo el
Calendario Gregoriano (años posteriores al 1753, Convierte una fecha del Calendario Republicano Francés
diseñado por Clavio y Lilio, e introducido por el Papa a la Cuenta de Días Juliana.
Gregorio XIII en Octubre de 1582, y en Gran Bretaña y Estas rutinas sólo convierten fechas entre los años 1 y 14
sus colonias en septiembre de 1752) se añaden dos (fechas Gregorianas del 22 de septiembre de 1792 al 22
factores de corrección para hacer el ciclo más preciso. de septiembre de 1806). Esto cubre ampliamente el
(El código se basa en un programa en C de Simon periodo en el que estuvo en uso este calendario.
Kershaw, <webmaster@ely.anglican.org>)
Ver easter_days() para calcular la Pascua antes del
1970 o después del 2037. GregorianToJD

easter_days (PHP 3, PHP 4 )


GregorianToJD -- Convierte de fecha Gregoriana a la
Cuenta de Días Juliana
(PHP 3>= 3.0.9, PHP 4 )
easter_days -- Obtiene el número de días tras el 21 de
marzo en que cae la Pascua en un año dado Descripción

Descripción int gregoriantojd ( int mes, int dia, int anno)

El rango válido para el Calendario Gregoriano es desde el


int easter_days ( [int anno [, int metodo]]) 4714 A.C. hasta el 9999 D.C.
Aunque este programa puede manejar fechas tan lejanas
Devuelve el número de días tras el 21 de marzo en que como el 4714 A.C., usarlo no tendría sentido. El
cae la Pascua en un año dado. Si no se especifica año, se calendario Gregoriano fue instituído el 15 de octubre de
asume el actual. 1582 (o el 5 de octubre de 1582 en el calendario Juliano).
A partir de PHP 4.3.0, el parametro anno es opcional y si Algunos países no lo aceptaron hasta mucho después.
se omite, usa por defecto el año en curso según Por ejemplo, Gran Bretaña se convirtió en 1752, la URSS
"localtime". en 1918 y Grecia en 1923. Muchos países europeos
El parámetro metodo fue introducido en la version PHP usaron el calendario Juliano antes que el Gregoriano.
4.3.0 y permite calcular fechas de pascua basadas en el Ejemplo 1. Funciones de calendario
Calendario Gregoriano durante los años 1582 - 1752 si se
le da el valor CAL_EASTER_ROMAN. Ver las constantes
de calendario para más información sobre estas <?php
constantes. $jd = GregorianToJD
Esta función se puede usar en lugar de easter_date() (10,11,1970);
para calcular la Pascua para años que se salen del rango echo "$jd\n";
de las marcas de fecha del UNIX (o sea, antes del 1970 o $gregorian =
después del 2037). JDToGregorian ($jd);
Ejemplo 1. ejemplo de easter_date() echo "$gregorian\n";
?>

echo easter_days (1999); /* 14,


i.e. April 4 */ JDDayOfWeek
echo easter_days (1492); /* 32,
i.e. April 22 */
echo easter_days (1913); /* 2, (PHP 3, PHP 4 )
i.e. March 23 */ JDDayOfWeek -- Devuelve el día de la semana
La fecha del Día de Pascua fue definida por el Concilio de
Nicea en el 325 D.C. como el domingo tras la primera Descripción
luna llena que cayera en o después del equinoccio de
Primavera. El equinoccio se supone que siempre cae en
el 21 de marzo, de modo que el cálculo se reduce a mixed jddayofweek ( int diajuliano, int modo)
determinar la fecha de la luna llena y la del domingo
siguiente. El algoritmo usado aquí fue introducido en el Devuelve el día de la semana. Dependiendo del modo,
año 532 por Dionisio Exiguo. Bajo el Calendario Juliano devuelve un entero ó una cadena.
(para años anteriores al 1753), se usa un ciclo simple de Tabla 1. Modos para el día de la semana
19 años para calcular las fases de la luna. Bajo el
Calendario Gregoriano (años posteriores al 1753, Mod
Significado
diseñado por Clavio y Lilio, e introducido por el Papa o
Gregorio XIII en Octubre de 1582, y en Gran Bretaña y devuelve el día de la semana como entero
sus colonias en septiembre de 1752) se añaden dos 0
(0=domingo, 1=lunes, etc)
factores de corrección para hacer el ciclo más preciso.
(El código se basa en un programa en C de Simon devuelve una cadena con el día de la semana (inglés,
1
Kershaw, <webmaster@ely.anglican.org>) gregoriano)
Vea también easter_date(). devuelve una cadena con el día de la semana
2
abreviado (inglés, gregoriano)
FrenchToJD
JDMonthName Descripción

(PHP 3, PHP 4 ) string jdtojewish ( int diajuliano)


JDMonthName -- Devuelve el nombre de un mes
Convierte una Cuenta de Días Juliana al Calendario Judío.
Descripción
JDToJulian
string jdmonthname ( int diajuliano, int modo)
(PHP 3, PHP 4 )
Devuelve una cadena que contiene el nombre del mes. JDToJulian -- Convierte de Cuenta de Días Juliana a
modo le dice a esta función a qué calendario debe Calendario Juliano
convertir la Cuenta de Días Juliana, y qué tipo de
nombres de mes debe devolver.
Tabla 1. Modos de calendario Descripción
Mod
Significado Valores
o string jdtojulian ( int diajuliano)
Gregoriano - Jan, Feb, Mar, Apr, May, Jun, Jul, Aug,
0
abreviado Sep, Oct, Nov, Dec Convierte una Cuenta de Días Juliana a una cadena que
contiene la fecha del Calendario Juliano en formato
January, February, March, April, May,
"mes/día/año".
1 Gregoriano June, July, August, September, October,
Novemb er, December
Juliano - Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, jdtounix
2
abreviado Sep, Oct, Nov, Dec
January, February, March, April, May, (PHP 4 )
3 Juliano June, July, August, September, October, jdtounix -- Convierte un dia Juliano a UNIX timestamp
Novemb er, December
Tishri, Heshvan, Kislev, Tevet, Shevat, Descripción
4 Judío AdarI, AdarII, Nisan, Iyyar, Sivan,
Tammuz, Av, Elul
int jdtounix ( int jday)
Vendemiaire, Brumaire, Frimaire,
Republicano Nivose, Pluviose, Ventose, Germinal,
5 Esta funció devuelve el "UNIX timestamp"
Francés Floreal, Prair ial, Messidor, Thermidor,
Fructidor, Extra correspondiante a el dia Juliano definido en jday ó falso
(FALSE) si jday no se encuentra en la época UNIX (años
entre 1970 y 2037 ó 2440588 <= jday <= 2465342 ). El
JDToFrench tiempo devuelto es localtime (y no GMT).
Ver también unixtojd().

(PHP 3, PHP 4 )
JDToFrench -- Convierte de Cuenta de Días al Calendario JewishToJD
Republicano Francés
(PHP 3, PHP 4 )
Descripción JewishToJD -- Convierte del Calendario Judío a la Cuenta
de Días Juliana

string jdtofrench ( int diajuliano)


Descripción

Convierte una Cuenta de Días Juliana al Calendario


Republicano Francés. int jewishtojd ( int mes, int dia, int anno)

JDToGregorian Aunque este programa puede manejar fechas tan lejanas


como el año 1 (3761 A.C.), usarlo no tendría sentido. El
Calendario Judío ha estado en uso miles de años, pero en
(PHP 3, PHP 4 ) los días primeros no había una fórmula que calculara el
JDToGregorian -- Convierte de Cuenta de Días a fecha comienzo de un mes. Un mes comenzaba cuando se veía
Gregoriana por primera vez la luna nueva.

Descripción JulianToJD

string jdtogregorian ( int diajuliano) (PHP 3, PHP 4 )


JulianToJD -- Convierte de Calendario Juliano a Cuenta de
Días Juliana
Convierte de Cuenta de Días Juliana a una cadena que
contiene la fecha Gregoriana en formato "mes/día/año"
Descripción
JDToJewish
int juliantojd ( int mes, int dia, int anno)
(PHP 3, PHP 4 )
JDToJewish -- Convierte de Cuenta de Días Juliana a Rango válido para el Calendario Juliano: del 4713 A.C al
Calendario Judío 9999 D.C.
Aunque este programa puede manejar fechas tan lejanas ccvs usa el usuario 'ccvs', PHP debe ejecutarse como
como el 4713 A.C., usarlo no tendría sentido. El 'ccvs' tambien).
calendario se creó en el 46 A.C., pero sus detalles no se
estabilizaron hasta al menos el 8 D.C., y quizás no lo
hiciera hasta el siglo IV. Además, el comienzo de un año Ver tambien
variaba de una a otra cultura: no todas aceptaban enero
como el primer mes.
Información adicional sobre CCVS se puede encontrar en
Atención http://www.redhat.com/products/ccvs. Red Hat casi no
Recordar que el actual sistema de calendario en uso en mantiene la documentación de CCVS, pero todavia es de
todo el mundo es el calendario Gregoriano. gran ayuda, se puede encontrar en
gregoriantojd() puede ser usada para convertir los dias http://www.redhat.com/products/ccvs/support/CCVS3.3do
del calendario Gregoriano a Cuenta de Días Juliana. cs/ProgPHP.html.
Tabla de contenidos
ccvs_add -- Añadir datos a una transacción
unixtojd ccvs_auth -- Realiza un test de una autorización a
crédito en una transacción
ccvs_command -- Ejecuta un comando que es peculiar
(PHP 4 ) para un protocolo concreto, y que no está disponible en
unixtojd -- Convierte de UNIX timestamp a dia Juliano el API general de CCVS
ccvs_count -- Encuentra cuantas transacciones de un
tipo dado están almacenadas en el sistema
Descripción ccvs_delete -- Borra una transacción
ccvs_done -- Finaliza el motor de CCVS y hace una
limpieza
int unixtojd ( [int timestamp]) ccvs_init -- Inicializa un CCVS para usarlo
ccvs_lookup -- Busca un item de un tipo en particular en
Devuelve el dia Juliano correspondiente a un UNIX la base de datos #
timestamp (segundos desde 01.01.1970), ó al dia actual ccvs_new -- Crea una nueva, transacción en blanco
si no se especifica timestamp ccvs_report -- Devuelve el estado del proceso de
Ver tambienjdtounix(). comunicación en background
ccvs_return -- Transfiere fondos del comerciante al
titular de la tarjeta
VII. Funciones del API de CCVS ccvs_reverse -- Realiza una revocación completa en una
autorización ya procesada
ccvs_sale -- Transfiere fondos del titular de la tarjeta al
Introducción
comerciante
ccvs_status -- Chequear el estado de una factura
Estas funciones interaccionan con el API de CCVS, ccvs_textvalue -- Obtiene el valor de retorno de texto
permitiendo trabajar con CCVS directamente desde un para una llamada anterior a una función
script PHP. CCVS es la solución de RedHat para el ccvs_void -- Realizar una revocación completa en una
intermediario en el procesamiento de tarjetas de crédito. transacción completada
Permite conectar directamente con las centrales de las
tarjetas desde una máquina *nix con un módem.
ccvs_add

Nota: CCVS ha sido discontinuado


(4.0.2 - 4.2.3 only)
por Red Hat y no existen planes de
ccvs_add -- Añadir datos a una transacción
ofrecer nuevas funcionalidades ó
contratos de ayuda. Los que
necesiten usar esta funcionalidad Descripción
pueden probar MCVE by Main Street
Softworks. Es similar en diseño y
tiene documentación para su uso cadena ccvs_add ( cadena sesión, cadena factura,
con PHP cadena argtype, cadena argval)

Aviso

Instalación Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros.

Para activar el soporte de CCVS en PHP hay que tener


instalado CCVS en vuestro sistema. Seguidamente es ccvs_auth
necesario configurar PHP con la opción --with-ccvs. Si se
usa esta opcion sin especificar el directorio donde CCVS
está instalado, PHP intentará encontrar CCVS en la (4.0.2 - 4.2.3 only)
localización por defecto (/usr/local/ccvs). Si CCVS está ccvs_auth -- Realiza un test de una autorización a
instalado en una localización no estándar, ejecutar crédito en una transacción
configure con: --with-ccvs=$ccvs_path, donde
$ccvs_path es el directorio donde CCVS esta instalado.
Descripcion
Tener en cuenta que el soporte de CCVS en PHP necesita
que $ccvs_path/lib y $ccvs_path/include existan, que
cv_api.h se encuentre en el directorio include y que cadena ccvs_auth ( cadena sesión, cadena factura)
libccvs.a se encuentre en el directorio lib.
Adicionalmente se necesita un proceso ccvs
ejecutandose en el sistema para las configuraciones que Aviso
se ejecuten desde PHP. Los procesos PHP deben
ejecutarse bajo el mismo usuario que use CCVS (p.ej. Si Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ccvs_command ccvs_init -- Inicializa un CCVS para usarlo

(4.0.2 - 4.2.3 only) Descripción


ccvs_command -- Ejecuta un comando que es peculiar
para un protocolo concreto, y que no está disponible en
el API general de CCVS cadena ccvs_init ( cadena nombre)

Descripcion Aviso
Esta función no está documentada actualmente, solamente
cadena ccvs_command ( cadena sesión, cadena tipo, se encuentra disponible la lista de parametros.
cadena argval)

ccvs_lookup
Aviso
Esta función no está documentada actualmente, solamente (4.0.2 - 4.2.3 only)
se encuentra disponible la lista de parametros. ccvs_lookup -- Busca un item de un tipo en particular en
la base de datos #

ccvs_count
Descripción

(4.0.2 - 4.2.3 only)


ccvs_count -- Encuentra cuantas transacciones de un cadena ccvs_lookup ( cadena sesión, cadena factura,
tipo dado están almacenadas en el sistema entero inum)

Descripción Aviso
Esta función no está documentada actualmente, solamente
entero ccvs_count ( cadena sesión, cadena tipo) se encuentra disponible la lista de parametros.

Aviso ccvs_new
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. (4.0.2 - 4.2.3 only)
ccvs_new -- Crea una nueva, transacción en blanco

ccvs_delete
Descripcion

(4.0.2 - 4.2.3 only)


ccvs_delete -- Borra una transacción cadena ccvs_new ( cadena sesión, cadena cadena)

Descripción Aviso
Esta función no está documentada actualmente, solamente
cadena ccvs_delete ( cadena sesión, cadena factura) se encuentra disponible la lista de parametros.

Aviso ccvs_report
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. (4.0.2 - 4.2.3 only)
ccvs_report -- Devuelve el estado del proceso de
comunicación en background
ccvs_done

Descripcion
(4.0.2 - 4.2.3 only)
ccvs_done -- Finaliza el motor de CCVS y hace una
limpieza cadena ccvs_report ( cadena sesión, cadena tipo)

Descripcion Aviso
Esta función no está documentada actualmente, solamente
cadena ccvs_done ( cadena sesió) se encuentra disponible la lista de parametros.

Aviso ccvs_return
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. (4.0.2 - 4.2.3 only)
ccvs_return -- Transfiere fondos del comerciante al
titular de la tarjeta
ccvs_init

Descripción
(4.0.2 - 4.2.3 only)
cadena ccvs_return ( cadena sesión, cadena factura) se encuentra disponible la lista de parametros.

Aviso
ccvs_void
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(4.0.2 - 4.2.3 only)
ccvs_void -- Realizar una revocación completa en una
ccvs_reverse transacción completada

(4.0.2 - 4.2.3 only) Descripción


ccvs_reverse -- Realiza una revocación completa en una
autorización ya procesada
cadena ccvs_void ( cadena sesión, cadena factura)

Descripcion
Aviso
Esta función no está documentada actualmente, solamente
cadena ccvs_reverse ( cadena sesión, cadena factura) se encuentra disponible la lista de parametros.

Aviso
VIII. soporte de las funciones COM para Windows
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Estas funciones solo están disponibles en la versión para
Windows de PHP. Estas funciones han sido añadidas en
ccvs_sale PHP4.
Tabla de contenidos
COM -- COM class
(4.0.2 - 4.2.3 only) VARIANT -- VARIANT class
ccvs_sale -- Transfiere fondos del titular de la tarjeta al com_addref -- Increases the components reference
comerciante counter.
com_get -- ???
com_invoke -- ???
Descripción com_isenum -- Grabs an IEnumVariant
com_load_typelib -- Loads a Typelib
cadena ccvs_sale ( cadena sesión, cadena factura) com_load -- ???
com_propget -- ???
com_propput -- ???
Aviso com_propset -- ???
com_release -- Decreases the components reference
Esta función no está documentada actualmente, solamente counter.
se encuentra disponible la lista de parametros. com_set -- ???

ccvs_status COM

(4.0.2 - 4.2.3 only) (no version information, might be only in CVS)


ccvs_status -- Chequear el estado de una factura COM -- COM class

Descripción Synopsis

cadena ccvs_status ( cadena sesión, cadena factura) $obj = new


COM("server.object")
Aviso
Esta función no está documentada actualmente, solamente Description
se encuentra disponible la lista de parametros.

The COM class provides a framework to integrate (D)COM


ccvs_textvalue components into your php scripts.

(4.0.2 - 4.2.3 only) Methods


ccvs_textvalue -- Obtiene el valor de retorno de texto
para una llamada anterior a una función string COM::COM ( string module_name [, string
server_name [, int codepage]])
Descripción
COM class constructor. Parameters:
module_name
cadena ccvs_textvalue ( cadena sesión) name or class-id of the requested component.
server_name
name of the DCOM server from which the
Aviso
component should be fetched. If NULL,
Esta función no está documentada actualmente, solamente localhost is assumed. To allow DCOM
com.allow_dcom has to be set to TRUE in VARIANT -- VARIANT class
php.ini.
codepage
specifies the codepage that is used to convert Synopsis
php-strings to unicode-strings and vice versa.
Possible values are CP_ACP, CP_MACCP,
CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, $vVar = new
CP_UTF7 and CP_UTF8. VARIANT($var)
Ejemplo 1. COM example (1)

Description
// starting word
$word = new COM("word.application") or die("Unable
to instanciate Word"); A simple container to wrap variables into VARIANT
print "Loaded Word, version {$word->Version}\n"; structures.

//bring it to front Methods


$word->Visible = 1;

//open an empty document string VARIANT::VARIANT ( [mixed value [, int type [,


$word->Documents->Add(); int codepage]]])

//do some weird stuff


VARIANT class constructor. Parameters:
$word->Selection->TypeText("This is a test...");
value
$word->Documents[1]->SaveAs("Useless test.doc");
initial value. if omitted an VT_EMPTY object is
created.
//closing word
type
$word->Quit();
specifies the content type of the VARIANT
object. Possible values are VT_UI1, VT_UI2,
//free the object
VT_UI4, VT_I1, VT_I2, VT_I4, VT_R4, VT_R8,
$word->Release();
VT_INT, VT_UINT, VT_BOOL, VT_ERROR,
$word = null;
VT_CY, VT_DATE, VT_BSTR, VT_DECIMAL,
Ejemplo 2. COM example (2) VT_UNKNOWN, VT_DISPATCH and
VT_VARIANT. These values are mutual
exclusive, but they can be combined with
$conn = new COM("ADODB.Connection") or VT_BYREF to specify being a value. If omitted,
die("Cannot start ADO"); the type of value is used. Consult the msdn
$conn->Open("Provider=SQLOLEDB; Data library for additional information.
Source=localhost; codepage
Initial Catalog=database; User ID=user; specifies the codepage that is used to convert
Password=password"); php-strings to unicode-strings and vice versa.
Possible values are CP_ACP, CP_MACCP,
$rs = $conn->Execute("SELECT * FROM CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP,
sometable"); // Recordset CP_UTF7 and CP_UTF8.

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n"; com_addref

for ($i=0; $i < $num_columns; $i++) (4.1.0 - 4.3.0 only)


{ com_addref -- Increases the components reference
$fld[$i] = $rs->Fields($i); counter.
}

$rowcount = 0; Description
while (!$rs->EOF)
{
for ($i=0; $i < $num_columns; $i++) void com_addref ( void)
{
echo $fld[$i]->value . "\t"; Increases the components reference counter.
}
echo "\n";
$rowcount++; // increments rowcount com_get
$rs->MoveNext();
}
(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)
$rs->Close(); com_get -- ???
$conn->Close();
Descripción
$rs->Release();
$conn->Release();
mixed com_get ( resource object, string property)
$rs = null;
$conn = null;
com_invoke

VARIANT (PHP 3>= 3.0.3)


com_invoke -- ???
(no version information, might be only in CVS)
Descripción com_propset

mixed com_invoke ( resource object, string (PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)
function_name [, mixed function parameters, ...]) com_propset -- ???

com_isenum Descripción

(4.1.0 - 4.3.0 only) void com_propset ( resource object, string property,


com_isenum -- Grabs an IEnumVariant mixed value)

Description Esta función es un alias para com_propput().

void com_isenum ( object com_module) com_release

Aviso (4.1.0 - 4.3.0 only)


com_release -- Decreases the components reference
Esta función no está documentada actualmente, solamente counter.
se encuentra disponible la lista de parametros.

Description
com_load_typelib
void com_release ( void)
(4.1.0 - 4.3.0 only)
com_load_typelib -- Loads a Typelib Decreases the components reference counter.

Description com_set

void com_load_typelib ( string typelib_name [, int (PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)
case_insensitive]) com_set -- ???

Aviso Descripción
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. void com_set ( resource object, string property, mixed
value)

com_load
Esta función es un alias para com_set().

(PHP 3>= 3.0.3)


IX. Funciones de Clases/Objectos
com_load -- ???

Introducción
Descripción

Estas funciones permiten obtener informacion sobre


string com_load ( string module name [, string server
clases y objetos. Se puede obtener el nombre de la clase
name])
a la que pertenece un objeto, asi como las propiedades
de sus miembros y métodos. Usando estas funciones se
com_propget puede obtener no solo lo comentado en la frase anterior,
tambien se puede obtener la familia del objeto (p.ej. que
clase está extendiendo la clase a la que pertenece el
(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only) objeto)
com_propget -- ???

Ejemplos
Descripción

En este ejemplo, definimos primero una clase base y una


mixed com_propget ( resource object, string property) extensión de esta clase. La clase base define un vegetal
genérico, si es comestible y su color. La subclase Spinach
com_propput añade un metodo para cocinarlo y otro para saber si esta
cocinado.
Ejemplo 1. classes.inc
(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)
com_propput -- ???
<?php
Descripción // base class with member properties
and methods
void com_propput ( resource object, string property, class Vegetable {
mixed value)
var $edible;
var $color; // instantiate 2 objects

function Vegetable( $edible, $veggie = new Vegetable(true,"blue");


$color="green" ) { $leafy = new Spinach();
$this->edible = $edible;
$this->color = $color; // print out information about objects
} echo "veggie: CLASS ".get_class($veggie)."\n";
echo "leafy: CLASS ".get_class($leafy);
function is_edible() { echo ", PARENT ".get_parent_class($leafy)."\n";
return $this->edible;
} // show veggie properties
echo "\nveggie: Properties\n";
function what_color() { print_vars($veggie);
return $this->color;
} // and leafy methods
echo "\nleafy: Methods\n";
} // end of class Vegetable print_methods($leafy);

// extends the base class echo "\nParentage:\n";


class Spinach extends Vegetable { class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
var $cooked = false; ?>
</pre>
function Spinach() {
One important thing to note in the example above is that
$this->Vegetable( true,
the object $leafy is an instance of the class Spinach
"green" );
which is a subclass of Vegetable, therefore the last part
}
of the script above will output:
function cook_it() { [...]
$this->cooked = true; Parentage:
} Object leafy does not belong to a subclass of
Spinach
function is_cooked() { Object leafy belongs to class spinach a
return $this->cooked; subclass of Vegetable
} Tabla de contenidos
call_user_method_array -- Call a user method given with
} // end of class Spinach an array of parameters [deprecated]
call_user_method -- Call a user method on an specific
?> object [deprecated]
Creamos 2 objetos de estas clases e imprimimos class_exists -- Checks if the class has been defined
información sobre ellos, incluyendo la jerarquia de clases get_class_methods -- Devuelve un vector (matriz
a la que pertenecen. También definimos algunas unidimensional) con los nombres de los métodos de la
funciones, especialmente para imprimir las variables de clase en question.
una manera ordenada. get_class_vars -- Devuelve un vector con las
Ejemplo 2. test_script.php propiedades (inicializadas por defecto) de la clase
get_class -- Returns the name of the class of an object
get_declared_classes -- Returns an array with the name
<pre> of the defined classes
<?php get_object_vars -- Devuelve un vector de propiedades del
objecto
include "classes.inc"; get_parent_class -- Retrieves the parent class name for
object or class
// utility functions is_a -- Returns TRUE if the object is of this class or has
this class as one of its parents
function print_vars($obj) { is_subclass_of -- Returns TRUE if the object has this
$arr = get_object_vars($obj); class as one of its parents
while (list($prop, $val) = each($arr)) method_exists -- Comprueba que el metódo de clase
echo "\t$prop = $val\n"; existe
}
call_user_method_array
function print_methods($obj) {
$arr = get_class_methods(get_class($obj));
foreach ($arr as $method) (PHP 4 >= 4.0.5)
echo "\tfunction $method()\n"; call_user_method_array -- Call a user method given with
} an array of parameters [deprecated]

function class_parentage($obj, $class) {


global $$obj; Description
if (is_subclass_of($$obj, $class)) {
echo "Object $obj belongs to class
".get_class($$obj); mixed call_user_method_array ( string method_name,
echo " a subclass of $class\n"; object obj [, array paramarr])
} else {
echo "Object $obj does not belong to a
Aviso
subclass of $class\n";
} The call_user_method_array() function is deprecated as
} of PHP 4.1.0, use the call_user_func_array() variety with
the array(&$obj, "method_name") syntax instead.
Calls the method referred by method_name from the This function returns TRUE if the class given by
user defined obj object, using the parameters in class_name has been defined, FALSE otherwise.
paramarr. See also get_declared_classes().
See also: call_user_func_array(), call_user_func(),
call_user_method().
get_class_methods

Nota: This function was added to


the CVS code after release of PHP (PHP 4 )
4.0.4pl1 get_class_methods -- Devuelve un vector (matriz
unidimensional) con los nombres de los métodos de la
clase en question.
call_user_method

Descripción
(PHP 3>= 3.0.3, PHP 4 )
call_user_method -- Call a user method on an specific
object [deprecated] vector get_class_methods ( string class_name)

Esta función devuelve un vector con los nombres de los


Description
métodos definidos en la clase especificada como
class_name.
mixed call_user_method ( string method_name, object
obj [, mixed parameter [, mixed ...]])
Nota: A partir de PHP 4.0.6, se
puede especificar el objeto a sí
Aviso mismo en vez de class_name. Por
ejemplo:
The call_user_method() function is deprecated as of PHP
4.1.0, use the call_user_func() variety with the
array(&$obj, "method_name") syntax instead. $class_methods =
Calls the method referred by method_name from the get_class_methods($my_class); // see below the
user defined obj object. An example of usage is below, full example
where we define a class, instantiate an object and use Ejemplo 1. get_class_methods() ejemplo
call_user_method() to call indirectly its print_info
method.
<?php <?php
class Country {
var $NAME; class myclass {
var $TLD; // constructor
function myclass() {
function Country($name, $tld) { return(TRUE);
$this->NAME = $name; }
$this->TLD = $tld;
} // method 1
function myfunc1() {
function print_info($prestr="") { return(TRUE);
echo $prestr."Country: ".$this- }
>NAME."\n";
echo $prestr."Top Level Domain: ". // method 2
$this->TLD."\n"; function myfunc2() {
} return(TRUE);
} }
}
$cntry = new Country("Peru","pe");
$my_object = new myclass();
echo "* Calling the object method
directly\n"; $class_methods =
$cntry->print_info(); get_class_methods(get_class($my_object));

echo "\n* Calling the same method foreach ($class_methods as $method_name) {


indirectly\n"; echo "$method_name\n";
call_user_method ("print_info", $cntry, }
"\t");
?> ?>
See also call_user_func_array(), call_user_func(), and Producira:
call_user_method_array().
myclas
s
class_exists myfunc
1
myfunc
(PHP 4 ) 2
class_exists -- Checks if the class has been defined
Ver también get_class_vars() y get_object_vars().

Description
get_class_vars

bool class_exists ( string class_name)


(PHP 4 )
get_class_vars -- Devuelve un vector con las See also get_parent_class(), gettype(), and
propiedades (inicializadas por defecto) de la clase is_subclass_of().

Descripción get_declared_classes

array get_class_vars ( string class_name) (PHP 4 )


get_declared_classes -- Returns an array with the name
of the defined classes
Esta función devuelve un vector con las propiedades que
han sido inicializadas por defecto en la clase. Los
elementos de este vector están estan organizados de la Description
forma varname => value.

array get_declared_classes ( void)


Nota: Las variables de la clase que
no estén inicializadas, no será
presentadas por get_class_vars(). This function returns an array of the names of the
declared classes in the current script.

Ejemplo 1. get_class_vars() ejemplo


Nota: In PHP 4.0.1pl2, three extra
classes are returned at the
beginning of the array: stdClass
<?php
(defined in Zend/zend.c),
OverloadedTestClass (defined in
class myclass {
ext/standard/basic_functions.c) and
Directory (defined in
var $var1; // this has no default
ext/standard/dir.c).
value...
var $var2 = "xyz";
var $var3 = 100; Also note that depending on what
libraries you have compiled into PHP,
// constructor additional classes could be present.
function myclass() { This means that you will not be able
return(TRUE); to define your own classes using
} these names. There is a list of
} predefined classes in the Predefined
Classes section of the appendices.
$my_class = new myclass();

$class_vars = See also class_exists().


get_class_vars(get_class($my_class));

foreach ($class_vars as $name => get_object_vars


$value) {
echo "$name : $value\n"; (PHP 4 )
} get_object_vars -- Devuelve un vector de propiedades del
objecto
?>
Producira:
Descripción
var2 :
xyz
var3 : array get_class_vars ( object obj)
100
Ver también get_class_methods(), get_object_vars() Esta función devuelve un vector con las propiedades
definidas en el objecto especificado como obj. Las
variables declaradas en la clase a la que pertenece obj,
get_class que no les ha sido asignado un valor, no serán devueltas
en el vector.
Ejemplo 1. Uso de get_object_vars()
(PHP 4 )
get_class -- Returns the name of the class of an object
<?php
Description class Point2D {
var $x, $y;
var $label;
string get_class ( object obj)
function Point2D($x, $y)
This function returns the name of the class of which the {
object obj is an instance. Returns FALSE if obj is not an $this->x = $x;
object. $this->y = $y;
}

Nota: get_class() returns a user function setLabel($label)


defined class name in lowercase. A {
class defined in a PHP extension is $this->label = $label;
returned in its original notation. }
is_subclass_of
function getPoint() {
return array("x" =>
$this->x, (PHP 4 )
"y" => $this- is_subclass_of -- Returns TRUE if the object has this
>y, class as one of its parents
"label" =>
$this->label);
} Description
}

// "$label" is declared but bool is_subclass_of ( object object, string class_name)


not defined
$p1 = new Point2D(1.233, This function returns TRUE if the object object, belongs
3.445); to a class which is a subclass of class_name, FALSE
print_r(get_object_vars($p1 otherwise.
)); See also get_class(), get_parent_class() and is_a().

$p1->setLabel("point #1");
print_r(get_object_vars($p1 method_exists
));

?> (PHP 4 )
method_exists -- Comprueba que el metódo de clase
El resultado de este programa es: existe
Array
( Descripción
[x] => 1.233
[y] => 3.445
) bool method_exists ( object object, string
method_name)
Array
(
[x] => 1.233 Esta función devuelve verdadero (TRUE) si el metódo
[y] => 3.445 referido por method_name ha sido definido en el objecto
[label] => object, en cualquier otro caso devuelve falso (FALSE)
point #1
) X. Funciones de ClibPDF
Ver tambien get_class_methods() y get_class_vars()!
ClibPDF Le permite crear documentos PDF con PHP. Está
get_parent_class disponible en FastIO pero no es software libre. Debería
leer la licencia antes de comenzar a utilizar ClibPDF. Si
usted no puede cumplir el acuerdo de la licencia
(PHP 4 ) considere el utilizar la pdflib de Thomas Merz, que
get_parent_class -- Retrieves the parent class name for tambien es muy potente. La funcionalidad y la API de
object or class ClibPDF son similares a la pdflib de Thomas Merz pero,
de acuerdo con FastIO, ClibPDF es mas rápida y crea
documentos mas pequeños. Esto puede haber cambiado
Description con la nueva versión 2.0 de pdflib. Un simple banco de
pruebas (el ejemplo pdfclock.c de pdflib 2.0 trasformado
string get_parent_class ( mixed obj) en un script php) en realidad no muestra ninguna
diferencia en velocidad. Por tanto, pruebe las dos y vea
cual hace el mejor trabajo para usted.
If obj is an object, returns the name of the parent class of Esta documentación debería ser leída junto con el
the class of which obj is an instance. manual de ClibPDF ya que este explica la librería con
If obj is a string, returns the name of the parent class of mucho mas detalle.
the class with that name. This functionality was added in Muchas funciones en le ClibPDF nativa y el módulo PHP,
PHP 4.0.5. así como en pdflib, tienen el mismo nombre. Todas las
See also get_class() and is_subclass_of() funciones excepto cpdf_open() toman el manejador del
documento com el primer parámetro. Actualmente este
manejador no se usa internamente desde que ClibPDF no
is_a
soporta la creación de varios documentos PDF al mismo
tiempo. Realmente, ni debería intentarlo, los resultados
(PHP 4 >= 4.2.0) son impredecibles. No puedo supervisar cuales son las
is_a -- Returns TRUE if the object is of this class or has consecuencias en un sistema multihilo. De acuerdo con
this class as one of its parents el autor de ClibPDF, esto cambiará en alguno de las
próximas veriones (la versión actual, cuando eto fue
escrito es 1.10). Si usted necesita esta capacidad, use el
Description módulo pdflib.

bool is_a ( object object, string class_name) Nota: La función cpdf_set_font()


ha cambiado desde que PHP3
This function returns TRUE if the object is of this class or soporta fuentes asiáticas. El
has this class as one of its parents, FALSE otherwise. parámetro que codifica ya no es un
See also get_class(), get_parent_class(), and entero sino una cadena.
is_subclass_of().
Una gran ventaja de ClibPDF sobre pdflib es la posibilidad
cpdf_rotate($pdf, 30.0);
de crear el documento PDF completamente en memoria
cpdf_moveto($pdf, $radius, 0.0);
sin usar ficheros temporales. Esto también proporciona la
cpdf_lineto($pdf, $radius-$margin, 0.0);
capaciad de pasar coordenadas en una unidad de
cpdf_stroke($pdf);
longitud predefinida. Esta es una cualidad útil pero
}
puede ser simulada con pdf_translate().
La mayoría de las funciones son fáciles de usar. La parte
$ltime = getdate();
mas difícil es, probablemente, crear un documento PDF
muy simple. El siguiente ejemplo debería ayudarle a
/* dibujar la aguja de las horas */
comenzar. En él se crea un documento con una página.
cpdf_save($pdf);
La página contiene el texto "Times-Roman" con una
cpdf_rotate($pdf, -(($ltime['minutos']/60.0) +
fuente de 30pt. El texto está subrayado.
$ltime['horas'] - 3.0) * 30.0);
Ejemplo 1. Ejemplo simple de ClibPDF
cpdf_moveto($pdf, -$radius/10, -$radius/20);
cpdf_lineto($pdf, $radius/2, 0.0);
cpdf_lineto($pdf, -$radius/10, $radius/20);
<?php cpdf_closepath($pdf);
$cpdf = cpdf_open(0); cpdf_fill($pdf);
cpdf_page_init($cpdf, 1, 0, 595, 842); cpdf_restore($pdf);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_set_font($cpdf, "Times-Roman", 30, /* dibujar el minutero */
"WinAnsiEncoding"); cpdf_save($pdf);
cpdf_set_text_rendering($cpdf, 1); cpdf_rotate($pdf, -(($ltime['segundos']/60.0) +
cpdf_text($cpdf, "Times Roman outlined", 50, $ltime['minutos'] - 15.0) * 6.0);
750); cpdf_moveto($pdf, -$radius/10, -$radius/20);
cpdf_moveto($cpdf, 50, 740); cpdf_lineto($pdf, $radius * 0.8, 0.0);
cpdf_lineto($cpdf, 330, 740); cpdf_lineto($pdf, -$radius/10, $radius/20);
cpdf_stroke($cpdf); cpdf_closepath($pdf);
cpdf_finalize($cpdf); cpdf_fill($pdf);
Header("Content-type: application/pdf"); cpdf_restore($pdf);
cpdf_output_buffer($cpdf);
cpdf_close($cpdf); /* dibujar la seguna mano */
?> cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
La distribución de pdflib contiene un ejemplo mas cpdf_setlinewidth($pdf, 2);
comlejo que crea una serie de páginas con un reloj cpdf_save($pdf);
analógico. Aquí está ese ejemplo convertido en PHP cpdf_rotate($pdf, -(($ltime['segundos'] - 15.0) * 6.0));
usando la extensión ClibPDF: cpdf_moveto($pdf, -$radius/5, 0.0);
Ejemplo 2. Ejemplo con pdfclock de la distribución cpdf_lineto($pdf, $radius, 0.0);
pdflib 2.0 cpdf_stroke($pdf);
cpdf_restore($pdf);

<?php /* dibujar un pequeño círculo en el centro */


$radius = 200; cpdf_circle($pdf, 0, 0, $radius/30);
$margin = 20; cpdf_fill($pdf);
$pagecount = 40;
cpdf_restore($pdf);
$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php3"); cpdf_finalize_page($pdf, $pagecount+1);
cpdf_set_title($pdf, "Reloj Analógico"); }

while($pagecount-- > 0) { cpdf_finalize($pdf);


cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + Header("Content-type: application/pdf");
$margin), 2 * ($radius + $margin), 1.0); cpdf_output_buffer($pdf);
cpdf_close($pdf);
cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0); /* ?>
limpiar */ Tabla de contenidos
cpdf_add_annotation -- Añade una anotación
cpdf_translate($pdf, $radius + $margin, $radius + cpdf_add_outline -- Añade una marca en la página actual
$margin); cpdf_arc -- Dibuja un arco
cpdf_save($pdf); cpdf_begin_text -- Inicializa una sección de texto
cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0); cpdf_circle -- Dibuja un círculo
cpdf_clip -- Ajusta al camino actual
/* cambio de minuto */ cpdf_close -- Cierra un documento PDF
cpdf_setlinewidth($pdf, 2.0); cpdf_closepath_fill_stroke -- Cierra, llena y traza el
for ($alpha = 0; $alpha < 360; $alpha += 6) camino actual
{ cpdf_closepath_stroke -- Cierra el camino y dibuja una
cpdf_rotate($pdf, 6.0); línea a lo largo del camino
cpdf_moveto($pdf, $radius, 0.0); cpdf_closepath -- Cierra el camino
cpdf_lineto($pdf, $radius-$margin/3, 0.0); cpdf_continue_text -- Pone texto en la línea siguiente
cpdf_stroke($pdf); cpdf_curveto -- Dibuja una curva
} cpdf_end_text -- Finaliza una sección de texto
cpdf_fill_stroke -- LLena y traza el camino actual
cpdf_restore($pdf); cpdf_fill -- LLena el camino actual
cpdf_save($pdf); cpdf_finalize_page -- Finaliza una página
cpdf_finalize -- Finaliza un documento
/* cambios de 5 minutos */ cpdf_global_set_document_limits -- Sets document limits
cpdf_setlinewidth($pdf, 3.0); for any pdf document
for ($alpha = 0; $alpha < 360; $alpha += 30) cpdf_import_jpeg -- Abre una imagen JPEG
{ cpdf_lineto -- Dibuja una línea
cpdf_moveto -- Define el punto actual Descripción
cpdf_newpath -- Starts a new path
cpdf_open -- Abre un nuevo documento PDF
cpdf_output_buffer -- Pone el documento PDF en el buffer void cpdf_add_annotation ( int pdf document, double
de memoria llx, double lly, double urx, double ury, string title, string
cpdf_page_init -- Comienza una nueva página content, int mode)
cpdf_place_inline_image -- Situa una imagen en la página
cpdf_rect -- Dibuja un rectángulo La función cpdf_add_annotation() añade una nota con
cpdf_restore -- Restaura un entorno formalmente salvado la esquina inferior izquierda en (llx, lly) y la esquina
cpdf_rlineto -- Dibuja una línea superior derecha en (urx, ury).
cpdf_rmoveto -- Define el punto actual El últomo parámetro opcional determina el tamaño de la
cpdf_rotate_text -- Sets text rotation angle unidad. Si es 0 o se omite, se usa la unidad por defecto
cpdf_rotate -- Define la rotación especificada para la página. De otro modo las
cpdf_save_to_file -- Escribe el documento PDF en un coordenadas se miden en puntos postscript,
fichero despreciando la unidad actual.
cpdf_save -- Salva el entorno actual
cpdf_scale -- Define la escala
cpdf_set_action_url -- Sets hyperlink cpdf_add_outline
cpdf_set_char_spacing -- Determina el espacio entre
caracteres
cpdf_set_creator -- Define el campo creator en el (PHP 3>= 3.0.9, PHP 4 )
documento PDF cpdf_add_outline -- Añade una marca en la página actual
cpdf_set_current_page -- Define la página actual
cpdf_set_font_directories -- Sets directories to search Descripción
when using external fonts
cpdf_set_font_map_file -- Sets fontname to filename
translation map when using external fonts void cpdf_add_outline ( int pdf document, string text)
cpdf_set_font -- Selecciona la fuente y el tamaño actual
cpdf_set_horiz_scaling -- Define la escala horizontal del
La función cpdf_add_outline() añade una marca con el
texto
texto text que apunta a la página actual.
cpdf_set_keywords -- Pone el valor del campo
Ejemplo 1. Añadiendo un contorno de página
'keywords'(palabras clave) de un documento PDF
cpdf_set_leading -- Define la distancias entre las líneas
de texto
cpdf_set_page_animation -- Define la separación entre <?php
páginas $cpdf = cpdf_open(0);
cpdf_set_subject -- Define el valor del campo subjet de cpdf_page_init($cpdf, 1, 0, 595,
un documento PDF 842);
cpdf_set_text_matrix -- Define la matriz de texto cpdf_add_outline($cpdf, 0, 0, 0, 1,
cpdf_set_text_pos -- Define la posición del texto "Página 1");
cpdf_set_text_rendering -- Determina cómo es // ...
presentado el texto // Algún dibujo
cpdf_set_text_rise -- Define la elevación del texto // ...
cpdf_set_title -- Define el campo title de un documento cpdf_finalize($cpdf);
PDF Header("Content-type:
cpdf_set_viewer_preferences -- How to show the application/pdf");
document in the viewer cpdf_output_buffer($cpdf);
cpdf_set_word_spacing -- Define el espacio entre cpdf_close($cpdf);
palabras ?>
cpdf_setdash -- Defina el patrón de la raya
cpdf_setflat -- Define la monotonía
cpdf_setgray_fill -- Pone el color de relleno al valor gris cpdf_arc
cpdf_setgray_stroke -- Define el color para dibujar al
valor gris
cpdf_setgray -- Pone el color de relleno y dibujo a gris (PHP 3>= 3.0.8, PHP 4 )
cpdf_setlinecap -- Define el parámetro linecap cpdf_arc -- Dibuja un arco
cpdf_setlinejoin -- Define el parámetro linejoin
cpdf_setlinewidth -- Define la profundidad de la línea Descripión
cpdf_setmiterlimit -- Define el límite del inglete
cpdf_setrgbcolor_fill -- Pone el color de relleno a l valor
de clor rgb void cpdf_arc ( int pdf document, double x-koor, double
cpdf_setrgbcolor_stroke -- Pone el color de dibujo al valor y-koor, double radius, double start, double end, int mode)
de color rgb
cpdf_setrgbcolor -- Pone el color de relleno y dibujo al
La función cpdf_arc() dibuja un arco con el centro rn el
valor de color rgb
punto (x-koor, y-koor) y radio radius, empezando en el
cpdf_show_xy -- Muestra texto en la posición
ángulo start y terminando en el ángulo end.
cpdf_show -- Muestra el texto en la posición actual
El último parámetro opcional especifica el tamaño de la
cpdf_stringwidth -- Devuelve la anchura del texto en la
unidad. Si es 0 o se omite, se usa la unidad especificada
fuente actual
por defecto. De otro modo las coordenadas son medidas
cpdf_stroke -- Dibuja una línea a lo largo del camino
en puntos postscript,despreciando la unidad actual.
cpdf_text -- Muestra texto conparámetros
Vea también cpdf_circle().
cpdf_translate -- Define el sistema de origen de
coordenadas
cpdf_begin_text
cpdf_add_annotation
(PHP 3>= 3.0.8, PHP 4 )
cpdf_begin_text -- Inicializa una sección de texto
(PHP 3>= 3.0.12, PHP 4 )
cpdf_add_annotation -- Añade una anotación
Descripción Descripción

void cpdf_begin_text ( int pdf document) void cpdf_closepath_fill_stroke ( int pdf document)

La función cpdf_begin_text() comienza una sección de La función cpdf_closepath_fill_stroke() cierra, llena el


texto. Debe ser terminada con cpdf_end_text(). interior del caminoa catual con el color actual de relleno
Ejemplo 1. Salida de texto y dibuja el camino actual.
Vea también cpdf_closepath(), cpdf_stroke(),
cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(),
<?php cpdf_begin_text($pdf); cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
cpdf_set_font($pdf, 16, "Helvetica",
"WinAnsiEncoding");
cpdf_closepath_stroke
cpdf_text($pdf, 100, 100, "Algún texto");
cpdf_end_text($pdf) ?>
Vea también cpdf_end_text(). (PHP 3>= 3.0.8, PHP 4 )
cpdf_closepath_stroke -- Cierra el camino y dibuja una
línea a lo largo del camino
cpdf_circle

Descripción
(PHP 3>= 3.0.8, PHP 4 )
cpdf_circle -- Dibuja un círculo
void cpdf_closepath_stroke ( int pdf document)

Descripción
La función cpdf_closepath_stroke() es una
combinación de cpdf_closepath() y cpdf_stroke().
void cpdf_circle ( int pdf document, double x-koor, Después limpia el camino.
double y-koor, double radius, int mode) Vea también cpdf_closepath(), cpdf_stroke().

La función cpdf_circle() dibuja un círculo con centro en cpdf_closepath


el punto (x-koor, y-koor) y radio radius.
El último parámetro opcional define el tamaño de la
unidad. Si es 0 o se omite, se usa el valor por defecto (PHP 3>= 3.0.8, PHP 4 )
para la página. De otro modo las coordenadas se miden cpdf_closepath -- Cierra el camino
en puntos postscript, despreciando la unidad actual.
Vea también cpdf_arc().
Descripción

cpdf_clip
void cpdf_closepath ( int pdf document)

(PHP 3>= 3.0.8, PHP 4 ) La función cpdf_closepath() cierra el camino actual.


cpdf_clip -- Ajusta al camino actual

cpdf_continue_text
Descripción

(PHP 3>= 3.0.8, PHP 4 )


void cpdf_clip ( int pdf document) cpdf_continue_text -- Pone texto en la línea siguiente

La función cpdf_clip() ajusta todos los dibujos al camino


Descripción
actual.

void cpdf_continue_text ( int pdf document, string text)


cpdf_close

La función cpdf_continue_text() pone la cadena text en


(PHP 3>= 3.0.8, PHP 4 ) la línea siguiente.
cpdf_close -- Cierra un documento PDF Vea también cpdf_show_xy(), cpdf_text(),
cpdf_set_leading(), cpdf_set_text_pos().
Descripción
cpdf_curveto
void cpdf_close ( int pdf document)
(PHP 3>= 3.0.8, PHP 4 )
La función cpdf_close() cierra un documento PDF. Esta cpdf_curveto -- Dibuja una curva
debería ser la última operación incluso después de
cpdf_finalize(), cpdf_output_buffer() y
Descripción
cpdf_save_to_file().
Vea también cpdf_open().
void cpdf_curveto ( int pdf document, double x1, double
y1, double x2, double y2, double x3, double y3, int
cpdf_closepath_fill_stroke
mode)

(PHP 3>= 3.0.8, PHP 4 ) La función cpdf_curveto() dibuja una curva Bezier
cpdf_closepath_fill_stroke -- Cierra, llena y traza el desde el punto actual al punto (x3, y3) usando (x1, y1) y
camino actual (x2, y2) como puntos de control.
El último parámetro opcional especifica el tamaño de la void cpdf_finalize_page ( int pdf document, int page
unidad. Si es 0 o se omite, se usa la unidad especificada number)
para la página. De otro modo las coordenadas se miden
en puntos postscript, despreciando la unidad en curso.
La función cpdf_finalize_page() finaliza una página con
Vea también cpdf_moveto(), cpdf_rmoveto(),
número de página page number. Esta función es sólo
cpdf_rlineto(), cpdf_lineto().
para ahorrar memoria. Una página terminada ocupa
menos memoria pero no puede volver a ser modificada.
cpdf_end_text Vea también cpdf_page_init().

(PHP 3>= 3.0.8, PHP 4 ) cpdf_finalize


cpdf_end_text -- Finaliza una sección de texto
(PHP 3>= 3.0.8, PHP 4 )
Descripción cpdf_finalize -- Finaliza un documento

void cpdf_end_text ( int pdf document) Descripción

La función cpdf_end_text() finaliza unasección de texto void cpdf_finalize ( int pdf document)
que fue inicializada con cpdf_begin_text().
Ejemplo 1. Salida de texto
La función cpdf_finalize() finaliza un documento. Aún se
tiene que llamar a cpdf_close().
Vea también cpdf_close().
<?php cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica",
"WinAnsiEncoding"); cpdf_global_set_document_limits
cpdf_text($pdf, 100, 100, "Algún texto");
cpdf_end_text($pdf) ?>
(PHP 4 )
Vea también cpdf_begin_text(). cpdf_global_set_document_limits -- Sets document limits
for any pdf document
cpdf_fill_stroke
Description
(PHP 3>= 3.0.8, PHP 4 )
cpdf_fill_stroke -- LLena y traza el camino actual void cpdf_global_set_document_limits ( int
maxpages, int maxfonts, int maximages, int
maxannotations, int maxobjects)
Descripción

La función cpdf_global_set_document_limits() define


void cpdf_fill_stroke ( int pdf document) varios límites del documento. Esta función debe ser
llamada antes de cpdf_open() para que haga efecto.
La función cpdf_fill_stroke() llena el interior del camino Ello define los límites de cualquier documento abierto
actual con el color de relleno actual y dibuja el camino con anterioridad.
actual. Vea también cpdf_open().
Vea también cpdf_closepath(), cpdf_stroke(),
cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(),
cpdf_import_jpeg
cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

(PHP 3>= 3.0.9, PHP 4 )


cpdf_fill
cpdf_import_jpeg -- Abre una imagen JPEG

(PHP 3>= 3.0.8, PHP 4 )


Descripción
cpdf_fill -- LLena el camino actual

int cpdf_open_jpeg ( int pdf document, string file name,


Descripción
double x-koor, double y-koor, double angle, double width,
double height, double x-scale, double y-scale, int mode)
void cpdf_fill ( int pdf document)
La función cpdf_import_jpeg() abre una imagen
La función cpdf_fill() llena el interior del camino actual almacenada en el fichero de nombre file name. El
con el color alctual de relleno. formato de la imagen debe ser JPEG. La imagen es
Vea también cpdf_closepath(), cpdf_stroke(), situada en la página actual en la posición (x-koor, y-
cpdf_setgray_fill(), cpdf_setgray(), koor). La imagen es rotada angle grados.
cpdf_setrgbcolor_fill(), cpdf_setrgbcolor(). El último parámetro opcional determina el tamaño de la
unidad. Si es 0 o se omite, se usa la unidad por defecto
especificada para la página. De otro modo las
cpdf_finalize_page coordenadas se miden en puntos postscript,
despreciando la unidad actual.
Vea también cpdf_place_inline_image(),
(PHP 3>= 3.0.10, PHP 4 )
cpdf_finalize_page -- Finaliza una página
cpdf_lineto
Descripción
(PHP 3>= 3.0.8, PHP 4 )
cpdf_lineto -- Dibuja una línea en todas las demás funciones que
escriben en el documento PDF.

Descripción
La librería ClibPDF toma el nombre
de fichero "-" como sinónimo de
void cpdf_lineto ( int pdf document, double x-koor, stdout (salida estándar). Si se
double y-koor, int mode) compila PHP como módulo de
apache esto no funcionará porque la
La función cpdf_lineto() dibuja una línea desde el punto manera en que ClibPDF direcciona a
actual al punto con coordenadas (x-koor, y-koor). la salida estándar no funciona con
El último parámetro opcional determina el tamaño de la apache. Usted puede solucionar este
unidad. Si es 0 o se omite, se usa el valor especificado problema evitando el enobre de
para la página por defecto. De otro modo las fichero y usando
coordenadas se miden en puntos postscript, cpdf_output_buffer() para la salida
despreciando la unidad actual. de documentos PDF.
Vea también cpdf_moveto(), cpdf_rmoveto(),
cpdf_curveto().
Vea también cpdf_close(), cpdf_output_buffer().

cpdf_moveto
cpdf_output_buffer

(PHP 3>= 3.0.8, PHP 4 )


(PHP 3>= 3.0.9, PHP 4 )
cpdf_moveto -- Define el punto actual
cpdf_output_buffer -- Pone el documento PDF en el buffer
de memoria
Descripción
Descripción
void cpdf_moveto ( int pdf document, double x-koor,
double y-koor, int mode)
void cpdf_output_buffer ( int pdf document)

La funcióncpdf_moveto() pone el punto actual en las


La función cpdf_output_buffer() muestra el documento
coordenadas x-koor y y-koor.
PDF por la salida estándar. El documento debe ser
El último parámetro opcional determina la longitud de la
creado en memoria, que es el caso de la función
unidad. Si es 0 o se omite, la unidad por defecto será la
cpdf_open() cuando ha sido llamada sin parámetros.
especificada para la página. De otro modo las
Vea también cpdf_open().
coordenadas se medirán en puntos postscript
despreciando la unidad en curso.
cpdf_page_init
cpdf_newpath
(PHP 3>= 3.0.8, PHP 4 )
cpdf_page_init -- Comienza una nueva página
(PHP 3>= 3.0.9, PHP 4 )
cpdf_newpath -- Starts a new path
Descripción
Description
void cpdf_page_init ( int pdf document, int page
number, int orientation, double height, double width,
void cpdf_newpath ( int pdf document)
double unit)

The cpdf_newpath() starts a new path on the document


La función cpdf_page_init() crea una nueva página de
given by the pdf document parameter.
altura height y profundidad width. La página tiene el
número page number y orientación orientation.
cpdf_open orientation puede ser 0 para retrato y 1 para paisaje. El
último parámetro opcional unit define la unidad del
sistema de coordenadas. El valor debería ser el número
(PHP 3>= 3.0.8, PHP 4 ) de puntos postscript por unidad. Como el valor de una
cpdf_open -- Abre un nuevo documento PDF pulgada el igual a 72 puntos, un valor de 72 sería la
unidad para una pulgada. Por defecto es 72.
Vea también cpdf_set_current_page().
Descripción

cpdf_place_inline_image
int cpdf_open ( int compression, string filename)

LA función cpdf_open() abre un documento PDF nuevo. (PHP 3>= 3.0.9, PHP 4 )
El primer parámetro activa la compresión del documento cpdf_place_inline_image -- Situa una imagen en la página
si no es igual a 0. El segundo parámetro, opcional, es el
fichero en el que el documento es escrito. Si es omitido, Descripción
el documento es creado en memoria y puede ser escrito
en un fichero mediante la función cpdf_save_to_file() o
escrito por la salida estándar con cpdf_output_buffer(). void cpdf_place_inline_image ( int pdf document, int
image, double x-koor, double y-koor, double angle,
double width, double height, int mode)
Nota: El valor de retorno será
necesario en nuevas versiones de
ClibPDF como el primer parámetro
La función cpdf_place_inline_image() situa una imagen Vea también cpdf_moveto(), cpdf_rmoveto(),
creada con las funciones de imagenes de PHP en la cpdf_curveto().
posición de la página (x-koor, y-koor). La imagen puede
ser escalada al mismo tiempo.
El último parámetro opcional determina el tamaño de la cpdf_rmoveto
unidad. Si es 0 o se omite, se usa la unidad por defecto
especificada para la página. De otro modo las (PHP 3>= 3.0.9, PHP 4 )
coordenadas son medidas en puntos postscript,
cpdf_rmoveto -- Define el punto actual
descartando la unidad actual.
Vea también cpdf_import_jpeg(),
Descripción
cpdf_rect
void cpdf_rmoveto ( int pdf document, double x-koor,
double y-koor, int mode)
(PHP 3>= 3.0.8, PHP 4 )
cpdf_rect -- Dibuja un rectángulo
La función cpdf_rmoveto() pone el punto actual relativo
a las coordenadas x-koor y y-koor.
Descripción El último parámetro opciona determina la loingitud de la
unidad. Si es 0 o se omite, la unidad por defecto será la
especificada para la página. De otro modo las
void cpdf_rect ( int pdf document, double x-koor, double
coordenadas se medirán en puntos postscript,
y-koor, double width, double height, int mode)
despreciando la unidad en curso.
Vea también cpdf_moveto().
La función cpdf_rect() dibuja un rectángulo con su
esquina inferior izquierda en el punto (x-koor, y-koor). La
anchura es widgth. La altura es height. cpdf_rotate_text
El último parámetro opcional define el tamaño de la
unidad. Si es 0 o se omite, se usa la unidad por defecto (PHP 3>= 3.0.9, PHP 4 )
especificada para la página. De otro modo las
cpdf_rotate_text -- Sets text rotation angle
coordenadas se miden en puntos postscript,
despreciando la unidad actual.
Description
cpdf_restore
void cpdf_rotate_text ( int pdfdoc, float angle)
(PHP 3>= 3.0.8, PHP 4 )
cpdf_restore -- Restaura un entorno formalmente salvado Aviso
Esta función no está documentada actualmente, solamente
Descripción se encuentra disponible la lista de parametros.

void cpdf_restore ( int pdf document)


cpdf_rotate

La función cpdf_restore() restaura el entorno salvado


con cpdf_save(). Funciona como el comando grestore (PHP 3>= 3.0.8, PHP 4 )
de postscript. Muy útil si se quiere trasladar o rotar un cpdf_rotate -- Define la rotación
objeto sin afectar ortros objetos.
Ejemplo 1. Salvar/Restaurar
Descripción

<?php cpdf_save($pdf); void cpdf_rotate ( int pdf document, double angle)


// hacer todo tipo de rotaciones,
transformaciones, ...
La función cpdf_rotate() define la rotación en angle
cpdf_restore($pdf) ?>
grados.
Vea también cpdf_save().

cpdf_save_to_file
cpdf_rlineto

(PHP 3>= 3.0.8, PHP 4 )


(PHP 3>= 3.0.9, PHP 4 ) cpdf_save_to_file -- Escribe el documento PDF en un
cpdf_rlineto -- Dibuja una línea fichero

Descripción Descripción

void cpdf_rlineto ( int pdf document, double x-koor, void cpdf_save_to_file ( int pdf document, string
double y-koor, int mode) filename)

La función cpdf_rlineto() dibuja una línea desde el La función cpdf_save_to_file() guarda el documento
punto actual al punto relativo con coordenadas (x-koor, PDF en un fichero si este documeto ha sido creado en
y-koor). memoria. Esta función no es necesaria si el documento
El último parámetro opcional determina la longitud de la PDF ha sido abierto mediante la especificación de un
unidad. Si es 0 o se omite, se usa el valor por defecto nombre de fichero en la función cpdf_open().
para la página. De otro modo las coordenadas se miden Vea también cpdf_output_buffer(), cpdf_open().
en puntos postscript, despreciando la unidad actual.
cpdf_save Descripción

(PHP 3>= 3.0.8, PHP 4 ) void cpdf_set_creator ( string creator)


cpdf_save -- Salva el entorno actual
La función cpdf_set_creator() define el creador de un
Descripción documento PDF.
Vea también cpdf_set_subject(), cpdf_set_title(),
cpdf_set_keywords().
void cpdf_save ( int pdf document)

cpdf_set_current_page
La función cpdf_save() salva el entorno actual. Funciona
como el comando gsave de postscript. Muy útil si se
quiere trasladar o trotar un objeto sin afetar a los demás. (PHP 3>= 3.0.9, PHP 4 )
Vea también cpdf_restore(). cpdf_set_current_page -- Define la página actual

cpdf_scale Descripción

(PHP 3>= 3.0.8, PHP 4 ) void cpdf_set_current_page ( int pdf document, int
cpdf_scale -- Define la escala page number)

Descripción La función cpdf_set_current_page() define la página en


la que se van a realizar todas las operaciones. Uno puede
cambiar entre páginas a menos que una página ha sido
void cpdf_scale ( int pdf document, double x-scale, finalizada con cpdf_finalize_page().
double y-scale) Vea también cpdf_finalize_page().

La función cpdf_scale() define el factor de escala en los cpdf_set_font_directories


dos sentidos.

(PHP 4 >= 4.0.6)


cpdf_set_action_url cpdf_set_font_directories -- Sets directories to search
when using external fonts
(PHP 3>= 3.0.9, PHP 4 )
cpdf_set_action_url -- Sets hyperlink Description

Description void cpdf_set_font_directories ( int pdfdoc, string


pfmdir, string pfbdir)
void cpdf_set_action_url ( int pdfdoc, float xll, float yll,
float xur, float xur, string url [, int mode])
Aviso
Esta función no está documentada actualmente, solamente
Aviso se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
cpdf_set_font_map_file

cpdf_set_char_spacing (PHP 4 >= 4.0.6)


cpdf_set_font_map_file -- Sets fontname to filename
translation map when using external fonts
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_char_spacing -- Determina el espacio entre
caracteres Description

Descripción void cpdf_set_font_map_file ( int pdfdoc, string


filename)
void cpdf_set_char_spacing ( int pdf document, double
space)
Aviso
Esta función no está documentada actualmente, solamente
LA función cpdf_set_char_spacing() define el espacio
se encuentra disponible la lista de parametros.
entre caracteres.
Vea también cpdf_set_word_spacing(),
cpdf_set_leading().
cpdf_set_font

cpdf_set_creator
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_font -- Selecciona la fuente y el tamaño actual
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_creator -- Define el campo creator en el
documento PDF Descripción
void cpdf_set_font ( int pdf document, string font name, void cpdf_set_page_animation ( int pdf document, int
double size, string encoding) transition, double duration)

La función cpdf_set_font() define la fuente actual, el La función cpdf_set_page_animation() define la


tamaño y la codificación. Actualmente solo son transición entre páginas que se siguen.
soportadas las fuentes estándar de postscript. El último El valor de transition puede ser
parámetro encoding puede tomar los siguientes valores: 0 para ninguno,
"MacRomanEncoding", "MacExpertEncoding", 1 para dos líneas que se barren a través de la pantalla,
"WinAnsiEncoding", y "NULL". "NULL" es para el cifrado revelen la página,
incluído en la fuente. Para mas información vea el
2 para múltiples líneas,
manual de ClibPDF, especialmente para cómo soportar
las fuentes asiáticas. 3 para que una caja revele la página,
4 para una única línea,
5 para que la página naterior se disipe para revelar la
cpdf_set_horiz_scaling pagina,
6 para que el efecto de disolución se mueva de un
(PHP 3>= 3.0.8, PHP 4 ) extremop de la página al otro,
cpdf_set_horiz_scaling -- Define la escala horizontal del 7 para que la página antígua simplemente sea
texto reemplazada por la nueva página (default)
El valor de duration es el número de segundos entre las
páginas que se pasan.
Descripción

cpdf_set_subject
void cpdf_set_horiz_scaling ( int pdf document, double
scale)
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_subject -- Define el valor del campo subjet de
La función cpdf_set_horiz_scaling() define la escala
un documento PDF
horizontal al scale por ciento.

Descripción
cpdf_set_keywords

void cpdf_set_subject ( string subject)


(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_keywords -- Pone el valor del campo
'keywords'(palabras clave) de un documento PDF La función cpdf_set_subject() define el asunto de un
documento PDF
Vea también cpdf_set_title(), cpdf_set_creator(),
Descripción cpdf_set_keywords().

void cpdf_set_keywords ( string keywords) cpdf_set_text_matrix

La función cpdf_set_keywords() define las palabras


(PHP 3>= 3.0.8, PHP 4 )
clave de un documento PDF.
cpdf_set_text_matrix -- Define la matriz de texto
Vea también cpdf_set_title(), cpdf_set_creator(),
cpdf_set_subject().
Descripción
cpdf_set_leading
void cpdf_set_text_matrix ( int pdf document, array
matrix)
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_leading -- Define la distancias entre las líneas
de texto La función cpdf_set_text_matrix() define una matriz
que describe una transformación aplicada a la fuente
actual de texto.
Descripción

cpdf_set_text_pos
void cpdf_set leading ( int pdf document, double
distance)
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_text_pos -- Define la posición del texto
La función cpdf_set_leading() define la distancia entre
las líneas de texto. Esto se usará si el texto es la salida
de cpdf_continue_text(). Descripción
Vea también cpdf_continue_text().

void cpdf_set_text_pos ( int pdf document, double x-


cpdf_set_page_animation koor, double y-koor, int mode)

(PHP 3>= 3.0.9, PHP 4 ) La función cpdf_set_text_pos() define la posición del


cpdf_set_page_animation -- Define la separación entre texto para la siguiente llamada a cpdf_show().
páginas El último parámetro opcional mode determina la longitud
de la unidad. Si es 0 o se omite, se usa el valor por
defecto para la página. De otro modo, las coordenadas
Descripción son medidas en puntos postscript, despreciando la
unidad actual.
Vea también cpdf_show(), cpdf_text(). cpdf_set_word_spacing

cpdf_set_text_rendering (PHP 3>= 3.0.8, PHP 4 )


cpdf_set_word_spacing -- Define el espacio entre
palabras
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_text_rendering -- Determina cómo es
presentado el texto Descripción

Descripción void cpdf_set_word_spacing ( int pdf document, double


space)

void cpdf_set_text_rendering ( int pdf document, int


mode) La función cpdf_set_word_spacing() especifica el
espacio entre palabras.
Vea también cpdf_set_char_spacing(),
La función cpdf_set_text_rendering() determina cómo cpdf_set_leading().
es presentado el texto. Los posibles valores para mode
son 0=llenar texto, 1=poner texto, 2=llenar y poner
texto, 3=invisible, 4=llenar texto y añadirlo al camino de cpdf_setdash
corte, 5=poner texto y añadirlo al camino de corte,
6=llenar y poner texto y añadirlo al camino de corte,
7=añadirlo al camino de corte (PHP 3>= 3.0.8, PHP 4 )
cpdf_setdash -- Defina el patrón de la raya

cpdf_set_text_rise
Descripción

(PHP 3>= 3.0.8, PHP 4 )


cpdf_set_text_rise -- Define la elevación del texto void cpdf_setdash ( int pdf document, double white,
double black)

Descripción
La función cpdf_setdash() define el patrón de la raya
white unidades blancas y black unidades negras. Si los
void cpdf_set_text_rise ( int pdf document, double dos son 0 se pone una línea sólida.
value)
cpdf_setflat
La función cpdf_set_text_rise() define la elevación del
texto a value unidades.
(PHP 3>= 3.0.8, PHP 4 )
cpdf_setflat -- Define la monotonía
cpdf_set_title

Descripción
(PHP 3>= 3.0.8, PHP 4 )
cpdf_set_title -- Define el campo title de un documento
PDF void cpdf_setflat ( int pdf document, double value)

La función cpdf_setflat() pone la monotonía a un valor


Descripción
de entre 0 y 100.

void cpdf_set_title ( string title)


cpdf_setgray_fill

La función cpdf_set_title() define el título de un


documento PDF (PHP 3>= 3.0.8, PHP 4 )
Vea también cpdf_set_subject(), cpdf_set_creator(), cpdf_setgray_fill -- Pone el color de relleno al valor gris
cpdf_set_keywords().
Descripción
cpdf_set_viewer_preferences
void cpdf_setgray_fill ( int pdf document, double value)
(PHP 3>= 3.0.9, PHP 4 )
cpdf_set_viewer_preferences -- How to show the La función cpdf_setgray_fill() define el valor de gris
document in the viewer actual para rellelanr un camino.
Vea también cpdf_setrgbcolor_fill().
Description
cpdf_setgray_stroke
void cpdf_set_viewer_preferences ( int pdfdoc, array
preferences) (PHP 3>= 3.0.8, PHP 4 )
cpdf_setgray_stroke -- Define el color para dibujar al
valor gris
Aviso
Esta función no está documentada actualmente, solamente
Descripción
se encuentra disponible la lista de parametros.
void cpdf_setgray_stroke ( int pdf document, double cpdf_setmiterlimit -- Define el límite del inglete
gray value)

Descripción
La función cpdf_setgray_stroke() pone el color de
dibujo actual al valor de gris dado.
Vea también cpdf_setrgbcolor_stroke(). void cpdf_setmiterlimit ( int pdf document, double
value)

cpdf_setgray
La función cpdf_setmiterlimit() define el límite del
inglete a un valor mayor o igual a 1.
(PHP 3>= 3.0.8, PHP 4 )
cpdf_setgray -- Pone el color de relleno y dibujo a gris
cpdf_setrgbcolor_fill

Descripción
(PHP 3>= 3.0.8, PHP 4 )
cpdf_setrgbcolor_fill -- Pone el color de relleno a l valor
void cpdf_setgray ( int pdf document, double gray de clor rgb
value)

Descripción
La función cpdf_setgray_stroke() pone el color de
relleno y dibujo al color gris dado.
Vea también cpdf_setrgbcolor_stroke(), void cpdf_setrgbcolor_fill ( int pdf document, double
cpdf_setrgbcolor_fill(). red value, double green value, double blue value)

cpdf_setlinecap La función cpdf_setrgbcolor_fill() pone el color rgb


actual para rellenar un camino.
Vea también cpdf_setrgbcolor_stroke(),
(PHP 3>= 3.0.8, PHP 4 ) cpdf_setrgbcolor().
cpdf_setlinecap -- Define el parámetro linecap

cpdf_setrgbcolor_stroke
Description

(PHP 3>= 3.0.8, PHP 4 )


void cpdf_setlinecap ( int pdf document, int value) cpdf_setrgbcolor_stroke -- Pone el color de dibujo al valor
de color rgb
La función cpdf_setlinecap() define el parámetro
linecap entre los valores 0 y 2. 0 = empalmar al final, 1 Descripción
= redondear, 2 = esquina proyectada

void cpdf_setrgbcolor_stroke ( int pdf document,


cpdf_setlinejoin double red value, double green value, double blue value)

(PHP 3>= 3.0.8, PHP 4 ) La función cpdf_setrgbcolor_stroke() pone el color de


cpdf_setlinejoin -- Define el parámetro linejoin dibujo actual al valor de color rgb dado.
Vea también cpdf_setrgbcolor_fill(),
cpdf_setrgbcolor().
Descripción

cpdf_setrgbcolor
void cpdf_setlinejoin ( int pdf document, long value)

(PHP 3>= 3.0.8, PHP 4 )


La función cpdf_setlinejoin() define el parámetro entre
cpdf_setrgbcolor -- Pone el color de relleno y dibujo al
un valor de 0 y 2. 0 = ingletes, 1 = redondear, 2 =
valor de color rgb
ángulo oblícuo

Descripción
cpdf_setlinewidth

void cpdf_setrgbcolor ( int pdf document, double red


(PHP 3>= 3.0.8, PHP 4 )
value, double green value, double blue value)
cpdf_setlinewidth -- Define la profundidad de la línea

La función cpdf_setrgbcolor_stroke() pone el color de


Descripción relleno y dibujo actual al color rgb dado.
Vea también cpdf_setrgbcolor_stroke(),
cpdf_setrgbcolor_fill().
void cpdf_setlinewidth ( int pdf document, double
width)
cpdf_show_xy
La función cpdf_setlinewidth() define la preofundidad
de la línea a width.
(PHP 3>= 3.0.8, PHP 4 )
cpdf_show_xy -- Muestra texto en la posición
cpdf_setmiterlimit
Descripción
(PHP 3>= 3.0.8, PHP 4 )
void cpdf_show_xy ( int pdf document, string text, Descripción
double x-koor, double y-koor, int mode)

void cpdf_text ( int pdf document, string text, double x-


La función cpdf_show_xy() muestra la cadena text en la koor, double y-koor, int mode, double orientation, int
posición con coordenadas (x-coor, y-coor). El último alignmode)
parámetro opcional determina la longitud de la unidad. Si
es 0 o se omite, se usa la unidad por defecto
especificada para la página. De otro modo las La función cpdf_text() muestra la cadena text en la
coordenadas son medidas en puntos postscript, posición de coordenadas (x-coor, y-coor). El parámero
despreciando la unidad actual. opcional determina la longitud de la unidad. Si es 0 o se
omite, se usa la unidad por defecto especificada para la
página. De otro modo las coordenadas son medidas en
Nota: La función cpdf_show_xy() puntos postscript despreciando la unidad actual. El
es idéntica a cpdf_text() sin el parámetro opcional orientation es la rotación del texto en
parámetro opcional. grados. El parámetro opcional alignmode determina
cómo está alineado el texto. Vea la documentación de
ClibPDF para los posibles valores.
Vea también cpdf_text(). Vea también cpdf_show_xy().

cpdf_show cpdf_translate

(PHP 3>= 3.0.8, PHP 4 ) (PHP 3>= 3.0.8, PHP 4 )


cpdf_show -- Muestra el texto en la posición actual cpdf_translate -- Define el sistema de origen de
coordenadas
Descripción
Descripción
void cpdf_show ( int pdf document, string text)
void cpdf_translate ( int pdf document, double x-koor,
La función cpdf_show() muestra la cadena text en la double y-koor, int mode)
posixción actual.
Vea también cpdf_text(), cpdf_begin_text(), La función cpdf_translate() define el sistema origen de
cpdf_end_text(). coordenadas en el punto (x-coor, y-coor).
El último parámetro opcional determina la longitud de la
unidad. Si es 0 o se omite, se usa la unidad por defecto
cpdf_stringwidth
especificada en la página. De otro modo las coordenadas
son medidas en puntos postscript, depreciando la unidad
(PHP 3>= 3.0.8, PHP 4 ) actual.
cpdf_stringwidth -- Devuelve la anchura del texto en la
fuente actual
XI. Crack functions

Descripción
Introducción

double cpdf_stringwidth ( int pdf document, string text)


These functions allow you to use the CrackLib library to
test the 'strength' of a password. The 'strength' of a
La función cpdf_stringwidth() devuelve la anchura de password is tested by that checks length, use of upper
la cadena text. Requiere haber definido antes una and lower case and checked against the specified
fuente. CrackLib dictionary. CrackLib will also give helpful
Vea también cpdf_set_font(). diagnostic messages that will help 'strengthen' the
password.
cpdf_stroke
Requerimientos
(PHP 3>= 3.0.8, PHP 4 )
cpdf_stroke -- Dibuja una línea a lo largo del camino More information regarding CrackLib along with the
library can be found at
http://www.users.dircon.co.uk/~crypto/.
Descripción

void cpdf_stroke ( int pdf document) Instalación

La función cpdf_stroke() dibuja una línea a lo largo del In order to use these functions, you must compile PHP
camino actual. with Crack support by using the --with-crack[=DIR]
Vea también cpdf_closepath(), option.
cpdf_closepath_stroke().

Configuración en tiempo de ejecución


cpdf_text

The behaviour of these functions is affected by settings


(PHP 3>= 3.0.8, PHP 4 ) in php.ini.
cpdf_text -- Muestra texto conparámetros Tabla 1. Crack configuration options
Defa Este módulo es EXPERIMENTAL. Esto significa que el
Name Changeable
ult comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
crack.default_dict PHP_INI_SYSTE
NULL en una futura version de PHP SIN AVISO. Quedas avisado, y
ionary M
utilizar este módulo es tu responsabiliad.
For further details and definition of the PHP_INI_*
crack_check() performs an obscure check with the
constants see ini_set().
given password on the specified dictionary . If dictionary
is not specified, the last opened dictionary is used.
Tipos de recursos
crack_closedict
Esta extensión no define ningún tipo de recurso.
(PHP 4 >= 4.0.5)
crack_closedict -- Closes an open CrackLib dictionary
Constantes predefinidas

Description
Esta extensión no define ninguna constante.

bool crack_closedict ( [resource dictionary])


Ejemplos
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
This example shows how to open a CrackLib dictionary, Aviso
test a given password, retrieve any diagnostic messages,
and close the dictionary. Este módulo es EXPERIMENTAL. Esto significa que el
Ejemplo 1. CrackLib example 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
<?php utilizar este módulo es tu responsabiliad.
// Open CrackLib Dictionary crack_closedict() closes the specified dictionary
$dictionary = identifier. If dictionary is not specified, the current
crack_opendict('/usr/local/lib/pw_dict') dictionary is closed.
or die('Unable to open CrackLib
dictionary');
crack_getlastmessage
// Perform password check
$check = crack_check($dictionary,
(PHP 4 >= 4.0.5)
'gx9A2s0x');
crack_getlastmessage -- Returns the message from the
last obscure check
// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password' Description

// Close dictionary
crack_closedict($dictionary); string crack_getlastmessage ( void)
?>

Aviso
Nota: If crack_check() returns Este módulo es EXPERIMENTAL. Esto significa que el
TRUE, crack_getlastmessage() comportamineto de estas funciones, nombre de funciones
will return 'strong password'. 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.
Tabla de contenidos
crack_check -- Performs an obscure check with the given crack_getlastmessage() returns the message from the
password last obscure check.
crack_closedict -- Closes an open CrackLib dictionary
crack_getlastmessage -- Returns the message from the
last obscure check crack_opendict
crack_opendict -- Opens a new CrackLib dictionary
(PHP 4 >= 4.0.5)
crack_check crack_opendict -- Opens a new CrackLib dictionary

(PHP 4 >= 4.0.5) Description


crack_check -- Performs an obscure check with the given
password resource crack_opendict ( string dictionary)

Description Returns a dictionary resource identifier on success, or


FALSE on failure.
bool crack_check ( [resource dictionary, string Aviso
password]) Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Returns TRUE if password is strong, or FALSE otherwise. y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Aviso
utilizar este módulo es tu responsabiliad. (PHP 4 >= 4.0.2)
curl_close -- Close a CURL session
crack_opendict() opens the specified CrackLib
dictionary for use with crack_check().
Description

Nota: Only one dictionary may be


open at a time. void curl_close ( int ch)

See also: crack_check(), and crack_closedict(). This functions closes a CURL session and frees all
ressources. The CURL handle, ch, is also deleted.

XII. CURL, Client URL Library Functions


curl_errno

PHP supports libcurl, a library, created by Daniel


Stenberg, that allows you to connect and communicate (PHP 4 >= 4.0.3)
to many different types of servers with many different curl_errno -- Return an integer containing the last error
types of protocols. libcurl currently supports the http, number
https, ftp, gopher, telnet, dict, file, and ldap protocols.
libcurl also supports HTTPS certificates, HTTP POST, HTTP Description
PUT, FTP uploading (this can also be done with PHP's ftp
extension), HTTP form based upload, proxies, cookies
and user+password authentication. int curl_errno ( resource ch)
In order to use the CURL functions you need to install the
CURL package. PHP requires that you use CURL 7.0.2-
beta or higher. PHP will not work with any version of Aviso
CURL below version 7.0.2-beta.
Esta función no está documentada actualmente, solamente
To use PHP's CURL support you must also compile PHP
se encuentra disponible la lista de parametros.
--with-curl[=DIR] where DIR is the location of the
directory containing the lib and include directories. In the
"include" directory there should be a folder named "curl"
which should contain the easy.h and curl.h files. There curl_error
should be a file named "libcurl.a" located in the "lib"
directory. (PHP 4 >= 4.0.3)
These functions have been added in PHP 4.0.2. curl_error -- Return a string containing the last error for
Once you've compiled PHP with CURL support, you can the current session
begin using the curl functions. The basic idea behind the
CURL functions is that you initialize a CURL session using
the curl_init(), then you can set all your options for the Description
transfer via the curl_exec() and then you finish off your
session using the curl_close(). Here is an example that
uses the CURL functions to fetch the PHP homepage into string curl_error ( resource ch)
a file:
Ejemplo 1. Using PHP's CURL module to fetch the
PHP homepage Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
<?php

$ch = curl_init curl_exec


("http://www.php.net/");
$fp = fopen
("php_homepage.txt", "w"); (PHP 4 >= 4.0.2)
curl_exec -- Perform a CURL session
curl_setopt ($ch,
CURLOPT_INFILE, $fp);
Description
curl_setopt ($ch,
CURLOPT_HEADER, 0);
bool curl_exec ( int ch)
curl_exec ($ch);
curl_close ($ch);
fclose ($fp); This function is should be called after you initialize a
?> CURL session and all the options for the session are set.
Its purpose is simply to execute the predefined CURL
Tabla de contenidos session (given by the ch).
curl_close -- Close a CURL session
curl_errno -- Return an integer containing the last error
number curl_getinfo
curl_error -- Return a string containing the last error for
the current session
curl_exec -- Perform a CURL session (PHP 4 >= 4.0.4)
curl_getinfo -- Get information regarding a specific curl_getinfo -- Get information regarding a specific
transfer transfer
curl_init -- Initialize a CURL session
curl_setopt -- Set an option for a CURL transfer Description
curl_version -- Return the current CURL version

string curl_getinfo ( resource ch [, int opt])


curl_close
Returns information about the last transfer, opt may be
one of the following:
• "namelookup_time"
• "connect_time"
• "pretransfer_time"
• "CURLINFO_EFFECTIVE_URL" - Last effective
URL • "size_upload"
• "CURLINFO_HTTP_CODE" - Last received HTTP • "size_download"
code • "speed_download"
• "CURLINFO_FILETIME" - Remote time of the • "speed_upload"
retrieved document, if -1 is returned the time
of the document is unknown • "download_content_length"
• "CURLINFO_TOTAL_TIME" - Total transaction • "upload_content_length"
time in seconds for last transfer • "starttransfer_time"
• "CURLINFO_NAMELOOKUP_TIME" - Time in • "redirect_time"
seconds until name resolving was complete
• "CURLINFO_CONNECT_TIME" - Time in seconds
curl_init
it took to establish the connection
• "CURLINFO_PRETRANSFER_TIME" - Time in
seconds from start until just before file transfer (PHP 4 >= 4.0.2)
begins curl_init -- Initialize a CURL session
• "CURLINFO_STARTTRANSFER_TIME" - Time in
seconds until the first byte is about to be Description
transfered
• "CURLINFO_REDIRECT_TIME" - Time in seconds int curl_init ( [string url])
of all redirection steps before final transaction
was started
The curl_init() will initialize a new session and return a
• "CURLINFO_SIZE_UPLOAD" - Total number of CURL handle for use with the curl_setopt(),
bytes uploaded curl_exec(), and curl_close() functions. If the optional
• "CURLINFO_SIZE_DOWNLOAD" - Total number url parameter is supplied then the CURLOPT_URL option
of bytes downloaded will be set to the value of the parameter. You can
manually set this using the curl_setopt() function.
• "CURLINFO_SPEED_DOWNLOAD" - Average Ejemplo 1. Initializing a new CURL session and
download speed fetching a webpage
• "CURLINFO_SPEED_UPLOAD" - Average upload
speed
<?php
• "CURLINFO_HEADER_SIZE" - Total size of all $ch = curl_init();
headers received
• "CURLINFO_REQUEST_SIZE" - Total size of curl_setopt ($ch, CURLOPT_URL,
issued requests, currently only for HTTP "http://www.zend.com/");
requests curl_setopt ($ch, CURLOPT_HEADER, 0);
• "CURLINFO_SSL_VERIFYRESULT" - Result of SSL curl_exec ($ch);
certification verification requested by setting
CURLOPT_SSL_VERIFYPEER curl_close ($ch);
• "CURLINFO_CONTENT_LENGTH_DOWNLOAD" - ?>
content-length of download, read from See also: curl_close(), curl_setopt()
Content-Length: field
• "CURLINFO_CONTENT_LENGTH_UPLOAD" -
curl_setopt
Specified size of upload
• "CURLINFO_CONTENT_TYPE" - Content-type of
downloaded object, NULL indicates server did (PHP 4 >= 4.0.2)
not send valid Content-Type: header curl_setopt -- Set an option for a CURL transfer

If called without the optional parameter opt an assoctive Description


array is returned with the following array elements which
correspond to opt options: bool curl_setopt ( int ch, string option, mixed value)

• "url" The curl_setopt() function will set options for a CURL


session identified by the ch parameter. The option
• "content_type" parameter is the option you want to set, and the value is
• "http_encode" the value of the option given by the option.
The value should be a long for the following options
• "header_size" (specified in the option parameter):
• "request_size"
• "filetime" • CURLOPT_INFILESIZE: When you are uploading
• "ssl_verify_result" a file to a remote site, this option should be
used to tell PHP what the expected size of the
• "redirect_count" infile will be.
• "total_time"
CURLOPT_LOW_SPEED_LIMIT for PHP to
• CURLOPT_VERBOSE: Set this option to a non-
consider it too slow and abort.
zero value if you want CURL to report
everything that is happening. • CURLOPT_RESUME_FROM: Pass a long as a
parameter that contains the offset, in bytes,
• CURLOPT_HEADER: Set this option to a non-
that you want the transfer to start from.
zero value if you want the header to be
included in the output. • CURLOPT_SSLVERSION: Pass a long as a
parameter that contains the SSL version (2 or
• CURLOPT_NOPROGRESS: Set this option to a
3) to use. By default PHP will try and determine
non-zero value if you don't want PHP to display
this by itself, although, in some cases you
a progress meter for CURL transfers
must set this manually.
• CURLOPT_TIMECONDITION: Pass a long as a
Nota: PHP automatically parameter that defines how the
sets this option to a non- CURLOPT_TIMEVALUE is treated. You can set
zero parameter, this this parameter to TIMECOND_IFMODSINCE or
should only be changed TIMECOND_ISUNMODSINCE. This is a HTTP-only
for debugging purposes. feature.
• CURLOPT_TIMEVALUE: Pass a long as a
• CURLOPT_NOBODY: Set this option to a non- parameter that is the time in seconds since
January 1st, 1970. The time will be used as
zero value if you don't want the body included
specified by the CURLOPT_TIMEVALUE option,
with the output.
or by default the TIMECOND_IFMODSINCE will
• CURLOPT_FAILONERROR: Set this option to a be used.
non-zero value if you want PHP to fail silently if
the HTTP code returned is greater than 300.
The default behaviour is to return the page The value parameter should be a string for the following
normally, ignoring the code. values of the option parameter:
• CURLOPT_UPLOAD: Set this option to a non-
zero value if you want PHP to prepare for an
upload.
• CURLOPT_URL: This is the URL that you want
PHP to fetch. You can also set this option when
• CURLOPT_POST: Set this option to a non-zero initializing a session with the curl_init()
value if you want PHP to do a regular HTTP function.
POST. This POST is a normal application/x-
www-from-urlencoded kind, most commonly
• CURLOPT_USERPWD: Pass a string formatted in
the [username]:[password] manner, for PHP to
used by HTML forms.
use for the connection. connection.
• CURLOPT_FTPLISTONLY: Set this option to a
• CURLOPT_PROXYUSERPWD: Pass a string
non-zero value and PHP will just list the names
formatted in the [username]:[password] format
of an FTP directory.
for connection to the HTTP proxy.
• CURLOPT_FTPAPPEND: Set this option to a non-
• CURLOPT_RANGE: Pass the specified range you
zero value and PHP will append to the remote
want. It should be in the "X-Y" format, where X
file instead of overwriting it.
or Y may be left out. The HTTP transfers also
• CURLOPT_NETRC: Set this option to a non-zero support several intervals, seperated with
value and PHP will scan your ~./netrc file to commas as in X-Y,N-M.
find your username and password for the
remote site that you're establishing a
• CURLOPT_POSTFIELDS: Pass a string containing
the full data to post in an HTTP "POST"
connection with.
operation.
• CURLOPT_FOLLOWLOCATION: Set this option to
• CURLOPT_REFERER: Pass a string containing
a non-zero value to follow any "Location: "
the "referer" header to be used in an HTTP
header that the server sends as a part of the
request.
HTTP header (note this is recursive, PHP will
follow as many "Location: " headers that it is • CURLOPT_USERAGENT: Pass a string
sent.) containing the "user-agent" header to be used
in an HTTP request.
• CURLOPT_PUT: Set this option a non-zero value
to HTTP PUT a file. The file to PUT must be set • CURLOPT_FTPPORT: Pass a string containing
with the CURLOPT_INFILE and the which will be used to get the IP address to
CURLOPT_INFILESIZE. use for the ftp "PORT" instruction. The POST
instruction tells the remote server to connect
• CURLOPT_MUTE: Set this option to a non-zero
to our specified IP address. The string may be
value and PHP will be completely silent with
a plain IP address, a hostname, a network
regards to the CURL functions.
interface name (under UNIX), or just a plain '-'
• CURLOPT_TIMEOUT: Pass a long as a to use the systems default IP address.
parameter that contains the maximum time, in
seconds, that you'll allow the curl functions to
• CURLOPT_COOKIE: Pass a string containing the
content of the cookie to be set in the HTTP
take.
header.
• CURLOPT_LOW_SPEED_LIMIT: Pass a long as a
• CURLOPT_SSLCERT: Pass a string containing
parameter that contains the transfer speed in
the filename of PEM formatted certificate.
bytes per second that the transfer should be
below during CURLOPT_LOW_SPEED_TIME • CURLOPT_SSLCERTPASSWD: Pass a string
seconds for PHP to consider it too slow and containing the password required to use the
abort. CURLOPT_SSLCERT certificate.
• CURLOPT_LOW_SPEED_TIME: Pass a long as a • CURLOPT_COOKIEFILE: Pass a string containing
parameter that contains the time in seconds the name of the file containing the cookiee
that the transfer should be below the data. The cookie file can be in Netscape
format, or just plain HTTP-style headers string cybercash_base64_encode ( string inbuff)
dumped into a file.
• CURLOPT_CUSTOMREQUEST: Pass a string to cybercash_decr
be used instead of GET or HEAD when doing an
HTTP request. This is useful for doing DELETE
or another, more obscure, HTTP request. (PHP 4 <= 4.2.3)
cybercash_decr -- ???

Nota: Don't do this


without making sure your Descripción
server supports the
command first.
array cybercash_decr ( string wmk, string sk, string
inbuff)
The following options expect a file descriptor that is
obtained by using the fopen() function: La función devuelve un array asociativo con los
elementos "errcode" y, si "errcode" es FALSE, "outbuff"
(string), "outLth" (long) y "macbuff" (string).
• CURLOPT_FILE: The file where the output of
your transfer should be placed, the default is
STDOUT. cybercash_encr
• CURLOPT_INFILE: The file where the input of
your transfer comes from. (PHP 4 <= 4.2.3)
• CURLOPT_WRITEHEADER: The file to write the cybercash_encr -- ???
header part of the output into.
• CURLOPT_STDERR: The file to write errors to Descripción
instead of stderr.
array cybercash_encr ( string wmk, string sk, string
curl_version inbuff)

La función devuelve un array asociativo con los


(PHP 4 >= 4.0.2)
elementos "errcode" y, si "errcode" es FALSE, "outbuff"
curl_version -- Return the current CURL version
(string), "outLth" (long) y "macbuff" (string).

Description
XIV. Crédit Mutuel CyberMUT functions

string curl_version ( void)


Introducción

The curl_version() function returns a string containing


the current CURL version. This extension allows you to process credit cards
transactions using Crédit Mutuel CyberMUT system
(http://www.creditmutuel.fr/centre_commercial/vendez_s
XIII. Funciones de pago electrónico ur_internet.html).
CyberMUT is a popular Web Payment Service in France,
provided by the Crédit Mutuel bank. If you are foreign in
Estas funciones solo están disponibles si el intérprete ha France, these functions will not be useful for you.
sido compilado con --with-cybercash=[DIR]. Estas The use of these functions is almost identical to the
funciones han sido añadidas en PHP4. original SDK functions, except for the parameters of
Tabla de contenidos return for cybermut_creerformulairecm() and
cybercash_base64_decode -- cybermut_creerreponsecm(), which are returned
cybercash_base64_encode -- ??? directly by functions PHP, whereas they had passed in
cybercash_decr -- ??? reference in the original functions.
cybercash_encr -- ??? These functions have been added in PHP 4.0.6.

cybercash_base64_decode Nota: These functions only provide


a link to CyberMUT SDK. Be sure to
(PHP 4 <= 4.2.3) read the CyberMUT Developers
cybercash_base64_decode -- Guide for full details of the required
parameters.

Descripción

string cybercash_base64_decode ( string inbuff) Instalación

cybercash_base64_encode These functions are only available if PHP has been


compiled with the --with-cybermut[=DIR] option, where
DIR is the location of libcm-mac.a and cm-mac.h . You
(PHP 4 <= 4.2.3) will require the appropriate SDK for your platform, which
cybercash_base64_encode -- ??? may be sent to you after your CyberMUT's subscription
(contact them via Web, or go to the nearest Crédit
Mutuel).
Descripción
Nota: This extension is not available cybermut_creerreponsecm() returns a string
on Windows platforms. containing delivery acknowledgement message.
The parameter is "OK" if the message of confirmation of
the payment was correctly identified by
Tabla de contenidos cybermut_testmac(). Any other chain is regarded as an
cybermut_creerformulairecm -- Generate HTML form of error message.
request for payment See also cybermut_creerformulairecm() and
cybermut_creerreponsecm -- Generate the cybermut_testmac().
acknowledgement of delivery of the confirmation of
payment
cybermut_testmac -- Make sure that there no was data cybermut_testmac
diddling contained in the received message of
confirmation
(4.0.5 - 4.2.3 only)
cybermut_testmac -- Make sure that there no was data
cybermut_creerformulairecm diddling contained in the received message of
confirmation

(4.0.5 - 4.2.3 only)


cybermut_creerformulairecm -- Generate HTML form of Description
request for payment

bool cybermut_testmac ( string code_MAC, string


Description version, string TPE, string cdate, string montant, string
ref_commande, string texte_libre, string code-retour)

string cybermut_creerformulairecm ( string url_CM,


string version, string TPE, string montant, string cybermut_testmac() is used to make sure that there
ref_commande, string texte_libre, string url_retour, string was not data diddling contained in the received message
url_retour_ok, string url_retour_err, string langue, string of confirmation. Pay attention to parameters code-retour
code_societe, string texte_bouton) and texte-libre, which cannot be evaluated as is, because
of the dash. You must retrieve them by using:

cybermut_creerformulairecm() is used to generate <?php


the HTML form of request for payment. $code_retour =
Ejemplo 1. First step of payment (equiv cgi1.c) $_GET["code-retour"];
$texte_libre =
$_GET["texte-libre"];
?>
<?php
// Directory where the keys are located Ejemplo 1. Last step of payment (equiv cgi2.c)
putenv("CMKEYDIR=/var/creditmut/cles");

// Version number <?php


$VERSION="1.2"; // Make sure that Enable Track Vars is ON.
// Directory where are located the keys
$retour = cybermut_creerformulairecm( putenv("CMKEYDIR=/var/creditmut/cles");
"https://www.creditmutuel.fr/test/telepaiem
ent/paiement.cgi", // Version number
$VERSION, $VERSION="1.2";
"1234567890",
"300FRF", $texte_libre = $_GET["texte-libre"];
$REFERENCE, $code_retour = $_GET["code-retour"];
$TEXTE_LIBRE,
$URL_RETOUR, $mac_ok = cybermut_testmac($MAC,$VERSION,$TPE,$date,$montant,
$URL_RETOUR_OK, $reference,$texte_libre,$code_retour);
$URL_RETOUR_ERR,
"francais", if ($mac_ok) {
"company",
"Paiement par carte bancaire"); //
// insert data processing here
echo $retour; //
?> //
See also cybermut_testmac() and
cybermut_creerreponsecm(). $result=cybermut_creerreponsecm("OK");
} else {
$result=cybermut_creerreponsecm("Document Falsifie");
cybermut_creerreponsecm }

?>
(4.0.5 - 4.2.3 only)
cybermut_creerreponsecm -- Generate the See also cybermut_creerformulairecm() and
acknowledgement of delivery of the confirmation of cybermut_creerreponsecm().
payment
XV. Cyrus IMAP administration functions
Description
Introducción
string cybermut_creerreponsecm ( string phrase)

Aviso
Esta función no está documentada actualmente, solamente cyrus_close -- Close connection to a Cyrus IMAP server
se encuentra disponible la lista de parametros.
Description

Nota: This extension is not available


on Windows platforms. bool cyrus_close ( resource connection)

Aviso

Instalación Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros.

To enable Cyrus IMAP support and to use these functions


you have to compile PHP with the --with-cyrus option. cyrus_connect

Constantes predefinidas (PHP 4 >= 4.1.0)


cyrus_connect -- Connect to a Cyrus IMAP server

Estas constantes están definidas por esta extensión y


estarán disponibles solamente cuando la extensión ha Description
sido o bien compilada dentro de PHP o grabada
dinamicamente en tiempo de ejecución.
CYRUS_CONN_NONSYNCLITERAL (integer) resource cyrus_connect ( [string host [, string port [, int
CYRUS_CONN_INITIALRESPONSE (integer) flags]]])
CYRUS_CALLBACK_NUMBERED (integer)
CYRUS_CALLBACK_NOLITERAL (integer)
Aviso
Tabla de contenidos
cyrus_authenticate -- Authenticate against a Cyrus IMAP Esta función no está documentada actualmente, solamente
server se encuentra disponible la lista de parametros.
cyrus_bind -- Bind callbacks to a Cyrus IMAP connection
cyrus_close -- Close connection to a Cyrus IMAP server
cyrus_connect -- Connect to a Cyrus IMAP server cyrus_query
cyrus_query -- Send a query to a Cyrus IMAP server
cyrus_unbind -- Unbind ...
(PHP 4 >= 4.1.0)
cyrus_query -- Send a query to a Cyrus IMAP server
cyrus_authenticate

Description
(PHP 4 >= 4.1.0)
cyrus_authenticate -- Authenticate against a Cyrus IMAP
server bool cyrus_query ( resource connection, string query)

Description Aviso
Esta función no está documentada actualmente, solamente
bool cyrus_authenticate ( resource connection [, string se encuentra disponible la lista de parametros.
mechlist [, string service [, string user [, int minssf [, int
maxssf]]]]])
cyrus_unbind

Aviso
(PHP 4 >= 4.1.0)
Esta función no está documentada actualmente, solamente cyrus_unbind -- Unbind ...
se encuentra disponible la lista de parametros.

Description
cyrus_bind
bool cyrus_unbind ( resource connection, string
(PHP 4 >= 4.1.0) trigger_name)
cyrus_bind -- Bind callbacks to a Cyrus IMAP connection

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
bool cyrus_bind ( resource connection, array callbacks)

XVI. Character type functions


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

The functions provided by this extension check whether a


cyrus_close character or string falls into a certain character class
according to the current locale (see also setlocale()).
When called with an integer argument these functions
(PHP 4 >= 4.1.0) behave exactly like their C counterparts from ctype.h.
When called with a string argument they will check every letters are just [A-Za-z]. The function is equivalent to
character in the string and will only return TRUE if every (ctype_alpha($text) || ctype_digit($text)).
character in the string matches the requested criteria. See also ctype_alpha(), ctype_digit(), and
When called with an empty string the result will always setlocale().
be TRUE.
Passing anything else but a string or integer will return
FALSE immediately. ctype_alpha

(PHP 4 >= 4.0.4)


Requerimientos
ctype_alpha -- Check for alphabetic character(s)

None besides functions from the standard C library which


Description
are always available.

bool ctype_alpha ( string text)


Instalación

Returns TRUE if every character in text is a letter from


Beginning with PHP 4.2.0 these functions are enabled by the current locale, FALSE otherwise. In the standard C
default. For older versions you have to configure and locale letters are just [A-Za-z] and ctype_alpha() is
compile PHP with --enable-ctype. You can disable ctype equivalent to (ctype_upper($text) || ctype_lower($text)),
support with --disable-ctype. but other languages have letters that are considered
The windows version of PHP has built in support for this neither upper nor lower case.
extension. You do not need to load any additional See also ctype_upper(), ctype_lower(), and
extension in order to use these functions. setlocale().

Nota: Builtin support for ctype is ctype_cntrl


available with PHP 4.3.0.

(PHP 4 >= 4.0.4)


ctype_cntrl -- Check for control character(s)

Configuración en tiempo de ejecución


Description

Esta extensión no define ninguna directiva de


configuración. bool ctype_cntrl ( string text)

Returns TRUE if every character in text has a special


Tipos de recursos
control function, FALSE otherwise. Control characters
are e.g. line feed, tab, esc.
Esta extensión no define ningún tipo de recurso.
ctype_digit
Constantes predefinidas
(PHP 4 >= 4.0.4)
ctype_digit -- Check for numeric character(s)
Esta extensión no define ninguna constante.
Tabla de contenidos
ctype_alnum -- Check for alphanumeric character(s) Description
ctype_alpha -- Check for alphabetic character(s)
ctype_cntrl -- Check for control character(s)
ctype_digit -- Check for numeric character(s) bool ctype_digit ( string text)
ctype_graph -- Check for any printable character(s)
except space
Returns TRUE if every character in text is a decimal
ctype_lower -- Check for lowercase character(s)
digit, FALSE otherwise.
ctype_print -- Check for printable character(s)
See also ctype_alnum() and ctype_xdigit().
ctype_punct -- Check for any printable character which is
not whitespace or an alphanumeric character
ctype_space -- Check for whitespace character(s) ctype_graph
ctype_upper -- Check for uppercase character(s)
ctype_xdigit -- Check for character(s) representing a
hexadecimal digit (PHP 4 >= 4.0.4)
ctype_graph -- Check for any printable character(s)
except space
ctype_alnum

Description
(PHP 4 >= 4.0.4)
ctype_alnum -- Check for alphanumeric character(s)
bool ctype_graph ( string text)

Description
Returns TRUE if every character in text is printable and
actually creates visible output (no white space), FALSE
bool ctype_alnum ( string text) otherwise.
See also ctype_alnum(), ctype_print(), and
ctype_punct().
Returns TRUE if every character in text is either a letter
or a digit, FALSE otherwise. In the standard C locale
ctype_lower bool ctype_upper ( string text)

(PHP 4 >= 4.0.4) Returns TRUE if every character in text is a uppercase


ctype_lower -- Check for lowercase character(s) letter in the current locale.
See also ctype_alpha() and ctype_lower().

Description
ctype_xdigit

bool ctype_lower ( string text)


(PHP 4 >= 4.0.4)
ctype_xdigit -- Check for character(s) representing a
Returns TRUE if every character in text is a lowercase hexadecimal digit
letter in the current locale.
See also ctype_alpha() and ctype_upper().
Description

ctype_print
bool ctype_xdigit ( string text)

(PHP 4 >= 4.0.4)


ctype_print -- Check for printable character(s) Returns TRUE if every character in text is a hexadecimal
'digit', that is a decimal digit or a character from [A-Fa-f] ,
FALSE otherwise.
Description See also ctype_digit().

bool ctype_print ( string text) XVII. Funciones de la capa de abstraccion de bases


de datos (dbm-style)
Returns TRUE if every character in text will actually
create output (including blanks). Returns FALSE if text Estas funciones son la base para el acceso a bases de
contains control characters or characters that do not datos del estilo Berkeley DB.
have any output or control function at all. Este es un nivel de abstraccion general para varias bases
See also ctype_cntrl(), ctype_graph(), and de datos. Como tal su funcionalidad esta limitada a un
ctype_punct(). grupo de modernas bases de datos como Sleepycat
Software's DB2. (Esta no debe confundirse con IBM DB2
software, la cual es soportada mediante las funciones
ctype_punct
ODBC.)
El comportamiento de varios aspectos depende de la
(PHP 4 >= 4.0.4) implementacion de la base de datos. Funciones como
ctype_punct -- Check for any printable character which is dba_optimize() y dba_sync() cumpliran su
not whitespace or an alphanumeric character funcionalidad con unas bases de datos pero no con otras.
Los siguientes manejadores (handlers) estan soportados:

Description
• dbm es el mas antiguo (original) tipo de base
bool ctype_punct ( string text) de datos de la familia de Berkeley DB. Se debe
evitar su uso, si es posible. Nosotros no
soportamos las funciones de compatibilidad de
Returns TRUE if every character in text is printable, but DB2 y gdbm, porque ellas solo son compatibles
neither letter, digit or blank, FALSE otherwise. a nivel de codigo fuente, pero no pueden
See also ctype_cntrl(), ctype_graph(), and manejar el formato original dbm.
ctype_punct().
• ndbm es un tipo mas nuevo y mas flexible que
dbm. Todavia tiene la mayoria de las
ctype_space limitaciones de dbm (Por lo tanto es
descartado).

(PHP 4 >= 4.0.4) • gdbm es el gestor de bases de datos de GNU


ctype_space -- Check for whitespace character(s) (database manager).
• db2 es Sleepycat Software's DB2. Es descrito
como "un conjunto de herramientas de
Description
programacion que proveen acceso de alto nivel
a bases de datos en aplicaciones standalone o
bool ctype_space ( string text) en el modelo cliente/servidor. "
• cdb es "una rapida, de confianza, sencilla
Returns TRUE if every character in text creates some herramienta para la creacion y lectura de
sort of white space, FALSE otherwise. Besides the blank bases de datos constantes." Fue creada por el
character this also includes tab, vertical tab, line feed, autor de qmail y puede encontrarse en here.
carriage return and form feed characters. Como la base es constante solo se soportan las
operaciones de lectura.

ctype_upper
Ejemplo 1. Ejemplo de DBA

(PHP 4 >= 4.0.4)


ctype_upper -- Check for uppercase character(s) <?php

Description $id = dba_open("/tmp/test.db",


void dba_close ( int handle)
"n", "db2");

if(!$id) { dba_close() cierra la conexion con una base de datos


echo "dba_open failed\n"; previamente abierta y libera todos los recursos
exit; especificados por handle.
} handle es un manejador (handle) de la base de datos
devuelto por dba_open().
dba_replace("key", "This is an dba_close() no devuelve ningun valor.
example!", $id); Ver tambien: dba_open() dba_popen()

if(dba_exists("key", $id)) {
echo dba_fetch("key", $id); dba_delete
dba_delete("key", $id);
}
(PHP 3>= 3.0.8, PHP 4 )
dba_delete -- Borra una entrada especificada por la clave
dba_close($id);
key
?>
DBA es "binary safe" y no tiene ningun limite arbitrario.
Hereda todas sus limitaciones de la implementacion de Descripcion
base de datos que tenga.
Todos las bases de datos basadas en ficheros deben bool dba_delete ( string key, int handle)
proveer un mecanismo para establecer el modo a la hora
de crear nuevas bases de datos, si ello es posible.
Habitualmente este modo es pasado como el cuarto dba_delete() borra la entrada especificada por key de la
argumento en dba_open() o en dba_popen(). base de datos especificada por handle.
Se puede acceder a todas las entradas de una base de key es la clave de la entrada que es borrada.
datos de modo secuencial (lineal) usando las funciones handle es un manejador (handle) de la base de datos
dba_firstkey() y dba_nextkey(). No se puede cambiar devuelto por dba_open().
la base de datos mientras se recorre (traversing) por ella. dba_delete() devuelve TRUE o FALSE, si la entrada es
Ejemplo 2. Recorriendo una base de datos borrada o no, respectivamente.
Ver tambien: dba_exists() dba_fetch() dba_insert()
dba_replace()
<?php
dba_exists
# ...open database...

$key = dba_firstkey($id); (PHP 3>= 3.0.8, PHP 4 )


dba_exists -- Comprueba si la clave key existe
while($key != false) {
if(...) { # remember the key to perform
some action later Descripcion
$handle_later[] = $key;
}
$key = dba_nextkey($id); bool dba_exists ( string key, int handle)
}
dba_exists() comprueba si la clave key existe en la
for($i = 0; $i < count($handle_later); $i+ base de datos especificada por handle.
+) key es la clave para la que se realiza la comprobacion.
dba_delete($handle_later[$i], $id); handle es un manejador (handle) de la base de datos
devuelto por dba_open().
?> dba_exists() devuelve TRUE o FALSE, si la clave es
Tabla de contenidos hallada o no, respectivamente.
dba_close -- Cerrar uba base de datos Ver tambien: dba_fetch() dba_delete() dba_insert()
dba_delete -- Borra una entrada especificada por la clave dba_replace()
key
dba_exists -- Comprueba si la clave key existe dba_fetch
dba_fetch -- Extrae los datos especificados por la clave
key
dba_firstkey -- Conseguir la primera clave (PHP 3>= 3.0.8, PHP 4 )
dba_handlers -- List handlers available dba_fetch -- Extrae los datos especificados por la clave
dba_insert -- Insertar una entrada key
dba_list -- List all open database files
dba_nextkey -- Extraer la siguiente clave
dba_open -- Abrir una base de datos Descripcion
dba_optimize -- Optimiza la base de datos
dba_popen -- Apertura persistente de una base de datos
string dba_fetch ( string key, int handle)
dba_replace -- Reemplaza o inserta una entrada
dba_sync -- Sincroniza la base de datos
dba_fetch() extrae los datos especificados por la clave
key de la base de datos determinada por handle.
dba_close key es la clave de la entrada de los datos que queremos
extraer.
handle es un manejador (handle) de la base de datos
(PHP 3>= 3.0.8, PHP 4 )
devuelto por dba_open().
dba_close -- Cerrar uba base de datos
dba_fetch() devuelve la cadena asociada o FALSE, si el
par key/data es hallado o no, respectivamente.
Descripcion Ver tambien: dba_exists() dba_delete() dba_insert()
dba_replace()
dba_firstkey dba_nextkey

(PHP 3>= 3.0.8, PHP 4 ) (PHP 3>= 3.0.8, PHP 4 )


dba_firstkey -- Conseguir la primera clave dba_nextkey -- Extraer la siguiente clave

Descripcion Descripcion

string dba_firstkey ( int handle) string dba_nextkey ( int handle)

dba_firstkey() devuelve la primera clave de la base de dba_nextkey() devuelve la siguiente clave de la base
datos especificada por handle y resetea el puntero de datos especificada por handle e incrementa el
interno de claves. Esto permite una busqueda lineal por puntero de claves interno.
toda la base de datos. handle es un manejador (handle) de la base de datos
handle es un manejador (handle) de la base de datos devuelto por dba_open().
devuelto por dba_open(). dba_nextkey() devuelve la clave o FALSE dependiendo
dba_firstkey() devuelve la clave o FALSE en funcion de de si tiene exito o falla, respectivamente.
si tiene exito o falla, respectivamente. Ver tambien: dba_firstkey()
Ver tambien: dba_nextkey()

dba_open
dba_handlers

(PHP 3>= 3.0.8, PHP 4 )


(PHP 4 >= 4.3.0) dba_open -- Abrir una base de datos
dba_handlers -- List handlers available

Descripcion
Description

int dba_open ( string path, string mode, string handler [,


array dba_handlers ( void) ...])

dba_handlers() returns an array with all handlers dba_open() establece una instancia para path con mode
suppoerted by this extension. usando handler.
When the internal cdb library is used you will see 'cdb' path normalmente es el "path" en el sistema de ficheros.
and 'cdb_make'. mode es "r" para acceso de lectura, "w" para
lectura/escritura de una base de datos ya existente, "c"
para lectura/escritura y creacion de una base datos si
dba_insert esta no existe, y "n" para crear, truncar y
lectura/escritura.
handler es el nombre de el manejador (handler) que sera
(PHP 3>= 3.0.8, PHP 4 )
usado para el acceso al path. Es pasado como un
dba_insert -- Insertar una entrada
parametro opcional a dba_open() y puede usarse en
lugar de ella.
Descripcion dba_open() devuelve un valor positivo de handler o
FALSE, en el caso de que la apertura de la base de datos
se realice o si falla, respectivamente.
bool dba_insert ( string key, string value, int handle) Ver tambien: dba_popen() dba_close()

dba_insert() inserta la entrada descrita con key y value dba_optimize


dentro de la base de datos especificada por handle.
Fallara si ya existe una entrada con el mismo parametro
key. (PHP 3>= 3.0.8, PHP 4 )
key es la clave de la entrada a ser insertada. dba_optimize -- Optimiza la base de datos
value es el valor a ser insertado.
handle es un manejador (handle) de la base de datos
devuelto por dba_open(). Descripcion
dba_insert() devuelve TRUE o FALSE, en funcion de si
tiene exito o falla, respectivamente.
bool dba_optimize ( int handle)
Ver tambien: dba_exists() dba_delete() dba_fetch()
dba_replace()
dba_optimize() optimiza la base de datos especificada
por handle.
dba_list handle es un manejador (handle) de la base de datos
devuelto por dba_open().
dba_optimize() devuelve TRUE o FALSE, si la
(PHP 4 >= 4.3.0)
optimizacion tiene exito o falla, respectivamente.
dba_list -- List all open database files
Ver tambien: dba_sync()

Description
dba_popen

array dba_list ( void)


(PHP 3>= 3.0.8, PHP 4 )
dba_popen -- Apertura persistente de una base de datos
dba_list() returns an associative array with all open
database files. This array is in the form:
resourceid=>filename. Descripcion
int dba_popen ( string path, string mode, string handler localtime -- Obtener la hora local
[, ...]) microtime -- devuelve el valor timestamp UNIX actual
con microsegundos
mktime -- obtiene el timestamp UNIX de una fecha
dba_popen() establece una instancia persistente para
strftime -- da formato a la hora o fecha local de acuerdo
path con mode usando handler.
con las convenciones locales
path normalmente es el "path" en el sistema de ficheros.
strtotime -- Procesar cualquier descripción textual de
mode es "r" para acceso de lectura, "w" para
fecha/hora en Inglés convirtiéndola en una timestamp de
lectura/escritura de una base de datos ya existente, "c"
UNIX.
para lectura/escritura y creacion de una base datos si
time -- devuelve el timestamp UNIX actual
esta no existe, y "n" para crear, truncar y
lectura/escritura.
handler es el nombre del manejador (handler) que sera checkdate
usado para el acceso al path. Es pasado como un
parametro opcional a dba_popen() y puede usarse en
lugar de ella. (PHP 3, PHP 4 )
dba_popen() devuelve un valor positivo de handler o checkdate -- valida una fecha u hora
FALSE, en el caso de que la apertura de la base de datos
se realice o si falla, respectivamente.
Ver tambien: dba_open() dba_close() Descripción

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

Devuelve un valor verdadero si la fecha dada es válida;


(PHP 3>= 3.0.8, PHP 4 )
en caso contrario, devuelve un valor falso. Comprueba la
dba_replace -- Reemplaza o inserta una entrada validez de la fecha formada por los argumentos. Se
considera válida una fecha si:
Descripcion

• el año está entre 0 y 32767, ambos incluidos


bool dba_replace ( string key, string value, int handle)
• el mes está entre 1 y 12, ambos incluidos

dba_replace() reemplaza o inserta la entrada descrita • el día está en el rango permitido para el mes
con key y value dentro de la base de datos especificada dado. Se tienen en consideración los años
por handle. bisiestos.
key es la clave de la entrada a insertar.
value es el valor a ser insertado.
date
handle es un manejador (handle) de la base de datos
devuelto por dba_open().
dba_replace() devuelve TRUE o FALSE, dependiendo (PHP 3, PHP 4 )
de si tiene exito o falla respectivamente. date -- da formato a la fecha/hora local
Ver tambien: dba_exists() dba_delete() dba_fetch()
dba_insert()
Descripción

dba_sync
string date ( string format [, int timestamp])

(PHP 3>= 3.0.8, PHP 4 )


dba_sync -- Sincroniza la base de datos Devuelve una cadena formateada de acuerdo con la
cadena de formato dada, utilizando el valor de
timestamp dado o la hora local actual si no hay
Descripcion parámetro.
Se reconocen los siguientes caracteres en la cadena de
formato:
bool dba_sync ( int handle)

dba_sync() sincroniza la base de datos especificada por • a - "am" o "pm"


handle. Esto probablemente realice una escritura fisica
en el disco, si es soportado.
• A - "AM" o "PM"
handle es un manejador (handle) de la base de datos • d - día del mes, dos dígitos con cero a la
devuelto por dba_open(). izquierda; es decir, de "01" a "31"
dba_sync() devuelve TRUE o FALSE, si la
sincronizacion tiene exito o falla, respectivamente.
• D - día de la semana, en texto, con tres letras;
por ejemplo, "Fri"
Ver tambien: dba_optimize()
• F - mes, en texto, completo; por ejemplo,
"January"
XVIII. Funciones de fecha y hora
• h - hora, de "01" a "12"

Tabla de contenidos • H - hora, de "00" a "23"


checkdate -- valida una fecha u hora • g - hour, sin ceros, de "1" a "12"
date -- da formato a la fecha/hora local
getdate -- obtiene información de fecha y hora • G - hour, sin ceros; de "0" a "23"
gettimeofday -- obtiene la hora actual • i - minutos; de "00" a "59"
gmdate -- da formato a una fecha/hora GMT/CUT
gmmktime -- obtiene el valor timestamp UNIX de una • j - día del mes sin cero inicial; de "1" a "31"
fecha GMT • l ('L' minúscula) - día de la semana, en texto,
gmstrftime -- da formato a una fecha/hora GMT/CUT completo; por ejemplo, "Friday"
según las convenciones locales
• L - "1" or "0", según si el año es bisiesto o no • "yday" - día del año, en número; por ejemplo,
"299"
• m - mes; de "01" a "12"
• n - mes sin cero inicial; de "1" a "12"
• "weekday" - día de la semana, en texto,
completo; por ejemplo, "Friday"
• M - mes, en texto, 3 letras; por ejemplo, "Jan"
• "month" - mes, en texto, completo; por
• s - segundos; de "00" a "59" ejemplo, "January"
• S - sufijo ordinal en inglés, en texto, 2
caracteres; por ejemplo, "th", "nd" gettimeofday
• t - número de días del mes dado; de "28" a
"31" (PHP 3>= 3.0.7, PHP 4 )
• U - segundos desde el valor de 'epoch' gettimeofday -- obtiene la hora actual
• w - día de la semana, en número, de "0"
(domingo) a "6" (sábado) Descripción
• Y - año, cuatro cifras; por ejemplo, "1999"
• y - año, dos cifras; por ejemplo, "99" array gettimeofday ( void)
• z - día del año; de "0" a "365"
Es un interfaz para gettimeofday(2). Devuelve un array
• Z - diferencia horaria en segundos (de "- asociativo que contiene los datos devueltos por esta
43200" a "43200") llamada al sistema.

Los caracteres no reconocidos se imprimen tal cual. El


formato "Z" siempre devuelve "0" en la función • "sec" - segundos
gmdate()() • "usec" - microsegundos
Ejemplo 1. Ejemplo de date()
• "minuteswest" - minutos al oeste de Greenwich
• "dsttime" - tipo de corrección dst
print (date("l dS of F Y h:i:s A"));
print ("July 1, 2000 is on a " . date("l",
mktime(0,0,0,7,1,2000))); gmdate
Es posible usar date() y mktime() juntas para obtener
fechas futuras o pasadas. (PHP 3, PHP 4 )
Ejemplo 2. Ejemplo de date() y mktime() gmdate -- da formato a una fecha/hora GMT/CUT

$tomorrow = mktime(0,0,0,date("m") Descripción


,date("d")+1,date("Y"));
$lastmonth = mktime(0,0,0,date("m")- string gmdate ( string format, int timestamp)
1,date("d"), date("Y"));
$nextyear = mktime(0,0,0,date("m"),
date("d"), date("Y")+1); Idéntica a la función data() excepto en que la hora
devuelta es la de Greenwich (GMT). Por ejemplo, si se
Para dar formato a fechas en otros idiomas, se deben utiliza en Finlandia (GMT +0200), la primera línea del
usar las funciones setlocale() y strftime(). ejemplo devuelve "Jan 01 1998 00:00:00", mientras la
Ver también gmdate() y mktime(). segunda imprime "Dec 31 1997 22:00:00".
Ejemplo 1. Ejemplo de gmdate()
getdate

echo date( "M d Y


(PHP 3, PHP 4 ) H:i:s",mktime(0,0,0,1,1,1998) );
getdate -- obtiene información de fecha y hora echo gmdate( "M d Y
H:i:s",mktime(0,0,0,1,1,1998) );
Descripción Ver también date(), mktime() y gmmktime().

array getdate ( int timestamp) gmmktime

Devuelve un array asociativo que contiene la información (PHP 3, PHP 4 )


de fecha del valor timestamp como los siguientes gmmktime -- obtiene el valor timestamp UNIX de una
elementos: fecha GMT

• "seconds" - segundos Descripción

• "minutes" - minutos
int gmmktime ( int hour, int minute, int second, int
• "hours" - horas month, int day, int year [, int is_dst])
• "mday" - día del mes
• "wday" - día de la semana, en número Idéntica a mktime(), excepto en que los parámetros
representan una fecha GMT.
• "mon" - mes, en número
• "year" - año, en número
gmstrftime
(PHP 3>= 3.0.12, PHP 4 ) Descripción
gmstrftime -- da formato a una fecha/hora GMT/CUT
según las convenciones locales
string microtime ( void)

Descripción
Devuelve la cadena "msec sec", donde sec es la hora
actual en número de segundos desde el valor Unix Epoch
string gmstrftime ( string format, int timestamp) (0:00:00 del 1 de enero de 1970, hora GMT), y msec es la
parte de microsegundos. Esta función sólo está
disponible en sistemas operativos con admiten la
Se comporta como strftime(), excepto en que la hora llamada al sistema gettimeofday().
devuelta es la de Greenwich (GMT). Por ejemplo, si se Ver también time().
utiliza en la zona horaria EST (GMT -0500), la primera
línea del ejemplo imprime "Dec 31 1998 20:00:00",
mientras la segunda imprime "Jan 01 1999 01:00:00". mktime
Ejemplo 1. Ejemplo de gmstrftime()

(PHP 3, PHP 4 )
mktime -- obtiene el timestamp UNIX de una fecha
setlocale ('LC_TIME','en_US');
echo strftime ("%b %d %Y %H:%M:
%S",mktime(20,0,0,12,31,98))."\n"; Descripción
echo gmstrftime ("%b %d %Y %H:%M:
%S",mktime(20,0,0,12,31,98))."\n";
int mktime ( int hour, int minute, int second, int month,
Ver también strftime().
int day, int year [, int is_dst])

localtime Advertencia: Véase el extraño orden de los argumentos,


que se diferencia del orden de argumentos en una
llamada mktime() de UNIX y que no permite eliminar
(PHP 4 )
parámetros de derecha a izquierda (ver abajo). Es un
localtime -- Obtener la hora local
error común mezclar estos valores en un script.
Devuelve el valor timestamp Unix correspondiente a los
Descripción argumentos dados. El timestamp es un entero de tipo
long que contiene el número de segundos entre el valor
Unix Epoch (1 de enero de 1970) y la hora especificada.
array localtime ( [int muestra_de_tiempo [, bool Se pueden eliminar argumentos en orden de derecha a
es_asociativo]]) izquierda; en los argumentos omitidos se toma el valor
de la fecha y hora locales.
La función localtime() devuelve un vector idético al de is_dst puede ponerse a 1 si la hora corresponde a horario
la estructura devuelta en C por la llamada a la misma de verano, 0 si no, o -1 (valor por omisión) si no se sabe.
función. El primer parámetro que se le pasa a
localtime() es el timestamp, una representació de una Nota: is_dst se añadió en la versión
fecha/hora concretas. Si no se proporciona, se utilizará la 3.0.10.
hora actual. El segundo argumento de localtime() es
es_asociativo. Si está a 0 o no es proporcionado, el
vector se devuelve como un vector normal, indizado mktime() es útil para realizar cálculos y validaciones
numéricamente. Si el argumento está a 1, el vector con fechas, ya que calcula automáticamente el valor
devuelto es un vector asociativo conteniendo los correcto para una entrada fuera de rango. Por ejemplo,
diferentes elementos de la estructura devuelta por C al cada una de las líneas siguientes produce la cadena "Jan-
llamar a la función localtime. Los nombres de las 01-1998".
diferentes claves del vector asociativo se encuentran a Ejemplo 1. Ejemplo de mktime()
continuación:

echo date( "M-d-Y",


• "tm_sec" - segundos mktime(0,0,0,12,32,1997) );
• "tm_min" - minutos echo date( "M-d-Y",
mktime(0,0,0,13,1,1997) );
• "tm_hour" - horas echo date( "M-d-Y",
mktime(0,0,0,1,1,1998) );
• "tm_mday" - día del mes
El último día de cada mes se puede expresar como el día
• "tm_mon" - mes del año, empezando en 0 que
"0" del mes siguiente, no el día -1. Los dos ejemplos
es Enero
siguientes producen la cadena "The last day in Feb 2000
• "tm_year" - Años que hacen desde 1900 is: 29".
Ejemplo 2. El último día del próximo mes
• "tm_wday" - Día de la semana
• "tm_yday" - Día del año
• "tm_isdst" - Si el cambio de hora para el ahorro $lastday=mktime(0,0,0,3,0,2000);
energético tiene efecto o no echo strftime("Last day in Feb 2000 is:
%d",$lastday);

microtime $lastday=mktime(0,0,0,4,-31,2000);
echo strftime("Last day in Feb 2000 is:
%d",$lastday);
(PHP 3, PHP 4 )
microtime -- devuelve el valor timestamp UNIX actual Ver también date() y time().
con microsegundos
strftime
(PHP 3, PHP 4 )
print(strftime("%A.\n"));
strftime -- da formato a la hora o fecha local de acuerdo
con las convenciones locales Este ejemplo funciona si se tienen los respectivos
`locales' instalados en el sistema.
Ver también setlocale() y mktime().
Descripción

strtotime
string strftime ( string format, int timestamp)

(PHP 3>= 3.0.12, PHP 4 )


Devuelve una cadena formateada según la cadena de
strtotime -- Procesar cualquier descripción textual de
formato dada utilizando el valor timestamp o la hora
fecha/hora en Inglés convirtiéndola en una timestamp de
local actual. Los nombres del mes y el día de la semana y
UNIX.
otras cadenas dependientes del idioma respetan lo
establecido con setlocale().
Se reconocen los siguientes especificadores de Descripción
conversión en la cadena de formato:

int strtotime ( string hora [, int ahora])


• %a - nombre del día de la semana abreviado
• %A - nombre del día de la semana completo La función espera que se le pase una cadena
conteniendo una fecha en formato Inglés e intentará
• %b - nombre del mes abreviado procesarla y convertirla a una timestamp (muestra de
• %B - nombre del mes completo tiempo) de UNIX relativa a la timestamp proporcionada
en ahora, o la hora actual si no se indica ninguna. Si falla,
• %c - representación de fecha y hora preferidas devolverá -1.
en el idioma actual Dado que strtotime() obra de acuerdo con la sintaxis de
• %d - día del mes en número (de 00 a 31) fechas de GNU, puede echar un vistazo a la página del
manual GNU titulada Date Input Formats (Formatos de
• %H - hora como un número de 00 a 23 entrada de fechas). La sintaxis descrita ahí es válida para
• %I - hora como un número de 01 a 12 el parátro hora.
Ejemplo 1. Ejemplos con strtotime()
• %j - día del año como un número de 001 a 366
• %m - mes como un número de 01 a 12
echo strtotime ("now"), "\n";
• %M - minuto en número echo strtotime ("10 September 2000"),
• %p - `am' o `pm', según la hora dada, o las "\n";
cadenas correspondientes en el idioma actual echo strtotime ("+1 day"), "\n";
echo strtotime ("+1 week"), "\n";
• %S - segundos en número echo strtotime ("+1 week 2 days 4 hours 2
• %U - número de la semana en el año, seconds"), "\n";
empezando con el primer domingo como el echo strtotime ("next Thursday"), "\n";
primer día de la primera semana echo strtotime ("last Monday"), "\n";

• %W - número de la semana en el año, Ejemplo 2. Comprobando si falla


empezando con el primer lunes como el primer
día de la primera semana
$str = 'No v&aacute;lida';
• %w - día de la semana en número (el domingo if (($timestamp = strtotime($str)) ===
es el 0) -1) {
• %x - representación preferida de la fecha sin la echo "La cadena ($str) no es
hora v&aacute;lida.";
} else {
• %X - representación preferida de la hora sin la echo "$str == ". date('l dS of F Y h:i:s
fecha A',$timestamp);
• %y - año en número de 00 a 99 }
• %Y - año en número de cuatro cifras
• %Z - nombre o abreviatura de la zona horaria Nota: El rango válido de una
timestamp suele ser desde Fri, 13
• %% - carácter `%'
Dec 1901 20:45:54 GMT (Viernes, 13
de diciembre) a Tue, 19 Jan 2038
Ejemplo 1. Ejemplo de strftime() 03:14:07 GMT (Martes, 19 de enero).
(Estas son las fechas que
corresponden a los valores mínimo y
máximo de un entero con signo de
setlocale ("LC_TIME", "C");
32 bits.)
print(strftime("%A in
Finnish is "));
setlocale ("LC_TIME", time
"fi_FI");
print(strftime("%A, in
French ")); (PHP 3, PHP 4 )
setlocale ("LC_TIME", time -- devuelve el timestamp UNIX actual
"fr_CA");
print(strftime("%A and in
German ")); Descripción
setlocale ("LC_TIME",
"de_DE"); int time ( void)
Devuelve la hora actual como número de segundos bool dbase_close ( int dbase_identifier)
transcurridos desde las 00:00:00 del 1 de enero de 1970
GMT (Unix Epoch).
Cierra el fichero asociado con dbase_identifier.
Ver también date().

dbase_create
XIX. Funciones para dBase

(PHP 3, PHP 4 )
Estas funciones permiten el acceso a datos almacenados
dbase_create -- crea una base de datos dBase
en formato dBase (dbf).
No hay soporte para índices o campos Memo. Tampoco
hay soporte para bloqueo: si dos procesos concurrentes Descripción
en el servidor modifican el mismo fichero dBase,
probablemente se destruirán los datos.
A diferencia de las bases de datos SQL, las "bases de int dbase_create ( string filename, array fields)
datos" dBase no pueden cambiar su definición. Una vez
creado el fichero, la definición de la base de datos es fija. El parámetro fields es un array de arrays, cada uno de
No hay índices que aceleren la búsqueda u organicen los los cuales describe el formato de un campo de la base de
datos de distinto modo. Los ficheros dBase son simples datos. Cada campo consiste de un nombre, un carácter
ficheros secuenciales con registros de longitud fija. Los que indica el tipo de campo, una longitud, y una
nuevos registros se añaden al final del fichero y los precisión.
registros borrados se conservan hasta que se llama a la Los tipos de campos disponibles son:
función dbase_pack()(). L
Se recomienda no utilizar ficheros dBase como bases de Lógico. No tienen longitud ni precisión.
datos, sino elegir cualquier servidor SQL; MySQL o M
Postgres son opciones habituales con PHP. El soporte Memo. (Sin soporte en PHP.) No tienen longitud
para dBase se proporciona para permitir importar y ni precisión.
exportar datos a y desde la base de datos web, ya que D
este formato de ficheros es aceptado habitualmente por Fecha (almacenada como AAAAMMDD). No
las hojas de datos y los organizadores de Windows. La tienen longitud ni precisión.
importación y exportación de datos es lo único para lo N
que sirve el soporte dBase. Número. Tienen longitud y precisión (número
Tabla de contenidos de cifras tras el punto decimal).
dbase_add_record -- añade un registro a un fichero C
dBase Cadena.
dbase_close -- cierra un fichero dBase Si la base de datos se crea con éxito, se devuelve un
dbase_create -- crea una base de datos dBase dbase_identifier; en caso contrario, devuelve FALSE.
dbase_delete_record -- borra un registro del fichero Ejemplo 1. Crear un fichero dBase
dBase
dbase_get_record_with_names -- lee un registro de un
fichero dBase como array asociativo
// "database" name
dbase_get_record -- lee un registro de un fichero dBase
$dbname =
dbase_numfields -- cuenta el número de campos en un
"/tmp/test.dbf";
fichero dBase
dbase_numrecords -- cuenta el número de registros en
// database "definition"
un fichero dBase
$def =
dbase_open -- abre un fichero dBase
array(
dbase_pack -- "empaqueta" un fichero dBase
array("date",
dbase_replace_record -- reemplaza un registro en un
"D"),
fichero dBase
array("name",
"C", 50),
dbase_add_record array("age", "N",
3, 0),
array("email", "C",
(PHP 3, PHP 4 ) 128),
dbase_add_record -- añade un registro a un fichero array("ismember",
dBase "L")
);
Descripción // creation
if (!
bool dbase_add_record ( int dbase_identifier, array dbase_create($dbname,
record) $def))
print "<strong>Error!
</strong>";
Añade los datos de record a la base de datos. Si el
número de elementos del registro proporcionado no es
igual al número de campos de la base de datos, la dbase_delete_record
operación fallará y la función devolverá FALSE.

(PHP 3, PHP 4 )
dbase_close dbase_delete_record -- borra un registro del fichero
dBase
(PHP 3, PHP 4 )
dbase_close -- cierra un fichero dBase Descripción

Descripción
bool dbase_delete_record ( int dbase_identifier, int dbase_numrecords
record)

(PHP 3, PHP 4 )
Marca el registro record para ser borrado del fichero de dbase_numrecords -- cuenta el número de registros en
datos. Para eliminar realmente el registro del fichero, un fichero dBase
debe llamarse a la función dbase_pack().

Descripción
dbase_get_record_with_names

int dbase_numrecords ( int dbase_identifier)


(PHP 3>= 3.0.4, PHP 4 )
dbase_get_record_with_names -- lee un registro de un
fichero dBase como array asociativo Devuelve el número de registros (filas) en el fichero
especificado. Los números de registro van de 1 a
dbase_numrecords($db), mientras los números de campo
Descripción van de 0 a dbase_numfields($db)-1.

array dbase_get_record_with_names ( int dbase_open


dbase_identifier, int record)

(PHP 3, PHP 4 )
Devuelve los datos del registro record en un array dbase_open -- abre un fichero dBase
asociativo. El array incluye también un elemento con
índice 'deleted' que vale 1 si el registro ha sido marcado
para borrar (ver dbase_delete_record(). Descripción
Cada campo se convierte al tipo PHP apropiado. (Las
fechas se transforman en cadenas.)
int dbase_open ( string filename, int flags)

dbase_get_record Los "flags" son los que utiliza la llamada al sistema


open(). Normalmente, 0 significa sólo lectura, 1 sólo
(PHP 3, PHP 4 ) escritura y 2 lectura y escritura.
dbase_get_record -- lee un registro de un fichero dBase Devuelve un dbase_identifier del fichero abierto, o
FALSE si no pudo abrirse el fichero.

Descripción
dbase_pack

array dbase_get_record ( int dbase_identifier, int


record) (PHP 3, PHP 4 )
dbase_pack -- "empaqueta" un fichero dBase

Devuelve los datos del registro record en un array. El


array se indexa a partir de 0, e incluye un elemento con Descripción
el índice asociativo 'deleted', que vale 1 si el registro ha
sido marcado para borrar (ver dbase_delete_record().
Cada campo se convierte al tipo PHP apropiado. (Las bool dbase_pack ( int dbase_identifier)
fechas se guardan como cadenas.)
Empaqueta el fichero especificado, borrando
definitivamente todos los registros marcados con la
dbase_numfields función dbase_delete_record().

(PHP 3, PHP 4 )
dbase_replace_record
dbase_numfields -- cuenta el número de campos en un
fichero dBase
(PHP 3>= 3.0.11, PHP 4 )
dbase_replace_record -- reemplaza un registro en un
Descripción fichero dBase

int dbase_numfields ( int dbase_identifier)


Descripción

Devuelve el número de campos (columnas) en el fichero


especificado. Los números de campo va de 0 a bool dbase_replace_record ( int dbase_identifier, array
dbase_numfields($db)-1, mientras los números de record, int dbase_record_number)
registros van de 1 a dbase_numrecords($db).
Ejemplo 1. Uso de dbase_numfields() Reemplaza los datos asociados con el registro
record_number con los datos de record en el fichero de
datos. Si el número de elementos del registro
$rec = proporcionado no es igual al número de campos de la
dbase_get_record($db, base de datos, la operación fallará y la función devolverá
$recno); FALSE.
$nf = dbase_numfields($db); dbase_record_number es un entero en el rango de 1 al
for ($i=0; $i < $nf; $i++) { número de registros en el fichero de datos (devuelto por
print $rec[$i]."<br>\n"; la función dbase_numrecords()).
}
XX. Funciones dbm
Estas funcione le permiten almacenar registros en una Descripción
base de datos estilo dbm. Este tipo de base de datos
(soportadas por las librerías db y gdbm de Berkeley, así
como por algunas librerías del sistema y por una librería bool dbmdelete ( int identif_dbm, string clave)
incluída para acceso a archivos de texto) guarda pares
clave/valor (en oposición a los registros completos Borra el valor para la clave en la base de datos.
soportados por las bases de datos relacionales). Devuelve FALSE si la clave no existía en la base de
Ejemplo 1. ejemplo de dbm datos.

$dbm = dbmopen("vistoya", dbmexists


"w");
if (dbmexists($dbm,
(PHP 3, PHP 4 )
$idusuario)) {
dbmexists -- dice si existe un valor para una clave dada
$visto_ya = dbmfetch($dbm,
en la base de datos dbm
$idusuario);
} else {
dbminsert($dbm, $idusuario, Descripción
time());
}
do_stuff(); bool dbmexists ( int identif_dbm, string clave)
dbmreplace($dbm, $idusuario,
time()); Devuelve TRUE si hay un valor asociado con la clave.
dbmclose($dbm);
Tabla de contenidos
dblist -- describe la librería compatible dbm que se está dbmfetch
usando
dbmclose -- cierra una base de datos dbm (PHP 3, PHP 4 )
dbmdelete -- borra el valor de una clave de una base de dbmfetch -- obtiene un valor para una clave desde la
datos dbm base de datos dbm
dbmexists -- dice si existe un valor para una clave dada
en la base de datos dbm
dbmfetch -- obtiene un valor para una clave desde la Descripción
base de datos dbm
dbmfirstkey -- obtiene la primera clave de una base de
datos dbm string dbmfetch ( int identif_dbm, string clave)
dbminsert -- inserta un valor para una clave en la base
de datos dbm Devuelve el valor asociado con la clave.
dbmnextkey -- obtiene la siguiente clave de una base de
datos dbm
dbmopen -- abre una base de datos dbm dbmfirstkey
dbmreplace -- sustituye el valor de una clave en la base
de datos dbm
(PHP 3, PHP 4 )
dbmfirstkey -- obtiene la primera clave de una base de
dblist datos dbm

(PHP 3, PHP 4 ) Descripción


dblist -- describe la librería compatible dbm que se está
usando
string dbmfirstkey ( int identif_dbm)

Descripción Devuelve la primera clave de la base de datos. Nótese


que no se garantiza ningún orden en particular, pues la
string dblist ( void) base de datos se crea utilizando una tabla hash, que no
garantiza ordenación alguna.

dbmclose
dbminsert

(PHP 3, PHP 4 )
dbmclose -- cierra una base de datos dbm (PHP 3, PHP 4 )
dbminsert -- inserta un valor para una clave en la base
de datos dbm
Descripción
Descripción
bool dbmclose ( int identif_dbm)

int dbminsert ( int identif_dbm, string clave, string


Desbloquea y cierra la base de datos especificada. valor)

dbmdelete Añade el valor a la base de datos con la clave


especificada.
Devuelve -1 si la base de datos se abrío en modo sólo
(PHP 3, PHP 4 ) lectura, 0 si la inserción tuvo éxito y 1 si la clave ya
dbmdelete -- borra el valor de una clave de una base de existía (para sustituir el valor, utilice dbmreplace().)
datos dbm
dbmnextkey Sustituye el valor para la clave especificada de la base
de datos.
También añadirá la clave a la base de datos si no existía
(PHP 3, PHP 4 ) antes.
dbmnextkey -- obtiene la siguiente clave de una base de
datos dbm
XXI. dbx functions

Descripción
Introducción

string dbmnextkey ( int identif_dbm, string clave)


The dbx module is a database abstraction layer (db 'X',
where 'X' is a supported database). The dbx functions
Devuelve la clave que sigue a clave. Llamando a
allow you to access all supported databases using a
dbmfirstkey() seguida de llamadas sucesivas a
single calling convention. The dbx-functions themselves
dbmnextkey() se pueden visitar todos los pares
do not interface directly to the databases, but interface
clave/valor de la base de datos dbm. Por ejemplo:
to the modules that are used to support these databases.
Ejemplo 1. Visitanco cada par clave/valor en una
base de datos dbm.
Requerimientos

$clave = dbmfirstkey($id_dbm);
while ($clave) { To be able to use a database with the dbx-module, the
echo "$clave = " . module must be either linked or loaded into PHP, and the
dbmfetch($id_dbm, $clave) . "\n"; database module must be supported by the dbx-module.
$clave = dbmnextkey($id_dbm, Currently, following databases are supported, but others
$clave); will follow:
}

• FrontBase (available from PHP 4.1.0).


dbmopen
• Microsoft SQL Server
• MySQL
(PHP 3, PHP 4 )
dbmopen -- abre una base de datos dbm • ODBC
• PostgreSQL
Descripción • Sybase-CT (available from PHP 4.2.0).
• Oracle (oci8) (available from PHP 4.3.0).
int dbmopen ( string fichero, string indicadores)
Documentation for adding additional database support to
El primer argumento es el nombre con sendero completo dbx can be found at
del archivo dbm que se va a abrir y el segundo es el http://www.guidance.nl/php/dbx/doc/.
modo de apertura, que puede ser "r", "n", "c" o "w", que
significan sólo lectura, nuevo (implica lectura/escritura y
suele truncar una base de datos si ya existía con ese Instalación
nombre), crear (implica lectura/escritura, pero sin truncar
la base de datos) y abrir para lectura/escritura,
respectivamente. In order to have these functions available, you must
Devuelve un identificador que se pasa al resto de compile PHP with dbx support by using the --enable-dbx
funciones dbm si tiene éxito, o FALSE si falla. option and all options for the databases that will be used,
Si se utiliza el soporte de ndbm, este creará los archivos e.g. for MySQL you must also specify --with-mysql=[DIR].
fichero.dir y fichero.pag. gdbm sólo utiliza un archivo y lo To get other supported databases to work with the dbx-
mismo hace el soporte interno de archivos de texto, module refer to their specific documentation.
mientras que el db de Berkeley crea un archivo
fichero.db. Nótese que el PHP hace su propio bloqueo de
archivo sobre el que pudiera realizar la propia librería Configuración en tiempo de ejecución
dbm. El PHP no borra los archivos .lck que crea. Los
utiliza simplemente como i-nodos fijos en los que hacer The behaviour of these functions is affected by settings
el bloqueo. Para más información sobre archivos dbm, in php.ini.
vea las páginas man de su Unix o obtenga el gdbm de Tabla 1. DBX Configuration Options
GNU desde ftp://prep.ai.mit.edu/pub/gnu.
Name Default Changeable

dbmreplace dbx.colnames_ "unchang PHP_INI_SYSTE


case ed" M
For further details and definition of the PHP_INI_*
(PHP 3, PHP 4 ) constants see ini_set().
dbmreplace -- sustituye el valor de una clave en la base
de datos dbm
Nota: This ini-option is available
available from PHP 4.3.0.
Descripción

Here is a short explanation of the configuration


bool dbmreplace ( int identif_dbm, string clave, string directives.
valor) dbx.colnames_case string
Columns names can be returned "unchanged"
or converted to "uppercase" or "lowercase".
This directive can be overridden with a flag to Nota: Always refer to the module-
dbx_query(). specific documentation as well.

Tipos de recursos See also: dbx_connect().

There are two resource types used in the dbx module. dbx_compare
The first one is the link-object for a database
connection, the second a result-object which helds the
(PHP 4 >= 4.1.0)
result of a query.
dbx_compare -- Compare two rows for sorting purposes

Constantes predefinidas Description

Estas constantes están definidas por esta extensión y int dbx_compare ( array row_a, array row_b, string
estarán disponibles solamente cuando la extensión ha column_key [, int flags])
sido o bien compilada dentro de PHP o grabada
dinamicamente en tiempo de ejecución.
DBX_MYSQL (integer) dbx_compare() returns 0 if the row_a[$column_key] is
DBX_ODBC (integer) equal to row_b[$column_key], and 1 or -1 if the former is
DBX_PGSQL (integer) greater or is smaller than the latter one, respectively, or
DBX_MSSQL (integer) vice versa if the flag is set to DBX_CMP_DESC.
DBX_FBSQL (integer) dbx_compare() is a helper function for dbx_sort() to
DBX_OCI8 (integer) (available from PHP 4.3.0) ease the make and use of the custom sorting function.
DBX_SYBASECT (integer) The flags can be set to specify comparison direction:
DBX_PERSISTENT (integer)
DBX_RESULT_INFO (integer)
DBX_RESULT_INDEX (integer) • DBX_CMP_ASC - ascending order
DBX_RESULT_ASSOC (integer)
DBX_COLNAMES_UNCHANGED (integer) (available
• DBX_CMP_DESC - descending order
from PHP 4.3.0)
DBX_COLNAMES_UPPERCASE (integer) (available from and the preferred comparison type:
PHP 4.3.0)
DBX_COLNAMES_LOWERCASE (integer) (available
from PHP 4.3.0)
DBX_CMP_NATIVE (integer)
• DBX_CMP_NATIVE - no type conversion
DBX_CMP_TEXT (integer) • DBX_CMP_TEXT - compare items as strings
DBX_CMP_NUMBER (integer)
DBX_CMP_ASC (integer)
• DBX_CMP_NUMBER - compare items
numerically
DBX_CMP_DESC (integer)
Tabla de contenidos
dbx_close -- Close an open connection/database One of the direction and one of the type constant can be
dbx_compare -- Compare two rows for sorting purposes combined with bitwise OR operator (|). The default value
dbx_connect -- Open a connection/database for the flags parameter is DBX_CMP_ASC |
dbx_error -- Report the error message of the latest DBX_CMP_NATIVE.
function call in the module (not just in the connection) Ejemplo 1. dbx_compare() example
dbx_escape_string -- Escape a string so it can safely be
used in an sql-statement.
dbx_query -- Send a query and fetch all results (if any) <?php
dbx_sort -- Sort a result from a dbx_query by a custom function user_re_order ($a, $b) {
sort function $rv = dbx_compare ($a, $b, "parentid",
DBX_CMP_DESC);
dbx_close if ( !$rv ) {
$rv = dbx_compare ($a, $b, "id",
DBX_CMP_NUMBER);
(PHP 4 >= 4.0.6) }
dbx_close -- Close an open connection/database return $rv;
}

Description $link = dbx_connect (DBX_ODBC, "", "db",


"username", "password")
or die ("Could not connect");
bool dbx_close ( object link_identifier)
$result = dbx_query ($link, "SELECT id, parentid,
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. description FROM table ORDER BY id");
Ejemplo 1. dbx_close() example // data in $result is now ordered by id

dbx_sort ($result, "user_re_order");


<?php // date in $result is now ordered by parentid
$link = dbx_connect(DBX_MYSQL, "localhost", "db", (descending), then by id
"username", "password")
or die ("Could not connect"); dbx_close ($link);
?>
print("Connected successfully"); See also dbx_sort().
dbx_close($link);
?>
dbx_connect
(PHP 4 >= 4.0.6) dbx_error -- Report the error message of the latest
dbx_connect -- Open a connection/database function call in the module (not just in the connection)

Description Description

object dbx_connect ( mixed module, string host, string string dbx_error ( object link_identifier)
database, string username, string password [, int
persistent])
dbx_error() returns a string containing the error
message from the last function call of the abstracted
dbx_connect() returns an object on success, FALSE on module (e.g. mysql module). If there are multiple
error. If a connection has been made but the database connections in the same module, just the last error is
could not be selected, the connection is closed and given. If there are connections on different modules, the
FALSE is returned. The persistent parameter can be set latest error is returned for the module specified by the
to DBX_PERSISTENT, if so, a persistent connection will link_identifier parameter.
be created. Ejemplo 1. dbx_error() example
The module parameter can be either a string or a
constant, though the latter form is preferred. The
possible values are given below, but keep in mind that <?php
they only work if the module is actually loaded. $link = dbx_connect(DBX_MYSQL, "localhost", "db",
"username", "password")
or die ("Could not connect");
• DBX_MYSQL or "mysql"
$result = dbx_query($link, "select id from
• DBX_ODBC or "odbc"
non_existing_table");
• DBX_PGSQL or "pgsql" if ( $result == 0 ) {
echo dbx_error ($link);
• DBX_MSSQL or "mssql"
}
• DBX_FBSQL or "fbsql" (available from PHP dbx_close ($link);
4.1.0) ?>
• DBX_SYBASECT or "sybase_ct" (available
from PHP 4.2.0)
Nota: Always refer to the module-
• DBX_OCI8 or "oci8" (available from PHP 4.3.0) specific documentation as well.

The host, database, username and password parameters The error message for Microsoft SQL
are expected, but not always used depending on the Server is actually the result of the
connect functions for the abstracted module. mssql_get_last_message()
The returned object has three properties: function.
database
It is the name of the currently selected
database. The error message for Oracle (oci8)
handle is not implemented (yet).
It is a valid handle for the connected database,
and as such it can be used in module-specific
dbx_escape_string
functions (if required).
$link = dbx_connect (DBX_MYSQL, "localhost",
"db", "username", "password"); (PHP 4 >= 4.3.0)
mysql_close ($link->handle); // dbx_close($link) dbx_escape_string -- Escape a string so it can safely be
would be better here used in an sql-statement.
module
It is used internally by dbx only, and is actually Description
the module number mentioned above.
Ejemplo 1. dbx_connect() example
string dbx_escape_string ( object link_identifier, string
text)
<?php
$link = dbx_connect (DBX_ODBC, "", "db", "username", dbx_escape_string() returns the text, escaped where
"password", DBX_PERSISTENT) necessary (such as quotes, backslashes etc). It returns
or die ("Could not connect"); NULL on error.
Ejemplo 1. dbx_escape_string() example
print ("Connected successfully");
dbx_close ($link);
?> <?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db",
"username", "password")
Nota: Always refer to the module- or die ("Could not connect");
specific documentation as well.
$text = dbx_escape_string($link, "It\'s quoted and
backslashed (\\).");
See also: dbx_close(). $result = dbx_query($link, "insert into tbl (txt) values
('".$text."')");
dbx_error if ( $result == 0 ) {
echo dbx_error ($link);
}
(PHP 4 >= 4.0.6) dbx_close ($link);
DBX_COLNAMES_UNCHANGED (available from PHP
?>
4.3.0)
See also: dbx_query(). The case of the returned column names will
not be changed.
DBX_COLNAMES_UPPERCASE (available from PHP
dbx_query 4.3.0)
The case of the returned column names will be
(PHP 4 >= 4.0.6) changed to uppercase.
dbx_query -- Send a query and fetch all results (if any) DBX_COLNAMES_LOWERCASE (available from PHP
4.3.0)
The case of the returned column names will be
Description changed to lowercase.
Note that DBX_RESULT_INDEX is always used,
regardless of the actual value of flags parameter. This
object dbx_query ( object link_identifier, string means that the following combinations is effective only:
sql_statement [, long flags])

dbx_query() returns an object or 1 on success, and 0 on • DBX_RESULT_INDEX


failure. The result object is returned only if the query
given in sql_statement produces a result set.
• DBX_RESULT_INDEX | DBX_RESULT_INFO
Ejemplo 1. How to handle the returned value • DBX_RESULT_INDEX | DBX_RESULT_INFO |
DBX_RESULT_ASSOC - this is the default, if
flags is not specified.
<?php
$link = dbx_connect(DBX_ODBC, "", "db",
The returing object has four or five properties depending
"username", "password")
on flags:
or die("Could not connect");
handle
It is a valid handle for the connected database,
$result = dbx_query($link, 'SELECT id, parentid,
and as such it can be used in module specific
description FROM table');
functions (if required).
if ( is_object($result) ) { $result = dbx_query ($link, "SELECT id
// ... do some stuff here, see detailed examples FROM table");
below ... mysql_field_len ($result->handle, 0);
// first, print out field names and types
cols and rows
// then, draw a table filled with the returned field
These contain the number of columns (or
values
fields) and rows (or records) respectively.
}
else if ( $result == 1 ) { $result = dbx_query ($link, 'SELECT id
echo("Query executed successfully, but no result FROM table');
set returned"); echo $result->rows; // number of
} records
else { echo $result->cols; // number of fields
exit("Query failed"); info (optional)
} It is returned only if either DBX_RESULT_INFO
or DBX_RESULT_ASSOC is specified in the
dbx_close($link); flags parameter. It is a 2 dimensional array,
?> that has two named rows (name and type) to
The flags parameter is used to control the amount of retrieve column information.
information that is returned. It may be any combination Ejemplo 2. lists each field's name and type
of the following constants with the bitwise OR operator
(|). The DBX_COLNAMES_* flags override the
dbx.colnames_case setting from php.ini. $result = dbx_query ($link, 'SELECT id FROM
DBX_RESULT_INDEX table',
It is always set, that is, the returned object has DBX_RESULT_INDEX |
a data property which is a 2 dimensional array DBX_RESULT_INFO);
indexed numerically. For example, in the
expression data[2][3] 2 stands for the row (or for ($i = 0; $i < $result->cols; $i++ ) {
record) number and 3 stands for the column echo $result->info['name'][$i] . "\n";
(or field) number. The first row and column are echo $result->info['type'][$i] . "\n";
indexed at 0. }
If DBX_RESULT_ASSOC is also specified, the
data
returning object contains the information
This property contains the actual resulting
related to DBX_RESULT_INFO too, even if it
data, possibly associated with column names
was not specified.
as well depending on flags. If
DBX_RESULT_INFO
DBX_RESULT_ASSOC is set, it is possible to
It provides info about columns, such as field
use $result->data[2]["field_name"].
names and field types.
Ejemplo 3. outputs the content of data property
DBX_RESULT_ASSOC
into HTML table
It effects that the field values can be accessed
with the respective column names used as
keys to the returned object's data property.
Associated results are actually references to $result = dbx_query ($link, 'SELECT id, parentid,
the numerically indexed data, so modifying description FROM table');
data[0][0] causes that data[0]
['field_name_for_first_column'] is modified as echo "<table>\n";
well. foreach ( $result->data as $row ) {
echo "<tr>\n";
foreach ( $row as $field ) { y en definitiva TODO lo documentado aqui, puede cambiar
echo "<td>$field</td>"; en una futura version de PHP SIN AVISO. Quedas avisado, y
} utilizar este módulo es tu responsabiliad.
echo "</tr>\n";
}
echo "</table>\n"; Introducción

Nota: Always refer to the module- db++, made by the German company Concept asa, is a
specific documentation as well. relational database system with high performance and
low memory and disk usage in mind. While providing SQL
as an additional language interface, it is not really a SQL
Column names for queries on an database in the first place but provides its own AQL
Oracle database are returned in query language which is much more influenced by the
lowercase. relational algebra then SQL is.
Concept asa always had an interest in supporting open
source languages, db++ has had Perl and Tcl call
See also: dbx_escape_string() and dbx_connect(). interfaces for years now and uses Tcl as its internal
stored procedure language.
dbx_sort
Requerimientos
(PHP 4 >= 4.0.6)
dbx_sort -- Sort a result from a dbx_query by a custom
This extension relies on external client libraries so you
sort function
have to have a db++ client installed on the system you
want to use this extension on.
Description Concept asa provides db++ Demo versions and
documentation for Linux, some other UNIX versions.
There is also a Windows version of db++, but this
bool dbx_sort ( object result, string extension doesn't support it (yet).
user_compare_function)

Instalación
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.

In order to build this extension yourself you need the


Nota: It is always better to use
db++ client libraries and header files to be installed on
ORDER BY SQL clause instead of
your system (these are included in the db++ installation
dbx_sort(), if possible.
archives by default). You have to run configure with
option --with-dbplus to build this extension.
Ejemplo 1. dbx_sort() example configure looks for the client libraries and header files
under the default paths /usr/dbplus, /usr/local/dbplus and
/opt/dblus. If you have installed db++ in a different place
<?php you have add the installation path to the configure
function user_re_order ($a, $b) { option like this: --with-dbplus=/your/installation/path.
$rv = dbx_compare ($a, $b, "parentid",
DBX_CMP_DESC);
if ( !$rv ) { Configuración en tiempo de ejecución
$rv = dbx_compare ($a, $b, "id",
DBX_CMP_NUMBER); Esta extensión no define ninguna directiva de
} configuración.
return $rv;
}
Tipos de recursos
$link = dbx_connect (DBX_ODBC, "", "db",
"username", "password")
or die ("Could not connect"); dbplus_relation

$result = dbx_query ($link, "SELECT id, parentid,


description FROM tbl ORDER BY id"); Most db++ functions operate on or return
// data in $result is now ordered by id dbplus_relation resources. A dbplus_relation is a handle
to a stored relation or a relation generated as the result
dbx_sort ($result, "user_re_order"); of a query.
// data in $result is now ordered by parentid
(descending), then by id
Constantes predefinidas
dbx_close ($link);
?> Estas constantes están definidas por esta extensión y
See also dbx_compare(). estarán disponibles solamente cuando la extensión ha
sido o bien compilada dentro de PHP o grabada
dinamicamente en tiempo de ejecución.
XXII. DB++ Functions

db++ error codes


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Tabla 1. DB++ Error Codes
comportamineto de estas funciones, nombre de funciones
PHP Constant db++ constant meaning PHP Constant db++ constant meaning
DBPLUS_ERR_NOERR Null error Caused by
ERR_NOERR DBPLUS_ERR_PREEXIT
(integer) condition ERR_PREEXIT invalid
(integer)
usage
Tried to
DBPLUS_ERR_DUPLICAT insert a DBPLUS_ERR_ONTRAP Caused by
ERR_DUPLICATE ERR_ONTRAP
E (integer) duplicate (integer) a signal
tuple
Error in the
DBPLUS_ERR_PREPROC
DBPLUS_ERR_EOSCAN End of scan ERR_PREPROC preprocess
ERR_EOSCAN (integer)
(integer) from rget() or
Relation is DBPLUS_ERR_DBPARSE Error in the
DBPLUS_ERR_EMPTY ERR_DBPARSE
ERR_EMPTY empty (integer) parser
(integer)
(server)
DBPLUS_ERR_DBRUNER Run error in
ERR_DBRUNERR
DBPLUS_ERR_CLOSE The server R (integer) db
ERR_CLOSE
(integer) can't close
Exit
The record condition
DBPLUS_ERR_WLOCKED DBPLUS_ERR_DBPREEXI
ERR_WLOCKED is write ERR_DBPREEXIT caused by
(integer) T (integer)
locked prexit() *
procedure
Relation
DBPLUS_ERR_LOCKED
ERR_LOCKED was already Wait a little
(integer) DBPLUS_ERR_WAIT
locked ERR_WAIT (Simple
(integer)
only)
Relation
DBPLUS_ERR_NOLOCK
ERR_NOLOCK cannot be A client
(integer)
locked DBPLUS_ERR_CORRUPT_ ERR_CORRUPT_TU sent a
TUPLE (integer) PLE corrupt
DBPLUS_ERR_READ Read error
ERR_READ tuple
(integer) on relation
The Simple
DBPLUS_ERR_WRITE Write error
ERR_WRITE routines
(integer) on relation
encountere
DBPLUS_ERR_WARNING
Create() ERR_WARNING0 d a non
DBPLUS_ERR_CREATE 0 (integer)
ERR_CREATE system call fatal error
(integer)
failed which was
corrected
Lseek()
DBPLUS_ERR_LSEEK
ERR_LSEEK system call The server
(integer)
failed should not
really die
Tuple
but after a
DBPLUS_ERR_LENGTH exceeds DBPLUS_ERR_PANIC
ERR_LENGTH ERR_PANIC disaster
(integer) maximum (integer)
send
length
ERR_PANIC
Open() to all its
DBPLUS_ERR_OPEN
ERR_OPEN system call clients
(integer)
failed
DBPLUS_ERR_FIFO Can't
ERR_FIFO
Relation (integer) create a fifo
DBPLUS_ERR_WOPEN already
ERR_WOPEN DBPLUS_ERR_PERM Permission
(integer) opened for ERR_PERM
(integer) denied
writing
DBPLUS_ERR_TCL
DBPLUS_ERR_MAGIC File is not a ERR_TCL TCL_error
ERR_MAGIC (integer)
(integer) relation
DBPLUS_ERR_RESTRICT Only two
File is a ERR_RESTRICTED
DBPLUS_ERR_VERSION ED (integer) users
ERR_VERSION very old
(integer)
relation An error in
the use of
Relation
the library
DBPLUS_ERR_PGSIZE uses a DBPLUS_ERR_USER
ERR_PGSIZE ERR_USER by an
(integer) different (integer)
application
page size
programme
Invalid crc r
DBPLUS_ERR_CRC
ERR_CRC in the
(integer) DBPLUS_ERR_UNKNOWN
superpage ERR_UNKNOWN
(integer)
Piped Tabla de contenidos
DBPLUS_ERR_PIPE relation dbplus_add -- Add a tuple to a relation
ERR_PIPE
(integer) requires dbplus_aql -- Perform AQL query
lseek() dbplus_chdir -- Get/Set database virtual current directory
Too many dbplus_close -- Close a relation
DBPLUS_ERR_NIDX dbplus_curr -- Get current tuple from relation
ERR_NIDX secondary
(integer) dbplus_errcode -- Get error string for given errorcode or
indices
last error
DBPLUS_ERR_MALLOC Malloc() call dbplus_errno -- Get error code for last operation
ERR_MALLOC
(integer) failed dbplus_find -- Set a constraint on a relation
DBPLUS_ERR_NUSERS Error use of dbplus_first -- Get first tuple from relation
ERR_NUSERS dbplus_flush -- Flush all changes made on a relation
(integer) max users
dbplus_freealllocks -- Free all locks held by this client Description
dbplus_freelock -- Release write lock on tuple
dbplus_freerlocks -- Free all tuple locks on given relation
dbplus_getlock -- Get a write lock on a tuple resource dbplus_aql ( string query [, string server [,
dbplus_getunique -- Get a id number unique to a relation string dbpath]])
dbplus_info -- ???
dbplus_last -- Get last tuple from relation
dbplus_lockrel -- Request write lock on relation Aviso
dbplus_next -- Get next tuple from relation Este módulo es EXPERIMENTAL. Esto significa que el
dbplus_open -- Open relation file comportamineto de estas funciones, nombre de funciones
dbplus_prev -- Get previous tuple from relation y en definitiva TODO lo documentado aqui, puede cambiar
dbplus_rchperm -- Change relation permissions en una futura version de PHP SIN AVISO. Quedas avisado, y
dbplus_rcreate -- Creates a new DB++ relation utilizar este módulo es tu responsabiliad.
dbplus_rcrtexact -- Creates an exact but empty copy of a
dbplus_aql() will execute an AQL query on the given
relation including indices
server and dbpath.
dbplus_rcrtlike -- Creates an empty copy of a relation
On success it will return a relation handle. The result
with default indices
data may be fetched from this relation by calling
dbplus_resolve -- Resolve host information for relation
dbplus_next() and dbplus_current(). Other relation
dbplus_restorepos -- ???
access functions will not work on a result relation.
dbplus_rkeys -- Specify new primary key for a relation
Further information on the AQL A... Query Language is
dbplus_ropen -- Open relation file local
provided in the original db++ manual.
dbplus_rquery -- Perform local (raw) AQL query
dbplus_rrename -- Rename a relation
dbplus_rsecindex -- Create a new secondary index for a dbplus_chdir
relation
dbplus_runlink -- Remove relation from filesystem
dbplus_rzap -- Remove all tuples from relation (4.1.0 - 4.2.3 only)
dbplus_savepos -- ??? dbplus_chdir -- Get/Set database virtual current directory
dbplus_setindex -- ???
dbplus_setindexbynumber -- ???
dbplus_sql -- Perform SQL query Description
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current string dbplus_chdir ( [string newdir])
tuple
dbplus_undo -- ???
dbplus_undoprepare -- ??? Aviso
dbplus_unlockrel -- Give up write lock on relation
dbplus_unselect -- Remove a constraint from relation Este módulo es EXPERIMENTAL. Esto significa que el
dbplus_update -- Update specified tuple in relation comportamineto de estas funciones, nombre de funciones
dbplus_xlockrel -- Request exclusive lock on relation y en definitiva TODO lo documentado aqui, puede cambiar
dbplus_xunlockrel -- Free exclusive lock on relation en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
dbplus_chdir() will change the virtual current directory
dbplus_add
where relation files will be looked for by dbplus_open().
dbplus_chdir() will return the absolute path of the
(4.1.0 - 4.2.3 only) current directory. Calling dbplus_chdir() without giving
dbplus_add -- Add a tuple to a relation any newdir may be used to query the current working
directory.

Description
dbplus_close

int dbplus_add ( resource relation, array tuple)


(4.1.0 - 4.2.3 only)
dbplus_close -- Close a relation
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Description
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 int dbplus_close ( resource relation)
utilizar este módulo es tu responsabiliad.
This function will add a tuple to a relation. The tuple data Aviso
is an array of attribute/value pairs to be inserted into the
given relation. After successful execution the tuple array Este módulo es EXPERIMENTAL. Esto significa que el
will contain the complete data of the newly created tuple, comportamineto de estas funciones, nombre de funciones
including all implicitly set domain fields like sequences. y en definitiva TODO lo documentado aqui, puede cambiar
The function will return zero (aka. DBPLUS_ERR_NOERR) en una futura version de PHP SIN AVISO. Quedas avisado, y
on success or a db++ error code on failure. See utilizar este módulo es tu responsabiliad.
dbplus_errcode() or the introduction to this chapter for Calling dbplus_close() will close a relation previously
more information on db++ error codes. opened by dbplus_open().

dbplus_aql dbplus_curr

(4.1.0 - 4.2.3 only) (4.1.0 - 4.2.3 only)


dbplus_aql -- Perform AQL query dbplus_curr -- Get current tuple from relation
Description int dbplus_find ( resource relation, array constraints,
mixed tuple)

int dbplus_curr ( resource relation, array tuple)


Aviso

Aviso Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. dbplus_find() will place a constraint on the given
relation. Further calls to functions like dbplus_curr() or
dbplus_curr() will read the data for the current tuple for dbplus_next() will only return tuples matching the given
the given relation and will pass it back as an associative constraints.
array in tuple. Constraints are triplets of strings containing of a domain
The function will return zero (aka. DBPLUS_ERR_NOERR) name, a comparison operator and a comparison value.
on success or a db++ error code on failure. See The constraints parameter array may consist of a
dbplus_errcode() or the introduction to this chapter for collection of string arrays, each of which contains a
more information on db++ error codes. domain, an operator and a value, or of a single string
See also dbplus_first(), dbplus_prev(), array containing a multiple of three elements.
dbplus_next(), and dbplus_last(). The comparison operator may be one of the following
strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular
expression match and 'BAND' or 'BOR' for bitwise
dbplus_errcode
operations.
See also dbplus_unselect().
(4.1.0 - 4.2.3 only)
dbplus_errcode -- Get error string for given errorcode or
dbplus_first
last error

(4.1.0 - 4.2.3 only)


Description
dbplus_first -- Get first tuple from relation

string dbplus_errcode ( int errno)


Description

Aviso int dbplus_first ( resource relation, array tuple)


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 Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y Este módulo es EXPERIMENTAL. Esto significa que el
utilizar este módulo es tu responsabiliad. comportamineto de estas funciones, nombre de funciones
dbplus_errcode() returns a cleartext error string for the y en definitiva TODO lo documentado aqui, puede cambiar
error code passed as errno of for the result code of the en una futura version de PHP SIN AVISO. Quedas avisado, y
last db++ operation if no parameter is given. utilizar este módulo es tu responsabiliad.
dbplus_curr() will read the data for the first tuple for the
given relation, make it the current tuple and pass it back
dbplus_errno
as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR)
(4.1.0 - 4.2.3 only) on success or a db++ error code on failure. See
dbplus_errno -- Get error code for last operation dbplus_errcode() or the introduction to this chapter for
more information on db++ error codes.
See also dbplus_curr(), dbplus_prev(),
Description dbplus_next(), and dbplus_last().

int dbplus_errno ( void) dbplus_flush

Aviso (4.1.0 - 4.2.3 only)


dbplus_flush -- Flush all changes made on a relation
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 Description
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
int dbplus_flush ( resource relation)
dbplus_errno() will return the error code returned by
the last db++ operation.
See also dbplus_errcode(). Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
dbplus_find 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
(4.1.0 - 4.2.3 only)
utilizar este módulo es tu responsabiliad.
dbplus_find -- Set a constraint on a relation
dbplus_flush() will write all changes applied to relation
since the last flush to disk.
Description
The function will return zero (aka. DBPLUS_ERR_NOERR) dbplus_getlock
on success or a db++ error code on failure. See
dbplus_errcode() or the introduction to this chapter for
more information on db++ error codes. (4.1.0 - 4.2.3 only)
dbplus_getlock -- Get a write lock on a tuple

dbplus_freealllocks
Description

(4.1.0 - 4.2.3 only)


dbplus_freealllocks -- Free all locks held by this client int dbplus_getlock ( resource relation, string tname)

Description Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
int dbplus_freealllocks ( void) 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
Aviso utilizar este módulo es tu responsabiliad.

Este módulo es EXPERIMENTAL. Esto significa que el dbplus_getlock() will request a write lock on the
comportamineto de estas funciones, nombre de funciones specified tuple. It will return zero on success or a non-
y en definitiva TODO lo documentado aqui, puede cambiar zero error code, especially DBPLUS_ERR_WLOCKED, on
en una futura version de PHP SIN AVISO. Quedas avisado, y failure.
utilizar este módulo es tu responsabiliad. See also dbplus_freelock(), dbplus_freerlocks(), and
dbplus_freealllocks().
dbplus_freeaalllocks() will free all tuple locks held by
this client.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_getunique
dbplus_freerlocks().

(4.1.0 - 4.2.3 only)


dbplus_freelock dbplus_getunique -- Get a id number unique to a relation

(4.1.0 - 4.2.3 only) Description


dbplus_freelock -- Release write lock on tuple

int dbplus_getunique ( resource relation, int uniqueid)


Description

Aviso
int dbplus_freelock ( resource relation, string tname)
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Este módulo es EXPERIMENTAL. Esto significa que el utilizar este módulo es tu responsabiliad.
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar dbplus_getunique() will obtain a number guaranteed to
en una futura version de PHP SIN AVISO. Quedas avisado, y be unique for the given relation and will pass it back in
utilizar este módulo es tu responsabiliad. the variable given as uniqueid.
The function will return zero (aka. DBPLUS_ERR_NOERR)
dbplus_freelock() will release a write lock on the given on success or a db++ error code on failure. See
tuple previously obtained by dbplus_getlock(). dbplus_errcode() or the introduction to this chapter for
See also dbplus_getlock(), dbplus_freerlocks(), and more information on db++ error codes.
dbplus_freealllocks().

dbplus_info
dbplus_freerlocks

(4.1.0 - 4.2.3 only)


(4.1.0 - 4.2.3 only) dbplus_info -- ???
dbplus_freerlocks -- Free all tuple locks on given relation

Description
Description

int dbplus_info ( resource relation, string key, array )


int dbplus_freerlocks ( resource relation)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas funciones, nombre de funciones
comportamineto de estas funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede cambiar
y en definitiva TODO lo documentado aqui, puede cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y
en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este módulo es tu responsabiliad.
utilizar este módulo es tu responsabiliad.
Not implemented yet.
dbplus_freerlocks() will free all tuple locks held on the
given relation.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_last
dbplus_freealllocks().

(4.1.0 - 4.2.3 only)


dbplus_last -- Get last tuple from relation dbplus_open

Description (4.1.0 - 4.2.3 only)


dbplus_open -- Open relation file

int dbplus_last ( resource relation, array tuple)


Description

Aviso
resource dbplus_open ( string name)
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 Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
dbplus_curr() will read the data for the last tuple for the y en definitiva TODO lo documentado aqui, puede cambiar
given relation, make it the current tuple and pass it back en una futura version de PHP SIN AVISO. Quedas avisado, y
as an associative array in tuple. utilizar este módulo es tu responsabiliad.
The function will return zero (aka. DBPLUS_ERR_NOERR)
on success or a db++ error code on failure. See The relation file name will be opened. name can be either
dbplus_errcode() or the introduction to this chapter for a file name or a relative or absolute path name. This will
more information on db++ error codes. be mapped in any case to an absolute relation file path
See also dbplus_first(), dbplus_curr(), dbplus_prev(), on a specific host machine and server.
and dbplus_next(). On success a relation file resource (cursor) is returned
which must be used in any subsequent commands
referencing the relation. Failure leads to a zero return
dbplus_lockrel value, the actual error code may be asked for by calling
dbplus_errno().

(no version information, might be only in CVS)


dbplus_lockrel -- Request write lock on relation dbplus_prev

Description (4.1.0 - 4.2.3 only)


dbplus_prev -- Get previous tuple from relation

int dbplus_lockrel ( resource relation)


Description

Aviso
int dbplus_prev ( resource relation, array tuple)
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 Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
dbplus_lockrel() will request a write lock on the given y en definitiva TODO lo documentado aqui, puede cambiar
relation. Other clients may still query the relation, but en una futura version de PHP SIN AVISO. Quedas avisado, y
can't alter it while it is locked. utilizar este módulo es tu responsabiliad.
dbplus_curr() will read the data for the next tuple for
dbplus_next the given relation, will make it the current tuple and will
pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR)
(4.1.0 - 4.2.3 only) on success or a db++ error code on failure. See
dbplus_next -- Get next tuple from relation dbplus_errcode() or the introduction to this chapter for
more information on db++ error codes.
See also dbplus_first(), dbplus_curr(), dbplus_next(),
Description
and dbplus_last().

int dbplus_next ( resource relation, array )


dbplus_rchperm

Aviso (4.1.0 - 4.2.3 only)


Este módulo es EXPERIMENTAL. Esto significa que el dbplus_rchperm -- Change relation permissions
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 Description
utilizar este módulo es tu responsabiliad.
dbplus_curr() will read the data for the next tuple for int dbplus_rchperm ( resource relation, int mask, string
the given relation, will make it the current tuple and will user, string group)
pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR)
on success or a db++ error code on failure. See Aviso
dbplus_errcode() or the introduction to this chapter for Este módulo es EXPERIMENTAL. Esto significa que el
more information on db++ error codes. comportamineto de estas funciones, nombre de funciones
See also dbplus_first(), dbplus_curr(), dbplus_prev(), y en definitiva TODO lo documentado aqui, puede cambiar
and dbplus_last(). en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
dbplus_rchperm() will change access permissions as resource dbplus_rcrtlike ( string name, resource
specified by mask, user and group. The values for these relation, int flag)
are operating system specific.

Aviso
dbplus_rcreate
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
(4.1.0 - 4.2.3 only) y en definitiva TODO lo documentado aqui, puede cambiar
dbplus_rcreate -- Creates a new DB++ relation en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.

Description dbplus_rcrtexact() will create an empty copy of the


given relation under a new name, but with default
indices. An existing relation by the same name will only
resource dbplus_rcreate ( string name, mixed domlist [, be overwritten if overwrite is TRUE and no other process
boolean overwrite]) is currently using the relation.

Aviso dbplus_resolve

Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones (4.1.0 - 4.2.3 only)
y en definitiva TODO lo documentado aqui, puede cambiar dbplus_resolve -- Resolve host information for relation
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Description
dbplus_rcreate() will create a new relation named
name. An existing relation by the same name will only be
overwritten if the relation is currently not in use and int dbplus_resolve ( string relation_name)
overwrite is set to TRUE.
domlist should contain the domain specification for the
new relation within an array of domain description Aviso
strings. ( dbplus_rcreate() will also accept a string with Este módulo es EXPERIMENTAL. Esto significa que el
space delimited domain description strings, but it is comportamineto de estas funciones, nombre de funciones
recommended to use an array). A domain description y en definitiva TODO lo documentado aqui, puede cambiar
string consists of a domain name unique to this relation, en una futura version de PHP SIN AVISO. Quedas avisado, y
a slash and a type specification character. See the db++ utilizar este módulo es tu responsabiliad.
documentation, especially the dbcreate(1) manpage, for
a description of available type specifiers and their dbplus_resolve() will try to resolve the given
meanings. relation_name and find out internal server id, real
hostname and the database path on this host. The
function will return an array containing these values
dbplus_rcrtexact under the keys 'sid', 'host' and 'host_path' or FALSE on
error.
See also dbplus_tcl().
(4.1.0 - 4.2.3 only)
dbplus_rcrtexact -- Creates an exact but empty copy of a
relation including indices dbplus_restorepos

Description (4.1.0 - 4.2.3 only)


dbplus_restorepos -- ???
resource dbplus_rcrtexact ( string name, resource
relation, boolean overwrite) Description

Aviso int dbplus_restorepos ( resource relation, array tuple)


Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y Este módulo es EXPERIMENTAL. Esto significa que el
utilizar este módulo es tu responsabiliad. comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
dbplus_rcrtexact() will create an exact but empty copy en una futura version de PHP SIN AVISO. Quedas avisado, y
of the given relation under a new name. An existing utilizar este módulo es tu responsabiliad.
relation by the same name will only be overwritten if
overwrite is TRUE and no other process is currently using Not implemented yet.
the relation.
dbplus_rkeys
dbplus_rcrtlike
(4.1.0 - 4.2.3 only)
(4.1.0 - 4.2.3 only) dbplus_rkeys -- Specify new primary key for a relation
dbplus_rcrtlike -- Creates an empty copy of a relation
with default indices
Description

Description
resource dbplus_rkeys ( resource relation, mixed
domlist)
Aviso y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Este módulo es EXPERIMENTAL. Esto significa que el
utilizar este módulo es tu responsabiliad.
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar dbplus_rrename() will change the name of relation to
en una futura version de PHP SIN AVISO. Quedas avisado, y name.
utilizar este módulo es tu responsabiliad.
dbplus_rkeys() will replace the current primary key for dbplus_rsecindex
relation with the combination of domains specified by
domlist.
domlist may be passed as a single domain name string or (4.1.0 - 4.2.3 only)
as an array of domain names. dbplus_rsecindex -- Create a new secondary index for a
relation

dbplus_ropen
Description

(4.1.0 - 4.2.3 only)


dbplus_ropen -- Open relation file local resource dbplus_rsecindex ( resource relation, mixed
domlist, int type)

Description
Aviso
resource dbplus_ropen ( string name) 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
Aviso en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones dbplus_rsecindex() will create a new secondary index
y en definitiva TODO lo documentado aqui, puede cambiar for relation with consists of the domains specified by
en una futura version de PHP SIN AVISO. Quedas avisado, y domlist and is of type type
utilizar este módulo es tu responsabiliad. domlist may be passed as a single domain name string or
as an array of domain names.
dbplus_ropen() will open the relation file locally for
quick access without any client/server overhead. Access
is read only and only dbplus_current() and dbplus_runlink
dbplus_next() may be applied to the returned relation.

(4.1.0 - 4.2.3 only)


dbplus_rquery dbplus_runlink -- Remove relation from filesystem

(4.1.0 - 4.2.3 only) Description


dbplus_rquery -- Perform local (raw) AQL query

int dbplus_runlink ( resource relation)


Description

Aviso
int dbplus_rquery ( string query, string dbpath)
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Este módulo es EXPERIMENTAL. Esto significa que el
utilizar este módulo es tu responsabiliad.
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar dbplus_unlink() will close and remove the relation.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
dbplus_rzap
dbplus_rquery() performs a local (raw) AQL query using
an AQL interpreter embedded into the db++ client
library. dbplus_rquery() is faster than dbplus_aql() but (4.1.0 - 4.2.3 only)
will work on local data only. dbplus_rzap -- Remove all tuples from relation

dbplus_rrename Description

(4.1.0 - 4.2.3 only) int dbplus_rzap ( resource relation)


dbplus_rrename -- Rename a relation

Aviso
Description
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
int dbplus_rrename ( resource relation, string name) 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 dbplus_rzap() will remove all tuples from relation.
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
dbplus_savepos
(4.1.0 - 4.2.3 only) Este módulo es EXPERIMENTAL. Esto significa que el
dbplus_savepos -- ??? comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
Description en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Not implemented yet.
int dbplus_savepos ( resource relation)

dbplus_tcl
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el (4.1.0 - 4.2.3 only)
comportamineto de estas funciones, nombre de funciones
dbplus_tcl -- Execute TCL code on server side
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. Description
Not implemented yet.
int dbplus_tcl ( int sid, string script)
dbplus_setindex
Aviso
(4.1.0 - 4.2.3 only) Este módulo es EXPERIMENTAL. Esto significa que el
dbplus_setindex -- ??? comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
Description en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
A db++ server will prepare a TCL interpreter for each
int dbplus_setindex ( resource relation, string client connection. This interpreter will enable the server
idx_name) to execute TCL code provided by the client as a sort of
stored procedures to improve the performance of
database operations by avoiding client/server data
Aviso
transfers and context switches.
Este módulo es EXPERIMENTAL. Esto significa que el dbplus_tcl() needs to pass the client connection id the
comportamineto de estas funciones, nombre de funciones TCL script code should be executed by.
y en definitiva TODO lo documentado aqui, puede cambiar dbplus_resolve() will provide this connection id. The
en una futura version de PHP SIN AVISO. Quedas avisado, y function will return whatever the TCL code returns or a
utilizar este módulo es tu responsabiliad. TCL error message if the TCL code fails.
Not implemented yet. See also dbplus_resolve().

dbplus_setindexbynumber dbplus_tremove

(4.1.0 - 4.2.3 only) (4.1.0 - 4.2.3 only)


dbplus_setindexbynumber -- ??? dbplus_tremove -- Remove tuple and return new current
tuple

Description
Description

int dbplus_setindexbynumber ( resource relation, int


idx_number) int dbplus_tremove ( resource relation, array tuple [,
array current])

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Not implemented yet.
dbplus_tremove() removes tuple from relation if it
perfectly matches a tuple within the relation. current, if
dbplus_sql given, will contain the data of the new current tuple after
calling dbplus_tremove().

(4.1.0 - 4.2.3 only)


dbplus_sql -- Perform SQL query dbplus_undo

Description (4.1.0 - 4.2.3 only)


dbplus_undo -- ???

resource dbplus_sql ( string query, string server, string


dbpath) Description

Aviso int dbplus_undo ( resource relation)


Aviso (4.1.0 - 4.2.3 only)
dbplus_update -- Update specified tuple in relation
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 Description
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
int dbplus_update ( resource relation, array old, array
Not implemented yet. new)

dbplus_undoprepare Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
(4.1.0 - 4.2.3 only) comportamineto de estas funciones, nombre de funciones
dbplus_undoprepare -- ??? 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.
Description
dbplus_update() replaces the tuple given by old with
the data from new if and only if old completely matches a
int dbplus_undoprepare ( resource relation) tuple within relation.

Aviso dbplus_xlockrel
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones (4.1.0 - 4.2.3 only)
y en definitiva TODO lo documentado aqui, puede cambiar dbplus_xlockrel -- Request exclusive lock on relation
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Description
Not implemented yet.

int dbplus_xlockrel ( resource relation)


dbplus_unlockrel

Aviso
(4.1.0 - 4.2.3 only)
dbplus_unlockrel -- Give up write lock on relation 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
Description en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
int dbplus_unlockrel ( resource relation) dbplus_xlockrel() will request an exclusive lock on
relation preventing even read access from other clients.
See also dbplus_xunlockrel().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el dbplus_xunlockrel
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 (4.1.0 - 4.2.3 only)
utilizar este módulo es tu responsabiliad. dbplus_xunlockrel -- Free exclusive lock on relation
dbplus_unlockrel() will release a write lock previously
obtained by dbplus_lockrel(). Description

dbplus_unselect int dbplus_xunlockrel ( resource relation)

(4.1.0 - 4.2.3 only)


Aviso
dbplus_unselect -- Remove a constraint from relation
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Description y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
int dbplus_unselect ( resource relation) utilizar este módulo es tu responsabiliad.
dbplus_xunlockrel() will release an exclusive lock on
relation previously obtained by dbplus_xlockrel().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el XXIII. Direct IO functions
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 Introducción
utilizar este módulo es tu responsabiliad.
Calling dbplus_unselect() will remove a constraint PHP supports the direct io functions as described in the
previously set by dbplus_find() on relation. Posix Standard (Section 6) for performing I/O functions at
a lower level than the C-Language stream I/O functions
dbplus_update (fopen(), fread(),..). The use of the DIO functions should
be considered only when direct control of a device is
needed. In all other cases, the standard filesystem mixed dio_fcntl ( resource fd, int cmd [, mixed arg])
functions are more than adequate.
The dio_fcntl() function performs the operation specified
Nota: This extension is not available by cmd on the file descriptor fd. Some commands require
on Windows platforms. additional arguments args to be supplied.
arg is an associative array, when cmd is F_SETLK or
F_SETLLW, with the following keys:

Requerimientos • "start" - offset where lock begins


• "length" - size of locked area. zero means to
Estas funciones están disponibles como parte del módulo end of file
estandar, el cual está siempre disponible.
• "wenth" - Where l_start is relative to: can be
SEEK_SET, SEEK_END and SEEK_CUR
Instalación • "type" - type of lock: can be F_RDLCK (read
lock), F_WRLCK (write lock) or F_UNLCK
(unlock)
To get these functions to work, you have to configure
PHP with --enable-dio.
cmd can be one of the following operations:
Configuración en tiempo de ejecución
• F_SETLK - Lock is set or cleared. If the lock is
Esta extensión no define ninguna directiva de held by someone else dio_fcntl() returns -1.
configuración. • F_SETLKW - like F_SETLK, but in case the lock
is held by someone else, dio_fcntl() waits
until the lock is released.
Tipos de recursos
• F_GETLK - dio_fcntl() returns an associative
array (as described above) if someone else
One resource type is defined by this extension: a file prevents lock. If there is no obstruction key
descriptor returnded by dio_open(). "type" will set to F_UNLCK.
• F_DUPFD - finds the lowest numbered available
Constantes predefinidas file descriptor greater or equal than arg and
returns them.

Esta extensión no define ninguna constante. • F_SETFL - Sets the file descriptors flags to the
Tabla de contenidos value specified by arg, Which can be
dio_close -- Closes the file descriptor given by fd O_APPEND,O_NONBLOCK or O_ASYNC . To use
dio_fcntl -- Performs a c library fcntl on fd O_ASYNC you will need to use the pcntl
dio_open -- Opens a new filename with specified extension.
permissions of flags and creation permissions of mode
dio_read -- Reads n bytes from fd and returns them, if n dio_open
is not specified, reads 1k block
dio_seek -- Seeks to pos on fd from whence
dio_stat -- Gets stat information about the file descriptor (PHP 4 >= 4.2.0)
fd dio_open -- Opens a new filename with specified
dio_tcsetattr -- Sets terminal attributes and baud rate for permissions of flags and creation permissions of mode
a serial port
dio_truncate -- Truncates file descriptor fd to offset bytes
dio_write -- Writes data to fd with optional truncation at Description
length
resource dio_open ( string filename, int flags [, int
dio_close mode])

dio_open() opens a file and returns a new file descriptor


(PHP 4 >= 4.2.0)
for it, or FALSE if any error occurred. If flags is O_CREAT,
dio_close -- Closes the file descriptor given by fd
optional third parameter mode will set the mode of the
file (creation permissions). The flags parameter can be
Description one of the following options:

void dio_close ( resource fd) • O_RDONLY - opens the file for read access
• O_WRONLY - opens the file for write access
The function dio_close() closes the file descriptor
resource. • O_RDWR - opens the file for both reading and
writing

dio_fcntl
The flags parameter can also include any combination of
the following flags:
(PHP 4 >= 4.2.0)
dio_fcntl -- Performs a c library fcntl on fd
• O_CREAT - creates the file, if it doesn't already
Description exist
• O_EXCL - if both, O_CREAT and O_EXCL are set, • "device" - device
dio_open() fails, if file already exists
• "inode" - inode
• O_TRUNC - if file exists, and its opened for
• "mode" - mode
write access, file will be truncated to zero
length. • "nlink" - number of hard links
• O_APPEND - write operations write data at the • "uid" - user id
end of file
• "gid" - group id
• O_NONBLOCK - sets non blocking mode
• "device_type" - device type (if inode device)
• "size" - total size in bytes
dio_read
• "blocksize" - blocksize

(PHP 4 >= 4.2.0) • "blocks" - number of blocks allocated


dio_read -- Reads n bytes from fd and returns them, if n • "atime" - time of last access
is not specified, reads 1k block
• "mtime" - time of last modification
• "ctime" - time of last change
Description

On error dio_stat() returns NULL.


string dio_read ( resource fd [, int n])

The function dio_read() reads and returns n bytes from dio_tcsetattr


file with descriptor resource. If n is not specified,
dio_read() reads 1K sized block and returns them. (PHP 4 >= 4.3.0)
dio_tcsetattr -- Sets terminal attributes and baud rate for
dio_seek a serial port

(PHP 4 >= 4.2.0) Description


dio_seek -- Seeks to pos on fd from whence
dio_tcsetattr ( resource fd, array options)
Description
The function dio_tcsetattr() sets the terminal attributes
and baud rate of the open resource. The currently
int dio_seek ( resource fd, int pos, int whence) available options are

The function dio_seek() is used to change the file


position of the file with descriptor resource. The • 'baud' - baud rate of the port - can be
parameter whence specifies how the position pos should 38400,19200,9600,4800,2400,1800,1200,600,
be interpreted: 300,200,150,134,110,75 or 50, default value is
9600

• SEEK_SET - specifies that pos is specified from


• 'bits' - data bits - can be 8,7,6 or 5 default
value is 8
the beginning of the file
• SEEK_CUR - Specifies that pos is a count of
• 'stop' - stop bits - can be 1 or 2 default value is
1
characters from the current file position. This
count may be positive or negative • 'parity' - can be 0,1 or 2 default value is 0
• SEEK_END - Specifies that pos is a count of
characters from the end of the file. A negative Ejemplo 1. Setting the baud rate on a serial port
count specifies a position within the current
extent of the file; a positive count specifies a
position past the current end. If you set the <?php
position past the current end, and actually
write data, you will extend the file with zeros $fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY |
up to that position O_NONBLOCK);

dio_stat dio_fcntl($fd,F_SETFL, O_SYNC );

dio_tcsetattr($fd, array(
(PHP 4 >= 4.2.0) 'baud' => 9600,
dio_stat -- Gets stat information about the file descriptor 'bits' => 8,
fd 'stop' =>1,
'parity' => 0
));
Description
while (1) {
array dio_stat ( resource fd)
$data = dio_read($fd,256);

Function dio_stat() returns information about the file if ($data) {


with file descriptor fd. dio_stat() returns an associative echo $data;
array with the following keys: }
}
(PHP 4 >= 4.0.5)
chroot -- Change the root directory
?>

Description
Nota: This function was introduced
in PHP 4.3.0.
bool chroot ( string directory)

dio_truncate
Changes the root directory of the current process to
directory. Devuelve TRUE si todo fue bien, FALSE en
(PHP 4 >= 4.2.0) caso de fallo..
dio_truncate -- Truncates file descriptor fd to offset bytes
Nota: It's not wise to use this
Description function when running in a
webserver environment, because it's
not possible to reset the root
bool dio_truncate ( resource fd, int offset) directory to / again at the end of the
request. This function will only
Function dio_truncate() causes the file referenced by fd function correct when you run PHP
to be truncated to at most offset bytes in size. If the file as command line too. (CLI)
previously was larger than this size, the extra data is
lost. If the file previously was shorter, it is unspecified Nota: Esta función no está
whether the file is left unchanged or is extended. In the implementada en plataformas
latter case the extended part reads as zero bytes. Windows.
Returns 0 on success, otherwise -1.

dir
dio_write

(PHP 3, PHP 4 )
(PHP 4 >= 4.2.0) dir -- clase directorio
dio_write -- Writes data to fd with optional truncation at
length
Descripcion
Description
new dir ( string directory)
int dio_write ( resource fd, string data [, int len])
Un mecanismo semi-orientado a objetos para leer
directorios. El parametro directory abre el directorio. Dos
The function dio_write() writes up to len bytes from propiedades estan disponibles cuando el directorio ha
data to file fd. If len is not specified, dio_write() writes sido abierto. La propiedad de manejo puede ser usada
all data to the specified file. dio_write() returns the con otras funciones de directorios tal como readdir(),
number of bytes written to fd. rewinddir() y closedir(). La propiedad de trayectoria
(path) es fijada para encaminar el directorio que ha sido
XXIV. Funciones con directorios abierto. Tres metodos estan disponibles: leer, rebobinar
y cerrar.
Ejemplo 1. dir() Ejemplo
Tabla de contenidos
chdir -- cambia de directorio
chroot -- Change the root directory $d = dir("/etc");
dir -- clase directorio echo "Handle: ".$d-
closedir -- cierra el manejador de directorios >handle."<br>\n";
getcwd -- gets the current working directory echo "Path: ".$d-
opendir -- abre el manejador de directorios >path."<br>\n";
readdir -- lee las entradas del manejador de directorios while($entry=$d->read())
rewinddir -- rebobinar el manejador de directorios {
echo $entry."<br>\n";
}
chdir $d->close();

(PHP 3, PHP 4 )
chdir -- cambia de directorio closedir

Description (PHP 3, PHP 4 )


closedir -- cierra el manejador de directorios

int chdir ( string directory)


Descripcion
Cambia el directorio PHP actual a directory. Devuelve
FALSE si no puede cambiar al directorio, TRUE si todo void closedir ( int dir_handle)
va bien.
Cierra la secuencia de directorio determinada por
chroot dir_handle. La secuencia debe de haber sido abierta
previamente con opendir().
getcwd rewinddir

(PHP 4 ) (PHP 3, PHP 4 )


getcwd -- gets the current working directory rewinddir -- rebobinar el manejador de directorios

Description Descripcion

string getcwd ( void) void rewinddir ( int dir_handle)

Returns the current working directory. Inizializa la secuencia de directorio determinada por
See also chdir(). dir_handle al principio del directorio.

opendir XXV. Funciones de DOM XML

(PHP 3, PHP 4 ) Aviso


opendir -- abre el manejador de directorios
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Descripcion 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.
int opendir ( string path)
Estas funciones son disponibles solamente si PHP fué
configurado con --with-dom=[DIR], usando al libreria de
Devuelve un manejador de directorio para ser usado con XML de GNOME. Usted va a necesitar como mínimo
las llamadas closedir(), readdir() y rewinddir(). libxml-2.0.0 (la versión beta no trabajará). Estas
functiones fueron añadidas en PHP4.
readdir Este module define las siguientes constantes:
Tabla 1. Constantes de XML
Valo Descripci
(PHP 3, PHP 4 ) Constante
r ón
readdir -- lee las entradas del manejador de directorios
XML_ELEMENT_NODE 1

Descripcion XML_ATTRIBUTE_NODE 2
XML_TEXT_NODE 3
string readdir ( int dir_handle) XML_CDATA_SECTION_N
4
ODE
Devuelve el nombre del siguiente fichero en el directorio. XML_ENTITY_REF_NODE 5
Los nombres de ficheros no son devueltos en ningun
XML_ENTITY_NODE 6
orden especial .
Ejemplo 1. Listar todos los ficheros en un XML_PI_NODE 7
directorio
XML_COMMENT_NODE 8
XML_DOCUMENT_NODE 9
<?php XML_DOCUMENT_TYPE_N
$handle=opendir('.'); 10
ODE
echo "Directory handle:
$handle\n"; XML_DOCUMENT_FRAG_N
11
echo "Files:\n"; ODE
while ($file = XML_NOTATION_NODE 12
readdir($handle)) {
echo "$file\n"; XML_GLOBAL_NAMESPAC
1
} E
closedir($handle); XML_LOCAL_NAMESPACE 2
?>
Este modulo define un número de clases. Las funciones
Tener en cuenta que readdir() devolvera tambien . y .. de DOM XML devuelven un árbol conteniendo la structura
Si no quereis estas entradas podeis borrarlas: del documento XML, en el cual cada nodo es un objecto
Ejemplo 2. Listar todos los ficheros en un perteneciente a una de estas clases.
directorio excepto . y .. Tabla de contenidos
DomAttribute->name -- Returns name of attribute
DomAttribute->specified -- Checks if attribute is
<?php specified
$handle=opendir('.'); DomAttribute->value -- Returns value of attribute
while ($file = DomDocument->add_root [deprecated] -- Adds a root
readdir($handle)) { node
if ($file != "." && $file ! DomDocument->create_attribute -- Create new attribute
= "..") { DomDocument->create_cdata_section -- Create new
echo "$file\n"; cdata node
} DomDocument->create_comment -- Create new
} comment node
DomDocument->create_element_ns -- Create new
closedir($handle); element node with an associated namespace
?>
DomDocument->create_element -- Create new element DomNode->set_namespace -- Sets namespace of a
node node.
DomDocument->create_entity_reference -- DomNode->unlink_node -- Deletes node
DomDocument->create_processing_instruction -- Creates DomProcessingInstruction->data -- Returns data of pi
new PI node node
DomDocument->create_text_node -- Create new text DomProcessingInstruction->target -- Returns target of pi
node node
DomDocument->doctype -- Returns the document type DomXsltStylesheet->process -- Applies the XSLT-
DomDocument->document_element -- Returns root Transformation on a DomDocument Object.
element node DomXsltStylesheet->result_dump_file -- Dumps the
DomDocument->dump_file -- Dumps the internal XML result from a XSLT-Transformation into a file
tree back into a file DomXsltStylesheet->result_dump_mem -- Dumps the
DomDocument->dump_mem -- Dumps the internal XML result from a XSLT-Transformation back into a string
tree back into a string domxml_new_doc -- Creates new empty XML document
DomDocument->get_element_by_id -- Searches for an domxml_open_file -- Creates a DOM object from XML file
element with a certain id domxml_open_mem -- Creates a DOM object of an XML
DomDocument->get_elements_by_tagname -- document
DomDocument->html_dump_mem -- Dumps the internal domxml_version -- Get XML library version
XML tree back into a string as HTML domxml_xmltree -- Creates a tree of PHP objects from an
DomDocument->xinclude -- Substitutes XIncludes in a XML document
DomDocument Object. domxml_xslt_stylesheet_doc -- Creates a
DomDocumentType->entities -- Returns list of entities DomXsltStylesheet Object from a DomDocument Object.
DomDocumentType->internal_subset -- Returns internal domxml_xslt_stylesheet_file -- Creates a
subset DomXsltStylesheet Object from a xsl document in a file.
DomDocumentType->name -- Returns name of domxml_xslt_stylesheet -- Creates a DomXsltStylesheet
document type Object from a xml document in a string.
DomDocumentType->notations -- Returns list of xpath_eval_expression -- Evaluates the XPath Location
notations Path in the given string
DomDocumentType->public_id -- Returns public id of xpath_eval -- Evaluates the XPath Location Path in the
document type given string
DomDocumentType->system_id -- Returns system id of xpath_new_context -- Creates new xpath context
document type xptr_eval -- Evaluate the XPtr Location Path in the given
DomElement->get_attribute_node -- Returns value of string
attribute xptr_new_context -- Create new XPath Context
DomElement->get_attribute -- Returns value of attribute
DomElement->get_elements_by_tagname -- Gets
elements by tagname DomAttribute->name
DomElement->has_attribute -- Checks to see if attribute
exists (no version information, might be only in CVS)
DomElement->remove_attribute -- Removes attribute
DomAttribute->name -- Returns name of attribute
DomElement->set_attribute -- Adds new attribute
DomElement->tagname -- Returns name of element
DomNode->add_namespace -- Adds a namespace Description
declaration to a node.
DomNode->append_child -- Adds new child at the end of
the children bool DomAttribute->name ( void)
DomNode->append_sibling -- Adds new sibling to a node
DomNode->attributes -- Returns list of attributes This function returns the name of the attribute.
DomNode->child_nodes -- Returns children of node See also domattribute_value().
DomNode->clone_node -- Clones a node
DomNode->dump_node -- Dumps a single node
DomNode->first_child -- Returns first child of node DomAttribute->specified
DomNode->get_content -- Gets content of node
DomNode->has_attributess -- Checks if node has
attributes (no version information, might be only in CVS)
DomNode->has_child_nodes -- Checks if node has DomAttribute->specified -- Checks if attribute is
children specified
DomNode->insert_before -- Inserts new node as child
DomNode->is_blank_node -- Checks if node is blank
Description
DomNode->last_child -- Returns last child of node
DomNode->next_sibling -- Returns the next sibling of
node bool DomAttribute->specified ( void)
DomNode->node_name -- Returns name of node
DomNode->node_type -- Returns type of node
DomNode->node_value -- Returns value of a node Check DOM standard for a detailed explanation.
DomNode->owner_document -- Returns the document
this node belongs to DomAttribute->value
DomNode->parent_node -- Returns the parent of the
node
DomNode->prefix -- Returns name space prefix of node (no version information, might be only in CVS)
DomNode->previous_sibling -- Returns the previous DomAttribute->value -- Returns value of attribute
sibling of node
DomNode->remove_child -- Removes child from list of
children Description
DomNode->replace_child -- Replaces a child
DomNode->replace_node -- Replaces node
bool DomAttribute->value ( void)
DomNode->set_content -- Sets content of node
DomNode->set_name -- Sets name of node
This function returns the value of the attribute.
See also domattribute_name(). Description

DomDocument->add_root [deprecated] string DomDocument->create_cdata_section ( string


content)

(no version information, might be only in CVS)


DomDocument->add_root [deprecated] -- Adds a root This function returns a new instance of class DomCData.
node The content of the cdata is the value of the passed
parameter. This node will not show up in the document
unless it is inserted with e.g.
Description domnode_append_child().
The return value is FALSE if an error occured.
See also domnode_append_child(),
resource DomDocument->add_root ( string name) domdocument_create_element(),
domdocument_create_text(),
domdocument_create_attribute(),
Aviso domdocument_create_processing_instruction(),
Este módulo es EXPERIMENTAL. Esto significa que el domdocument_create_entity_reference(), and
comportamineto de estas funciones, nombre de funciones domnode_insert_before().
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. DomDocument->create_comment

Adds a root element node to a dom document and


returns the new node. The element name is given in the (no version information, might be only in CVS)
passed parameter. DomDocument->create_comment -- Create new
Ejemplo 1. Creating a simple HTML document comment node
header
Description
<?php
$doc = domxml_new_doc("1.0"); object DomDocument->create_comment ( string
$root = $doc- content)
>add_root("HTML");
$head = $root-
>new_child("HEAD", ""); This function returns a new instance of class
$head->new_child("TITLE", "Hier DomComment. The content of the comment is the value
der Titel"); of the passed parameter. This node will not show up in
echo htmlentities($doc- the document unless it is inserted with e.g.
>dump_mem()); domnode_append_child().
?> The return value is FALSE if an error occured.
See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
DomDocument->create_attribute
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
(no version information, might be only in CVS) domdocument_create_entity_reference() and
DomDocument->create_attribute -- Create new attribute domnode_insert_before().

Description DomDocument->create_element_ns

object DomDocument->create_attribute ( string (no version information, might be only in CVS)


name, string value) DomDocument->create_element_ns -- Create new
element node with an associated namespace
This function returns a new instance of class
DomAttribute. The name of the attribute is the value of Description
the first parameter. The value of the attribute is the
value of the second parameter. This node will not show
up in the document unless it is inserted with e.g. object DomDocument->create_element_ns ( string
domnode_append_child(). uri, string name [, string prefix])
The return value is FALSE if an error occured.
See also domnode_append_child(), This function returns a new instance of class
domdocument_create_element(), DomElement. The tag name of the element is the value
domdocument_create_text(), of the passed parameter name. The URI of the
domdocument_create_cdata_section(), namespace is the value of the passed parameter uri. If
domdocument_create_processing_instruction(), there is already a namespace declaration with the same
domdocument_create_entity_reference(), and uri in the root-node of the document, the prefix of this is
domnode_insert_before(). taken, otherwise it will take the one provided in the
optional parameter prefix or generate a random one. This
node will not show up in the document unless it is
DomDocument->create_cdata_section
inserted with e.g. domnode_append_child().
The return value is FALSE if an error occured.
(no version information, might be only in CVS) See also domdocument_create_element_ns(),
DomDocument->create_cdata_section -- Create new domnode_add_namespace(),
cdata node domnode_set_namespace(),
domnode_append_child(),
domdocument_create_text(),
domdocument_create_comment(), parameter. This node will not show up in the document
domdocument_create_attribute(), unless it is inserted with e.g.
domdocument_create_processing_instruction(), domnode_append_child().
domdocument_create_entity_reference(), and The return value is FALSE if an error occured.
domnode_insert_before(). See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
DomDocument->create_element domdocument_create_cdata_section(),
domdocument_create_attribute(),
domdocument_create_entity_reference(), and
(no version information, might be only in CVS)
domnode_insert_before().
DomDocument->create_element -- Create new element
node
DomDocument->create_text_node
Description
(no version information, might be only in CVS)
DomDocument->create_text_node -- Create new text
object DomDocument->create_element ( string
node
name)

This function returns a new instance of class Description


DomElement. The tag name of the element is the value
of the passed parameter. This node will not show up in
object DomDocument->create_text_node ( string
the document unless it is inserted with e.g.
content)
domnode_append_child().
The return value is FALSE if an error occured.
See also domdocument_create_element_ns(), This function returns a new instance of class DomText.
domnode_append_child(), The content of the text is the value of the passed
domdocument_create_text(), parameter. This node will not show up in the document
domdocument_create_comment(), unless it is inserted with e.g.
domdocument_create_attribute(), domnode_append_child().
domdocument_create_processing_instruction(), The return value is FALSE if an error occured.
domdocument_create_entity_reference(), and See also domnode_append_child(),
domnode_insert_before(). domdocument_create_element(),
domdocument_create_comment(),
domdocument_create_text(),
DomDocument->create_entity_reference domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference(), and
(no version information, might be only in CVS)
domnode_insert_before().
DomDocument->create_entity_reference --

DomDocument->doctype
Description

(no version information, might be only in CVS)


object DomDocument->create_entity_reference
DomDocument->doctype -- Returns the document type
( string content)

This function returns a new instance of class Description


DomEntityReference. The content of the entity
reference is the value of the passed parameter. This
object DomDocument->doctype ( void)
node will not show up in the document unless it is
inserted with e.g. domnode_append_child().
The return value is FALSE if an error occured. This function returns an object of class
See also domnode_append_child(), DomDocumentType. In versions of PHP before 4.3 this
domdocument_create_element(), has been the class Dtd, but the DOM Standard does not
domdocument_create_text(), know such a class.
domdocument_create_cdata_section(), See also the methods of class DomDocumentType.
domdocument_create_processing_instruction(),
domdocument_create_attribute(), and
domnode_insert_before(). DomDocument->document_element

DomDocument->create_processing_instruction (no version information, might be only in CVS)


DomDocument->document_element -- Returns root
element node
(no version information, might be only in CVS)
DomDocument->create_processing_instruction -- Creates
new PI node Description

Description object DomDocument->document_element ( void)

This function returns the root element node of a


string DomDocument-
document.
>create_processing_instruction ( string content)
The following example returns just the element with
name CHAPTER and prints it. The other node -- the
This function returns a new instance of class DomCData. comment -- is not returned.
The content of the pi is the value of the passed Ejemplo 1. Retrieving root element
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
<?php comportamineto de estas funciones, nombre de funciones
include("example.inc"); y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
if(!$dom = utilizar este módulo es tu responsabiliad.
domxml_open_mem($xmlstr)) { Creates an XML document from the dom representation.
echo "Error while parsing the This function usually is called after building a new dom
document\n"; document from scratch as in the example below. The
exit; format specifies whether the output should be neatly
} formatted, or not.
Ejemplo 1. Creating a simple HTML document
$root = $dom- header
>document_element();
print_r($root);
?> <?php
$doc = domxml_new_doc("1.0");
$root = $doc-
DomDocument->dump_file >create_element("HTML");
$root = $doc->append_child($root);
$head = $doc-
(no version information, might be only in CVS) >create_element("HEAD");
DomDocument->dump_file -- Dumps the internal XML $head = $root-
tree back into a file >append_child($head);
$title = $doc-
Description >create_element("TITLE");
$title = $head->append_child($title);
$text = $doc-
string DomDocument->dump_file ( string filename [, >create_text_node("This is the
bool compressionmode [, bool format]]) title");
$text = $title->append_child($text);
echo "<PRE>";
Creates an XML document from the dom representation.
echo htmlentities($doc-
This function usually is called after building a new dom
>dump_mem(true));
document from scratch as in the example below. The
echo "</PRE>";
format specifies whether the output should be neatly
?>
formatted, or not. The first parameter specifies the name
of the filename and the second parameter, whether it
should be compressed or not.
Ejemplo 1. Creating a simple HTML document Nota: The first parameter was
header added in PHP 4.3.0.

See also domdocument_dump_file(),


<?php domdocument_html_dump_mem().
$doc = domxml_new_doc("1.0");
$root = $doc-
>create_element("HTML"); DomDocument->get_element_by_id
$root = $doc->append_child($root);
$head = $doc-
>create_element("HEAD"); (no version information, might be only in CVS)
$head = $root- DomDocument->get_element_by_id -- Searches for an
>append_child($head); element with a certain id
$title = $doc-
>create_element("TITLE"); Description
$title = $head->append_child($title);
$text = $doc-
>create_text_node("This is the object DomDocument->get_element_by_id ( string id)
title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", This function is similar to
false, true); domdocument_get_elements_by_tagname() but
?> searches for an element with a given id. According to the
DOM standard this requires a DTD which defines the
See also domdocument_dump_mem() attribute ID to be of type ID, though the current
domdocument_html_dump_mem(). implementation simply does an xpath search for "//*[@ID
= '%s']". This does not comply to the DOM standard
which requires to return null if it is not known which
DomDocument->dump_mem attribute is of type id. This behaviour is likely to be fixed,
so do not rely on the current behaviour.
(no version information, might be only in CVS) See also domdocument_get_elements_by_tagname()
DomDocument->dump_mem -- Dumps the internal XML
tree back into a string DomDocument->get_elements_by_tagname

Description (no version information, might be only in CVS)


DomDocument->get_elements_by_tagname --
string DomDocument->dump_mem ( [bool format [,
string encoding]])
Description DomDocumentType->entities

array DomDocument->get_elements_by_tagname (no version information, might be only in CVS)


( string name) DomDocumentType->entities -- Returns list of entities

See also domdocument_add_root() Description

DomDocument->html_dump_mem array DomDocumentType->entities ( void)

(no version information, might be only in CVS) Aviso


DomDocument->html_dump_mem -- Dumps the internal
XML tree back into a string as HTML Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

Description
DomDocumentType->internal_subset
string DomDocument->html_dump_mem ( void)
(no version information, might be only in CVS)
Creates an HTML document from the dom DomDocumentType->internal_subset -- Returns internal
representation. This function usually is called after subset
building a new dom document from scratch as in the
example below.
Description
Ejemplo 1. Creating a simple HTML document
header
bool DomDocumentType->internal_subset ( void)

<?php
$doc = domxml_new_doc("1.0"); Aviso
$root = $doc-
Esta función no está documentada actualmente, solamente
>create_element("HTML");
se encuentra disponible la lista de parametros.
$root = $doc->append_child($root);
$head = $doc-
>create_element("HEAD");
$head = $root- DomDocumentType->name
>append_child($head);
$title = $doc- (no version information, might be only in CVS)
>create_element("TITLE"); DomDocumentType->name -- Returns name of
$title = $head->append_child($title); document type
$text = $doc-
>create_text_node("This is the
title"); Description
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc- string DomDocumentType->name ( void)
>html_dump_mem());
echo "</PRE>"; This function returns the name of the document type.
?>
See also domdocument_dump_file(),
DomDocumentType->notations
domdocument_html_dump_mem().

(no version information, might be only in CVS)


DomDocument->xinclude
DomDocumentType->notations -- Returns list of
notations
(no version information, might be only in CVS)
DomDocument->xinclude -- Substitutes XIncludes in a
Description
DomDocument Object.

array DomDocumentType->notations ( void)


Description

int DomDocument->xinclude ( void) Aviso


Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones DomDocumentType->public_id
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. (no version information, might be only in CVS)
DomDocumentType->public_id -- Returns public id of
Aviso document type
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. Description
string DomDocumentType->public_id ( void) (no version information, might be only in CVS)
DomElement->get_attribute -- Returns value of attribute
This function returns the public id of the document type.
The following example echos nothing. Description
Ejemplo 1. Retrieving the public id

object DomElement->get_attribute ( string name)


<?php
include("example.inc"); Returns the attribute with name name of the current
node.
if(!$dom = (PHP >= 4.3 only) If no attribute with given name is
domxml_open_mem($xmlstr)) { found, an empty string is returned.
echo "Error while parsing the See also domelement_set_attribute()
document\n";
exit;
} DomElement->get_elements_by_tagname

$doctype = $dom->doctype();
echo $doctype->public_id(); (no version information, might be only in CVS)
?> DomElement->get_elements_by_tagname -- Gets
elements by tagname

DomDocumentType->system_id Description

(no version information, might be only in CVS) bool DomElement->get_elements_by_tagname


DomDocumentType->system_id -- Returns system id of ( string name)
document type

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
string DomDocumentType->system_id ( void)

Returns the system id of the document type. DomElement->has_attribute


The following example echos
'/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'.
(no version information, might be only in CVS)
Ejemplo 1. Retrieving the system id
DomElement->has_attribute -- Checks to see if attribute
exists
<?php
include("example.inc"); Description

if(!$dom =
domxml_open_mem($xmlstr)) { bool DomElement->has_attribute ( string name)
echo "Error while parsing the
document\n";
exit; Aviso
} Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
$doctype = $dom->doctype();
echo $doctype->system_id();
?> DomElement->remove_attribute

DomElement->get_attribute_node (no version information, might be only in CVS)


DomElement->remove_attribute -- Removes attribute

(no version information, might be only in CVS)


DomElement->get_attribute_node -- Returns value of Description
attribute
bool DomElement->remove_attribute ( string name)
Description

Aviso
object DomElement->get_attribute_node ( object
Esta función no está documentada actualmente, solamente
attr)
se encuentra disponible la lista de parametros.

Aviso
DomElement->set_attribute
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(no version information, might be only in CVS)
DomElement->set_attribute -- Adds new attribute
DomElement->get_attribute
Description
bool DomElement->set_attribute ( string name, string makes it quite easy to duplicate large parts of a xml
value) document. The return value is the appended child. If you
plan to do further modifications on the appended child
you must use the returned node.
Sets an attribute with name name ot the given value. If
(PHP >= 4.3) The new child newnode is first unlinked
the attribute does not exist, it will be created.
from its existing context, if it already existed in a
Ejemplo 1. Setting an attribute
document. Therefore the node is moved and not copies
anymore. This is the behaviour according to the W3C
specifications. If you want to duplicate large parts of a
<?php xml document, use DomNode->clone_node() before
$doc = appending.
domxml_new_doc("1.0"); The following example will add a new element node to a
$node = $doc- fresh document and sets the attribute "align" to "left".
>create_element("para"); Ejemplo 1. Adding a child
$newnode = $doc-
>append_child($node);
$newnode-
<?php
>set_attribute("align", "left");
$doc =
?>
domxml_new_doc("1.0");
See also domelement_get_attribute() $node = $doc-
>create_element("para");
$newnode = $doc-
DomElement->tagname >append_child($node);
$newnode-
(no version information, might be only in CVS) >set_attribute("align", "left");
DomElement->tagname -- Returns name of element ?>
The above example could also be written as the
following:
Description Ejemplo 2. Adding a child

string DomElement->tagname ( void)


<?php
$doc =
Aviso domxml_new_doc("1.0");
$node = $doc-
Esta función no está documentada actualmente, solamente
>create_element("para");
se encuentra disponible la lista de parametros.
$node->set_attribute("align",
"left");
$newnode = $doc-
DomNode->add_namespace >append_child($node);
?>
(no version information, might be only in CVS) A more comples example is the one below. It first
DomNode->add_namespace -- Adds a namespace searches for a certain element, duplicates it including its
declaration to a node. children and adds it as a sibling. Finally a new attribute is
added to one of the children of the new sibling and the
whole document is dumped.
Description Ejemplo 3. Adding a child

bool DomNode->add_namespace ( string uri, string


prefix) <?php
include("example.inc");
See also domdocument_create_element_ns(), if(!$dom = domxml_open_mem($xmlstr)) {
domnode_set_namespace() echo "Error while parsing the document\n";
exit;
DomNode->append_child }

$elements = $dom-
(no version information, might be only in CVS) >get_elements_by_tagname("informaltable");
DomNode->append_child -- Adds new child at the end of print_r($elements);
the children $element = $elements[0];

$parent = $element->parent_node();
Description $newnode = $parent-
>append_child($element);
$children = $newnode->children();
object DomNode->append_child ( object newnode)
$attr = $children[1]->set_attribute("align",
"left");
This functions appends a child to an existing list of
children or creates a new list of children. The child can be echo "<PRE>";
created with e.g. domdocument_create_element(), $xmlfile = $dom->dump_mem();
domdocument_create_text() etc. or simply by using echo htmlentities($xmlfile);
any other node. echo "</PRE>";
(PHP < 4.3) Before a new child is appended it is first ?>
duplicated. Therefore the new child is a completely new
The above example could also be done with
copy which can be modified without changing the node
domnode_insert_before() instead of
which was passed to this function. If the node passed has
domnode_append_child().
children itself, they will be duplicated as well, which
See also domnode_insert_before(), Aviso
domnode_clone_node().
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
DomNode->append_sibling

(no version information, might be only in CVS) DomNode->dump_node


DomNode->append_sibling -- Adds new sibling to a node
(no version information, might be only in CVS)
Description DomNode->dump_node -- Dumps a single node

object DomNode->append_sibling ( object newnode) Description

This functions appends a sibling to an existing node. The string DomNode->dump_node ( void)
child can be created with e.g.
domdocument_create_element(),
domdocument_create_text() etc. or simply by using Aviso
any other node. Esta función no está documentada actualmente, solamente
Before a new sibling is added it is first duplicated. se encuentra disponible la lista de parametros.
Therefore the new child is a completely new copy which
can be modified without changing the node which was See also domdocument_dump_mem().
passed to this function. If the node passed has children
itself, they will be duplicated as well, which makes it DomNode->first_child
quite easy to duplicate large parts of a xml document.
The return value is the added sibling. If you plan to do
further modifications on the added sibling you must use (no version information, might be only in CVS)
the returned node. DomNode->first_child -- Returns first child of node
This function has been added to provide the behaviour of
domnode_append_child() as it works till PHP 4.2.
See also domnode_append_before(). Description

DomNode->attributes bool DomNode->first_child ( void)

Returns the first child of the node.


(no version information, might be only in CVS)
(PHP >= 4.3 only) If no first child is found, NULL is
DomNode->attributes -- Returns list of attributes
returned.
See also domnode_last_child(),
Description domnode_next_sibling(),
domnode_previous_sibling().

array DomNode->attributes ( void)


DomNode->get_content
This function only returns an array of attributes if the
node is of type XML_ELEMENT_NODE. (no version information, might be only in CVS)
(PHP >= 4.3 only) If no attributes are found, NULL is DomNode->get_content -- Gets content of node
returned.

Description
DomNode->child_nodes

string DomNode->get_content ( void)


(no version information, might be only in CVS)
DomNode->child_nodes -- Returns children of node
Aviso

Description Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros.

array DomNode->child_nodes ( void)


DomNode->has_attributess
Returns all children of the node.
See also domnode_next_sibling(), (no version information, might be only in CVS)
domnode_previous_sibling(). DomNode->has_attributess -- Checks if node has
attributes
DomNode->clone_node
Description
(no version information, might be only in CVS)
DomNode->clone_node -- Clones a node bool DomNode->has_attributes ( void)

Description This function checks if the node has attributes.


See also domnode_has_child_nodes().
object DomNode->clone_node ( void)
DomNode->has_child_nodes
(no version information, might be only in CVS) Aviso
DomNode->has_child_nodes -- Checks if node has
children Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

Description
DomNode->last_child
bool DomNode->has_child_nodes ( void)
(no version information, might be only in CVS)
This function checks if the node has children. DomNode->last_child -- Returns last child of node
See also domnode_child_nodes().
Description
DomNode->insert_before
object DomNode->last_child ( void)
(no version information, might be only in CVS)
DomNode->insert_before -- Inserts new node as child Returns the last child of the node.
(PHP >= 4.3 only) If no last child is found, NULL is
Description returned.
See also domnode_first_child(),
domnode_next_sibling(),
object DomNode->insert_before ( object newnode, domnode_previous_sibling().
object refnode)
DomNode->next_sibling
This function inserts the new node newnode right before
the node refnode. The return value is the inserted node.
If you plan to do further modifications on the appended (no version information, might be only in CVS)
child you must use the returned node. DomNode->next_sibling -- Returns the next sibling of
(PHP >= 4.3 only) If newnode already is part of a node
document, it will be first unlinked from its existing
context. If refnode is NULL, then newnode will be inserted
Description
at the end of the list of children.
domnode_insert_before() is very similar to
domnode_append_child() as the following example object DomNode->next_sibling ( void)
shows which does the same as the example at
domnode_append_child().
Ejemplo 1. Adding a child This function returns the next sibling of the current node.
If there is no next sibling it returns FALSE (< 4.3) or null
(>= 4.3). You can use this function to iterate over all
include("example.inc"); children of a node as shown in the example.
Ejemplo 1. Iterate over children
if(!$dom = domxml_open_mem($xmlstr)) {
echo "Error while parsing the document\n";
exit; <?php
} include("example.inc");

$elements = $dom- if(!$dom = domxml_open_mem($xmlstr))


>get_elements_by_tagname("informaltable"); {
print_r($elements); echo "Error while parsing the
$element = $elements[0]; document\n";
exit;
$newnode = $element- }
>insert_before($element, $element);
$children = $newnode->children(); $elements = $dom-
$attr = $children[1]->set_attribute("align", >get_elements_by_tagname("tbody");
"left"); $element = $elements[0];
$child = $element->first_child();
echo "<PRE>";
$xmlfile = $dom->dump_mem(); while($child) {
echo htmlentities($xmlfile); print_r($child);
echo "</PRE>"; $child = $child->next_sibling();
}
See also domnode_append_child(). ?>
See also domnode_previous_sibling().
DomNode->is_blank_node

DomNode->node_name
(no version information, might be only in CVS)
DomNode->is_blank_node -- Checks if node is blank
(no version information, might be only in CVS)
DomNode->node_name -- Returns name of node
Description

Description
bool DomNode->is_blank_node ( void)

string DomNode->node_name ( void)


Returns name of the node. The name has different Type Meaning
meanings for the different types of nodes as illustrated in
the following table. uction without target
Tabla 1. Meaning of value DomText content of text
Type Meaning
DomAttribute value of attribute
DomNode->owner_document
DomAttribute
DomCDataSection #cdata-section (no version information, might be only in CVS)
DomComment #comment DomNode->owner_document -- Returns the document
this node belongs to
DomDocument #document
document type
DomDocumentType Description
name
DomElement tag name
object DomNode->owner_document ( void)
DomEntity name of entity
DomEntityReferenc name of entity This function returns the document the current node
e reference belongs to.
DomNotation notation name The following example will create two identical lists of
children.
DomProcessingInstr Ejemplo 1. Finding the document of a node
target
uction
DomText #text
<?php
$doc =
DomNode->node_type domxml_new_doc("1.0");
$node = $doc-
>create_element("para");
(no version information, might be only in CVS) $node = $doc-
DomNode->node_type -- Returns type of node >append_child($node);
$children = $doc->children();
print_r($children);
Description
$doc2 = $node-
int DomNode->node_type ( void) >owner_document();
$children = $doc2-
>children();
Returns the type of the node. All possible types are listed print_r($children);
in the table in the introduction. ?>
See also domnode_insert_before().
DomNode->node_value
DomNode->parent_node
(no version information, might be only in CVS)
DomNode->node_value -- Returns value of a node
(no version information, might be only in CVS)
DomNode->parent_node -- Returns the parent of the
Description node

string DomNode->node_value ( void) Description

Returns value of the node. The value has different object DomNode->parent_node ( void)
meanings for the different types of nodes as illustrated in
the following table.
Tabla 1. Meaning of value This function returns the parent node.
(PHP >= 4.3 only) If no parent is found, NULL is returned.
Type Meaning The following example will show two identical lists of
DomAttribute value of attribute children.
Ejemplo 1. Finding the document of a node
DomAttribute
DomCDataSection content
<?php
DomComment content of comment $doc =
DomDocument null domxml_new_doc("1.0");
$node = $doc-
DomDocumentType null >create_element("para");
DomElement null $node = $doc-
>append_child($node);
DomEntity null $children = $doc->children();
DomEntityReferenc print_r($children);
null
e
$doc2 = $node-
DomNotation null >parent_node();
DomProcessingInstr entire content $children = $doc2-
>children();
print_r($children); echo "</PRE>";
?> ?>
See also domnode_append_child().

DomNode->prefix
DomNode->replace_child

(no version information, might be only in CVS)


DomNode->prefix -- Returns name space prefix of node (no version information, might be only in CVS)
DomNode->replace_child -- Replaces a child

Description
Description

string DomNode->prefix ( void)


object DomNode->replace_child ( object oldnode,
object newnode)
Returns the name space prefix of the node.

(PHP 4.2) This function replaces the child oldnode with


DomNode->previous_sibling the passed new node. If the new node is already a child it
will not be added a second time. If the old node cannot
be found the function returns FALSE. If the replacement
(no version information, might be only in CVS)
succeds the old node is returned.
DomNode->previous_sibling -- Returns the previous
(PHP 4.3) This function replaces the child oldnode with
sibling of node
the passed newnode, even if the new node already is a
child of the DomNode. If newnode was already inserted
Description in the document it is first unlinked from its existing
context. If the old node cannot be found the function
returns FALSE. If the replacement succeds the old node
object DomNode->previous_sibling ( void) is returned. (This behaviour is according to the W3C
specs).
This function returns the previous sibling of the current See also domnode_append_child()
node. If there is no previous sibling it returns FALSE (<
4.3) or NULL (>= 4.3). You can use this function to DomNode->replace_node
iterate over all children of a node as shown in the
example.
See also domnode_next_sibling(). (no version information, might be only in CVS)
DomNode->replace_node -- Replaces node
DomNode->remove_child
Description
(no version information, might be only in CVS)
DomNode->remove_child -- Removes child from list of object DomNode->replace_node ( object newnode)
children
(PHP 4.2) This function replaces an existing node with the
Description passed new node. Before the replacement newnode is
copied if it has a parent to make sure a node which is
already in the document will not be inserted a second
object DomNode->remove_child ( object oldchild) time. This behaviour enforces doing all modifications on
the node before the replacement or to refetch the
This functions removes a child from a list of children. If inserted node afterwards with functions like
child cannot be removed or is not a child the function will domnode_first_child(), domnode_child_nodes() etc..
return FALSE. If the child could be removed the (PHP 4.3) This function replaces an existing node with the
functions returns the old child. passed new node. It is not copied anymore. If newnode
Ejemplo 1. Removing a child was already inserted in the document it is first unlinked
from its existing context. If the replacement succeds the
old node is returned.
See also domnode_append_child()
<?php
include("example.inc");
DomNode->set_content
if(!$dom = domxml_open_mem($xmlstr))
{
echo "Error while parsing the (no version information, might be only in CVS)
document\n"; DomNode->set_content -- Sets content of node
exit;
}
Description
$elements = $dom-
>get_elements_by_tagname("tbody"); bool DomNode->set_content ( void)
$element = $elements[0];
$children = $element->child_nodes();
$child = $element- Aviso
>remove_child($children[0]);
Esta función no está documentada actualmente, solamente
echo "<PRE>"; se encuentra disponible la lista de parametros.
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
DomNode->set_name Description

(no version information, might be only in CVS) string DomProcessingInstruction->target ( void)


DomNode->set_name -- Sets name of node

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
bool DomNode->set_name ( void)

Sets name of node. DomXsltStylesheet->process


See also domnode_node_name().
(no version information, might be only in CVS)
DomNode->set_namespace DomXsltStylesheet->process -- Applies the XSLT-
Transformation on a DomDocument Object.

(no version information, might be only in CVS)


DomNode->set_namespace -- Sets namespace of a Description
node.
object DomXsltStylesheet->process ( object
Description DomDocument [, array xslt_parameters [, bool
param_is_xpath]])

void DomNode->set_namespace ( string uri [, string


prefix]) Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Sets the namespace of a node to uri. If there is already a comportamineto de estas funciones, nombre de funciones
namespace declaration with the same uri in one of the y en definitiva TODO lo documentado aqui, puede cambiar
parent nodes of the node, the prefix of this is taken, en una futura version de PHP SIN AVISO. Quedas avisado, y
otherwise it will take the one provided in the optional utilizar este módulo es tu responsabiliad.
parameter prefix or generate a random one.
See also domdocument_create_element_ns(), Aviso
domnode_add_namespace() Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
DomNode->unlink_node See also domxml_xslt_stylesheet(),
domxml_xslt_stylesheet_file(),
domxml_xslt_stylesheet_doc()
(no version information, might be only in CVS)
DomNode->unlink_node -- Deletes node
DomXsltStylesheet->result_dump_file

Description
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_file -- Dumps the
object DomNode->unlink_node ( void) result from a XSLT-Transformation into a file

Aviso Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. string DomXsltStylesheet->result_dump_file ( object
DomDocument, string filename)

DomProcessingInstruction->data
Aviso

(no version information, might be only in CVS) Este módulo es EXPERIMENTAL. Esto significa que el
DomProcessingInstruction->data -- Returns data of pi comportamineto de estas funciones, nombre de funciones
node 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.
Description This function is only available since PHP 4.3
Since DomXsltStylesheet->process() always returns a
string DomProcessingInstruction->data ( void) well-formed XML DomDocument, no matter what output
method was declared in <xsl:output> and similar
attributes/elements, it's of not much use, if you want to
Aviso output HTML 4 or text data. This function on the contrary
honors <xsl:output method="html|text"> and other
Esta función no está documentada actualmente, solamente output control directives. See the example for instruction
se encuentra disponible la lista de parametros. of how to use it.
Ejemplo 1. Saving the result of a XSLT
transformation in a file
DomProcessingInstruction->target

(no version information, might be only in CVS) <?php


DomProcessingInstruction->target -- Returns target of pi $filename = "stylesheet.xsl";
node
$xmldoc = Este módulo es EXPERIMENTAL. Esto significa que el
domxml_open_file("data.xml"); comportamineto de estas funciones, nombre de funciones
$xsldoc = y en definitiva TODO lo documentado aqui, puede cambiar
domxml_xslt_stylesheet_file($filenam en una futura version de PHP SIN AVISO. Quedas avisado, y
e); utilizar este módulo es tu responsabiliad.
$result = $xsldoc- Creates a new dom document from scratch and returns
>process($xmldoc); it.
print $xsldoc- See also domdocument_add_root()
>result_dump_file($result,"filename")
;
?> domxml_open_file
See also domxml_xslt_result_dump_mem(),
domxml_xslt_process() (PHP 4 >= 4.2.1)
domxml_open_file -- Creates a DOM object from XML file
DomXsltStylesheet->result_dump_mem
Description
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_mem -- Dumps the object domxml_open_file ( string filename)
result from a XSLT-Transformation back into a string

The function parses the XML document in the file named


Description filename and returns an object of class "Dom document",
having the properties as listed above. The file is
accessed read-only.
string DomXsltStylesheet->result_dump_mem Ejemplo 1. Opening a xml document from a file
( object DomDocument)

Aviso <?php

Este módulo es EXPERIMENTAL. Esto significa que el if(!$dom =


comportamineto de estas funciones, nombre de funciones domxml_open_file("example.xml"))
y en definitiva TODO lo documentado aqui, puede cambiar {
en una futura version de PHP SIN AVISO. Quedas avisado, y echo "Error while parsing the
utilizar este módulo es tu responsabiliad. document\n";
This function is only available since PHP 4.3 exit;
Since DomXsltStylesheet->process() always returns a }
well-formed XML DomDocument, no matter what output
method was declared in <xsl:output> and similar $root = $dom-
attributes/elements, it's of not much use, if you want to >document_element();
output HTML 4 or text data. This function on the contrary ?>
honors <xsl:output method="html|text"> and other See also domxml_open_mem(), domxml_new_doc().
output control directives. See the example for instruction
of how to use it.
Ejemplo 1. Outputting the result of a XSLT domxml_open_mem
transformation
(PHP 4 >= 4.2.1)
domxml_open_mem -- Creates a DOM object of an XML
<?php
document
$filename = "stylesheet.xsl";
$xmldoc =
domxml_open_file("data.xml"); Description
$xsldoc =
domxml_xslt_stylesheet_file($filenam
e); object domxml_open_mem ( string str)
$result = $xsldoc-
>process($xmldoc); The function parses the XML document in str and returns
print $xsldoc- an object of class "Dom document", having the
>result_dump_mem($result); properties as listed above. This function,
?> domxml_open_file() or domxml_new_doc() must be
See also domxml_xslt_result_dump_file(), called before any other function calls.
domxml_xslt_process() Ejemplo 1. Opening a xml document in a string

domxml_new_doc <?php
include("example.inc");
(PHP 4 >= 4.2.1)
domxml_new_doc -- Creates new empty XML document if(!$dom =
domxml_open_mem($xmlstr)) {
echo "Error while parsing the
Description document\n";
exit;
}
object domxml_new_doc ( string version)
$root = $dom-
>document_element();
Aviso ?>
See also domxml_open_file(), domxml_new_doc(). (PHP 4 >= 4.2.0)
domxml_xslt_stylesheet_file -- Creates a
DomXsltStylesheet Object from a xsl document in a file.
domxml_version

Description
(PHP 4 >= 4.1.0)
domxml_version -- Get XML library version
object domxml_xslt_stylesheet_file ( string xsl file)

Description
Aviso
string domxml_version ( void) 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
This function returns the version of the XML library
en una futura version de PHP SIN AVISO. Quedas avisado, y
version currently used.
utilizar este módulo es tu responsabiliad.

domxml_xmltree Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.2.1)
domxml_xmltree -- Creates a tree of PHP objects from an See also domxsltstylesheet->process(),
XML document domxml_xslt_stylesheet(),
domxml_xslt_stylesheet_doc()

Description
domxml_xslt_stylesheet

object domxml_xmltree ( string str)


(PHP 4 >= 4.2.0)
domxml_xslt_stylesheet -- Creates a DomXsltStylesheet
Aviso Object from a xml document in a string.
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Description
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. object domxml_xslt_stylesheet ( string xsl document)
The function parses the XML document in str and returns
a tree PHP objects as the parsed document. This function Aviso
is isolated from the other functions, which means you
cannot access the tree with any of the other functions. Este módulo es EXPERIMENTAL. Esto significa que el
Modifying it, for example by adding nodes, makes no comportamineto de estas funciones, nombre de funciones
sense since there is currently no way to dump it as an y en definitiva TODO lo documentado aqui, puede cambiar
XML file. However this function may be valuable if you en una futura version de PHP SIN AVISO. Quedas avisado, y
want to read a file and investigate the content. utilizar este módulo es tu responsabiliad.

Aviso
domxml_xslt_stylesheet_doc Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.2.0) See also domxsltstylesheet->process(),
domxml_xslt_stylesheet_doc -- Creates a domxml_xslt_stylesheet_file(),
DomXsltStylesheet Object from a DomDocument Object. domxml_xslt_stylesheet_doc()

Description xpath_eval_expression

object domxml_xslt_stylesheet_doc ( object (PHP 4 >= 4.0.4)


DocDocument Object) xpath_eval_expression -- Evaluates the XPath Location
Path in the given string

Aviso
Description
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 array xpath_eval_expression ( object xpath_context)
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Esta función no está documentada actualmente, solamente comportamineto de estas funciones, nombre de funciones
se encuentra disponible la lista de parametros. y en definitiva TODO lo documentado aqui, puede cambiar
See also domxsltstylesheet->process(), en una futura version de PHP SIN AVISO. Quedas avisado, y
domxml_xslt_stylesheet(), utilizar este módulo es tu responsabiliad.
domxml_xslt_stylesheet_file() See also xpath_eval()

domxml_xslt_stylesheet_file xpath_eval
(PHP 4 >= 4.0.4) XXVI. .NET functions
xpath_eval -- Evaluates the XPath Location Path in the
given string
Introducción

Description
Aviso
array xpath_eval ( object xpath context, string xpath Este módulo es EXPERIMENTAL. Esto significa que el
expression [, object contextnode]) 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
Aviso utilizar este módulo es tu responsabiliad.
Este módulo es EXPERIMENTAL. Esto significa que el Tabla de contenidos
comportamineto de estas funciones, nombre de funciones dotnet_load -- Loads a DOTNET module
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. dotnet_load

The optional contextnode can be specified for doing


relative XPath queries. (no version information, might be only in CVS)
See also xpath_new_context() dotnet_load -- Loads a DOTNET module

xpath_new_context Description

(PHP 4 >= 4.0.4) int dotnet_load ( string assembly_name [, string


xpath_new_context -- Creates new xpath context datatype_name [, int codepage]])

Description Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
object xpath_new_context ( object dom document) 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
Aviso utilizar este módulo es tu responsabiliad.
Este módulo es EXPERIMENTAL. Esto significa que el Aviso
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar Esta función no está documentada actualmente, solamente
en una futura version de PHP SIN AVISO. Quedas avisado, y se encuentra disponible la lista de parametros.
utilizar este módulo es tu responsabiliad.
See also xpath_eval()
XXVII. Error Handling and Logging Functions

xptr_eval
These are functions dealing with error handling and
logging. They allow you to define your own error handling
(PHP 4 >= 4.0.4) rules, as well as modify the way the errors can be logged.
xptr_eval -- Evaluate the XPtr Location Path in the given This allows you to change and enhance error reporting to
string suit your needs.
With the logging functions, you can send messages
directly to other machines, to an email (or email to pager
Description gateway!), to system logs, etc., so you can selectively
log and monitor the most important parts of your
applications and websites.
int xptr_eval ( [object xpath_context, string eval_str]) The error reporting functions allow you to customize
what level and kind of error feedback is given, ranging
from simple notices to customized functions returned
Aviso
during errors.
Esta función no está documentada actualmente, solamente Tabla de contenidos
se encuentra disponible la lista de parametros. debug_backtrace -- Generates a backtrace
error_log -- envía un mensaje de error a algún lugar
error_reporting -- establece que errores PHP son
xptr_new_context registrados
restore_error_handler -- Restores the previous error
handler function
(PHP 4 >= 4.0.4) set_error_handler -- Sets a user-defined error handler
xptr_new_context -- Create new XPath Context function.
trigger_error -- Generates a user-level
error/warning/notice message
Description
user_error -- Generates a user-level error/warning/notice
message
string xptr_new_context ( [object doc_handle])
debug_backtrace
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.3.0)
se encuentra disponible la lista de parametros. debug_backtrace -- Generates a backtrace
Description
["function"] => string(12)
"include_once"
array debug_backtrace ( void) }
}
*/
debug_backtrace() generates a PHP backtrace and
returns this information as an associative array. The See also trigger_error().
possible returned elements are listed in the following
table:
error_log
Tabla 1. Possible returned elements from
debug_backtrace()
Name Type Description (PHP 3, PHP 4 )
error_log -- envía un mensaje de error a algún lugar
functi strin The current function name. See also
on g __FUNCTION__.
Descripción
integ
line The current line number. See also __LINE__.
er
strin int error_log ( string message, int message_type [,
file The current file name. See also __FILE__. string destination [, string extra_headers]])
g
strin
class The current class name. See also __CLASS__ Envía un mensaje de error al log de errores del servidor
g
web, a un puerto TCP o a un fichero. El primer
strin parámetro, message (mensaje), es el mensaje de error
type The current class type.
g que debe ser registrado. El segundo parámetro,
If inside a function, this lists the functions message_type (tipo de mensaje) indica el lugar al que
args array arguments. If inside a included file, this lists debe dirigirse:
the included file name(s). Tabla 1. error_log() tipos de log

The following is a simple example. message es enviado al registro de sistema de PHP,


Ejemplo 1. debug_backtrace() example utilizando el mecanismo de registro de sistema del
0
Sistema Operativo, o a un fichero, dependiendo del valor
de la directiva de configuración error_log
// filename: a.php message es enviado por correo electrónico a la dirección
<?php del parámetro destination (destino). Este es el único tipo
1 de mensaje donde se utiliza el cuarto parámetro,
function a_test($str) { extra_headers. Este tipo de mensaje utiliza la misma
funcionalidad interna que mail() realiza.
print "\nHi: $str";
message es enviado a través de la conexión de
depuración de PHP. Esta opción está disponible sólo si la
var_dump(debug_backtrace(
depuración remota ha sido activada. En este caso el
)); 2
parámetro destination especifica el nombre de host o
}
dirección IP y, opcionalmente, el número de puerto del
socket que recibe la información de depuración.
a_test('friend');
?> 3 message es añadido al fichero destination.
Ejemplo 1. error_log() ejemplos
// filename: b.php
<?php
include_once '/tmp/a.php';
// Send notification through the server log
?>
if we can not
// connect to the database.
/* Results when executing
if (!Ora_Logon($username, $password)) {
/tmp/b.php
error_log("Oracle database not
available!", 0);
Hi: friend
}
array(2) {
[0]=>
// Notify administrator by email if we run
array(4) {
out of FOO
["file"] => string(10)
if (!($foo = allocate_new_foo()) {
"/tmp/a.php"
error_log("Big trouble, we're all out of
["line"] => int(10)
FOOs!", 1,
["function"] => string(6)
"operator@mydomain.com");
"a_test"
}
["args"]=>
array(1) {
// other ways of calling error_log():
[0] => &string(6) "friend"
error_log("You messed up!", 2,
}
"127.0.0.1:7000");
}
error_log("You messed up!", 2, "loghost");
[1]=>
error_log("You messed up!", 3,
array(4) {
"/var/tmp/my-errors.log");
["file"] => string(10)
"/tmp/b.php"
["line"] => int(2)
["args"] => error_reporting
array(1) {
[0] => string(10)
(PHP 3, PHP 4 )
"/tmp/a.php"
error_reporting -- establece que errores PHP son
}
registrados
Descripción
define (FATAL,E_USER_ERROR);
define (ERROR,E_USER_WARNING);
int error_reporting ( [int level]) define (WARNING,E_USER_NOTICE);

// set the error reporting level for this script


Establece el nivel de registro de los errores PHP y error_reporting (FATAL + ERROR + WARNING);
devuelve el nivel anterior. El nivel de registro es una
máscara de bits de los valores siguientes (siga los // error handler function
enlaces a los valores internos para obtener sus function myErrorHandler ($errno, $errstr) {
significados): switch ($errno) {
Tabla 1. error_reporting() valores de bit case FATAL:
valo nombre echo "<b>FATAL</b> [$errno] $errstr<br>\n";
r interno echo " Fatal error in line ".__LINE__." of file
".__FILE__;
1 E_ERROR echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
2 E_WARNING echo "Aborting...<br>\n";
exit -1;
4 E_PARSE break;
8 E_NOTICE case ERROR:
echo "<b>ERROR</b> [$errno] $errstr<br>\n";
16 E_CORE_ERROR break;
E_CORE_WARNIN case WARNING:
32 echo "<b>WARNING</b> [$errno] $errstr<br>\n";
G
break;
default:
restore_error_handler echo "Unkown error type: [$errno] $errstr<br>\n";
break;
}
(PHP 4 >= 4.0.1) }
restore_error_handler -- Restores the previous error
handler function // function to test the error handling
function scale_by_log ($vect, $scale) {
if ( !is_numeric($scale) || $scale <= 0 )
Description trigger_error("log(x) for x <= 0 is undefined, you
used: scale = $scale",
FATAL);
void restore_error_handler ( void)
if (!is_array($vect)) {
trigger_error("Incorrect input vector, array of values
Used after changing the error handler function using expected", ERROR);
set_error_handler(), to revert to the previous error return null;
handler (which could be the built-in or a user defined }
function) for ($i=0; $i<count($vect); $i++) {
See also error_reporting(), set_error_handler(), if (!is_numeric($vect[$i]))
trigger_error(), user_error() trigger_error("Value at position $i is not a number,
using 0 (zero)",
WARNING);
set_error_handler $temp[$i] = log($scale) * $vect[$i];
}
(PHP 4 >= 4.0.1) return $temp;
set_error_handler -- Sets a user-defined error handler }
function.
// set to the user defined error handler
$old_error_handler =
Description set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a


string set_error_handler ( string error_handler) non-numeric item
echo "vector a\n";
Sets a user function (error_handler) to handle errors in a $a = array(2,3,"foo",5.5,43.3,21.11);
script. Returns the previously defined error handler (if print_r($a);
any), or FALSE on error. This function can be used for
defining your own way of handling errors during runtime, // now generate second array, generating a warning
for example in applications in which you need to do echo "----\nvector b - a warning (b = log(PI) * a)\n";
cleanup of data/files when a critical error happens, or $b = scale_by_log($a, M_PI);
when you need to trigger an error under certain print_r($b);
conditions (using trigger_error())
The user function needs to accept 2 parameters: the // this is trouble, we pass a string instead of an array
error code, and a string describing the error. The echo "----\nvector c - an error\n";
example below shows the handling of internal execptions $c = scale_by_log("not array",2.3);
by triggering errors and handling them with a user var_dump($c);
defined function:
Ejemplo 1. Error handling with set_error_handler() // this is a critical error, log of zero or negative number
and trigger_error() is undefined
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);
<?php
?>
// redefine the user error constants - PHP4 only And when you run this sample script, the output will be
void user_error ( string error_msg [, int error_type])
vector a
Array
( This is an alias for the function trigger_error().
[0] => 2 See also error_reporting(), set_error_handler(),
[1] => 3 restore_error_handler(), and trigger_error()
[2] => foo
[3] => 5.5
[4] => 43.3 XXVIII. FrontBase Functions
[5] => 21.11
)
Introducción
----
vector b - a warning (b = log(PI) * a)
<b>WARNING</b> [1024] Value at position 2 is not a These functions allow you to access FrontBase database
number, using 0 (zero)<br> servers. More information about FrontBase can be found
Array at http://www.frontbase.com/.
( Documentation for FrontBase can be found at
[0] => 2.2894597716988 http://www.frontbase.com/cgi-
[1] => 3.4341896575482 bin/WebObjects/FrontBase.woa/wa/productsPage?
[2] => 0 currentPage=Documentation.
[3] => 6.2960143721717 Frontbase support has been added to PHP 4.0.6.
[4] => 49.566804057279
[5] => 24.165247890281
) Requerimientos
----
vector c - an error
<b>ERROR</b> [512] Incorrect input vector, array of You must install the FrontBase database server or at
values expected<br> least the fbsql client libraries to use this functions. You
NULL can get FrontBase from http://www.frontbase.com/.
----
vector d - fatal error
<b>FATAL</b> [256] log(x) for x <= 0 is undefined, you Instalación
used: scale = -2.5<br>
Fatal error in line 16 of file trigger_error.php, PHP In order to have these functions available, you must
4.0.1pl2 (Linux)<br> compile PHP with fbsql support by using the --with-
Aborting...<br> fbsql[=DIR] option. If you use this option without
See also error_reporting(), restore_error_handler(), specifying the path to fbsql, PHP will search for the fbsql
trigger_error(), user_error() client libraries in the default installation location for the
platform. Users who installed FrontBase in a non
standard directory should always specify the path to
trigger_error fbsql: --with-fbsql=/path/to/fbsql. This will force PHP to
use the client libraries installed by FrontBase, avoiding
any conflicts.
(PHP 4 >= 4.0.1)
trigger_error -- Generates a user-level
error/warning/notice message Configuración en tiempo de ejecución

Description The behaviour of these functions is affected by settings


in php.ini.
void trigger_error ( string error_msg [, int error_type]) Tabla 1. FrontBase configuration options
Name Default Changeable
Used to trigger a user error condition, it can be used by PHP_INI_SYSTE
in conjunction with the built-in error handler, or with a fbsql.allow_persistent "1"
M
user defined function that has been set as the new error
handler (set_error_handler()). This function is useful PHP_INI_SYSTE
fbsql.generate_warnings "0"
when you need to generate a particular response to an M
exception at runtime. For example: PHP_INI_SYSTE
fbsql.autocommit "1"
if (assert ($divisor == 0)) M
trigger_error ("Cannot divide by zero", PHP_INI_SYSTE
E_USER_ERROR); fbsql.max_persistent "-1"
M
PHP_INI_SYSTE
fbsql.max_links "128"
M
Nota: See set_error_handler() for
a more extensive example. PHP_INI_SYSTE
fbsql.max_connections "128"
M
See also error_reporting(), set_error_handler(), PHP_INI_SYSTE
fbsql.max_results "128"
restore_error_handler(), user_error() M
PHP_INI_SYSTE
fbsql.batchSize "1000"
user_error M
PHP_INI_SYSTE
fbsql.default_host NULL
M
(PHP 4 )
user_error -- Generates a user-level error/warning/notice "_SYSTE PHP_INI_SYSTE
fbsql.default_user
message M" M
fbsql.default_password "" PHP_INI_SYSTE
Description
Name Default Changeable fbsql_field_len -- Returns the length of the specified field
fbsql_field_name -- Get the name of the specified field in
M a result
PHP_INI_SYSTE fbsql_field_seek -- Set result pointer to a specified field
fbsql.default_database "" offset
M
fbsql_field_table -- Get name of the table the specified
fbsql.default_database_p PHP_INI_SYSTE field is in
""
assword M fbsql_field_type -- Get the type of the specified field in a
For further details and definition of the PHP_INI_* result
constants see ini_set(). fbsql_free_result -- Free result memory
fbsql_get_autostart_info -- No description given yet
fbsql_hostname -- Get or set the host name used with a
Tipos de recursos connection
fbsql_insert_id -- Get the id generated from the previous
INSERT operation
fbsql_list_dbs -- List databases available on a FrontBase
server
Constantes predefinidas fbsql_list_fields -- List FrontBase result fields
fbsql_list_tables -- List tables in a FrontBase database
fbsql_next_result -- Move the internal result pointer to
Estas constantes están definidas por esta extensión y the next result
estarán disponibles solamente cuando la extensión ha fbsql_num_fields -- Get number of fields in result
sido o bien compilada dentro de PHP o grabada fbsql_num_rows -- Get number of rows in result
dinamicamente en tiempo de ejecución. fbsql_password -- Get or set the user password used with
FBSQL_ASSOC (integer) a connection
FBSQL_NUM (integer) fbsql_pconnect -- Open a persistent connection to a
FBSQL_BOTH (integer) FrontBase Server
FBSQL_LOCK_DEFERRED (integer) fbsql_query -- Send a FrontBase query
FBSQL_LOCK_OPTIMISTIC (integer) fbsql_read_blob -- Read a BLOB from the database
FBSQL_LOCK_PESSIMISTIC (integer) fbsql_read_clob -- Read a CLOB from the database
FBSQL_ISO_READ_UNCOMMITTED (integer) fbsql_result -- Get result data
FBSQL_ISO_READ_COMMITTED (integer) fbsql_rollback -- Rollback a transaction to the database
FBSQL_ISO_REPEATABLE_READ (integer) fbsql_select_db -- Select a FrontBase database
FBSQL_ISO_SERIALIZABLE (integer) fbsql_set_lob_mode -- Set the LOB retrieve mode for a
FBSQL_ISO_VERSIONED (integer) FrontBase result set
FBSQL_UNKNOWN (integer) fbsql_set_transaction -- Set the transaction locking and
FBSQL_STOPPED (integer) isolation
FBSQL_STARTING (integer) fbsql_start_db -- Start a database on local or remote
FBSQL_RUNNING (integer) server
FBSQL_STOPPING (integer) fbsql_stop_db -- Stop a database on local or remote
FBSQL_NOEXEC (integer) server
FBSQL_LOB_DIRECT (integer) fbsql_tablename -- Get table name of field
FBSQL_LOB_HANDLE (integer) fbsql_username -- Get or set the host user used with a
Tabla de contenidos connection
fbsql_affected_rows -- Get number of affected rows in fbsql_warnings -- Enable or disable FrontBase warnings
previous FrontBase operation
fbsql_autocommit -- Enable or disable autocommit
fbsql_change_user -- Change logged in user of the active fbsql_affected_rows
connection
fbsql_close -- Close FrontBase connection
fbsql_commit -- Commits a transaction to the database (PHP 4 >= 4.0.6)
fbsql_connect -- Open a connection to a FrontBase Server fbsql_affected_rows -- Get number of affected rows in
fbsql_create_blob -- Create a BLOB previous FrontBase operation
fbsql_create_clob -- Create a CLOB
fbsql_create_db -- Create a FrontBase database
Description
fbsql_data_seek -- Move internal result pointer
fbsql_database_password -- Sets or retrieves the
password for a FrontBase database int fbsql_affected_rows ( [resource link_identifier])
fbsql_database -- Get or set the database name used
with a connection
fbsql_db_query -- Send a FrontBase query fbsql_affected_rows() returns the number of rows
fbsql_db_status -- Get the status for a given database affected by the last INSERT, UPDATE or DELETE query
fbsql_drop_db -- Drop (delete) a FrontBase database associated with link_identifier. If the link identifier isn't
fbsql_errno -- Returns the numerical value of the error specified, the last link opened by fbsql_connect() is
message from previous FrontBase operation assumed.
fbsql_error -- Returns the text of the error message from
previous FrontBase operation
Nota: If you are using transactions,
fbsql_fetch_array -- Fetch a result row as an associative
you need to call
array, a numeric array, or both
fbsql_affected_rows() after your
fbsql_fetch_assoc -- Fetch a result row as an associative
INSERT, UPDATE, or DELETE query,
array
not after the commit.
fbsql_fetch_field -- Get column information from a result
and return as an object
fbsql_fetch_lengths -- Get the length of each output in a If the last query was a DELETE query with no WHERE
result clause, all of the records will have been deleted from the
fbsql_fetch_object -- Fetch a result row as an object table but this function will return zero.
fbsql_fetch_row -- Get a result row as an enumerated
array
fbsql_field_flags -- Get the flags associated with the Nota: When using UPDATE,
specified field in a result FrontBase will not update columns
where the new value is the same as
the old value. This creates the
possibility that
fbsql_affected_rows() may not <?php
actually equal the number of rows $link = fbsql_connect ("localhost",
matched, only the number of rows "_SYSTEM", "secret")
that were literally affected by the or die ("Could not connect");
query. print ("Connected successfully");
fbsql_close ($link);
?>
If the last query failed, this function will return -1.
See also: fbsql_num_rows(). See also: fbsql_connect() and fbsql_pconnect().

fbsql_autocommit fbsql_commit

(PHP 4 >= 4.0.6) (PHP 4 >= 4.0.6)


fbsql_autocommit -- Enable or disable autocommit fbsql_commit -- Commits a transaction to the database

Description Description

bool fbsql_autocommit ( resource link_identifier [, bool bool fbsql_commit ( [resource link_identifier])


OnOff])
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
fbsql_autocommit() returns the current autocommit fbsql_commit() ends the current transaction by writing
status. if the optional OnOff parameter is given the auto all inserts, updates and deletes to the disk and unlocking
commit status will be changed. With OnOff set to TRUE all row and table locks held by the transaction. This
each statement will be committed automatically, if no command is only needed if autocommit is set to false.
errors was found. With OnOff set to FALSE the user must See also: fbsql_autocommit() and fbsql_rollback()
commit or rollback the transaction using either
fbsql_commit() or fbsql_rollback().
See also: fbsql_commit() and fbsql_rollback() fbsql_connect

fbsql_change_user (PHP 4 >= 4.0.6)


fbsql_connect -- Open a connection to a FrontBase Server

(no version information, might be only in CVS)


fbsql_change_user -- Change logged in user of the active Description
connection
resource fbsql_connect ( [string hostname [, string
Description username [, string password]]])

Returns a positive FrontBase link identifier on success, or


resource fbsql_change_user ( string user, string an error message on failure.
password [, string database [, resource link_identifier]]) fbsql_connect() establishes a connection to a FrontBase
server. The following defaults are assumed for missing
fbsql_change_user() changes the logged in user of the optional parameters: hostname = 'NULL', username =
current active connection, or the connection given by the '_SYSTEM' and password = empty password.
optional parameter link_identifier. If a database is If a second call is made to fbsql_connect() with the
specified, this will default or current database after the same arguments, no new link will be established, but
user has been changed. If the new user and password instead, the link identifier of the already opened link will
authorization fails, the current connected user stays be returned.
active. The link to the server will be closed as soon as the
execution of the script ends, unless it's closed earlier by
explicitly calling fbsql_close().
fbsql_close Ejemplo 1. fbsql_connect() example

(PHP 4 >= 4.0.6)


fbsql_close -- Close FrontBase connection <?php

$link = fbsql_connect ("localhost",


Description "_SYSTEM", "secret")
or die ("Could not connect");
print ("Connected successfully");
boolean fbsql_close ( [resource link_identifier]) fbsql_close ($link);

Returns: TRUE on success, FALSE on error. ?>


fbsql_close() closes the connection to the FrontBase See also fbsql_pconnect() and fbsql_close().
server that's associated with the specified link identifier.
If link_identifier isn't specified, the last opened link is
used. fbsql_create_blob
Using fbsql_close() isn't usually necessary, as non-
persistent open links are automatically closed at the end
of the script's execution. (PHP 4 >= 4.2.0)
Ejemplo 1. fbsql_close() example fbsql_create_blob -- Create a BLOB
Description bool fbsql_create_db ( string database name [, resource
link_identifier])

string fbsql_create_blob ( string blob_data [, resource


link_identifier]) fbsql_create_db() attempts to create a new database
on the server associated with the specified link identifier.
Ejemplo 1. fbsql_create_db() example
Returns: A resource handle to the newly created blob.
fbsql_create_blob() creates a blob from blob_data. The
returned resource handle can be used with insert and
<?php
update commands to store the blob in the database.
$link = fbsql_pconnect ("localhost",
Ejemplo 1. fbsql_create_blob() example
"_SYSTEM", "secret")
or die ("Could not connect");
if (fbsql_create_db ("my_db")) {
<?php print("Database created
$link = fbsql_pconnect ("localhost", "_SYSTEM", successfully\n");
"secret") } else {
or die ("Could not connect"); printf("Error creating database: %s\n",
$filename = "blobfile.bin"; fbsql_error ());
$fp = fopen($filename, "rb"); }
$blobdata = fread($fp, filesize($filename)); ?>
fclose($fp);
See also: fbsql_drop_db().
$blobHandle = fbsql_create_blob($blobdata, $link);
fbsql_data_seek
$sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN)
VALUES ($blobHandle);";
$rs = fbsql_query($sql, $link); (PHP 4 >= 4.0.6)
?> fbsql_data_seek -- Move internal result pointer
See also: fbsql_create_clob(), fbsql_read_blob(),
fbsql_read_clob(), and fbsql_set_lob_mode(). Description

fbsql_create_clob
bool fbsql_data_seek ( resource result_identifier, int
row_number)
(PHP 4 >= 4.2.0)
fbsql_create_clob -- Create a CLOB Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
fbsql_data_seek() moves the internal row pointer of the
FrontBase result associated with the specified result
Description
identifier to point to the specified row number. The next
call to fbsql_fetch_row() would return that row.
string fbsql_create_clob ( string clob_data [, resource Row_number starts at 0.
link_identifier]) Ejemplo 1. fbsql_data_seek() example

Returns: A resource handle to the newly created CLOB.


<?php
fbsql_create_clob() creates a clob from clob_data. The
$link = fbsql_pconnect ("localhost",
returned resource handle can be used with insert and
"_SYSTEM", "secret")
update commands to store the clob in the database.
or die ("Could not connect");
Ejemplo 1. fbsql_create_clob() example
fbsql_select_db ("samp_db")
or die ("Could not select database");
<?php
$link = fbsql_pconnect ("localhost", "_SYSTEM", $query = "SELECT last_name, first_name
"secret") FROM friends;";
or die ("Could not connect"); $result = fbsql_query ($query)
$filename = "clob_file.txt"; or die ("Query failed");
$fp = fopen($filename, "rb");
$clobdata = fread($fp, filesize($filename)); # fetch rows in reverse order
fclose($fp);
for ($i = fbsql_num_rows ($result) - 1; $i >=0;
$clobHandle = fbsql_create_clob($clobdata, $link); $i--) {
if (!fbsql_data_seek ($result, $i)) {
$sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) printf ("Cannot seek to row %d\n", $i);
VALUES ($clobHandle);"; continue;
$rs = fbsql_query($sql, $link); }
?>
See also: fbsql_create_blob(), fbsql_read_blob(), if(!($row = fbsql_fetch_object ($result)))
fbsql_read_clob(), and fbsql_set_lob_mode(). continue;

printf("%s %s<BR>\n", $row->last_name,


fbsql_create_db $row->first_name);
}
(PHP 4 >= 4.0.6) fbsql_free_result ($result);
fbsql_create_db -- Create a FrontBase database ?>

Description
fbsql_database_password fbsql_db_query() selects a database and executes a
query on it. If the optional link identifier isn't specified,
the function will try to find an open link to the FrontBase
(PHP 4 >= 4.0.6) server and if no such link is found it'll try to create one as
fbsql_database_password -- Sets or retrieves the if fbsql_connect() was called with no arguments
password for a FrontBase database See also fbsql_connect().

Description fbsql_db_status

string fbsql_database_password ( resource (PHP 4 >= 4.1.0)


link_identifier [, string database_password]) fbsql_db_status -- Get the status for a given database

Returns: The database password associated with the link


Description
identifier.
fbsql_database_password() sets and retrieves the
database password used by the connection. if a database int fbsql_db_status ( string database_name [, resource
is protected by a database password, the user must call link_identifier])
this function before calling fbsql_select_db(). if the
second optional parameter is given the function sets the
database password for the specified link identifier. If no Returns: An integer value with the current status.
link identifier is specified, the last opened link is fbsql_db_status() requests the current status of the
assumed. If no link is open, the function will try to database specified by database_name. If the
establish a link as if fbsql_connect() was called, and link_identifier is omitted the default link_identifier will be
use it. used.
This function does not change the database password in The return value can be one of the following constants:
the database nor can it be used to retrive the database
password for a database.
Ejemplo 1. fbsql_create_clob() example • FALSE - The exec handler for the host was
invalid. This error will occur when the
link_identifier connects directly to a database
<?php by using a port number. FBExec can be
$link = fbsql_pconnect ("localhost", available on the server but no connection has
"_SYSTEM", "secret") been made for it.
or die ("Could not connect"); • FBSQL_UNKNOWN - The Status is unknown.
fbsql_database_password($link, "secret
db password"); • FBSQL_STOPPED - The database is not running.
fbsql_select_db($database, $link); Use fbsql_start_db() to start the database.
?> • FBSQL_STARTING - The database is starting.
See also: fbsql_connect(), fbsql_pconnect() and • FBSQL_RUNNING - The database is running and
fbsql_select_db(). can be used to perform SQL operations.
• FBSQL_STOPPING - The database is stopping.
fbsql_database
• FBSQL_NOEXEC - FBExec is not running on the
server and it is not possible to get the status of
(PHP 4 >= 4.0.6) the database.
fbsql_database -- Get or set the database name used
with a connection
See also: fbsql_start_db() and fbsql_stop_db().

Description
fbsql_drop_db

string fbsql_database ( resource link_identifier [, string


database]) (PHP 4 >= 4.0.6)
fbsql_drop_db -- Drop (delete) a FrontBase database

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
bool fbsql_drop_db ( string database_name [, resource
link_identifier])
fbsql_db_query
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
fbsql_drop_db() attempts to drop (remove) an entire
(PHP 4 >= 4.0.6) database from the server associated with the specified
fbsql_db_query -- Send a FrontBase query link identifier.

Description fbsql_errno

resource fbsql_db_query ( string database, string query (PHP 4 >= 4.0.6)


[, resource link_identifier]) fbsql_errno -- Returns the numerical value of the error
message from previous FrontBase operation
Returns: A positive FrontBase result identifier to the
query result, or FALSE on error.
Description
int fbsql_errno ( [resource link_identifier]) If two or more columns of the result have the same field
names, the last column will take precedence. To access
the other column(s) of the same name, you must the
Returns the error number from the last fbsql function, or
numeric index of the column or make an alias for the
0 (zero) if no error occurred.
column.
Errors coming back from the fbsql database backend
don't issue warnings. Instead, use fbsql_errno() to select t1.f1 as foo t2.f1 as bar
retrieve the error code. Note that this function only from t1, t2
returns the error code from the most recently executed
An important thing to note is that using
fbsql function (not including fbsql_error() and
fbsql_fetch_array() is NOT significantly slower than
fbsql_errno()), so if you want to use it, make sure you
using fbsql_fetch_row(), while it provides a significant
check the value before calling another fbsql function.
added value.
<?php The optional second argument result_type in
fbsql_connect("marliesle"); fbsql_fetch_array() is a constant and can take the
echo fbsql_errno().": ".fbsql_error()."<BR>"; following values: FBSQL_ASSOC, FBSQL_NUM, and
fbsql_select_db("nonexistentdb"); FBSQL_BOTH.
echo fbsql_errno().": ".fbsql_error()."<BR>"; For further details, see also fbsql_fetch_row() and
$conn = fbsql_query("SELECT * FROM fbsql_fetch_assoc().
nonexistenttable;"); Ejemplo 1. fbsql_fetch_array() example
echo fbsql_errno().": ".fbsql_error()."<BR>";
?>
See also: fbsql_error() and fbsql_warnings(). <?php
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select user_id,
fbsql_error fullname from table");
while ($row = fbsql_fetch_array ($result)) {
echo "user_id: ".$row["user_id"]."<br>\n";
(PHP 4 >= 4.0.6) echo "user_id: ".$row[0]."<br>\n";
fbsql_error -- Returns the text of the error message from echo "fullname: ".$row["fullname"]."<br>\n";
previous FrontBase operation echo "fullname: ".$row[1]."<br>\n";
}
fbsql_free_result ($result);
Description
?>

string fbsql_error ( [resource link_identifier])


fbsql_fetch_assoc
Returns the error text from the last fbsql function, or ''
(the empty string) if no error occurred. (PHP 4 >= 4.0.6)
Errors coming back from the fbsql database backend fbsql_fetch_assoc -- Fetch a result row as an associative
don't issue warnings. Instead, use fbsql_error() to array
retrieve the error text. Note that this function only
returns the error text from the most recently executed
fbsql function (not including fbsql_error() and Description
fbsql_errno()), so if you want to use it, make sure you
check the value before calling another fbsql function.
array fbsql_fetch_assoc ( resource result)
<?php
fbsql_connect("marliesle");
echo fbsql_errno().": ".fbsql_error()."<BR>"; Returns an associative array that corresponds to the
fbsql_select_db("nonexistentdb"); fetched row, or FALSE if there are no more rows.
echo fbsql_errno().": ".fbsql_error()."<BR>"; fbsql_fetch_assoc() is equivalent to calling
$conn = fbsql_query("SELECT * FROM fbsql_fetch_array() with FBSQL_ASSOC for the optional
nonexistenttable;"); second parameter. It only returns an associative array.
echo fbsql_errno().": ".fbsql_error()."<BR>"; This is the way fbsql_fetch_array() originally worked. If
?> you need the numeric indices as well as the associative,
use fbsql_fetch_array().
See also: fbsql_errno() and fbsql_warnings(). If two or more columns of the result have the same field
names, the last column will take precedence. To access
the other column(s) of the same name, you must use
fbsql_fetch_array
fbsql_fetch_array() and have it return the numeric
indices as well.
(PHP 4 >= 4.0.6) An important thing to note is that using
fbsql_fetch_array -- Fetch a result row as an associative fbsql_fetch_assoc() is NOT significantly slower than
array, a numeric array, or both using fbsql_fetch_row(), while it provides a significant
added value.
For further details, see also fbsql_fetch_row() and
Description fbsql_fetch_array().
Ejemplo 1. fbsql_fetch_assoc() example
array fbsql_fetch_array ( resource result [, int
result_type])
<?php
fbsql_connect ($host, $user, $password);
Returns an array that corresponds to the fetched row, or $result = fbsql_db_query
FALSE if there are no more rows. ("database","select * from table");
fbsql_fetch_array() is an extended version of while ($row = fbsql_fetch_assoc ($result))
fbsql_fetch_row(). In addition to storing the data in the {
numeric indices of the result array, it also stores the data echo $row["user_id"];
in associative indices, using the field names as keys. echo $row["fullname"];
}
array fbsql_fetch_lengths ( [resource result])
fbsql_free_result ($result);
?>
Returns: An array that corresponds to the lengths of each
field in the last row fetched by fbsql_fetch_row(), or
fbsql_fetch_field FALSE on error.
fbsql_fetch_lengths() stores the lengths of each result
column in the last row returned by fbsql_fetch_row(),
(PHP 4 >= 4.0.6) fbsql_fetch_array() and fbsql_fetch_object() in an
fbsql_fetch_field -- Get column information from a result array, starting at offset 0.
and return as an object See also: fbsql_fetch_row().

Description fbsql_fetch_object

object fbsql_fetch_field ( resource result [, int (PHP 4 >= 4.0.6)


field_offset]) fbsql_fetch_object -- Fetch a result row as an object

Returns an object containing field information. Description


fbsql_fetch_field() can be used in order to obtain
information about fields in a certain query result. If the
field offset isn't specified, the next field that wasn't yet object fbsql_fetch_object ( resource result [, int
retrieved by fbsql_fetch_field() is retrieved. result_type])
The properties of the object are:
Returns an object with properties that correspond to the
fetched row, or FALSE if there are no more rows.
• name - column name fbsql_fetch_object() is similar to fbsql_fetch_array(),
• table - name of the table the column belongs with one difference - an object is returned, instead of an
to array. Indirectly, that means that you can only access the
data by the field names, and not by their offsets
• max_length - maximum length of the column (numbers are illegal property names).
• not_null - 1 if the column cannot be NULL The optional argument result_type is a constant and can
take the following values: FBSQL_ASSOC, FBSQL_NUM,
• type - the type of the column and FBSQL_BOTH.
Speed-wise, the function is identical to
fbsql_fetch_array(), and almost as quick as
Ejemplo 1. fbsql_fetch_field() example
fbsql_fetch_row() (the difference is insignificant).
Ejemplo 1. fbsql_fetch_object() example
<?php
fbsql_connect ($host, $user, $password)
<?php
or die ("Could not connect");
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database",
$result = fbsql_db_query ("database",
"select * from table")
"select * from table");
or die ("Query failed");
while ($row = fbsql_fetch_object ($result))
# get column metadata
{
$i = 0;
echo $row->user_id;
while ($i < fbsql_num_fields ($result)) {
echo $row->fullname;
echo "Information for column
}
$i:<BR>\n";
fbsql_free_result ($result);
$meta = fbsql_fetch_field ($result);
?>
if (!$meta) {
echo "No information See also: fbsql_fetch_array() and fbsql_fetch_row().
available<BR>\n";
}
echo "<PRE> fbsql_fetch_row
max_length: $meta->max_length
name: $meta->name
(PHP 4 >= 4.0.6)
not_null: $meta->not_null
fbsql_fetch_row -- Get a result row as an enumerated
table: $meta->table
array
type: $meta->type
</PRE>";
$i++; Description
}
fbsql_free_result ($result);
?> array fbsql_fetch_row ( resource result)
See also fbsql_field_seek().
Returns: An array that corresponds to the fetched row, or
FALSE if there are no more rows.
fbsql_fetch_lengths fbsql_fetch_row() fetches one row of data from the
result associated with the specified result identifier. The
row is returned as an array. Each result column is stored
(PHP 4 >= 4.0.6)
in an array offset, starting at offset 0.
fbsql_fetch_lengths -- Get the length of each output in a
Subsequent call to fbsql_fetch_row() would return the
result
next row in the result set, or FALSE if there are no more
rows.
Description
See also: fbsql_fetch_array(), fbsql_fetch_object(),
user_id
fbsql_data_seek(), fbsql_fetch_lengths(), and
passwor
fbsql_result().
d

fbsql_field_flags
fbsql_field_seek

(PHP 4 >= 4.0.6)


fbsql_field_flags -- Get the flags associated with the (PHP 4 >= 4.0.6)
specified field in a result fbsql_field_seek -- Set result pointer to a specified field
offset

Description
Description

string fbsql_field_flags ( resource result, int field_offset)


bool fbsql_field_seek ( resource result, int field_offset)
fbsql_field_flags() returns the field flags of the
specified field. The flags are reported as a single word Seeks to the specified field offset. If the next call to
per flag separated by a single space, so that you can split fbsql_fetch_field() doesn't include a field offset, the
the returned value using explode(). field offset specified in fbsql_field_seek() will be
returned.
See also: fbsql_fetch_field().
fbsql_field_len

fbsql_field_table
(PHP 4 >= 4.0.6)
fbsql_field_len -- Returns the length of the specified field
(PHP 4 >= 4.0.6)
fbsql_field_table -- Get name of the table the specified
Description field is in

int fbsql_field_len ( resource result, int field_offset) Description

fbsql_field_len() returns the length of the specified


string fbsql_field_table ( resource result, int
field.
field_offset)

fbsql_field_name Returns the name of the table that the specified field is
in.
(PHP 4 >= 4.0.6)
fbsql_field_name -- Get the name of the specified field in fbsql_field_type
a result

(PHP 4 >= 4.0.6)


Description fbsql_field_type -- Get the type of the specified field in a
result
string fbsql_field_name ( resource result, int
field_index) Description

fbsql_field_name() returns the name of the specified


string fbsql_field_type ( resource result, int field_offset)
field index. result must be a valid result identifier and
field_index is the numerical offset of the field.
fbsql_field_type() is similar to the fbsql_field_name()
function. The arguments are identical, but the field type
Nota: field_index starts at 0. is returned instead. The field type will be one of "int",
"real", "string", "blob", and others as detailed in the
FrontBase documentation.
e.g. The index of the third field
Ejemplo 1. fbsql_field_type() example
would actually be 2, the index of the
fourth field would be 3 and so on.
<?php
Ejemplo 1. fbsql_field_name() example
fbsql_connect ("localhost", "_SYSTEM", "");
fbsql_select_db ("wisconsin");
// The users table consists of three fields: $result = fbsql_query ("SELECT * FROM onek;");
// user_id $fields = fbsql_num_fields ($result);
// username $rows = fbsql_num_rows ($result);
// password. $i = 0;
$table = fbsql_field_table ($result, $i);
$res = fbsql_db_query("users", "select * echo "Your '".$table."' table has ".$fields." fields and ".
from users", $link); $rows." records <BR>";
echo "The table has the following fields <BR>";
echo fbsql_field_name($res, 0) . "\n"; while ($i < $fields) {
echo fbsql_field_name($res, 2); $type = fbsql_field_type ($result, $i);
$name = fbsql_field_name ($result, $i);
The above example would produce the following output: $len = fbsql_field_len ($result, $i);
fbsql_insert_id() returns the ID generated for an
$flags = fbsql_field_flags ($result, $i);
column defined as DEFAULT UNIQUE by the previous
echo $type." ".$name." ".$len." ".$flags."<BR>";
INSERT query using the given link_identifier. If
$i++;
link_identifier isn't specified, the last opened link is
}
assumed.
fbsql_close();
fbsql_insert_id() returns 0 if the previous query does
not generate an DEFAULT UNIQUE value. If you need to
?>
save the value for later, be sure to call fbsql_insert_id()
immediately after the query that generates the value.
fbsql_free_result
Nota: The value of the FrontBase
SQL function LAST_INSERT_ID()
(PHP 4 >= 4.0.6) always contains the most recently
fbsql_free_result -- Free result memory generated DEFAULT UNIQUE value,
and is not reset between queries.
Description
fbsql_list_dbs
bool fbsql_free_result ( resource result)
(PHP 4 >= 4.0.6)
fbsql_free_result() will free all memory associated with fbsql_list_dbs -- List databases available on a FrontBase
the result identifier result. server
fbsql_free_result() only needs to be called if you are
concerned about how much memory is being used for
queries that return large result sets. All associated result Description
memory is automatically freed at the end of the script's
execution. resource fbsql_list_dbs ( [resource link_identifier])

fbsql_get_autostart_info fbsql_list_dbs() will return a result pointer containing


the databases available from the current fbsql daemon.
Use the fbsql_tablename() function to traverse this
(PHP 4 >= 4.1.0) result pointer.
fbsql_get_autostart_info -- No description given yet Ejemplo 1. fbsql_list_dbs() example

Description
$link = fbsql_connect('localhost',
'myname', 'secret');
array fbsql_get_autostart_info ( [resource $db_list = fbsql_list_dbs($link);
link_identifier])
while ($row =
fbsql_fetch_object($db_list)) {
Aviso echo $row->Database . "\n";
Esta función no está documentada actualmente, solamente }
se encuentra disponible la lista de parametros. The above example would produce the following output:
databas
e1
fbsql_hostname
databas
e2
(PHP 4 >= 4.0.6) databas
fbsql_hostname -- Get or set the host name used with a e3
connection ...

Description Nota: The above code would just as


easily work with fbsql_fetch_row()
or other similar functions.
string fbsql_hostname ( resource link_identifier [, string
host_name])
fbsql_list_fields
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.0.6)
se encuentra disponible la lista de parametros. fbsql_list_fields -- List FrontBase result fields

Description
fbsql_insert_id

resource fbsql_list_fields ( string database_name,


(PHP 4 >= 4.0.6) string table_name [, resource link_identifier])
fbsql_insert_id -- Get the id generated from the previous
INSERT operation
fbsql_list_fields() retrieves information about the given
tablename. Arguments are the database name and the
Description table name. A result pointer is returned which can be
used with fbsql_field_flags(), fbsql_field_len(),
fbsql_field_name(), and fbsql_field_type().
int fbsql_insert_id ( [resource link_identifier])
A result identifier is a positive integer. The function
from table2;";
returns FALSE if an error occurs. A string describing the
$rs = fbsql_query($SQL, $link);
error will be placed in $phperrmsg, and unless the
do {
function was called as @fbsql() then this error string will
while ($row = fbsql_fetch_row($rs)) {
also be printed out.
}
Ejemplo 1. fbsql_list_fields() example
} while (fbsql_next_result($rs));
fbsql_free_result($rs);
fbsql_close ($link);
$link = fbsql_connect('localhost', ?>
'myname', 'secret');

$fields = fbsql_list_fields("database1",
fbsql_num_fields
"table1", $link);
$columns = fbsql_num_fields($fields);
(PHP 4 >= 4.0.6)
for ($i = 0; $i < $columns; $i++) { fbsql_num_fields -- Get number of fields in result
echo fbsql_field_name($fields, $i) .
"\n";;
} Description
The above example would produce the following output:
field int fbsql_num_fields ( resource result)
1
field fbsql_num_fields() returns the number of fields in a
2 result set.
field See also: fbsql_db_query(), fbsql_query(),
3 fbsql_fetch_field(), and fbsql_num_rows().
...

fbsql_num_rows
fbsql_list_tables
(PHP 4 >= 4.0.6)
(PHP 4 >= 4.0.6) fbsql_num_rows -- Get number of rows in result
fbsql_list_tables -- List tables in a FrontBase database
Description
Description
int fbsql_num_rows ( resource result)
resource fbsql_list_tables ( string database [, resource
link_identifier]) fbsql_num_rows() returns the number of rows in a
result set. This command is only valid for SELECT
fbsql_list_tables() takes a database name and returns statements. To retrieve the number of rows returned
a result pointer much like the fbsql_db_query() from a INSERT, UPDATE or DELETE query, use
function. The fbsql_tablename() function should be fbsql_affected_rows().
used to extract the actual table names from the result Ejemplo 1. fbsql_num_rows() example
pointer.

<?php
fbsql_next_result
$link = fbsql_connect("localhost",
"username", "password");
(PHP 4 >= 4.0.6)
fbsql_select_db("database", $link);
fbsql_next_result -- Move the internal result pointer to
the next result
$result = fbsql_query("SELECT * FROM
table1;", $link);
Description $num_rows = fbsql_num_rows($result);

echo "$num_rows Rows\n";


bool fbsql_next_result ( resource result_id)
?>
When sending more than one SQL statement to the See also: fbsql_affected_rows(), fbsql_connect(),
server or executing a stored procedure with multiple fbsql_select_db(), and fbsql_query().
results will cause the server to return multiple result sets.
This function will test for additional results available form
the server. If an additional result set exists it will free the fbsql_password
existing result set and prepare to fetch the words from
the new result set. The function will return TRUE if an (PHP 4 >= 4.0.6)
additional result set was available or FALSE otherwise.
fbsql_password -- Get or set the user password used with
Ejemplo 1. fbsql_next_result() example a connection

<?php Description
$link = fbsql_connect ("localhost",
"_SYSTEM", "secret");
fbsql_select_db("MyDB", $link); string fbsql_password ( resource link_identifier [, string
$SQL = "Select * from table1; select * password])
Aviso $result = fbsql_query ("SELECT *
WHERE 1=1")
Esta función no está documentada actualmente, solamente
or die ("Invalid query");
se encuentra disponible la lista de parametros.
?>
The following query is semantically invalid if my_col is
fbsql_pconnect not a column in the table my_tbl, so fbsql_query() fails
and returns FALSE:
Ejemplo 2. fbsql_query() example
(PHP 4 >= 4.0.6)
fbsql_pconnect -- Open a persistent connection to a
FrontBase Server <?php
$result = fbsql_query ("SELECT my_col
Description FROM my_tbl")
or die ("Invalid query");
?>
resource fbsql_pconnect ( [string hostname [, string fbsql_query() will also fail and return FALSE if you don't
username [, string password]]]) have permission to access the table(s) referenced by the
query.
Returns: A positive FrontBase persistent link identifier on Assuming the query succeeds, you can call
success, or FALSE on error. fbsql_num_rows() to find out how many rows were
fbsql_pconnect() establishes a connection to a returned for a SELECT statement or
FrontBase server. The following defaults are assumed for fbsql_affected_rows() to find out how many rows were
missing optional parameters: host = 'localhost', affected by a DELETE, INSERT, REPLACE, or UPDATE
username = "_SYSTEM" and password = empty statement.
password. For SELECT statements, fbsql_query() returns a new
fbsql_pconnect() acts very much like fbsql_connect() result identifier that you can pass to fbsql_result().
with two major differences. When you are done with the result set, you can free the
To set Frontbase server port number, use resources associated with it by calling
fbsql_select_db(). fbsql_free_result(). Although, the memory will
First, when connecting, the function would first try to find automatically be freed at the end of the script's
a (persistent) link that's already open with the same execution.
host, username and password. If one is found, an See also: fbsql_affected_rows(), fbsql_db_query(),
identifier for it will be returned instead of opening a new fbsql_free_result(), fbsql_result(), fbsql_select_db(),
connection. and fbsql_connect().
Second, the connection to the SQL server will not be
closed when the execution of the script ends. Instead,
the link will remain open for future use. fbsql_read_blob
This type of links is therefore called 'persistent'.
(PHP 4 >= 4.2.0)
fbsql_query fbsql_read_blob -- Read a BLOB from the database

(PHP 4 >= 4.0.6) Description


fbsql_query -- Send a FrontBase query
string fbsql_read_blob ( string blob_handle [, resource
Description link_identifier])

Returns: A string containing the BLOB specified by


resource fbsql_query ( string query [, resource blob_handle.
link_identifier]) fbsql_read_blob() reads BLOB data from the database.
If a select statement contains BLOB and/or BLOB columns
fbsql_query() sends a query to the currently active FrontBase will return the data directly when data is
database on the server that's associated with the fetched. This default behavior can be changed with
specified link identifier. If link_identifier isn't specified, fbsql_set_lob_mode() so the fetch functions will return
the last opened link is assumed. If no link is open, the handles to BLOB and CLOB data. If a handle is fetched a
function tries to establish a link as if fbsql_connect() user must call fbsql_read_blob() to get the actual BLOB
was called with no arguments, and use it. data from the database.
Ejemplo 1. fbsql_read_blob() example

Nota: The query string shall always


end with a semicolon. <?php
$link = fbsql_pconnect ("localhost", "_SYSTEM",
fbsql_query() returns TRUE (non-zero) or FALSE to "secret")
indicate whether or not the query succeeded. A return or die ("Could not connect");
value of TRUE means that the query was legal and could $sql = "SELECT BLOB_COLUMN FROM
be executed by the server. It does not indicate anything BLOB_TABLE;";
about the number of rows affected or returned. It is $rs = fbsql_query($sql, $link);
perfectly possible for a query to succeed but affect no $row_data = fbsql_fetch_row($rs);
rows or return no rows. // $row_data[0] will now contain the blob data for
The following query is syntactically invalid, so teh first row
fbsql_query() fails and returns FALSE: fbsql_free_result($rs);
Ejemplo 1. fbsql_query() example
$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
<?php
// $row_data[0] will now contain a handle to the
When working on large result sets, you should consider
BLOB data in the first row
using one of the functions that fetch an entire row
$blob_data = fbsql_read_blob($row_data[0]);
(specified below). As these functions return the contents
fbsql_free_result($rs);
of multiple cells in one function call, they're MUCH
quicker than fbsql_result(). Also, note that specifying a
?>
numeric offset for the field argument is much quicker
See also: fbsql_create_blob(), fbsql_read_blob(), than specifying a fieldname or tablename.fieldname
fbsql_read_clob(), and fbsql_set_lob_mode(). argument.
Calls to fbsql_result() should not be mixed with calls to
other functions that deal with the result set.
fbsql_read_clob Recommended high-performance alternatives:
fbsql_fetch_row(), fbsql_fetch_array(), and
(PHP 4 >= 4.2.0) fbsql_fetch_object().
fbsql_read_clob -- Read a CLOB from the database
fbsql_rollback
Description
(PHP 4 >= 4.0.6)
string fbsql_read_clob ( string clob_handle [, resource fbsql_rollback -- Rollback a transaction to the database
link_identifier])
Description
Returns: A string containing the CLOB specified by
clob_handle.
fbsql_read_clob() reads CLOB data from the database. bool fbsql_rollback ( [resource link_identifier])
If a select statement contains BLOB and/or CLOB
columns FrontBase will return the data directly when Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
data is fetched. This default behavior can be changed fbsql_rollback() ends the current transaction by rolling
with fbsql_set_lob_mode() so the fetch functions will back all statements issued since last commit. This
return handles to BLOB and CLOB data. If a handle is command is only needed if autocommit is set to false.
fetched a user must call fbsql_read_clob() to get the See also: fbsql_autocommit() and fbsql_commit()
actual CLOB data from the database.
Ejemplo 1. fbsql_read_clob() example
fbsql_select_db

<?php (PHP 4 >= 4.0.6)


$link = fbsql_pconnect ("localhost", "_SYSTEM", fbsql_select_db -- Select a FrontBase database
"secret")
or die ("Could not connect");
$sql = "SELECT CLOB_COLUMN FROM Description
CLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs); bool fbsql_select_db ( string database_name [, resource
// $row_data[0] will now contain the clob data for link_identifier])
teh first row
fbsql_free_result($rs); Returns: TRUE on success, FALSE on error.
fbsql_select_db() sets the current active database on
$rs = fbsql_query($sql, $link); the server that's associated with the specified link
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE); identifier. If no link identifier is specified, the last opened
$row_data = fbsql_fetch_row($rs); link is assumed. If no link is open, the function will try to
// $row_data[0] will now contain a handle to the establish a link as if fbsql_connect() was called, and
CLOB data in the first row use it.
$clob_data = fbsql_read_clob($row_data[0]); The client contacts FBExec to obtain the port number to
fbsql_free_result($rs); use for the connection to the database. If the database
name is a number the system will use that as a port
?> number and it will not ask FBExec for the port number.
See also: fbsql_create_blob(), fbsql_read_blob(), The FrontBase server can be stared as FRontBase
fbsql_read_clob(), and fbsql_set_lob_mode(). -FBExec=No -port=<port number> <database name>.
Every subsequent call to fbsql_query() will be made on
the active database.
fbsql_result if the database is protected with a database password,
the user must call fbsql_database_password() before
selecting the database.
(PHP 4 >= 4.0.6) See also: fbsql_connect(), fbsql_pconnect(),
fbsql_result -- Get result data fbsql_database_password() and fbsql_query().

Description fbsql_set_lob_mode

mixed fbsql_result ( resource result, int row [, mixed (PHP 4 >= 4.2.0)
field]) fbsql_set_lob_mode -- Set the LOB retrieve mode for a
FrontBase result set
fbsql_result() returns the contents of one cell from a
FrontBase result set. The field argument can be the
field's offset, or the field's name, or the field's table dot Description
field's name (tabledname.fieldname). If the column name
has been aliased ('select foo as bar from...'), use the alias bool fbsql_set_lob_mode ( resource result, string
instead of the column name. database_name)
Returns: TRUE on success, FALSE on error. bool fbsql_stop_db ( string database_name [, resource
fbsql_set_lob_mode() sets the mode for retrieving LOB link_identifier])
data from the database. When BLOB and CLOB data is
stored in FrontBase it can be stored direct or indirect.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
Direct stored LOB data will always be fetched no matter
fbsql_stop_db()
the setting of the lob mode. If the LOB data is less than
See also: fbsql_db_status() and fbsql_start_db().
512 bytes it will always be stored directly.

fbsql_tablename
• FBSQL_LOB_DIRECT - LOB data is retrieved
directly. When data is fetched from the
database with fbsql_fetch_row(), and other (PHP 4 >= 4.2.0)
fetch functions, all CLOB and BLOB columns fbsql_tablename -- Get table name of field
will be returned as ordinary columns. This is
the default value on a new FrontBase result. Description
• FBSQL_LOB_HANDLE - LOB data is retrieved as
handles to the data. When data is fetched from
the database with fbsql_fetch_row (), and string fbsql_tablename ( resource result, int i)
other fetch functions, LOB data will be returned
as a handle to the data if the data is stored fbsql_tablename() takes a result pointer returned by
indirect or the data if it is stored direct. If a the fbsql_list_tables() function as well as an integer
handle is returned it will be a 27 byte string index and returns the name of a table. The
formatted as fbsql_num_rows() function may be used to determine
"@'000000000000000000000000'". the number of tables in the result pointer.
Ejemplo 1. fbsql_tablename() example
See also: fbsql_create_blob(), fbsql_create_clob(),
fbsql_read_blob(), and fbsql_read_clob().
<?php
fbsql_connect ("localhost",
fbsql_set_transaction "_SYSTEM", "");
$result = fbsql_list_tables
("wisconsin");
(PHP 4 >= 4.2.0) $i = 0;
fbsql_set_transaction -- Set the transaction locking and while ($i < fbsql_num_rows
isolation ($result)) {
$tb_names[$i] =
fbsql_tablename ($result, $i);
Description echo $tb_names[$i] . "<BR>";
$i++;
void fbsql_set_transaction ( resource link_identifier, int }
Locking, int Isolation) ?>

Aviso fbsql_username
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. (PHP 4 >= 4.0.6)
fbsql_username -- Get or set the host user used with a
connection
fbsql_start_db

Description
(PHP 4 >= 4.0.6)
fbsql_start_db -- Start a database on local or remote
server string fbsql_username ( resource link_identifier [, string
username])

Description
Aviso

bool fbsql_start_db ( string database_name [, resource Esta función no está documentada actualmente, solamente
link_identifier]) se encuentra disponible la lista de parametros.

Devuelve TRUE si todo fue bien, FALSE en caso de fallo. fbsql_warnings


fbsql_start_db()
See also: fbsql_db_status() and fbsql_stop_db().
(PHP 4 >= 4.0.6)
fbsql_warnings -- Enable or disable FrontBase warnings
fbsql_stop_db

Description
(PHP 4 >= 4.0.6)
fbsql_stop_db -- Stop a database on local or remote
server bool fbsql_warnings ( [bool OnOff])

Description Returns TRUE if warnings is turned on otherwise FALSE.


fbsql_warnings() enables or disables FrontBase
warnings.
XXIX. Funciones filePro Devuelve la anchura de el campo correspondiente a
field_number.

Estas funciones permiten acceso en modo de solo-lectura


a datos guardados en bases de datos filePro. filepro_retrieve
filePro es una marca registrada de fP Technologies, Inc.
Mas informacion sobre filePro puede encontrarse en
http://www.fptech.com/. (PHP 3, PHP 4 )
Tabla de contenidos filepro_retrieve -- extrae informacion de una base de
filepro_fieldcount -- encuentra cuantos campos existen datos filePro
en una base de datos filePro
filepro_fieldname -- obtiene el nombre de un campo
Descripcion
filepro_fieldtype -- obtiene el tipo de campo
filepro_fieldwidth -- obtiene la anchura de un campo
filepro_retrieve -- extrae informacion de una base de string filepro_retrieve ( int row_number, int
datos filePro field_number)
filepro_rowcount -- encuentra cuantas filas existen en
una base de datos filePro
filepro -- lee y verifica el fichero de mapeo Devuelve la informacion de la base de datos contenida
en la localizacion especificada.

filepro_fieldcount
filepro_rowcount

(PHP 3, PHP 4 )
filepro_fieldcount -- encuentra cuantos campos existen (PHP 3, PHP 4 )
en una base de datos filePro filepro_rowcount -- encuentra cuantas filas existen en
una base de datos filePro

Descripcion
Descripcion

int filepro_fieldcount ( void)


int filepro_rowcount ( void)

Devuelve el numero de campos (columnas) existentes en


la base de datos filePro abierta. Devuelve el numero de filas (entradas) existentes en la
Ver tambien filepro(). base de datos filePro abierta.
Ver tambien filepro().

filepro_fieldname
filepro

(PHP 3, PHP 4 )
filepro_fieldname -- obtiene el nombre de un campo (PHP 3, PHP 4 )
filepro -- lee y verifica el fichero de mapeo

Descripcion
Descripcion

string filepro_fieldname ( int field_number)


bool filepro ( string directory)

Devuelve el nombre del campo correspondiente a


field_number. Lee y verifica el fichero de mapeo, guardando la relacion
de campos e informacion.
Ningun bloqueo es realizado, por ello, no se deberia
filepro_fieldtype modificar la base de datos filePro cuando puede ser
abierta con PHP.

(PHP 3, PHP 4 )
filepro_fieldtype -- obtiene el tipo de campo XXX. Funciones del sistema de ficheros

Descripcion Tabla de contenidos


basename -- Devuelve la parte del path correspondiente
al nombre del fichero
string filepro_fieldtype ( int field_number) chgrp -- Cambia el grupo de un fichero
chmod -- Cambia permisos de un fichero
Devuelve el tipo de campo del campo correspondiente a chown -- Cambia el propietario de un fichero
field_number. clearstatcache -- Limpia la cache de estado de un fichero
copy -- Copia un fichero
delete -- Una entrada manual inútil
filepro_fieldwidth dirname -- Devuelve la parte del path correspondiente al
directorio
disk_free_space -- Returns available space in directory
(PHP 3, PHP 4 ) disk_total_space -- Returns the total size of a directory
filepro_fieldwidth -- obtiene la anchura de un campo diskfreespace -- Devuelve el espacio disponible en un
directorio
fclose -- Cierra el apuntador a un fichero abierto
Descripcion
feof -- Verifica si el apuntador a un fichero está al final
del fichero (end-of-file)
int filepro_fieldwidth ( int field_number) fflush -- Flushes the output to a file
fgetc -- Obtiene un caracter del fichero apuntado
fgetcsv -- Obtiene una línea del fichero apuntado y Descripción
extrae los campos CSV
fgets -- Obtiene una línea del fichero apuntado
fgetss -- Obtiene una línea del fichero apuntado y quita string basename ( string path)
las etiquetas HTML
file_exists -- Verifica si un fichero existe Dada una cadena (string) que contiene el path de un
file_get_contents -- Reads entire file into a string fichero, esta función devuelve el nombre base del
file -- lee un fichero completo hacia un array fichero.
fileatime -- Obtiene la última fecha de acceso a un En Windows, tanto la barra (/) como la barra inversa (\)
fichero pueden usarse como caracter separador en el path. En
filectime -- Obtiene la fecha de cambio del inode del otros entornos, se usa la barra directa (/).
fichero Ejemplo 1. Ejemplo de basename()
filegroup -- Obtiene el grupo de un fichero
fileinode -- Obtiene el inode del fichero
filemtime -- Obtiene la fecha de modificación del fichero $path = "/home/httpd/html/index.php3";
fileowner -- Obtiene el propietario del fichero $file = basename($path); // $file toma el
fileperms -- Obtiene los permisos del fichero valor "index.php3"
filesize -- Obtiene el tamaño del fichero
filetype -- Obtiene el tipo de fichero Ver también: dirname()
flock -- Bloqueo de ficheros portable y asesorado
fnmatch -- Match filename against a pattern
chgrp
fopen -- Abre un fichero o una URL
fpassthru -- Saca todos los datos restantes del fichero
apuntado (PHP 3, PHP 4 )
fputs -- Escribe en el fichero apuntado chgrp -- Cambia el grupo de un fichero
fread -- Lee ficheros en plan binario
fscanf -- Parses input from a file according to a format
fseek -- Sitúa el apuntador a un fichero Descripción
fstat -- Gets information about a file using an open file
pointer
ftell -- Pregunta por la posición del apuntador de int chgrp ( string filename, mixed group)
lectura/escritura de un fichero
ftruncate -- Truncates a file to a given length Trata de cambiar el grupo al que pertenece el fichero
fwrite -- Escribe ficheros en plan binario filename al grupo group. Sólo el superusuario puede
glob -- Find pathnames matching a pattern cambiar el grupo de un fichero arbitrariamente; otros
is_dir -- Dice si el fichero nombrado es un directorio usuarios pueden cambiar el grupo del fichero a cualquier
is_executable -- Dice si el fichero nombrado es ejecutable grupo del cual el usuario sea miembro.
is_file -- Dice si el fichero nombrado es un fichero regular Devuelve TRUE en caso de éxito; en otro caso devuelve
is_link -- Dice si el fichero indicado es un enlace FALSE.
simbólico En Windows, no hace nada y devuelve TRUE.
is_readable -- Dice si el fichero indicado se puede leer Ver también chown() y chmod().
is_uploaded_file -- Tells whether the file was uploaded via
HTTP POST
is_writable -- Tells whether the filename is writable chmod
is_writeable -- Dice si se puede escribir en el fichero
indicado
link -- Crea un enlace fuerte (PHP 3, PHP 4 )
linkinfo -- Consigue información sobre un enlace chmod -- Cambia permisos de un fichero
lstat -- Da información sobre un fichero o enlace
simbólico Descripción
mkdir -- Crea un directorio
move_uploaded_file -- Moves an uploaded file to a new
location int chmod ( string filename, int mode)
parse_ini_file -- Parse a configuration file
pathinfo -- Returns information about a file path
Trata de cambiar los permisos del fichero especificado
pclose -- Cierra el fichero de proceso apuntado
por filename a los permisos dados por mode.
popen -- Abre el fichero de proceso apuntado
Cuidado que mode no es asumido de forma automática
readfile -- Muestra el contenido de un fichero
como un valor octal. Para asegurar que se hace la
readlink -- Devuelve el objetivo de un enlace simbólico
operación esperada necesitas anteponer un cero (0)
realpath -- Returns canonicalized absolute pathname
como prefijo del parámetro mode:
rename -- Renombra un fichero
rewind -- Rebobina la posición del apuntador al fichero chmod( "/somedir/somefile", 755 ); // decimal;
rmdir -- Elimina un directorio probablemente incorrecto
set_file_buffer -- Fija el buffer de fichero del fichero chmod( "/somedir/somefile", 0755 ); // octal; valor
apuntado correcto de mode
stat -- Da información sobre un fichero
Devuelve TRUE en caso de éxito y FALSE en otro caso.
symlink -- Crea un enlace simbólico Ver también chown() y chgrp().
tempnam -- Crea un fichero de nombre único
tmpfile -- Creates a temporary file
touch -- Fija la fecha de modificación de un fichero chown
umask -- Cambia la umask actual
unlink -- Borra un fichero
(PHP 3, PHP 4 )
chown -- Cambia el propietario de un fichero
basename

Descripción
(PHP 3, PHP 4 )
basename -- Devuelve la parte del path correspondiente
al nombre del fichero int chown ( string filename, mixed user)
Trata de cambiar el propietario del fichero filename al Esto es una entrada manual inútil para satisfacer a esas
usuario user. Sólo el superusuario puede cambiar el personas que están buscando unlink() o unset() en el
propietario de un fichero. lugar equivocado.
Devuelve TRUE en caso de éxito; en otro caso devuelve Ver también: unlink() para borrar ficheros, unset() para
FALSE. borrar variables.

Nota: En Windows, no hace nada y dirname


devuelve TRUE.

(PHP 3, PHP 4 )
Ver también chown() y chmod(). dirname -- Devuelve la parte del path correspondiente al
directorio

clearstatcache
Descripción

(PHP 3, PHP 4 )
clearstatcache -- Limpia la cache de estado de un fichero string dirname ( string path)

Descripción Dada una cadena (string) conteniendo el path a un


fichero, esta función devolverá el nombre del directorio.
En Windows, tanto la barra (/) como la barra inversa (\)
void clearstatcache ( void) son usadas como separadores de caracteres. En otros
entornos, debe usarse la barra directa (/).
Ejemplo 1. Ejemplo de dirname()
Invocar la llamada del sistema stat o lstat es bastante
costoso en la mayoría de los sistemas. Por lo tanto, el
resultado de la última llamada a cualquiera de las
funciones de estado (listadas abajo) es guardado para $path = "/etc/passwd";
usarlo en la próxima llamada de este tipo empleando el $file = dirname($path); // $file toma
mismo nombre de fichero. Si deseas forzar un nuevo el valor "/etc"
chequeo del estado del fichero, por ejemplo si el fichero Ver también: basename()
está siendo chequeado muchas veces y puede cambiar o
desaparecer, usa esta función para borrar los resultados
almacenados en memoria de la última llamada. disk_free_space
Este valor sólo es cacheado durante el tiempo de vida de
una petición simple.
Entre las funciones afectadas se incluyen stat(), lstat(), (PHP 4 >= 4.1.0)
file_exists(), is_writeable(), is_readable(), disk_free_space -- Returns available space in directory
is_executable(), is_file(), is_dir(), is_link(),
filectime(), fileatime(), filemtime(), fileinode(), Description
filegroup(), fileowner(), filesize(), filetype(), y
fileperms().
float disk_free_space ( string directory)
copy
Given a string containing a directory, this function will
return the number of bytes available on the
(PHP 3, PHP 4 ) corresponding filesystem or disk partition.
copy -- Copia un fichero Ejemplo 1. disk_free_space() example

Descripción
$df = disk_free_space("/"); // $df contains the
number of bytes
int copy ( string source, string dest) // available on "/"

Hace una copia de un fichero. Devuelve TRUE si la copia


disk_total_space
tiene éxito, y FALSE en otro caso.
Ejemplo 1. Ejemplo de copy()
(PHP 4 >= 4.1.0)
disk_total_space -- Returns the total size of a directory
if (!copy($file, $file.'.bak'))
{
print("failed to copy Description
$file...<br>\n");
}
float disk_total_space ( string directory)
Ver también: rename().
Given a string containing a directory, this function will
delete return the total number of bytes on the corresponding
filesystem or disk partition.
Ejemplo 1. disk_total_space() example
(no version information, might be only in CVS)
delete -- Una entrada manual inútil
$df = disk_total_space("/"); // $df contains
the total number of
Descripción
// bytes available on "/"

void delete ( string file)


diskfreespace The file pointer must be valid, and must point to a file
successfully opened by fopen(), popen(), or
fsockopen().
(PHP 3>= 3.0.7, PHP 4 )
diskfreespace -- Devuelve el espacio disponible en un
directorio fgetc

Descripción (PHP 3, PHP 4 )


fgetc -- Obtiene un caracter del fichero apuntado

float diskfreespace ( string directory)


Descripción
Dada una cadena (string) conteniendo el nombre de un
directorio, esta función devolverá el número de bytes string fgetc ( int fp)
disponibles en el disco correspondiente.
Ejemplo 1. Ejemplo de diskfreespace()
Devuelve una cadena (string) conteniendo un simple
caracter leido del fichero apuntado por fp. Devuelve
FALSE para EOF (como hace feof()).
$df = diskfreespace("/"); // $df contiene el
El apuntador al fichero debe ser valido, y debe apuntar a
numero de bytes
un fichero abierto con éxito por fopen(), popen(), o
// disponibles en "/"
fsockopen().
Ver también fread(), fopen(), popen(), fsockopen(), y
fgets().
fclose

fgetcsv
(PHP 3, PHP 4 )
fclose -- Cierra el apuntador a un fichero abierto
(PHP 3>= 3.0.8, PHP 4 )
fgetcsv -- Obtiene una línea del fichero apuntado y
Description extrae los campos CSV

int fclose ( int fp) Descripción

Se cierra el fichero apuntado por fp.


Devuelve TRUE en caso de éxito y FALSE en caso de array fgetcsv ( int fp, int length [, string delimiter])
fallo.
El apuntador al fichero debe ser válido y debe apuntarse Parecida a fgets() excepto que fgetcsv() parsea la línea
a un fichero abierto con éxito con fopen() o con que lee buscando campos en formato CSV y devuelve un
fsockopen(). array conteniendo los campos leidos. El delimitador de
campo es una coma, a menos que se especifique otro
delimitador con el tercer parámetro opcional.
feof fp debe ser un apuntador válido a un fichero abierto con
éxito por fopen(), popen(), o fsockopen()
(PHP 3, PHP 4 ) la longitud debe ser mayor que la línea más larga que
feof -- Verifica si el apuntador a un fichero está al final pueda encontrarse en le fichero CSV (permitiendo
del fichero (end-of-file) arrastrar caracteres de fin de línea)
fgetcsv() devuelve FALSE en caso de error, incluyendo el
fin de fichero.
Descripción NOTA: Una línea en blanco en un fichero CSV se devuelve
como un array que contiene un único campo nulo, y esto
no será tratado como un error.
int feof ( int fp) Ejemplo 1. Ejemplo de fgetcsv() - Leer e imprimir el
contenido completo de un fichero CSV
Devuelve TRUE si el apuntador del fichero está en EOF o
si ocurre un error; en otro caso devuelve FALSE.
The file pointer must be valid, and must point to a file El $row = 1;
apuntador al fichero debe ser válido, y debe apuntar a un $fp = fopen ("test.csv","r");
fichero abierto con éxito por fopen(), popen(), o while ($data = fgetcsv ($fp,
fsockopen(). 1000, ",")) {
$num = count ($data);
print "<p> $num fields in line
fflush $row: <br>";
$row++;
for ($c=0; $c<$num; $c++) {
(PHP 4 >= 4.0.1)
print $data[$c] . "<br>";
fflush -- Flushes the output to a file
}
}
Description fclose ($fp);

bool fflush ( resource handle) fgets

This function forces a write of all buffered output to the


(PHP 3, PHP 4 )
resource pointed to by the file handle handle. Returns
fgets -- Obtiene una línea del fichero apuntado
TRUE if successful, FALSE otherwise.
Descripción (PHP 4 >= 4.3.0)
file_get_contents -- Reads entire file into a string

string fgets ( int fp, int length)


Description
Devuelve una cadena de como mucho length - 1 bytes
leidos del fichero apuntado por fp. La lectura acaba string file_get_contents ( string filename [, int
cuando son leidos length - 1 bytes, cuando se llega a una use_include_path])
nueva línea (el caracter de nueva línea se incluye en el
valor devuelto), o cuando se llega a un EOF (lo que
ocurra primero). Identical to file(), except that file_get_contents()
Si ocurre un error, devuelve FALSE. returns the file in a string.
Fallos Comunes:
Los que hayan usado la semantica de 'C' de la función Nota: Esta función es segura
fgets deben darse cuenta de la diferencia que hay en
bináriamente.
como el EOF es devuelto por esta función.
El apuntador al fichero debe ser válido, y debe apuntar a
un fichero abierto con éxito con fopen(), popen(), o Sugerencia: Puede usar una URL
fsockopen(). como nombre de archivo con esta
A continuación un ejemplo sencillo: función si los "fopen wrappers" han
Ejemplo 1. Leyendo un fichero línea por línea sido activados. Consulte fopen()
para más detalles.

$fd = fopen
("/tmp/inputfile.txt", "r"); See also: fgets(), file(), fread(), include(), and
while (!feof($fd)) { readfile().
$buffer = fgets($fd,
4096); file
echo $buffer;
}
fclose ($fd); (PHP 3, PHP 4 )
Ver también fread(), fopen(), popen(), fgetc(), y file -- lee un fichero completo hacia un array
fsockopen().
Descripción
fgetss
array file ( string filename [, int use_include_path])
(PHP 3, PHP 4 )
fgetss -- Obtiene una línea del fichero apuntado y quita Idéntica a readfile(), excepto que file() devuelve el
las etiquetas HTML fichero en un array. Cada elemento del array
corresponde a una línea del fichero, con el caracter de
nueva línea incluido.
Descripción Se puede utilizar el segundo parámetro opcional y
ponerle el valor "1", si también se quiere buscar el
string fgetss ( int fp, int length [, string allowable_tags]) fichero en el include_path.
Ver también readfile(), fopen(), y popen().

Idéntica a fgets(), excepto que fgetss trata de quitar


cualquier etiqueta HTML y PHP del texto que lee. fileatime
Se puede utilizar el tercer parámetro opcional para
especificar etiquetas que no deben de quitarse.
(PHP 3, PHP 4 )
fileatime -- Obtiene la última fecha de acceso a un
Nota: allowable_tags fue añadido en fichero
PHP 3.0.13, PHP4B3.
Descripción
Ver también fgets(), fopen(), fsockopen(), popen(), y
strip_tags().
int fileatime ( string filename)

file_exists Devuelve la fecha a la que el fichero fue accedido por


última vez, o FALSE en caso de error.
(PHP 3, PHP 4 ) Los resultados de esta función son cacheados. Ver
file_exists -- Verifica si un fichero existe clearstatcache() para más detalles.

Descripción filectime

int file_exists ( string filename) (PHP 3, PHP 4 )


filectime -- Obtiene la fecha de cambio del inode del
fichero
Devuelve TRUE si el fichero especificado por filename
existe; y FALSE en otro caso.
El resultado de esta función es cacheado. Ver Descripción
clearstatcache() para más detalles.
int filectime ( string filename)
file_get_contents
Devuelve el momento en el que el fichero fue cambiado fileperms
por última vez, o FALSE en caso de error.
Los resultados de esta función son cacheados. Ver
clearstatcache() para más detalles. (PHP 3, PHP 4 )
fileperms -- Obtiene los permisos del fichero

filegroup
Descripción

(PHP 3, PHP 4 )
filegroup -- Obtiene el grupo de un fichero int fileperms ( string filename)

Devuelve los permisos del fichero, o FALSE en caso de


Descripción
error.
Los resultados de esta función son cacheados. Ver
int filegroup ( string filename) clearstatcache() para más detalles.

Devuelve el identificador (ID) de grupo del propietario del filesize


fichero, o FALSE en caso de un error. El ID del grupo es
devuelto en formato numérico, usar posix_getgrgid()
para obtener el nombre del grupo. (PHP 3, PHP 4 )
Los resultados de esta función son cacheados. Ver filesize -- Obtiene el tamaño del fichero
clearstatcache() para más detalles.
Descripción
fileinode
int filesize ( string filename)
(PHP 3, PHP 4 )
fileinode -- Obtiene el inode del fichero Devuelve el tamaño del fichero, o FALSE en caso de
error.
Los resultados de esta función son cacheados. Ver
Descripción
clearstatcache() para más detalles.

int fileinode ( string filename)


filetype

Devuelve el número de inode del fichero, o FALSE en


caso de un error. (PHP 3, PHP 4 )
Los resultados de esta función son cacheados. Ver filetype -- Obtiene el tipo de fichero
clearstatcache() para más detalles.
Descripción
filemtime
string filetype ( string filename)
(PHP 3, PHP 4 )
filemtime -- Obtiene la fecha de modificación del fichero Devuelve el tipo de fichero. Valores posibles son fifo,
char, dir, block, link, file, y unknown.
Devuelve FALSE si ocurre un error.
Descripción
Los resultados de esta función son cacheados. Ver
clearstatcache() para más detalles.
int filemtime ( string filename)
flock
Devuelve el momento en el que el fichero fue modificado
por última vez, o FALSE en caso de un error.
Los resultados de esta función son cacheados. Ver (PHP 3>= 3.0.7, PHP 4 )
clearstatcache() para más detalles. flock -- Bloqueo de ficheros portable y asesorado

fileowner Description

(PHP 3, PHP 4 ) bool flock ( int fp, int operation)


fileowner -- Obtiene el propietario del fichero
PHP soporta un método portable de bloquear ficheros
completos de manera asesorada (lo que significa que
Descripción
todos los programas que acceden tienen que usar el
mismo modo de bloqueo o éste no funcionará).
int fileowner ( string filename) flock() opera sobre fp el cual debe ser un apuntador a
un fichero abierto. operation toma uno de los siguientes
valores:
Devuelve el identificador (ID) de usuario del propietario
del fichero, o FALSE en caso de error. El ID de usuario se
devuelve en formato numérico, usar posix_getpwuid()
para obtener el nombre del usuario.
• Para que adquiera un bloqueo compartido
(lectura), fija operation a 1.
Los resultados de esta función son cacheados. Ver
clearstatcache() para más detalles. • Para adquirir un bloqueo exclusivo (escritura),
fija operation a 2.
mode puede ser cualquiera de lo siguiente:
• Para liberar un bloqueo (compartido o
exclusivo), fija operation a 3.
• Si no quieres que flock() bloquee mientras • 'r' - Abre para sólo lectura; sitúa el apuntador
está activado, suma 4 al valor de operation. del fichero al comienzo del mismo.
• 'r+' - Abre para lectura y escritura; situa el
flock() permite establece un modelo simple de apuntador del fichero al comienzo del fichero.
lectura/escritura el cual puede usarse en prácticamente
cualquier plataforma (incluyendo la mayoria de sistemas
• 'w' - Abre para sólo escritura; sitúa el
apuntador del fichero al comienzo del fichero y
Unix e incluso Windows).
trunca el fichero con longitud cero. Si el fichero
flock() devuelve TRUE en caso de éxito y FALSE en
no existe, trata de crearlo.
caso de error (ej. cuando no se puede establecer un
bloqueo). • 'w+' - Abre el fichero para lectura y escritura;
sitúa el apuntador del fichero al comienzo del
fichero y trunca el fichero con longitud cero. Si
fnmatch el fichero no existe, trata de crearlo.
• 'a' - Abre sólo para escribir (añadir); sitúa el
(PHP 4 >= 4.3.0) apuntador del fichero al final del mismo. Si el
fnmatch -- Match filename against a pattern fichero no existe, trata de crearlo.
• 'a+' - Abre para lectura y escritura
Description (añadiendo); sitúa el apuntador del fichero al
final del mismo. Si el fichero no existe, trata de
crearlo.
array fnmatch ( string pattern, string string [, int flags])

Además, mode puede contener la letra 'b'. Esto es útil


fnmatch() checks if the passed string would match the para sistemas que diferencian entre ficheros binarios y
given shell wildcard pattern. de texto (ej. es inútil en Unix). Si no se necesita, será
This is especialy usefull for filenames, but may also be ignorado.
used on regular strings. The average user may be used Puede usarse el tercer parámetro opcional y fijarlo a "1",
to shell patterns or at least in their simplest form to '?' si también se quiere buscar el fichero en el include_path.
and '*' wildcards so using fnmatch() instead of ereg() Ejemplo 1. Ejemplo de fopen()()
or preg_match() for frontend search expression input
may be way more convenient for non-programming
users.
Ejemplo 1. Checking a color name against a shell $fp = fopen("/home/rasmus/file.txt",
wildcard pattern. "r");
$fp = fopen("http://www.php.net/", "r");
$fp =
fopen("ftp://user:password@example.co
if(fnmatch("*gr[ae]y", m/", "w");
$color)) {
echo "some form of Si experimentas problemas a la hora de leer y escribir a
gray ..."; ficheros y estas usando la version de PHP como módulo
} para el servidor, recuerda que debes asegurar que los
ficheros y directorios que estas usando son accesibles al
See also glob(), ereg(), preg_match() and the unix proceso servidor.
manpage on fnmatch(3) for flag names (as long as they En la plataforma Windows, ten cuidado de escribir
are not documented here ). correctamente las barras invertidas en el path del fichero
(poniéndolas dobles), o usa barras directas.
fopen $fp =
fopen("c:\\data\\info.txt",
"r");
(PHP 3, PHP 4 )
fopen -- Abre un fichero o una URL Ver también fclose(), fsockopen(), y popen().

Descripción fpassthru

int fopen ( string filename, string mode [, int (PHP 3, PHP 4 )


use_include_path]) fpassthru -- Saca todos los datos restantes del fichero
apuntado
Si filename comienza con "http://" (no es sensible a
mayúsculas), se abre una conexión HTTP 1.0 hacia el Descripción
servidor especificado y se devuelve un apuntador de
fichero al comienzo del texto de respuesta.
No maneja redirecciones HTTP, por eso se debe incluir int fpassthru ( int fp)
una barra final cuando se trata de directorios.
Si filename comienza con "ftp://" (no es sensible a Lee hasta el EOF del fichero apuntado y escribe los
mayúsculas), se abre una conexión ftp hacia el servidor resultados a la salida estándar (stdout).
especificado y se devuelve un apuntador al fichero Si ocurre un error, fpassthru() devuelve FALSE.
requerido. Si el servidor no soporta ftp en modo pasivo, El apuntador al fichero debe ser válido, y debe apuntar a
esto fallará. Se pueden abrir fichero via ftp para leer o un fichero abierto con éxito por fopen(), popen(), o
para escribir (pero no ambas cosas simultáneamente). fsockopen(). El fichero se cierra cuando fpassthru()
Si filename no comienza con nada de lo anterior, el termina de leerlo (dejando fp sin ninguna utilidad).
fichero se abre del sistema de ficheros, y se devuelve un Si sólo quieres volcar el contenido de un fichero a stdout
apuntador al fichero abierto. puedes If you just want to dump the contents of a file to
Si el abrir el fichero falla, la función devuelve FALSE.
stdout you may usar la función readfile(), la cual te libra
while ($userinfo = fscanf ($handle,
de la llamada a fopen().
"%s\t%s\t%s\n")) {
Ver también readfile(), fopen(), popen(), y
list ($name, $profession,
fsockopen()
$countrycode) = $userinfo;
//... do something with the values
fputs }
fclose($handle);
Ejemplo 2. users.txt
(PHP 3, PHP 4 )
fputs -- Escribe en el fichero apuntado
javier argonaut
Descripción pe
hiroshi sculptor
jp
int fputs ( int fp, string str [, int length]) robert slacker us
luigi florist it
fputs() es un alias de fwrite(), y es idéntico a él en
todo. Notar que el parámetro length es opcional y si no
se pone la cadena entera será escrita. Nota: Prior to PHP 4.3.0, the
maximum number of characters
read from the file was 512 (or up to
fread the first \n, whichever came first). As
of PHP 4.3.0 arbitrarily long lines will
be read and scanned.
(PHP 3, PHP 4 )
fread -- Lee ficheros en plan binario
See also fread(), fgets(), fgetss(), sscanf(), printf(),
and sprintf().
Descripción

fseek
string fread ( int fp, int length)

fread() lee hasta length bytes del apuntador de fichero (PHP 3, PHP 4 )
referenciado por fp. La lectura acaba cuando length fseek -- Sitúa el apuntador a un fichero
bytes se han leido o se alcanza EOF, lo que ocurra
primero.
Descripción
// Mete el contenido de un fichero
en una cadena
$filename = int fseek ( int fp, int offset)
"/usr/local/something.txt";
$fd = fopen ($filename, "r"); Fija el indicador de posición del fichero referenciado por
$contents = fread ($fd, filesize fp a tantos bytes como indica offset. Es equivalente a la
($filename)); llamada (en C) fseek(fp, offset, SEEK_SET).
fclose ($fd); Si va bien, devuelve 0; en otro caso, devuelve -1. Tener
Ver también fwrite(), fopen(), fsockopen(), popen(), en cuenta que situarse más alla de EOF no se considera
fgets(), fgetss(), file(), y fpassthru(). un error.
No puede usarse sobre apuntadores de ficheros
devueltos por fopen() si usan los formatos "http://" or
fscanf "ftp://".
Ver también ftell() y rewind().
(PHP 4 >= 4.0.1)
fscanf -- Parses input from a file according to a format fstat

Description (PHP 4 )
fstat -- Gets information about a file using an open file
pointer
mixed fscanf ( resource handle, string format [, string
var1])
Description
The function fscanf() is similar to sscanf(), but it takes
its input from a file associated with handle and interprets array fstat ( resource handle)
the input according to the specified format. If only two
parameters were passed to this function, the values
parsed will be returned as an array. Otherwise, if optional Gathers the statistics of the file opened by the file
parameters are passed, the function will return the pointer handle. This function is similar to the stat()
number of assigned values. The optional parameters function except that it operates on an open file pointer
must be passed by reference. instead of a filename.
Any whitespace in the format string matches any Returns an array with the statistics of the file with the
whitespace in the input stream. This means that even a following elements:
tab \t in the format string can match a single space
character in the input stream.
1. device
Ejemplo 1. fscanf() Example
2. inode
3. number of links
4. user id of owner
$handle = fopen ("users.txt","r"); 5. group id owner
6. device type if inode device * (PHP 4 >= 4.3.0)
7. size in bytes glob -- Find pathnames matching a pattern
8. time of last access
9. time of last modification
10. time of last change Description
11. blocksize for filesystem I/O *
12. number of blocks allocated array glob ( string pattern [, int flags])

* - only valid on systems supporting the st_blksize type-- The glob() function searches for all the pathnames
other systems (i.e. Windows) return -1 matching pattern according to the rules used by the
The results of this function are cached. See shell. No tilde expansion or parameter substitution is
clearstatcache() for more details. done.
Returns an array containing the matched files/directories
or FALSE on error.
ftell
Valid flags:

(PHP 3, PHP 4 )
ftell -- Pregunta por la posición del apuntador de • GLOB_MARK - Adds a slash to each item
lectura/escritura de un fichero returned
• GLOB_NOSORT - Return files as they appear
Descripción in the directory (no sorting)
• GLOB_NOCHECK - Return the search pattern
if no files matching it were found
int ftell ( int fp)
• GLOB_NOESCAPE - Backslashes do not quote
Devuelve la posición del apuntador de fichero metacharacters
referenciado por fp; es decir, la distancia en la secuencia • GLOB_BRACE - Expands {a,b,c} to match 'a',
del fichero. 'b', or 'c'
Si ocurre un error, devuelve FALSE.
El apuntador al fichero debe ser válido, y debe referirse a • GLOB_ONLYDIR - Return only directory
The file pointer must be valid, and must point to a file un entries which match the pattern
fichero abierto con éxito por fopen() o popen().
Ver también fopen(), popen(), fseek() y rewind(). Ejemplo 1. Convenient way how glob() can replace
opendir() and friends.
ftruncate

<?php
(PHP 4 ) foreach (glob("*.txt") as $filename) {
ftruncate -- Truncates a file to a given length echo "$filename size " .
filesize($filename) . "\n";
}
Description
/* Output will look something like:
bool ftruncate ( resource handle, int size)
funclist.txt size 44686
funcsummary.txt size 267625
Takes the filepointer, handle, and truncates the file to quickref.txt size 137820
length, size. Devuelve TRUE si todo fue bien, FALSE en
caso de fallo. */
?>
fwrite See also opendir(), readdir() and closedir(),
fnmatch().

(PHP 3, PHP 4 )
fwrite -- Escribe ficheros en plan binario is_dir

Descripción (PHP 3, PHP 4 )


is_dir -- Dice si el fichero nombrado es un directorio

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


Descripción
fwrite() escribe el contenido de string al fichero
apuntado por fp. Si se da el argumento length, la bool is_dir ( string filename)
escritura acaba antes de que length bytes sean escritos
o se alcance el final de string, lo que ocurra primero.
Tener en cuenta que si se da el argumento length, Devuelve TRUE si el nombre del fichero existe y es un
entonces la opción de configuración directorio.
magic_quotes_runtime será ignorada y los caracteres de Los resultados de esta función son cacheados. Ver
barra no se quitarán de la cadena string. clearstatcache() para más detalles.
Ver también fread(), fopen(), fsockopen(), popen(), y Ver también is_file() y is_link().
fputs().
is_executable
glob
(PHP 3, PHP 4 )
is_executable -- Dice si el fichero nombrado es ejecutable is_uploaded_file -- Tells whether the file was uploaded via
HTTP POST

Descripción
Description

bool is_executable ( string filename)


bool is_uploaded_file ( string filename)
Devuelve TRUE si el fichero indicado existe y es
ejecutable. Returns TRUE if the file named by filename was
Los resultados de esta función son cacheados. Ver uploaded via HTTP POST. This is useful to help ensure
clearstatcache() para más detalles. that a malicious user hasn't tried to trick the script into
Ver también is_file() y is_link(). working on files upon which it should not be working--for
instance, /etc/passwd.
This sort of check is especially important if there is any
is_file chance that anything done with uploaded files could
reveal their contents to the user, or even to other users
on the same system.
(PHP 3, PHP 4 )
is_uploaded_file() is available only in versions of PHP 3
is_file -- Dice si el fichero nombrado es un fichero regular
after PHP 3.0.16, and in versions of PHP 4 after 4.0.2. If
you are stuck using an earlier version, you can use the
Descripción following function to help protect yourself:

bool is_file ( string filename) Nota: The following example will


not work in versions of PHP 4 after
4.0.2. It depends on internal
Devuelve TRUE si el fichero nombrado existe y es un functionality of PHP which changed
fichero regular. after that version.
Los resultados de esta función son cacheados. Ver
clearstatcache() para más detalles.
Ver también is_dir() y is_link().
<?php
/* Userland test for uploaded file. */
is_link function is_uploaded_file($filename) {
if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
$tmp_file = dirname(tempnam('', ''));
(PHP 3, PHP 4 ) }
is_link -- Dice si el fichero indicado es un enlace $tmp_file .= '/' . basename($filename);
simbólico /* User might have trailing slash in php.ini... */
return (ereg_replace('/+', '/', $tmp_file) == $filename);
}
Descripción
/* This is how to use it, since you also don't have
bool is_link ( string filename) * move_uploaded_file() in these older versions: */
if (is_uploaded_file($HTTP_POST_FILES['userfile'])) {
copy($HTTP_POST_FILES['userfile'],
Devuelve TRUE si el fichero indicado existe y es un "/place/to/put/uploaded/file");
enlace simbólico. } else {
Los resultados de esta función son cacheados. Ver echo "Possible file upload attack: filename
clearstatcache() para más detalles. '$HTTP_POST_FILES[userfile]'.";
Ver también is_dir() y is_file(). }
?>
is_readable See also move_uploaded_file(), and the section
Handling file uploads for a simple usage example.

(PHP 3, PHP 4 )
is_readable -- Dice si el fichero indicado se puede leer is_writable

Descripción (PHP 4 )
is_writable -- Tells whether the filename is writable

bool is_readable ( string filename)


Description
Devuelve TRUE si el fichero indicado existe y se puede
leer. bool is_writable ( string filename)
Recuerda que PHP puede acceder al fichero con el
identificador de usuario con el que el servidor web se
ejecuta (a menudo 'nobody'). No se tienen en cuenta las Returns TRUE if the filename exists and is writable. The
limitaciones de modos seguros. filename argument may be a directory name allowing
Los resultados de esta función son cacheados. Ver you to check if a directory is writeable.
clearstatcache() para más detalles. Keep in mind that PHP may be accessing the file as the
Ver también is_writeable(). user id that the web server runs as (often 'nobody'). Safe
mode limitations are not taken into account.
The results of this function are cached. See
is_uploaded_file clearstatcache() for more details.
This function will not work on remote files; the file to be
examined must be accessible via the server's filesystem.
(PHP 3>= 3.0.17, PHP 4 >= 4.0.3) See also is_readable().
is_writeable enlace simbólico, y no los del fichero al que apunta el
enlace simbólico.
Devuelve un array conteniendo los datos del fichero con
(PHP 3, PHP 4 ) los siguientes elementos:
is_writeable -- Dice si se puede escribir en el fichero
indicado
1. dispositivo (device)
2. inode
Descripción 3. número de enlaces
4. id de usuario del propietario
5. id de grupo del propietario
bool is_writeable ( string filename)
6. tipo de disposivo si es un inode device *
7. tamaño en bytes
Devuelve TRUE si el fichero indicado existe y se puede 8. fecha del último acceso
escribir en él. El argumento filename puede ser el 9. fecha de la última modificación
nombre de un directorio, lo que permite verificar si un 10. fecha del último cambio
directorio tiene permiso de escritura. 11. tamaño de bloque para el sistema I/O *
Recuerda que PHP puede acceder al fichero con el 12. número de bloques ocupados
identificador de usuario con el que el servidor web se
ejecuta (a menudo 'nobody'). No se tienen en cuenta las
limitaciones de modos seguros. * - sólo válido en sistemas que soportan el tipo st_blksize
Los resultados de esta función son cacheados. Ver --otros sistemas (como Windows) devuelven -1
clearstatcache() para más detalles. Los resultados de esta función son cacheados. Ver
Ver también is_readable(). clearstatcache() para más detalles.

link mkdir

(PHP 3, PHP 4 ) (PHP 3, PHP 4 )


link -- Crea un enlace fuerte mkdir -- Crea un directorio

Descripción Descripción

int link ( string target, string link) int mkdir ( string pathname, int mode)

link() crea un enlace fuerte. Trata de crear el directorio especificado por pathname.
Ver también symlink() para crear enlaces débiles, y Ten en cuenta que debes especifiar el modo como un
readlink() junto con linkinfo(). número octal, lo que significa que debes anteponerle un
0 al número.
mkdir
linkinfo
("/path/to/my/dir",
0700);
(PHP 3, PHP 4 ) Devuelve TRUE en caso de éxito y FALSE en caso de
linkinfo -- Consigue información sobre un enlace fallo.
Ver también rmdir().
Descripción
move_uploaded_file
int linkinfo ( string path)
(PHP 4 >= 4.0.3)
linkinfo() da el campo st_dev de la extructura stat de move_uploaded_file -- Moves an uploaded file to a new
UNIX C devuelto por la llamada al sistema lstat. Esta location
función se usa para verificar si un enlace (apuntado por
path) existe realmente (usando el mismo método que la
Description
macro S_ISLNK definida en stat.h). Devuelve 0 o FALSE
en caso de error.
Ver también symlink(), link(), y readlink(). bool move_uploaded_file ( string filename, string
destination)
lstat
This function checks to ensure that the file designated by
filename is a valid upload file (meaning that it was
(PHP 3>= 3.0.4, PHP 4 ) uploaded via PHP's HTTP POST upload mechanism). If the
lstat -- Da información sobre un fichero o enlace file is valid, it will be moved to the filename given by
simbólico destination.
If filename is not a valid upload file, then no action will
Descripción occur, and move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for
some reason, no action will occur, and
array lstat ( string filename) move_uploaded_file() will return FALSE. Additionally, a
warning will be issued.
This sort of check is especially important if there is any
Reúne los datos del fichero o enlace simbólico indicado chance that anything done with uploaded files could
por filename. Esta función es idéntica a la función stat() reveal their contents to the user, or even to other users
excepto que si el nombre en el parámetro filename es un on the same system.
enlace simbólico, son devueltos los datos (status) del
Nota: Cuando safe-mode (modo-
seguro) está activado, PHP
[second_section]
comprueba si el fichero(s)/directorios
path = /usr/local/bin
que vas a utilizar, tienen la misma
URL =
UID que el script que está siendo
"http://www.example.com/~usern
ejecutado.
ame"
Ejemplo 2. parse_ini_file() example
Nota: move_uploaded_file() is not
affected by the normal safe mode
UID-restrictions. This is not unsafe <?php
because move_uploaded_file()
only operates on files uploaded via define ('BIRD', 'Dodo bird');
PHP.
// Parse without sections
$ini_array =
Aviso parse_ini_file("sample.ini");
If the destination file already exists, it will be overwritten. print_r($ini_array);
See also is_uploaded_file(), and the section Handling // Parse with sections
file uploads for a simple usage example. $ini_array =
parse_ini_file("sample.ini", TRUE);
parse_ini_file print_r($ini_array);

?>
(PHP 4 ) Would produce:
parse_ini_file -- Parse a configuration file
Array
(
Description [one] => 1
[five] => 5
[animal] => Dodo bird
array parse_ini_file ( string filename [, bool [path] => /usr/local/bin
process_sections]) [URL] =>
http://www.example.com/~username
parse_ini_file() loads in the ini file specified in filename, )
and returns the settings in it in an associative array. By Array
setting the last process_sections parameter to TRUE, you (
get a multidimensional array, with the section names and [first_section] => Array
settings included. The default for process_sections is (
FALSE [one] => 1
[five] => 5
[animal] = Dodo bird
Nota: This function has nothing to )
do with the php.ini file. It is already
processed, the time you run your [second_section] => Array
script. This function can be used to (
read in your own application's [path] => /usr/local/bin
configuration files. [URL] =>
http://www.example.com/~username
)
Nota: If a value in the ini file
contains any non-alphanumeric
)
characters it needs to be enclosed in
double-quotes (").
pathinfo
Nota: Since PHP 4.2.1 this function
is also affected by safe_mode and
open_basedir. (PHP 4 >= 4.0.3)
pathinfo -- Returns information about a file path

The structure of the ini file is similar to that of the


php.ini's. Description
Constants may also be parsed in the ini file so if you
define a constant as an ini value before running array pathinfo ( string path)
parse_ini_file(), it will be integrated into the results.
Only ini values are evaluated. For example:
Ejemplo 1. Contents of sample.ini pathinfo() returns an associative array containing
information about path. The following array elements are
returned: dirname, basename and extension.
; This is a sample configuration Ejemplo 1. pathinfo() Example
file
; Comments start with ';', as in
php.ini <?php

[first_section] $path_parts =
one = 1 pathinfo("/www/htdocs/index.html");
five = 5
animal = BIRD echo $path_parts["dirname"] . "\n";
int readfile ( string filename [, int use_include_path])
echo $path_parts["basename"] .
"\n";
echo $path_parts["extension"] . "\n"; Lee un fichero y lo escribe a la salida estándar.
Devuelve el número de bytes leidos del fichero. Si ocurre
?> un error, se devuelve FALSE y a menos que la función
fuera llamada como @readfile, se imprime un mensaje
Would produce:
de error
/ Si filename comienzo por "http://" (no es sensible a
www/htdo mayúsculas), se abre una conexión HTTP 1.0 al servidor
cs especificado y el texto de la respuesta se escribe a la
index.htm salida estándar.
l No maneja redirecciones HTTP, por eso se debe incluir
html una barra final cuando se trata de directorios.
Si filename comienza con "ftp://" (no es sensible a
mayúsculas), se abre una conexión ftp al servidor
Nota: For information on retrieving especificado y el fichero que se pide se escribe en la
the current path info, read the salida estándar. Si el servidor no soporta ftp en modo
section on predefined reserved pasivo, la función fallará.
variables. Si filename no comienza con ninguna de las cadenas
anteriores, el fichero será abierto del sistema de ficheros
y su contenido escrito en la salida estándar.
See also dirname(), basename(), parse_url() and Se puede usar el segundo parámetro opcional y fijarlo a
realpath(). "1", si si quieres que también se busque el fichero en el
include_path.
Ver también fpassthru(), file(), fopen(), include(),
pclose
require(), y virtual().

(PHP 3, PHP 4 )
readlink
pclose -- Cierra el fichero de proceso apuntado

(PHP 3, PHP 4 )
Descripción
readlink -- Devuelve el objetivo de un enlace simbólico

int pclose ( int fp)


Descripción

Cierra un fichero que representa un tuberia (pipe) abierta


con popen(). string readlink ( string path)
El apuntador al fichero debe ser válido, y debe haber sido
devuelto por una llamada con éxito a popen(). readlink() hace lo mismo que la función C readlink C y
Devuelve el estado de terminación del proceso que devuelve el contenido del path del enlace simbólico o 0
estaba ejecutándose. en caso de error.
Ver también popen(). Ver también symlink(), readlink() y linkinfo().

popen realpath

(PHP 3, PHP 4 ) (PHP 4 )


popen -- Abre el fichero de proceso apuntado realpath -- Returns canonicalized absolute pathname

Descripción Description

int popen ( string command, string mode) string realpath ( string path)

Abre una tubería (pipe) a un proceso ejecutado haciendo realpath() expands all symbolic links and resolves
fork al comando dado por command references to '/./', '/../' and extra '/' characters in the
Devuelve un apuntador de fichero idéntico al devuelto input path and return the canonicalized absolute
por fopen(), excepto que este es unidireccional (sólo pathname. The resulting path will have no symbolic link,
puede usarse o para leer o para escribir) y debe cerrarse '/./' or '/../' components.
con pclose(). Este apuntador puede usarse con fgets(), realpath() returns FALSE on failure, e.g. if the file does
fgetss(), y fputs(). not exists.
Si ocurre un error, devuelve FALSE. Ejemplo 1. realpath() example
$fp = popen
("/bin/ls", "r");
$real_path = realpath
Ver también pclose().
("../../index.php");
See also: basename(), dirname(), and pathinfo().
readfile

rename
(PHP 3, PHP 4 )
readfile -- Muestra el contenido de un fichero
(PHP 3, PHP 4 )
rename -- Renombra un fichero
Descripción
Descripción array stat ( string filename)

int rename ( string oldname, string newname) Recoje los datos sobre el fichero indicado por filename.
Devuelve un array conteniendo los datos del fichero con
los siguientes elementos:
Trata de renombrar oldname como newname.
Devuelve TRUE en caso de éxito y FALSE en caso de
fallo. 1. dispositivo (device)
2. inode
3. modo de protección del inode
rewind 4. número de enlaces
5. id de usuario del propietario
6. id de grupo del propietario
(PHP 3, PHP 4 )
7. tipo de dispositivo si es un inode device *
rewind -- Rebobina la posición del apuntador al fichero
8. tamaño en bytes
9. fecha del último acceso access
Descripción 10. fecha de la última modificación
11. fecha del último cambio
12. tamaño del bloque para el sistema I/O *
int rewind ( int fp) 13. número de bloques ocupados

Fija el indicador de posición del fichero dado por fp al * - sólo válido en sistemas que soportan el tipo st_blksize
comienzo de del fichero. --otros sistemas (como Windows) devuelven -1
Si ocurre un error, devuelve 0. Los resultados de esta función son cacheados. Ver
El apuntador al fichero debe ser válido, y debe apuntar a clearstatcache() para más detalles.
un fichero abierto con éxito por fopen().
Ver también fseek() y ftell().
symlink
rmdir
(PHP 3, PHP 4 )
symlink -- Crea un enlace simbólico
(PHP 3, PHP 4 )
rmdir -- Elimina un directorio
Descripción
Descripción
int symlink ( string target, string link)
int rmdir ( string dirname)
symlink() crea un enlace simbólico del objetivo target
con el nombre especificado por link.
Trata de eliminar el directorio indicado por pathname. El Ver también link() para crear enlaces fuertes, y
directorio debe estar vacio, y los permisos relevantes readlink() junto con linkinfo().
deben permitir esto.
Si ocurre un error, devuelve 0.
Ver también mkdir(). tempnam

set_file_buffer (PHP 3, PHP 4 )


tempnam -- Crea un fichero de nombre único
(PHP 3>= 3.0.8, PHP 4 >= 4.0.1)
set_file_buffer -- Fija el buffer de fichero del fichero Descripción
apuntado

string tempnam ( string dir, string prefix)


Description
Crea un fichero temporal de nombre único en el
int fwrite ( int fp, int buffer) directorio especificado. Si el directorio no existe
tempnam() puede generar un fichero en el directorio
temporal del sistema.
set_file_buffer() fija el buffer para operaciones de El comportamiento de la función tempnam() depende
escritura en el apuntador de fichero fp con buffer bytes. del sistema. En Windows la variable de entorno TMP se
Si buffer es 0 entonces las operaciones de escritura no impone sobre el parámetro dir, en Linux la variable de
usan un buffer intermedio. entorno TMPDIR tiene preferencia, mientras que en SVR4
La función devuelve 0 en caso de éxito, o EOF si la siempre se usará el parámetro dir si si el directorio al que
petición no se puede realizar. apunta existe. Consulta la documentación del sistema
Tener en cuenta que por defecto cualquier fopen hace sobre la función tempnam(3) en caso de duda.
una llamada a set_file_buffer de 8K. Devuelve el nombre del nuevo fichero temporal, o una
Ver también fopen(). cadena nula en caso de fallo.
Ejemplo 1. Ejemplo de tempnam()
stat

$tmpfname = tempnam
(PHP 3, PHP 4 ) ("/tmp", "FOO");
stat -- Da información sobre un fichero

tmpfile
Descripción
(PHP 3>= 3.0.13, PHP 4 ) XXXI. Funciones Forms Data Format (Formato de
tmpfile -- Creates a temporary file Datos de Formularios)

Description El Formato de Datos de Formulario (FDF) está diseñado


para el manejo de formularios en archivos PDF. Se
aconseja leer la información disponible en
resource tmpfile ( void) http://partners.adobe.com/asn/developer/acrosdk/forms.
html para más información sobre lo que es FDF y cómo
Creates a temporary file with an unique name in write se usa en general.
mode, returning a file handle similar to the one returned
by fopen(). The file is automatically removed when
Nota: Actualmente Adobe sólo
closed (using fclose()), or when the script ends.
proporciona una versión compatible
For details, consult your system documentation on the
con libc5 para Linux. Las pruebas
tmpfile(3) function, as well as the stdio.h header file.
con glibc2 provocaron un fallo de
Ejemplo 1. tmpfile() example
segmentado. Si alguien es capaz de
hacerla funcionar, por favor
coméntelo en esta página.
$temp = tmpfile();
fwrite($temp, "writing to
tempfile"); Nota: Si tiene problemas
fclose($temp); // this configurando php con soporte de
removes the file fdftk, compruebe si el archivo de
See also tempnam(). cabecera FdfTk.h y la librería
libFdfTk.so están en su lugar
correcto. Deberían encontrarse
touch respectivamente en fdftk-dir/include
y en fdftk-dir/lib. Este problema no
se dará si se limita a desempaqueta
(PHP 3, PHP 4 ) la distribucón del FtdTk.
touch -- Fija la fecha de modificación de un fichero

La idea general del FDF es similar a los formularios


Descripción HTML. La diferencia básicamente está en el formato en
que se transmiten los datos al servidor cuando se pulsa
el botón de envío (este es realmente el Formato de Datos
int touch ( string filename, int time)
de Formulario) y el formato del formulario en sí mismo
(que es el Formato de Documento Portable, PDF).
Trata de fijar la fecha de modificación del fichero Procesar lo datos del FDF es una de las características
indicado por filename al valor dado por time. Si no se que proporcionan las funciones fdf. Pero aún hay más.
pone la opción time, se utiliza la fecha actual. Uno también puede tomar un formulario PDF y rellenar
Si el fichero no existe, será creado. los campos de entrada con datos sin modificar el
Devuelve TRUE en caso de éxito y FALSE en otro caso. formulario en sí mismo. En dicho caso, lo que se hace es
crear un documento FDF (fdf_create()), fijar los valores
de cada campo de entrada (fdf_set_value()) y asociarlo
umask con un formulario PDF (fdf_set_file()). Finalmente, debe
ser enviado al navegador con el MimeType
application/vnd.fdf. El plug-in de Acrobar reader de su
(PHP 3, PHP 4 )
navegador reconoce el MimeType, lee el formulario PDF
umask -- Cambia la umask actual
asociado y rellena los datos a partir del documento FDF.
Los siguientes ejemplos muestran cómo se evalúan los
Descripción datos de los formularios.
Ejemplo 1. Evaluando un documento FDF

int umask ( int mask)


<?php
umask() fija las umask PHP con la mascara & 0777 y y // Guarda los datos FDF en un archivo temporal
devuelve la antigua umask. Cuando PHP se está usando $fdffp = fopen("test.fdf", "w");
como un módulo del servidor, la umask se restaura fwrite($fdffp, $HTTP_FDF_DATA,
cuando cada petición es finalizada. strlen($HTTP_FDF_DATA));
umask() sin argumentos sólamente devuelve la umask fclose($fdffp);
actual.
// Abre archivo temporal y evalúa los datos
// El formulario pdf contenía varios campos de texto
unlink con los nombres
// volumen, fecha, comentario, editorial, preparador, y
dos casillas de verificación
(PHP 3, PHP 4 ) // muestra_editorial y muestra_preparador.
unlink -- Borra un fichero $fdf = fdf_open("test.fdf");
$volume = fdf_get_value($fdf, "volumen");
Descripción echo "El campo volumen tiene el valor
'<B>$volume</B>'<BR>";

int unlink ( string filename) $date = fdf_get_value($fdf, "fecha");


echo "El campo fecha tiene el valor
'<B>$date</B>'<BR>";
Borra el fichero filename. Es similar a la función unlink()
del Unix C.
$comment = fdf_get_value($fdf, "comentario");
Devuelve 0 o FALSE en caso de error.
echo "El campo comentario tiene el valor
Ver también rmdir() para borrar directorios.
'<B>$comment</B>'<BR>"; <?php
$fdf = fdf_create();
if(fdf_get_value($fdf, "muestra_editorial") == "On") { fdf_add_doc_javascript($fdf, "PlusOne", "function
$publisher = fdf_get_value($fdf, "editorial"); PlusOne(x)\r{\r return x+1;\r}\r");
echo "El campo editorial tiene el valor fdf_save($fdf);
'<B>$publisher</B>'<BR>"; ?>
} else
echo "No se debe mostrar la editorial.<BR>";
will create a FDF like this:
if(fdf_get_value($fdf, "muestra_preparador") == "On")
{
$preparer = fdf_get_value($fdf, "preparador"); %FDF-1.2
echo "El campo preparador tiene el valor %âãÏÓ
'<B>$preparer</B>'<BR>"; 1 0 obj
} else <<
echo "No se debe mostrar el preparador.<BR>"; /FDF << /JavaScript << /Doc [ (PlusOne)(function
fdf_close($fdf); PlusOne\(x\)\r{\r return x+1;\r}\r)] >> >>
?> >>
Tabla de contenidos endobj
fdf_add_doc_javascript -- Adds javascript code to the FDF trailer
document <<
fdf_add_template -- Adds a template into the FDF /Root 1 0 R
document
fdf_close -- Cerrar un documento FDF >>
fdf_create -- Crear un documento FDF %%EOF
fdf_errno -- Return error code for last fdf operation
fdf_error -- Return error description for fdf error code
fdf_get_ap -- Get the appearance of a field fdf_add_template
fdf_get_attachment -- Extracts uploaded file embedded in
the FDF
fdf_get_encoding -- Get the value of the /Encoding key (PHP 3>= 3.0.13, PHP 4 )
fdf_get_file -- Obtener el valor de la clave /F fdf_add_template -- Adds a template into the FDF
fdf_get_status -- Obtener el valor de la clave /STATUS document
fdf_get_value -- Obtener el valor de un campo
fdf_get_version -- Gets version number for FDF api or file
Description
fdf_header -- Sets FDF-specific output headers
fdf_next_field_name -- Obtener el nombre del siguiente
campo bool fdf_add_template ( int fdfdoc, int newpage, string
fdf_open_string -- Read a FDF document from a string filename, string template, int rename)
fdf_open -- Abrir un documento FDF
fdf_save_string -- Returns the FDF document as a string
fdf_save -- Guardar un documeto FDF Aviso
fdf_set_ap -- Ajusta la apariencia de un campo
fdf_set_encoding -- Sets FDF character encoding Esta función no está documentada actualmente, solamente
fdf_set_file -- Fijar el valor de la clave /F se encuentra disponible la lista de parametros.
fdf_set_flags -- Sets a flag of a field
fdf_set_javascript_action -- Sets an javascript action of a
field fdf_close
fdf_set_opt -- Sets an option of a field
fdf_set_status -- Fija el valor de la clave /STATUS
(PHP 3>= 3.0.6, PHP 4 )
fdf_set_submit_form_action -- Sets a submit form action
fdf_close -- Cerrar un documento FDF
of a field
fdf_set_target_frame -- Set target frame for form display
fdf_set_value -- Fijar el valor de un campo Descripción
fdf_set_version -- Sets version number for a FDF file

void fdf_close ( int fdf_document)


fdf_add_doc_javascript
La función fdf_close() cierra un documento FDF.
(PHP 4 >= 4.3.0) Vea también fdf_open().
fdf_add_doc_javascript -- Adds javascript code to the FDF
document
fdf_create

Description
(PHP 3>= 3.0.6, PHP 4 )
fdf_create -- Crear un documento FDF
bool fdf_add_doc_javascript ( resource fdfdoc, string
script_name, string script_code)
Descripción

Adds a script to the FDF, which Acrobat then adds to the


doc-level scripts of a document, once the FDF is imported int fdf_create ( void )
into it. It is strongly suggested to use '\r' for linebreaks
within script_code. La función fdf_create() crea un documento FDF nuevo.
Ejemplo 1. Adding JavaScript code to a FDF Esta función se necesita si se desea rellenar los campos
de entrada en un documento PDF.
Ejemplo 1. Rellenando un documento PDF
(PHP 4 >= 4.3.0)
fdf_get_attachment -- Extracts uploaded file embedded in
the FDF
<?php
$outfdf = fdf_create();
Description
fdf_set_value($outfdf, "volumen",
$volume, 0);
array fdf_get_attachment ( resource fdf_document,
fdf_set_file($outfdf, string fieldname, string savepath)
"http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf); Extracts a file uploaded by means of the "file selection"
Header("Content-type: field fieldname and stores it under savepath. savepath
application/vnd.fdf"); may be the name of a plain file or an existing directory in
$fp = fopen("outtest.fdf", "r"); which the file is to be created under its original name.
fpassthru($fp); Any existing file under the same name will be
unlink("outtest.fdf"); overwritten.
?>
Vea también fdf_close(), fdf_save(), fdf_open(). Nota: There seems to be no other
way to find out the original filename
but to store the file using a directory
fdf_errno as savepath and check for the
basename it was stored under.
(PHP 4 >= 4.3.0)
fdf_errno -- Return error code for last fdf operation The returned array contains the following fields:

Description
• path - path were the file got stored

int fdf_errno ( void)


size - size of the stored file in bytes
fdf_errno() returns the error code set by the last fdf_...
() function call. This is zero for a successfull operation or type - mimetype if given in the FDF
a non-zero error code on failure. A textual description
may be obtained using the fdf_error() function.
See also fdf_error(). Ejemplo 1. Storing an uploaded file

fdf_error <?php
$fdf =
fdf_open_string($HTTP_FDF_DATA);
(PHP 4 >= 4.3.0)
$data = fdf_get_attachment($fdf,
fdf_error -- Return error description for fdf error code
"filename", "/tmpdir");
echo "The uploaded file is stored in
Description $data[path]";
?>

string fdf_error ( [int error_code])


fdf_get_encoding
fdf_error() returns a textual description for the fdf error
code given in error_code. The function uses the internal
(PHP 4 >= 4.3.0)
error code set by the last operation if no error_code is
fdf_get_encoding -- Get the value of the /Encoding key
given, so fdf_error() is a convenient shortcut for
fdf_error(fdf_errno()).
See also fdf_errno(). Description

fdf_get_ap string fdf_get_encoding ( resource fdf_document)

(PHP 4 >= 4.3.0) The fdf_get_encoding() returns the value of the


fdf_get_ap -- Get the appearance of a field /Encoding key. An empty string is returned if the default
PDFDocEncoding/Unicode scheme is used.
See also fdf_set_encoding().
Description

fdf_get_file
bool fdf_get_ap ( resource fdf_document, string field, int
face, string filename)
(PHP 3>= 3.0.6, PHP 4 )
fdf_get_file -- Obtener el valor de la clave /F
The fdf_get_ap() function gets the appearance of a field
(i.e. the value of the /AP key) and stores it in a file. The
possible values of face are FDFNormalAP, Descripción
FDFRolloverAP and FDFDownAP. The appearance is
stored in filename.
string fdf_get_file ( int fdf_document)

fdf_get_attachment
La función fdf_set_file() devuelve el valor de la clave /F. fdf_next_field_name -- Obtener el nombre del siguiente
Vea también fdf_set_file(). campo

fdf_get_status Descripción

(PHP 3>= 3.0.6, PHP 4 ) string fdf_next_field_name ( int fdf_document, string


fdf_get_status -- Obtener el valor de la clave /STATUS fieldname)

Descripción La función fdf_next_field_name() devuelve el nombre


del campo tras el campo fieldname o el nombre del
primer campo si el segundo parámetro es NULL.
string fdf_get_status ( int fdf_document) Vea también fdf_set_field(), fdf_get_field().

La función fdf_get_status() devuelve el valor de la fdf_open_string


clave /STATUS.
Vea también fdf_set_status().
(PHP 4 >= 4.3.0)
fdf_open_string -- Read a FDF document from a string
fdf_get_value

Description
(PHP 3>= 3.0.6, PHP 4 )
fdf_get_value -- Obtener el valor de un campo
resource fdf_open_string ( string fdf_data)

Descripción
The fdf_open_string() function reads form data from a
string. fdf_data must contain the data as returned from a
string fdf_get_value ( int fdf_document, string PDF form or created using fdf_create() and
fieldname) fdf_save_string().
You can fdf_open_string() together with
$HTTP_FDF_DATA to process fdf form input from a
La función fdf_get_value() devuelve el valor de un
remote client.
campo.
Ejemplo 1. Accessing the form data
Vea también fdf_set_value().

fdf_get_version <?php
$fdf =
fdf_open_string($HTTP_FDF_DAT
(PHP 4 >= 4.3.0) A);
fdf_get_version -- Gets version number for FDF api or file ...
fdf_close($fdf);
Description ?>
See also fdf_open(), fdf_close(), fdf_create() and
fdf_save_string().
string fdf_get_version ( [resource fdf_document])

fdf_open
This function will return the fdf version for the given
fdf_document, or the toolkit api version number if no
parameter is given. (PHP 3>= 3.0.6, PHP 4 )
For the current FDF toolkit 5.0 the api version number is fdf_open -- Abrir un documento FDF
'5.0' and the document version number is either '1.2',
'1.3' or '1.4'.
See also fdf_set_version(). Descripción

fdf_header int fdf_open ( string filename)

(PHP 4 >= 4.3.0) La función fdf_open() abre un archivo con datos de


fdf_header -- Sets FDF-specific output headers formulario. Este archivo debe contener los datos tal y
como se devuelven en un formulario PDF. Actualmente
dicho archivo debe crearse "manualmente" usando la
Description función fopen() y escribiendo en éste el contenido de
HTTP_FDF_DATA usando fwrite(). No existe un
mecanismo similar al de los formularios HTML donde se
bool fdf_header ( void) crea una variable para cada campo de entrada.
Ejemplo 1. Accediendo a los datos del formulario
This is a convenience function to set appropriate HTTP
headers for FDF output. It sets the Content-type: to
application/vnd.fdf. <?php
// Guarda los datos FDF en un archivo
temporal
fdf_next_field_name $fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA,
(PHP 3>= 3.0.6, PHP 4 ) strlen($HTTP_FDF_DATA));
fclose($fdffp);
el PHP se utiliza como un módulo del apache. En tal caso
se deberá escribir a un fichero y utilizar p. ej.
// Abre archivo temporal y evalúa los datos
fpassthru() para visualizarlo.
$fdf = fdf_open("test.fdf");
Vea también fdf_close() y el ejemplo para fdf_create().
...
fdf_close($fdf);
?> fdf_set_ap
Vea también fdf_close().
(PHP 3>= 3.0.6, PHP 4 )
fdf_save_string fdf_set_ap -- Ajusta la apariencia de un campo

(PHP 4 >= 4.3.0) Descripción


fdf_save_string -- Returns the FDF document as a string
void fdf_set_ap ( int fdf_document, string field_name, int
Description face, string filename, int page_number)

La función fdf_set_ap() ajusta la apariencia de un


string fdf_save_string ( resource fdf_document)
campo (p. ej. el valor de la clave /AP). Los valores
posibles de face son 1=FDFNormalAP, 2=FDFRolloverAP,
The fdf_save_string() function returns the FDF 3=FDFDownAP.
document as a string.
Ejemplo 1. Retrieving FDF as a string
fdf_set_encoding

<?php (PHP 4 >= 4.1.0)


$fdf = fdf_create(); fdf_set_encoding -- Sets FDF character encoding
fdf_set_value($fdf,
"foo", "bar");
$str = Description
fdf_save_string($fdf);
fdf_close($fdf);
echo $str; bool fdf_set_encoding ( resource fdf_document, string
?> encoding)

fdf_set_encoding() sets the character encoding in FDF


will output something like document fdf_document. encoding should be the valid
encoding name. Currently the following values are
supported: "Shift-JIS", "UHC", "GBK","BigFive". An empty
%FDF-1.2 string resets the encoding to the default
%âãÏÓ PDFDocEncoding/Unicode scheme.
1 0 obj
<<
/FDF << /Fields 2 fdf_set_file
0 R >>
>> (PHP 3>= 3.0.6, PHP 4 )
endobj fdf_set_file -- Fijar el valor de la clave /F
2 0 obj
[
<< /T (foo)/V Descripción
(bar)>>
]
endobj void fdf_set_file ( int fdf_document, string filename)
trailer
<< La función fdf_set_file() fija el valor de la clave /F. La
/Root 1 0 R clave /F es simplemente una referencia a un formulario
PDF que se va a rellenar con datos. En un entorno web es
>> un URL (p.ej. http:/testfdf/resultlabel.pdf).
%%EOF Vea también fdf_get_file() y el ejemplo para
See also fdf_save(), fdf_open_string(), fdf_create() fdf_create().
and fdf_close().
fdf_set_flags
fdf_save
(PHP 4 >= 4.0.2)
(PHP 3>= 3.0.6, PHP 4 ) fdf_set_flags -- Sets a flag of a field
fdf_save -- Guardar un documeto FDF
Description
Descripción
bool fdf_set_flags ( resource fdf_document, string
int fdf_save ( string filename) fieldname, int whichFlags, int newFlags)

La función fdf_save() guarda un documento FDF. El kit The fdf_set_flags() sets certain flags of the given field
de FDF proporciona una forma de volcar el documento a fieldname.
stdout si el parámetro filename es '.'. Esto no funciona si See also fdf_set_opt().
fdf_set_javascript_action bool fdf_set_target_frame ( resource fdf_document,
string frame_name)

(PHP 4 >= 4.0.2)


fdf_set_javascript_action -- Sets an javascript action of a Sets the target frame to display a result PDF defined with
field fdf_save_file() in.
See also fdf_save_file().

Description
fdf_set_value

bool fdf_set_javascript_action ( resource


fdf_document, string fieldname, int trigger, string script) (PHP 3>= 3.0.6, PHP 4 )
fdf_set_value -- Fijar el valor de un campo

fdf_set_javascript_action() sets a javascript action for


the given field fieldname. Descripción
See also fdf_set_submit_form_action().

void fdf_set_value ( int fdf_document, string fieldname,


fdf_set_opt string value, int isName)

(PHP 4 >= 4.0.2) La función fdf_set_value() fija el valor de un campo. El


fdf_set_opt -- Sets an option of a field parámetro final determina si el valor del campo se
deberá convertir a un Nombre PDF (isName = 1) o
convertir en una Cadena PDF (isName = 0).
Description Vea también fdf_get_value().

bool fdf_set_opt ( resource fdf_document, string fdf_set_version


fieldname, int element, string str1, string str2)

(PHP 4 >= 4.3.0)


The fdf_set_opt() sets options of the given field fdf_set_version -- Sets version number for a FDF file
fieldname.
See also fdf_set_flags().
Description

fdf_set_status
string fdf_set_version ( resource fdf_document, string
version)
(PHP 3>= 3.0.6, PHP 4 )
fdf_set_status -- Fija el valor de la clave /STATUS
This function will set the fdf version for the given
fdf_document. Some features supported by this
Descripción extension are only available in newer fdf versions. For
the current FDF toolkit 5.0 version may be either '1.2',
'1.3' or '1.4'.
void fdf_set_status ( int fdf_document, string status) See also fdf_get_version().

La función fdf_set_status() fija el valor de la clave


XXXII. FriBiDi functions
/STATUS.
Vea también fdf_get_status().
Introducción
fdf_set_submit_form_action
FriBiDi is a free implementation of the Unicode
Bidirectional Algorithm.
(PHP 4 >= 4.0.2)
fdf_set_submit_form_action -- Sets a submit form action
of a field
Requerimientos

Description
You must download and install the FriBiDi package.

bool fdf_set_submit_form_action ( resource


fdf_document, string fieldname, int trigger, string script, Instalación
int flags)
To enable FriBiDi support in PHP you must compile --with-
The fdf_set_submit_form_action() sets a submit form fribidi[=DIR] where DIR is the FriBiDi install directory.
action for the given field fieldname.
See also fdf_set_javascript_action().
Configuración en tiempo de ejecución

fdf_set_target_frame

(PHP 4 >= 4.3.0) Tipos de recursos


fdf_set_target_frame -- Set target frame for form display

Description
Constantes predefinidas
Estas constantes están definidas por esta extensión y ftp_quit -- Cierra una conexión FTP
estarán disponibles solamente cuando la extensión ha ftp_rawlist -- Devuelve una lista detallada de ficheros del
sido o bien compilada dentro de PHP o grabada directorio dado.
dinamicamente en tiempo de ejecución. ftp_rename -- Renombra un fichero del servidor FTP.
FRIBIDI_CHARSET_UTF8 (integer) ftp_rmdir -- Borra un directorio
FRIBIDI_CHARSET_8859_6 (integer) ftp_set_option -- Set miscellaneous runtime FTP options
FRIBIDI_CHARSET_8859_8 (integer) ftp_site -- Sends a SITE command to the server
FRIBIDI_CHARSET_CP1255 (integer) ftp_size -- Devuelve el tamaño del fichero especificado.
FRIBIDI_CHARSET_CP1256 (integer) ftp_ssl_connect -- Opens an Secure SSL-FTP connection
FRIBIDI_CHARSET_ISIRI_3342 (integer) ftp_systype -- Devuelve el identificador de tipo de
Tabla de contenidos sistema del servidor FTP remoto.
fribidi_log2vis -- Convert a logical string to a visual one

ftp_cdup
fribidi_log2vis

(PHP 3>= 3.0.13, PHP 4 )


(PHP 4 >= 4.0.4) ftp_cdup -- Cambia al directorio padre
fribidi_log2vis -- Convert a logical string to a visual one

Descripción
Description

int ftp_cdup ( int ftp_stream)


string fribidi_log2vis ( string str, string direction, int
charset)
Si tiene éxito, devuelve TRUE. En caso de error,
devuelve FALSE.
Aviso Cambia al directorio padre.

Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones ftp_chdir
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
(PHP 3>= 3.0.13, PHP 4 )
utilizar este módulo es tu responsabiliad.
ftp_chdir -- Cambia de directorio en un servidor FTP
Aviso
Esta función no está documentada actualmente, solamente Descripción
se encuentra disponible la lista de parametros.
int ftp_chdir ( int ftp_stream, string directory)
XXXIII. Funciones FTP
Si tiene éxito, devuelve TRUE. En caso de error,
devuelve FALSE.
FTP es el acrónimo de File Transfer Protocol (Protocolo de Cambia al directorio especificado por el parámetro
Transferencia de Ficheros. directory.
Cuando se utiliza el módulo FTP, se definen las siguientes
constantes: FTP_ASCII, y FTP_BINARY.
Tabla de contenidos ftp_close
ftp_cdup -- Cambia al directorio padre
ftp_chdir -- Cambia de directorio en un servidor FTP
ftp_close -- Closes an FTP connection (PHP 4 >= 4.2.0)
ftp_connect -- Establece una conexión FTP ftp_close -- Closes an FTP connection
ftp_delete -- Borra un fichero del servidor FTP.
ftp_exec -- Requests execution of a program on the FTP Description
server
ftp_fget -- Descarga un fichero del servidor FTP y lo
guarda en un fichero abierto. void ftp_close ( resource ftp_stream)
ftp_fput -- Sube un fichero abierto al servidor FTP.
ftp_get_option -- Retrieves various runtime behaviours of
the current FTP stream ftp_close() closes ftp_stream and releases the resource.
ftp_get -- Descarga un fichero del servidor FTP. After calling this function, you can no longer use the FTP
ftp_login -- Comienza la sesion en una conexión FTP connection and must create a new one with
ftp_mdtm -- Devuelve la fecha de última modificación del ftp_connect().
fichero especificado. See also ftp_connect()
ftp_mkdir -- Crea un directorio
ftp_nb_continue -- Continues retrieving/sending a file ftp_connect
(non-blocking)
ftp_nb_fget -- Retrieves a file from the FTP server and
writes it to an open file (non-blocking) (PHP 3>= 3.0.13, PHP 4 )
ftp_nb_fput -- Stores a file from an open file to the FTP ftp_connect -- Establece una conexión FTP
server (non-blocking)
ftp_nb_get -- Retrieves a file from the FTP server and
writes it to a local file (non-blocking) Descripción
ftp_nb_put -- Stores a file on the FTP server (non-
blocking)
int ftp_connect ( string host [, int port])
ftp_nlist -- Devuelve una lista de ficheros del directorio
dado.
ftp_pasv -- Activa o desactiva el modo pasivo. Si tiene éxito, devuelve un flujo FTP. En caso de error,
ftp_put -- Sube un fichero al servidor FTP. devuelve FALSE.
ftp_pwd -- Devuelve el nombre del directorio actual
ftp_connect() establece una conexión FTP al host remoto. El modo de transferencia especificado por el
especificado. El parámetro port especifica un puerto parámetro mode debe ser FTP_ASCII o bien FTP_BINARY.
alternativo al que conectar. Si se omite o es cero, se usa
el puerto FTP por defecto, 21.
ftp_get_option

ftp_delete
(PHP 4 >= 4.2.0)
ftp_get_option -- Retrieves various runtime behaviours of
(PHP 3>= 3.0.13, PHP 4 ) the current FTP stream
ftp_delete -- Borra un fichero del servidor FTP.

Description
Descripción

mixed ftp_get_option ( resource ftp_stream, int option)


int ftp_delete ( int ftp_stream, string path)

Nota: This function is only available


Si tiene éxito, devuelve TRUE. En caso de error, in CVS.
devuelve FALSE.
ftp_delete() borra el fichero especificado por el
parámetro path del servidor FTP. Returns the value on success or FALSE if the given
option is not supported. In the latter case, a warning
message is also thrown.
ftp_exec This function returns the value for the requested option
from the specified ftp_stream . Currently, the following
options are supported:
(PHP 4 >= 4.0.3)
Tabla 1. Supported runtime FTP options
ftp_exec -- Requests execution of a program on the FTP
server FTP_TIMEOUT_S Returns the current timeout used for
EC network related operations.

Description Ejemplo 1. ftp_get_option() example

bool ftp_exec ( resource ftp_stream, string command) // Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id,
Sends a SITE EXEC command request to the FTP server. FTP_TIMEOUT_SEC);
Returns the output of the command if successful;
otherwise returns FALSE.
ftp_get

ftp_fget
(PHP 3>= 3.0.13, PHP 4 )
ftp_get -- Descarga un fichero del servidor FTP.
(PHP 3>= 3.0.13, PHP 4 )
ftp_fget -- Descarga un fichero del servidor FTP y lo
guarda en un fichero abierto. Descripción

Descripción int ftp_get ( int ftp_stream, string local_file, string


remote_file, int mode)

int ftp_fget ( int ftp_stream, int fp, string remote_file, int


Si tiene éxito, devuelve TRUE. En caso de error,
mode)
devuelve FALSE.
ftp_get() baja el fichero remote_file del servidor FTP, y
Si tiene éxito, devuelve TRUE. En caso de error, lo guarda localmente como local_file. El modo de
devuelve FALSE. transferencia especificado por el parámetro mode debe
ftp_fget() baja el fichero remote_file del servidor FTP, y ser FTP_ASCII o bien FTP_BINARY.
lo escribe en el puntero a fichero fp. El modo de
transferencia especificado por el parámetro mode debe
ser FTP_ASCII o bien FTP_BINARY. ftp_login

ftp_fput (PHP 3>= 3.0.13, PHP 4 )


ftp_login -- Comienza la sesion en una conexión FTP

(PHP 3>= 3.0.13, PHP 4 )


ftp_fput -- Sube un fichero abierto al servidor FTP. Descripción

Descripción int ftp_login ( int ftp_stream, string username, string


password)

int ftp_fput ( int ftp_stream, string remote_file, int fp, int


Si tiene éxito, devuelve TRUE. En caso de error,
mode)
devuelve FALSE.
Inicia una sesion (envía identificador de usuario y
Si tiene éxito, devuelve TRUE. En caso de error, contraseña) en el flujo FTP especificado.
devuelve FALSE
ftp_fput() sube los datos apuntados por el puntero a
fichero fp hasta alcanzar el final del fichero. Los ftp_mdtm
resultados se guardan en el fichero remote_file del FTP
(PHP 3>= 3.0.13, PHP 4 ) (PHP 4 >= 4.3.0)
ftp_mdtm -- Devuelve la fecha de última modificación del ftp_nb_fput -- Stores a file from an open file to the FTP
fichero especificado. server (non-blocking)

Descripción Description

int ftp_mdtm ( int ftp_stream, string remote_file) bool ftp_nb_fput ( resource ftp_stream, string
remote_file, resource fp, int mode [, int startpos])
Si tiene éxito, devuelve una marca de tiempo UNIX (UNIX
timestamp). En caso de error, devuelve -1. ftp_nb_fput() uploads the data from the file pointer fp
ftp_mdtm() comprueba la fecha de última modificación until it reaches the end of the file. The results are stored
de un fichero, y la devuelve como una marca de tiempo in remote_file on the FTP server. The transfer mode
UNIX. Si se produce algún error, o el fichero no existe, specified must be either FTP_ASCII or FTP_BINARY. The
devuelve -1. Tenga en cuenta que no todos los difference between this function and the ftp_fput() is
servidores soportan esta característica. that this function uploads the file asynchronously, so
your program can perform other operations while the file
is being downloaded.
ftp_mkdir Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
See also ftp_nb_put(), ftp_nb_continue(), ftp_put()
and ftp_fput().
(PHP 3>= 3.0.13, PHP 4 )
ftp_mkdir -- Crea un directorio
ftp_nb_get
Descripción
(PHP 4 >= 4.3.0)
ftp_nb_get -- Retrieves a file from the FTP server and
string ftp_mkdir ( int ftp_stream, string directory)
writes it to a local file (non-blocking)

Si tiene éxito, devuelve el nombre del directorio recién


creado. En caso de error, devuelve FALSE. Description
Crea el directorio especificado por el parámetro
directory.
bool ftp_nb_get ( resource ftp_stream, string local_file,
string remote_file, int mode [, int resumepos])
ftp_nb_continue
ftp_nb_get() retrieves remote_file from the FTP server,
and saves it to local_file locally. The transfer mode
(PHP 4 >= 4.3.0)
specified must be either FTP_ASCII or FTP_BINARY. The
ftp_nb_continue -- Continues retrieving/sending a file
difference between this function and the ftp_get() is
(non-blocking)
that this function retrieves the file asynchronously, so
your program can perform other operations while the file
Description is being downloaded.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
Ejemplo 1. ftp_nb_get() example
bool ftp_nb_continue ( resource ftp_stream)

Continues retrieving/sending a file nbronously // Initate the download


Returns FTP_FAILED or FTP_FINISHED or $ret = ftp_nb_get($my_connection, "test",
FTP_MOREDATA. "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

ftp_nb_fget // Do whatever you want


echo ".";
(PHP 4 >= 4.3.0) // Continue downloading...
ftp_nb_fget -- Retrieves a file from the FTP server and $ret = ftp_nb_continue ($my_connection);
writes it to an open file (non-blocking) }
if ($ret != FTP_FINISHED) {
Description echo "There was an error downloading the file...";
exit(1);
}
bool ftp_nb_fget ( resource ftp_stream, resource fp, Ejemplo 2. Resuming a download with ftp_nb_get()
string remote_file, int mode [, int resumepos])

ftp_nb_fget() retrieves remote_file from the FTP server, // Initate


and writes it to the given file pointer, fp. The transfer $ret = ftp_nb_get ($my_connection, "test",
mode specified must be either FTP_ASCII or "README", FTP_BINARY,
FTP_BINARY. The difference between this function and filesize("test"));
the ftp_fget() is that this function retrieves the file // OR: $ret = ftp_nb_get ($my_connection, "test",
asynchronously, so your program can perform other "README",
operations while the file is being downloaded. // FTP_BINARY, FTP_AUTORESUME);
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. while ($ret == FTP_MOREDATA) {
See also ftp_nb_get().
// Do whatever you want
echo ".";
ftp_nb_fput
// Continue downloading... $ret = ftp_nb_put ($my_connection,
$ret = ftp_nb_continue ($my_connection); "test.remote", "test.local",
} FTP_BINARY,
if ($ret != FTP_FINISHED) { ftp_size("test.remote"));
echo "There was an error downloading the file..."; // OR: $ret = ftp_nb_put ($my_connection,
exit(1); "test.remote", "test.local",
} // FTP_BINARY,
FTP_AUTORESUME);
Ejemplo 3. Resuming a download at position 100 to
a new file with ftp_nb_get()
while ($ret == FTP_MOREDATA) {

// Do whatever you want


// Disable Autoseek echo ".";
ftp_set_option ($my_connection, FTP_AUTOSEEK,
FALSE); // Continue uploading...
$ret = ftp_nb_continue ($my_connection);
// Initiate }
$ret = ftp_nb_get ($my_connection, "newfile", if ($ret != FTP_FINISHED) {
"README", FTP_BINARY, 100); echo "There was an error uploading the file...";
while ($ret == FTP_MOREDATA) { exit(1);
}
...
See also ftp_nb_fput(), ftp_nb_continue(), ftp_put()
// Continue downloading... and ftp_fput().
$ret = ftp_nb_continue ($my_connection);
}
ftp_nlist
In the example above, "newfile" is 100 bytes smaller
than "README" on the FTP server because we started
reading at offset 100. If we have not have disabled (PHP 3>= 3.0.13, PHP 4 )
FTP_AUTOSEEK, the first 100 bytes of newfile will be ftp_nlist -- Devuelve una lista de ficheros del directorio
'\0'. dado.
See also ftp_nb_fget(), ftp_nb_continue(), ftp_get()
and ftp_fget().
Descripción

ftp_nb_put
int ftp_nlist ( int ftp_stream, string directory)

(PHP 4 >= 4.3.0) Si tiene éxito, devuelve un array de nombres de fichero.


ftp_nb_put -- Stores a file on the FTP server (non- En caso de error, devuelve FALSE.
blocking)

ftp_pasv
Description

(PHP 3>= 3.0.13, PHP 4 )


bool ftp_nb_put ( resource ftp_stream, string ftp_pasv -- Activa o desactiva el modo pasivo.
remote_file, string local_file, int mode [, int startpos])

Descripción
ftp_nb_put() stores local_file on the FTP server, as
remote_file. The transfer mode specified must be either
FTP_ASCII or FTP_BINARY. The difference between this int ftp_pasv ( int ftp_stream, int pasv)
function and the ftp_put() is that this function uploads
the file asynchronously, so your program can perform
other operations while the file is being downloaded. Si tiene éxito, devuelve TRUE. En caso de error,
Devuelve TRUE si todo fue bien, FALSE en caso de fallo. devuelve FALSE.
Ejemplo 1. ftp_nb_put() example ftp_pasv() activa el modo pasivo si el parámetro pasv es
TRUE (desactiva el modo pasivo si pasv es FALSE.) En
modo pasivo, las conexiones de datos son iniciadas por
el cliente, en lugar de ser iniciadas por el servidor.
// Initiate the Upload
$ret = ftp_nb_put($my_connection, "test.remote",
"test.local", FTP_BINARY); ftp_put
while ($ret == FTP_MOREDATA) {

// Do whatever you want (PHP 3>= 3.0.13, PHP 4 )


echo "."; ftp_put -- Sube un fichero al servidor FTP.

// Continue uploading...
$ret = ftp_nb_continue ($my_connection); Descripción
}
if ($ret != FTP_FINISHED) { int ftp_put ( int ftp_stream, string remote_file, string
echo "There was an error uploading the file..."; local_file, int mode)
exit(1);
}
Si tiene éxito, devuelve TRUE. En caso de error,
Ejemplo 2. Resuming an upload with ftp_nb_put() devuelve FALSE.
ftp_put() sube el fichero local local_file al servidor FTP y
lo guarda como remote_file. El modo de transferencia
// Initiate
especificado por el parámetro mode debe ser FTP_ASCII o int ftp_rmdir ( int ftp_stream, string directory)
bien FTP_BINARY.
Si tiene éxito, devuelve TRUE. En caso de error,
ftp_pwd devuelve FALSE.
Borra el directorio especificado por el parámetro
directory.
(PHP 3>= 3.0.13, PHP 4 )
ftp_pwd -- Devuelve el nombre del directorio actual
ftp_set_option

Descripción
(PHP 4 >= 4.2.0)
ftp_set_option -- Set miscellaneous runtime FTP options
int ftp_pwd ( int ftp_stream)

Description
Devuelve el directorio actual, o FALSE en caso de error.

bool ftp_set_option ( resource ftp_stream, int option,


ftp_quit mixed value)

(PHP 3>= 3.0.13, PHP 4 ) Nota: This function is only available


ftp_quit -- Cierra una conexión FTP in CVS.

Descripción Returns TRUE if the option could be set; FALSE if not. A


warning message will be thrown if the option is not
supported or the passed value doesn't match the
int ftp_quit ( int ftp_stream)
expected value for the given option.
This function controls various runtime options for the
ftp_connect() cierra el flujo FTP ftp_stream. specified FTP stream. The value parameter depends on
which option parameter is chosen to be altered.
Currently, the following options are supported:
ftp_rawlist Tabla 1. Supported runtime FTP options
Changes the timeout in seconds used for
(PHP 3>= 3.0.13, PHP 4 ) FTP_TIMEOUT_S all network related functions. value must
ftp_rawlist -- Devuelve una lista detallada de ficheros del EC be an integer that is greater than 0. The
directorio dado. default timeout is 90 seconds.
When enabled, GET or PUT requests with
Descripción a resumepos or startpos parameter will
FTP_AUTOSEEK
first seek to the requested position within
the file. This is enabled by default.
int ftp_rawlist ( int ftp_stream, string directory)
Ejemplo 1. ftp_set_option() example

ftp_rawlist() ejecuta el comando FTP LIST, y devuelve el


resultado como un array. Cada elemento del array // Set the network timeout to 10
corresponde a una línea de texto. La salida no se procesa seconds
de ninguna forma. Se puede utilizar el identificador de ftp_set_option($conn_id,
tipo de sistema devuelto por ftp_systype() para FTP_TIMEOUT_SEC, 10);
determinar cómo se deben interpretar los resultados.

ftp_rename ftp_site

(PHP 3>= 3.0.13, PHP 4 ) (PHP 3>= 3.0.15, PHP 4 )


ftp_rename -- Renombra un fichero del servidor FTP. ftp_site -- Sends a SITE command to the server

Descripción Description

int ftp_rename ( int ftp_stream, string from, string to) bool ftp_site ( resource ftp_stream, string cmd)

Si tiene éxito, devuelve TRUE. En caso de error, ftp_site() sends the command specified by cmd to the
devuelve FALSE. FTP server. SITE commands are not standardized, and
ftp_rename() renombra el fichero especificado por el vary from server to server. They are useful for handling
parámetro from con el nuevo nombre to such things as file permissions and group membership.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.

ftp_rmdir
ftp_size

(PHP 3>= 3.0.13, PHP 4 )


ftp_rmdir -- Borra un directorio (PHP 3>= 3.0.13, PHP 4 )
ftp_size -- Devuelve el tamaño del fichero especificado.

Descripción
Descripción
int ftp_size ( int ftp_stream, string remote_file) function_exists -- Devuelve TRUE si la función dada ha
sido definida
get_defined_functions -- Returns an array of all defined
Si tiene éxito devuelve el tamaño del fichero, o -1 en
functions
caso de error.
register_shutdown_function -- Registra una función para
ftp_size() devuelve el tamaño de un fichero. Si ocurre
su ejecución en el cierre.
algún error, o si el fichero no existe, devuelve -1. No
register_tick_function -- Register a function for execution
todos los servidores soportan esta característica.
on each tick
unregister_tick_function -- De-register a function for
ftp_ssl_connect execution on each tick

(PHP 4 >= 4.3.0) call_user_func_array


ftp_ssl_connect -- Opens an Secure SSL-FTP connection
(PHP 4 >= 4.0.4)
Description call_user_func_array -- Call a user function given with an
array of parameters

resource ftp_ssl_connect ( string host [, int port [, int


timeout]]) Description

Returns a SSL-FTP stream on success or FALSE on error. mixed call_user_func_array ( callback function [, array
ftp_ssl_connect() opens a SSL-FTP connection to the paramarr])
specified host. The port parameter specifies an alternate
port to connect to. If it's omitted or set to zero then the
Call a user defined function given by function, with the
default FTP port 21 will be used.
parameters in paramarr. For example:
The timeout parameter specifies the timeout for all
subsequent network operations. If omitted, the default function debug($var, $val)
value is 90 seconds. The timeout can be changed and echo "***DEBUGGING\nVARIABLE:
queried at any time with ftp_set_option() and $var\nVALUE:";
ftp_get_option(). if (is_array($val) || is_object($val) ||
is_resource($val))
print_r($val);
Why this function may not exist: else
ftp_ssl_connect() is only available echo "\n$val\n";
if OpenSSL support is enabled into echo "***\n";
your version of PHP. If it's undefined }
and you've compiled FTP support
then this is why. $c = mysql_connect();
$host = $_SERVER["SERVER_NAME"];
See also ftp_connect()
call_user_func_array ('debug',
array("host", $host));
ftp_systype call_user_func_array ('debug', array("c",
$c));
call_user_func_array ('debug',
(PHP 3>= 3.0.13, PHP 4 ) array("_POST", $_POST));
ftp_systype -- Devuelve el identificador de tipo de
See also: call_user_func(), call_user_method(),
sistema del servidor FTP remoto.
call_user_method_array().

Descripción
call_user_func

int ftp_systype ( int ftp_stream)


(PHP 3>= 3.0.3, PHP 4 )
call_user_func -- Call a user function given by the first
Devuelve el tipo de sistema remoto, o FALSE en caso de parameter
error.

Description
XXXIV. Function Handling functions

mixed call_user_func ( string function_name [, mixed


These functions all handle various operations involved in parameter [, mixed ...]])
working with functions.
Tabla de contenidos
call_user_func_array -- Call a user function given with an Call a user defined function given by the function_name
parameter. Take the following:
array of parameters
call_user_func -- Call a user function given by the first function barber ($type) {
parameter print "You wanted a $type haircut,
create_function -- Create an anonymous (lambda-style) no problem";
function }
func_get_arg -- Devuelve un elemento de la lista de call_user_func ('barber',
argumentos. "mushroom");
func_get_args -- Devuelve un array que contiene la lista call_user_func ('barber', "shave");
de argumentos de una función.
func_num_args -- Devuelve el número de argumentos
pasados a la función. create_function
(PHP 4 >= 4.0.1)
night", $garr);
create_function -- Create an anonymous (lambda-style)
function and when you run the code above, the output will be:
Using the first array of anonymous
Description functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
string create_function ( string args, string code) a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
Creates an anonymous function from the parameters
ln(a/b) = 0.27122299212594
passed, and returns a unique name for it. Usually the
args will be passed as a single quote delimited string,
Using the second array of anonymous
and this is also recommended for the code. The reason
functions
for using single quoted strings, is to protect the variable
** "Twas the night" and "Twas brilling and
names from parsing, otherwise, if you use double quotes
the slithy toves"
there will be a need to escape the variable names, e.g. \
** Look the same to me! (looking at the
$avar.
first 3 chars)
You can use this function, to (for example) create a
CRCs: -725381282 , 1908338681
function from information gathered at run time:
similar(a,b) = 11(45.833333333333%)
Ejemplo 1. Creating an anonymous function with
create_function() But perhaps the most common use for of lambda-style
(anonymous) functions is to create callback functions, for
example when using array_walk() or usort()
$newfunc = create_function('$a,$b','return "ln($a) + Ejemplo 3. Using anonymous functions as callback
ln($b) = ".log($a * $b);'); functions
echo "New anonymous function: $newfunc\n";
echo $newfunc(2,M_E)."\n";
// outputs $av = array("the ","a ","that ","this ");
// New anonymous function: lambda_1 array_walk($av, create_function('&$v,$k','$v =
// ln(2) + ln(2.718281828459) = 1.6931471805599 $v."mango";'));
print_r($av); // for PHP3 use var_dump()
Or, perhaps to have general handler function that can
// outputs:
apply a set of operations to a list of parameters:
// Array
Ejemplo 2. Making a general processing function
// (
with create_function()
// [0] => the mango
// [1] => a mango
// [2] => that mango
function process($var1, $var2, $farr) { // [3] => this mango
for ($f=0; $f < count($farr); $f++) // )
echo $farr[$f]($var1,$var2)."\n";
} // an array of strings ordered from shorter to
longer
// create a bunch of math functions $sv = array("small","larger","a big string","it is
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} a string thing");
else {return false;}'; print_r($sv);
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\ // outputs:
$b,\$b*\$b+\$a);"; // Array
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = // (
".log($a)/$b;} else {return false;}'; // [0] => small
$farr = array( // [1] => larger
create_function('$x,$y', 'return "some trig: ".(sin($x) // [2] => a big string
+ $x*cos($y));'), // [3] => it is a string thing
create_function('$x,$y', 'return "a hypotenuse: // )
".sqrt($x*$x + $y*$y);'),
create_function('$a,$b', $f1), // sort it from longer to shorter
create_function('$a,$b', $f2), usort($sv, create_function('$a,$b','return
create_function('$a,$b', $f3) strlen($b) - strlen($a);'));
); print_r($sv);
// outputs:
echo "\nUsing the first array of anonymous // Array
functions\n"; // (
echo "parameters: 2.3445, M_PI\n"; // [0] => it is a string thing
process(2.3445, M_PI, $farr); // [1] => a big string
// [2] => larger
// now make a bunch of string processing functions // [3] => small
$garr = array( // )
create_function('$b,$a','if (strncmp($a,$b,3) == 0)
return "** \"$a\" '.
'and \"$b\"\n** Look the same to me! (looking at the
func_get_arg
first 3 chars)";'),
create_function('$a,$b','; return "CRCs: ".crc32($a)."
, ".crc32(b);'), (PHP 4 )
create_function('$a,$b','; return "similar(a,b) = func_get_arg -- Devuelve un elemento de la lista de
".similar_text($a,$b,&$p)."($p%)";') argumentos.
);
echo "\nUsing the second array of anonymous
functions\n"; Descripción
process("Twas brilling and the slithy toves", "Twas the
int func_get_arg ( int arg_num) func_num_args

Devuelve el argumento que está en la posición arg_num (PHP 4 )


en la lista de argumentos de una función definida por el func_num_args -- Devuelve el número de argumentos
usuario. Los argumentos de la función se cuentan pasados a la función.
comenzando por la posición cero. func_get_arg()
generará un aviso si se llama desde fuera de la definición
de la función. Descripción
Si arg_num es mayor que el número de argumentos
pasados realmente, se generará un aviso y
func_get_arg() devolverá FALSE. int func_num_args ( void )

<?php
function foo() { Devuelve el número de argumentos pasados a la función
$numargs = func_num_args(); actual definida por el usuario. func_num_args()
echo "Number of arguments: generará un aviso si es llamada desde fuera de la
$numargs<br>\n"; definición de la función.
if ( $numargs >= 2 ) { <?php
echo "Second argument is: " . function foo() {
func_get_arg( 1 ) . "<br>\n"; $numargs = func_num_args();
} echo "Number of arguments:
} $numargs\n";
}
foo( 1, 2, 3 );
?> foo( 1, 2, 3 ); // Prints 'Number of
func_get_arg() puede utilizarse conjuntamente con arguments: 3'
func_num_args() y func_get_args() para permitir a las ?>
funciones definidas por el usuario que acepten listas de func_num_args() puede utilizarse conjuntamente con
argumentos de longitud variable. func_get_arg() y func_get_args() para permitir a las
funciones definidas por el usuario que acepten listas de
argumentos de longitud variable.
Nota: Esta función fue añadida en
PHP 4.
Nota: Esta función fue añadida en
PHP 4.
func_get_args

function_exists
(PHP 4 )
func_get_args -- Devuelve un array que contiene la lista
de argumentos de una función. (PHP 3>= 3.0.7, PHP 4 )
function_exists -- Devuelve TRUE si la función dada ha
sido definida
Descripción

Descripción
int func_get_args ( void )

Devuelve un array en el que cada elemento es el int function_exists ( string function_name)


miembro correspondiente de la lista de argumentos de la
función definida por el usuario actual. func_get_args() Consulta la lista de funciones definidas buscando
generará un aviso si es llamada desde fuera de la function_name (nombre de función). Devuelve TRUE si
definición de la función. encuentra el nombre de función dado, FALSE en otro
<?php caso.
function foo() {
$numargs = func_num_args(); get_defined_functions
echo "Number of arguments:
$numargs<br>\n";
if ( $numargs >= 2 ) { (PHP 4 >= 4.0.4)
echo "Second argument is: " . get_defined_functions -- Returns an array of all defined
func_get_arg( 1 ) . "<br>\n"; functions
}
$arg_list = func_get_args();
for ( $i = 0; $i < $numargs; $i++ ) { Description
echo "Argument $i is: " . $arg_list[$i] .
"<br>\n";
array get_defined_functions ( void)
}
}
This function returns an multidimensional array
foo( 1, 2, 3 ); containing a list of all defined functions, both built-in
?> (internal) and user-defined. The internal functions will be
accessible via $arr["internal"], and the user defined ones
func_get_args() puede utilizarse conjuntamente con
func_num_args() y func_get_arg() para permitir a las using $arr["user"] (see example below).
funciones definidas por el usuario que acepten listas de function myrow($id, $data) {
argumentos de longitud variable. return
"<tr><th>$id</th><td>$data</td
></tr>\n";
Nota: Esta función fue añadida en }
PHP 4.
(PHP 4 >= 4.0.3)
unregister_tick_function -- De-register a function for
$arr = get_defined_functions();
execution on each tick
print_r($arr);
Will output something along the lines of: Description
Array
( void unregister_tick_function ( string function_name)
[internal] => Array
(
De-registers the function named by function_name so it
[0] =>
is no longer executed when a tick is called.
zend_version
[1] =>
func_num_args XXXV. GNU Gettext
[2] =>
func_get_arg
[3] => Tabla de contenidos
func_get_args bind_textdomain_codeset -- Specify the character
[4] => strlen encoding in which the messages from the DOMAIN
[5] => strcmp message catalog will be returned
[6] => bindtextdomain -- Establece la ruta para un dominio
strncmp dcgettext -- Omite el dominio para una única busqueda
... dcngettext -- Plural version of dcgettext
[750] => dgettext -- Omite el dominio actual
bcscale dngettext -- Plural version of dgettext
[751] => gettext -- Realiza una busqueda del mensaje en el
bccomp dominio actual
) ngettext -- Plural version of gettext
textdomain -- Establece el dominio actual
[user] => Array
(
[0] => myrow bind_textdomain_codeset
)
(PHP 4 >= 4.2.0)
) bind_textdomain_codeset -- Specify the character
See also get_defined_vars() and encoding in which the messages from the DOMAIN
get_defined_constants(). message catalog will be returned

register_shutdown_function Description

(PHP 3>= 3.0.4, PHP 4 ) string bind_textdomain_codeset ( string domain, string


register_shutdown_function -- Registra una función para codeset)
su ejecución en el cierre.

Aviso
Descripción
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
int register_shutdown_function ( string func)

bindtextdomain
Registra la función nombrada en func para que se
ejecute cuando el script procese su finalización.
Aviso: (PHP 3>= 3.0.7, PHP 4 )
Debido a que no se permite ningún tipo de salida en el bindtextdomain -- Establece la ruta para un dominio
navegador en esta función, no será capaz de depurarla
utilizando sentencias como print o echo.
Descripción

register_tick_function
string bindtextdomain ( string domain, string directory)

(PHP 4 >= 4.0.3)


register_tick_function -- Register a function for execution La función bindtextdomain() establece la ruta para el
on each tick dominio.

Description dcgettext

void register_tick_function ( callback function [, mixed (PHP 3>= 3.0.7, PHP 4 )


arg]) dcgettext -- Omite el dominio para una única busqueda

Registers the function named by func to be executed Description


when a tick is called.
string dcgettext ( string domain, string message, int
unregister_tick_function category)
Esta función permite omitir el dominio actual para una
putenv ("LANG=de");
busqueda de un mensaje. Además permite especificar
una categoría.
// Especifica la localización de las tablas
de traducción
dcngettext bindtextdomain ("myPHPApp",
"./locale");

(PHP 4 >= 4.2.0) // Elige un dominio


dcngettext -- Plural version of dcgettext textdomain ("myPHPApp");

// Imprime un mensaje de prueba


Description print (gettext ("Welcome to My PHP
Application"));
string dcngettext ( string domain, string msgid1, string ?>
msgid2, int n, int category)

ngettext
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.2.0)
se encuentra disponible la lista de parametros. ngettext -- Plural version of gettext

dgettext Description

(PHP 3>= 3.0.7, PHP 4 ) string ngettext ( string msgid1, string msgid2, int n)
dgettext -- Omite el dominio actual
Aviso
Descripción Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
string dgettext ( string domain, string message)

textdomain
La función dgettext() permite omitir el dominio actual
para una única busqueda.
(PHP 3>= 3.0.7, PHP 4 )
textdomain -- Establece el dominio actual
dngettext

Descripción
(PHP 4 >= 4.2.0)
dngettext -- Plural version of dgettext
int textdomain ( [string library])
Description
Esta función establece el dominio en el que se realizarán
las busquedas provocadas por las llamadas a gettext(),
string dngettext ( string domain, string msgid1, string normalmente el nombre dado a la aplicación. Se
msgid2, int n) devuelve el dominio anterior. Puede llamar a la función
sin parámetros para obtener el dominio actual sin
necesidad de cambiarlo.
Aviso
Esta función no está documentada actualmente, solamente XXXVI. GMP functions
se encuentra disponible la lista de parametros.

These functions allow you to work with arbitrary-length


gettext integers using GNU MP library. In order to have these
functions available, you must compile PHP with GMP
support by using the --with-gmp option.
(PHP 3>= 3.0.7, PHP 4 ) You can download the GMP library from
gettext -- Realiza una busqueda del mensaje en el http://www.swox.com/gmp/. This site also has the GMP
dominio actual manual available.
You will need GMP version 2 or better to use these
functions. Some functions may require more recent
Descripción
version of the GMP library.
These functions have been added in PHP 4.0.4.
string gettext ( string message)
Nota: Most GMP functions accept
Esta función devuelve la traducción de la cadena si GMP number arguments, defined as
encuentra una en la tabla de traducciones, o el mensaje resource below. However, most of
enviado si no se encuentra ninguna. Puede usar un these functions will accept also
carácter de subrayado como un alias para esta función. numeric and string arguments, given
Ejemplo 1. gettext()-check it's possible to convert the latter to
number. Also, if there's faster
function that can operate on integer
<?php arguments, it would be used instead
// Establece el idioma en alemán of slower function when supplied
arguments are integers. This is done gmp_add
transparently, so the bootom line is
that you can use integers in every
function that expects GMP number. (PHP 4 >= 4.0.4)
See also gmp_init() function. gmp_add -- Add numbers

Ejemplo 1. Factorial function using GMP Description

resource gmp_add ( resource a, resource b)


<?php
function fact ($x) {
if ($x <= 1) Add two GMP numbers. The result will be GMP number
return 1; representing the sum of the arguments.
else
return gmp_mul ($x,
gmp_and
fact ($x-1));
}
(PHP 4 >= 4.0.4)
print gmp_strval (fact gmp_and -- Logical AND
(1000)) . "\n";
?>
Description
This will calculate factiorial of 1000 (pretty big number)
very fast.
Tabla de contenidos resource gmp_and ( resource a, resource b)
gmp_abs -- Absolute value
gmp_add -- Add numbers
gmp_and -- Logical AND Calculates logical AND of two GMP numbers.
gmp_clrbit -- Clear bit
gmp_cmp -- Compare numbers gmp_clrbit
gmp_com -- Calculates one's complement of a
gmp_div_q -- Divide numbers
gmp_div_qr -- Divide numbers and get quotient and (PHP 4 >= 4.0.4)
remainder gmp_clrbit -- Clear bit
gmp_div_r -- Remainder of the division of numbers
gmp_div -- Divide numbers
gmp_divexact -- Exact division of numbers Description
gmp_fact -- Factorial
gmp_gcd -- Calculate GCD
resource gmp_clrbit ( resource &a, int index)
gmp_gcdext -- Calculate GCD and multipliers
gmp_hamdist -- Hamming distance
gmp_init -- Create GMP number Clears (sets to 0) bit index in a.
gmp_intval -- Convert GMP number to integer
gmp_invert -- Inverse by modulo
gmp_jacobi -- Jacobi symbol gmp_cmp
gmp_legendre -- Legendre symbol
gmp_mod -- Modulo operation (PHP 4 >= 4.0.4)
gmp_mul -- Multiply numbers gmp_cmp -- Compare numbers
gmp_neg -- Negate number
gmp_or -- Logical OR
gmp_perfect_square -- Perfect square check Description
gmp_popcount -- Population count
gmp_pow -- Raise number into power
gmp_powm -- Raise number into power with modulo int gmp_cmp ( resource a, resource b)
gmp_prob_prime -- Check if number is "probably prime"
gmp_random -- Random number Returns positive value if a > b, zero if a = b and negative
gmp_scan0 -- Scan for 0 value if a < b.
gmp_scan1 -- Scan for 1
gmp_setbit -- Set bit
gmp_sign -- Sign of number gmp_com
gmp_sqrt -- Square root
gmp_sqrtrm -- Square root with remainder
gmp_strval -- Convert GMP number to string (PHP 4 >= 4.0.4)
gmp_sub -- Subtract numbers gmp_com -- Calculates one's complement of a
gmp_xor -- Logical XOR
Description
gmp_abs
resource gmp_com ( resource a)
(PHP 4 >= 4.0.4)
gmp_abs -- Absolute value
Aviso
Esta función no está documentada actualmente, solamente
Description se encuentra disponible la lista de parametros.

resource gmp_abs ( resource a)


gmp_div_q
Returns absolute value of a.
(PHP 4 >= 4.0.4) See also gmp_div_q(), gmp_div_qr()
gmp_div_q -- Divide numbers

gmp_div
Description

(PHP 4 >= 4.0.4)


resource gmp_div_q ( resource a, resource b [, int gmp_div -- Divide numbers
round])

Description
Divides a by b and returns the integer result. The result
rounding is defined by the round, which can have the
following values: resource gmp_divexact ( resource a, resource b)

This function is an alias to gmp_div_q().


• GMP_ROUND_ZERO: The result is truncated
towards 0.
gmp_divexact
• GMP_ROUND_PLUSINF: The result is rounded
towards +infinity.
• GMP_ROUND_MINUSINF: The result is rounded (PHP 4 >= 4.0.4)
towards -infinity. gmp_divexact -- Exact division of numbers

This function can also be called as gmp_div(). Description


See also gmp_div_r(), gmp_div_qr()
resource gmp_divexact ( resource n, resource d)
gmp_div_qr
Divides n by d, using fast "exact division" algorithm. This
function produces correct results only when it is known in
(PHP 4 >= 4.0.4) advance that d divides n.
gmp_div_qr -- Divide numbers and get quotient and
remainder
gmp_fact
Description
(PHP 4 >= 4.0.4)
gmp_fact -- Factorial
array gmp_div_qr ( resource n, resource d [, int round])

The function divides n by d and returns array, with the Description


first element being [n/d] (the integer result of the
division) and the second being (n - [n/d] * d) (the resource gmp_fact ( int a)
remainder of the division).
See the gmp_div_q() function for description of the
round argument. Calculates factorial (a!) of a.
Ejemplo 1. Division of GMP numbers
gmp_gcd
<?php
$a = gmp_init (PHP 4 >= 4.0.4)
("0x41682179fbf5"); gmp_gcd -- Calculate GCD
$res = gmp_div_qr ($a,
"0xDEFE75");
printf("Result is: q - %s, r - %s", Description
gmp_strval ($res[0]),
gmp_strval ($res[1]));
resource gmp_gcd ( resource a, resource b)
?>
See also gmp_div_q(), gmp_div_r().
Calculate greatest common divisor of a and b. The result
is always positive even if either of or both input operands
gmp_div_r are negative.

(PHP 4 >= 4.0.4) gmp_gcdext


gmp_div_r -- Remainder of the division of numbers
(PHP 4 >= 4.0.4)
Description gmp_gcdext -- Calculate GCD and multipliers

resource gmp_div_r ( resource n, resource d [, int Description


round])
array gmp_gcdext ( resource a, resource b)
Calculates remainder of the integer division of n by d.
The remainder has the sign of the n argument, if not
Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b),
zero.
where gcd is gretest common divisor. Returns array with
See the gmp_div_q() function for description of the
respective elements g, s and t.
round argument.
gmp_hamdist resource gmp_invert ( resource a, resource b)

(PHP 4 >= 4.0.4) Computes the inverse of a modulo b. Returns FALSE if


gmp_hamdist -- Hamming distance an inverse does not exist.

Description gmp_jacobi

int gmp_hamdist ( resource a, resource b) (PHP 4 >= 4.0.4)


gmp_jacobi -- Jacobi symbol

Returns the hamming distance between a and a. Both


operands should be non-negative. Description

gmp_init int gmp_jacobi ( resource a, resource p)

(PHP 4 >= 4.0.4) Computes Jacobi symbol of a and p. p should be odd and
gmp_init -- Create GMP number must be positive.

Description gmp_legendre

resource gmp_init ( mixed number) (PHP 4 >= 4.0.4)


gmp_legendre -- Legendre symbol

Creates a GMP number from integer or string. String


representation can be decimal or hexadecimal. In the Description
latter case, the string should start with 0x.
Ejemplo 1. Creating GMP number
int gmp_legendre ( resource a, resource p)

<?php Compute the Legendre symbol of a and p. p should be


$a = gmp_init (123456); odd and must be positive.
$b = gmp_init
("0xFFFFDEBACDFEDF7200");
?> gmp_mod

(PHP 4 >= 4.0.4)


Nota: It is not necessary to call this gmp_mod -- Modulo operation
function if you want to use integer or
string in place of GMP number in
GMP functions, like gmp_add(). Description
Function arguments are
automatically converted to GMP
numbers, if such conversion is resource gmp_mod ( resource n, resource d)
possible and needed, using the same
rules as gmp_init(). Calculates n modulo d. The result is always non-negative,
the sign of d is ignored.
gmp_intval
gmp_mul
(PHP 4 >= 4.0.4)
gmp_intval -- Convert GMP number to integer (PHP 4 >= 4.0.4)
gmp_mul -- Multiply numbers
Description
Description
int gmp_intval ( resource gmpnumber)
resource gmp_mul ( resource a, resource b)
This function allows to convert GMP number to integer.
Aviso Multiplies a by b and returns the result.

This function returns useful result only if the number


actually fits the PHP integer (i.e., signed long type). If you gmp_neg
want just to print the GMP number, use gmp_strval().
(PHP 4 >= 4.0.4)
gmp_neg -- Negate number
gmp_invert

Description
(PHP 4 >= 4.0.4)
gmp_invert -- Inverse by modulo
resource gmp_neg ( resource a)
Description
Returns -a.
gmp_or gmp_prob_prime -- Check if number is "probably prime"

(PHP 4 >= 4.0.4) Description


gmp_or -- Logical OR

int gmp_prob_prime ( resource a [, int reps])


Description
If this function returns 0, a is definitely not prime. If it
resource gmp_or ( resource a, resource b) returns 1, then a is "probably" prime. If it returns 2, then
a is surely prime. Reasonable values of reps vary from 5
to 10 (default being 10); a higher value lowers the
Calculates logical inclusive OR of two GMP numbers. probability for a non-prime to pass as a "probable" prime.
The function uses Miller-Rabin's probabilistic test.
gmp_perfect_square
gmp_random
(PHP 4 >= 4.0.4)
gmp_perfect_square -- Perfect square check (PHP 4 >= 4.0.4)
gmp_random -- Random number
Description
Description
bool gmp_perfect_square ( resource a)
resource gmp_random ( int limiter)
Returns TRUE if a is a prefect square, FALSE otherwise.
See also: gmp_sqrt(), gmp_sqrtrm(). Generate a random number. The number will be up to
limiter words long. If limiter is negative, negative
numbers are generated.
gmp_popcount

gmp_scan0
(PHP 4 >= 4.0.4)
gmp_popcount -- Population count
(PHP 4 >= 4.0.4)
gmp_scan0 -- Scan for 0
Description

Description
int gmp_popcount ( resource a)

Return the population count of a. int gmp_scan0 ( resource a, int start)

Scans a, starting with bit start, towards more significant


gmp_pow
bits, until the first clear bit is found. Returns the index of
the found bit.
(PHP 4 >= 4.0.4)
gmp_pow -- Raise number into power
gmp_scan1

Description
(PHP 4 >= 4.0.4)
gmp_scan1 -- Scan for 1
resource gmp_pow ( resource base, int exp)
Description
Raise base into power exp. The case of 0^0 yields 1. exp
cannot be negative.
int gmp_scan1 ( resource a, int start)

gmp_powm
Scans a, starting with bit start, towards more significant
bits, until the first set bit is found. Returns the index of
(PHP 4 >= 4.0.4) the found bit.
gmp_powm -- Raise number into power with modulo
gmp_setbit
Description
(PHP 4 >= 4.0.4)
resource gmp_powm ( resource base, resource exp, gmp_setbit -- Set bit
resource mod)
Description
Calculate (base raised into power exp) modulo mod. If
exp is negative, result is undefined.
resource gmp_setbit ( resource &a, int index [, bool
set_clear])
gmp_prob_prime
Sets bit index in a. set_clear defines if the bit is set to 0
(PHP 4 >= 4.0.4) or 1. By default the bit is set to 1.
gmp_sign resource gmp_sub ( resource a, resource b)

(PHP 4 >= 4.0.4) Subtract b from a and returns the result.


gmp_sign -- Sign of number
gmp_xor
Description
(PHP 4 >= 4.0.4)
int gmp_sign ( resource a) gmp_xor -- Logical XOR

Return sign of a - 1 if a is positive and -1 if it's negative. Description

gmp_sqrt resource gmp_xor ( resource a, resource b)

(PHP 4 >= 4.0.4) Calculates logical exclusive OR (XOR) of two GMP


gmp_sqrt -- Square root numbers.

Description XXXVII. Funciones HTTP

resource gmp_sqrt ( resource a) Estas funciones permiten manipular la salida que se


envía al navegador remoto a nivel de protocolo HTTP.
Tabla de contenidos
Calculates square root of a. header -- Manda una cabecera HTTP
headers_sent -- Checks if or where headers have been
sent
gmp_sqrtrm
setcookie -- Envía una cookie

(no version information, might be only in CVS)


header
gmp_sqrtrm -- Square root with remainder

(PHP 3, PHP 4 )
Description
header -- Manda una cabecera HTTP

array gmp_sqrtrm ( resource a)


Descripción

Returns array where first element is the integer square


root of a (see also gmp_sqrt()), and the second is the int header ( string string)
remainder (i.e., the difference between a and the first
element squared). La función header() se utiliza al comienzo de un fichero
HTML para enviar las cadenas de texto de la cabecera
HTTP. Consulte la Especificación HTTP 1.1 para obtener
gmp_strval
más información sobre las cabeceras http. Nota:
Recuerde que la función header() debe llamarse antes
(PHP 4 >= 4.0.4) de que se genere salida alguna, bien con etiquetas HTML
gmp_strval -- Convert GMP number to string normales o con PHP. Un error muy frecuente consiste en
leer código con include() o con auto_prepend, y que
dicho código inserte espacios o líneas en blanco antes de
Description llamar a header().
Hay dos casos especiales de llamadas a header. La
primera es la cabecera "Location". No sólo envía esta
string gmp_strval ( resource gmpnumber [, int base]) cabecera al navegador, sino que también devuelve un
código de estado REDIRECT a Apache. Desde el punto de
Convert GMP number to string representation in base vista del programador de scripts esto no debería ser
base. The default base is 10. Allowed values for the base importante, pero para la gente que comprende las
are from 2 to 36. interioridades de Apache sí puede serlo.
Ejemplo 1. Converting GMP number to string header("Location: http://www.php.net"); /* Redirect
browser to PHP web site */
exit; /* Make sure that code below does not get executed
<?php when we redirect. */
$a = gmp_init("0x41682179fbf5");
printf ("Decimal: %s, 36-based: %s", gmp_strval($a), El segundo caso especial se produce con cualquier
gmp_strval($a,36)); cabecera que comience con la cadena, "HTTP/" (las
?> mayúsculas no son significativas). Por ejemplo, si tiene la
directiva ErrorDocument 404 de Apache apuntando a un
script PHP, es una buena idea asegurarse de que su
script de PHP genera realmente un 404. La primera cosa
gmp_sub
que debe hacer en su script sería:
header("http/1.0 404 Not
(PHP 4 >= 4.0.4) Found");
gmp_sub -- Subtract numbers
Los scripts de PHP a menudo generan HTML dinámico
que no debe almacenarse en la caché del navegador
Description cliente o en la caché de cualquier proxy situado entre el
servidor y el navegador cliente. Se puede obligar a
muchos proxies y clientes a que deshabiliten el setcookie
almacenamiento en caché con
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); (PHP 3, PHP 4 )
// Date in the past setcookie -- Envía una cookie
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "
GMT"); // always modified
header("Cache-Control: no-cache, must-revalidate"); Descripción
// HTTP/1.1
header("Pragma: no-cache"); //
HTTP/1.0 int setcookie ( string name, string value, int expire,
string path, string domain, int secure)

headers_sent setcookie() define una cookie para ser enviada con el


resto de la información de la cabecera. Las cookies
deben enviarse antes de mandar cualquier otra cabecera
(PHP 3>= 3.0.8, PHP 4 ) (esta es una restricción de las cookies, no de PHP). Esto
headers_sent -- Checks if or where headers have been requiere que sitúe las llamadas a esta función antes de
sent cualquier etiqueta <html> o <head>.
Todos los parámetros excepto name son opcionales. Si
sólo se especifica el parámetro name, la cookie con ese
Description
nombre se borrará del cliente remoto. También puede
sustituir cualquier parámetro por una cadena de texto
boolean headers_sent ( [string &file [, int &line]]) vacía ("") y saltar así ese parámetro. Los parámetros
expire y secure son números enteros y no se pueden
saltar con una cadena de texto vacía. En su lugar utilice
headers_sent() will return FALSE if no HTTP headers un cero (0). El parámetro expire es un entero de tiempo
have already been sent or TRUE otherwise. If the típico de UNIX tal como lo devuelven las funciones
optional file and line parameters are set, time() o mktime(). El parámetro secure indica que la
headers_sent() will put the php source file name and cookie se debe transmitir única y exclusivamente sobre
line number where output started in the file and line una conexión segura HTTPS.
variables. Fallos habituales:
You can't add any more header lines using the header() Las cookies no se hacen visibles hasta la siguiente carga
function once the header block has already been sent. de una página para la que la cookie deba estar visible.
Using this function you can at least prevent getting HTTP Las llamadas múltiples a setcookie() en el mismo script
header related error messages. Another option is to use se ejecutarán en orden inverso. Si está intentando borrar
Output Buffering. una cookie antes de insertar otra, debe situar la llamada
de inserción antes de la de borrado.
New parameters: The optional file A continuación se muestran algunos ejemplos::
and line parameters where added in Ejemplo 1. setcookie(), ejemplos
PHP 4.3.0.

setcookie("TestCookie","Test Value");
Ejemplo 1. Examples using headers_sent() setcookie("TestCookie",$value,time()+3600); /*
expire in 1 hour */
setcookie("TestCookie",$value,time()
<?php +3600,"/~rasmus/",".utoronto.ca",1);
Tenga en cuenta que el campo value de la cookie se
// If no headers are sent, send one codifica como URL (urlencode) automáticamente cuando
if (!headers_sent()) { envía la cookie. Cuando ésta se recibe, se descodifica
header ('Location: http://www.example.com/'); autómaticamente y se asigna a una variable con el
exit; mismo nombre que el nombre de la cookie. Para ver el
} contenido de nuestra cookie de prueba en un script,
simplemente utilice uno de los siguientes ejemplos:
// An example using the optional file and line
parameters, as of PHP 4.3.0 echo $TestCookie;
// Note that $filename and $linenum are passed in for echo
later use. $HTTP_COOKIE_VARS["TestCooki
// Do not assign them values beforehand. e"];
if (!headers_sent($filename, $linenum)) { También puede utilizar arrays de cookies empleando la
header ('Location: http://www.example.com/'); notación de array en el nombre de la cookie. Esto tiene
exit; como efecto establecer tantas cookies como elementos
de array, pero cuando el script recibe la cookie, se
// You would most likely trigger an error here. guardan los valores en un array con el nombre de la
} else { cookie:
print "Headers already sent in $filename on line setcookie( "cookie[three]",
$linenum\n" . "cookiethree" );
"Cannot redirect, for now please click this <a setcookie( "cookie[two]", "cookietwo"
". );
"href=\"http://www.example.com\">link</a> setcookie( "cookie[one]", "cookieone"
instead\n"; );
exit; if ( isset( $cookie ) ) {
} while( list( $name, $value ) = each(
$cookie ) ) {
?> echo "$name ==
$value<br>\n";
See also ob_start(), trigger_error(), and header() for }
a more detailed discussion of the matters involved. }
Para obtener más información sobre las cookies, consulte modificarse fácilmente. El documento que contiene el
la especificación de cookies de Netscape, que se enlace no se ve afectado. Incluso se puede añadir un
encuentra en enlace a un documento sin alterarlo.
http://www.netscape.com/newsref/std/cookie_spec.html. Decir que hw_pipedocument() y hw_gettext() hacen
Microsoft Internet Explorer 4 con Service Pack 1 no automáticamente la inserción de enlaces no es tan
funciona correctamente con las cookies que tienen simple como suena. Insertar los enlaces implica una
asociado el parámetro path. cierta jerarquía en los documentos. En un servidor web
Netscape Communicator 4.05 y Microsoft Internet esto viene dado por el sistema de archivos, pero el
Explorer 3.x funcionan aparentemente de manera Hyperwave tiene su propia jerarquía y los nombres no
incorrecta cuando no se especifican los parámetros path representan la posición de un objeto en dicha jerarquía.
y time. Por tanto, la creación de los enlaces precisa
primeramente de realizar un mapeado entre el espacio
de nombres y la jerarquía del Hyperwave y el espacio de
XXXVIII. Funciones para Hyperwave nombres respectivo de una jerarquía de web. La
diferencia fundamental entre Hyperwave y la web es la
distinción clara entre nombres y jerarquía que se da en el
Introducción
primero. El nombre no contiene ninguna información
sobre la posición del objeto en la jerarquía. En la web, el
Hyperwave ha sido desarrollado en el IICM en Graz. nombre también contiene la información sobre la
Comenzó con el nombre Hyper-G y cambió a Hyperwave posición en la jerarquía del objeto. Esto nos lleva a dos
cuando fue comercializado (Si lo recuerdo bien, fue en posibles formas de mapeo. O bien se reflejan la jerarquía
1996). del Hyperwave y el nombre del objeto Hyperwave en el
Hyperwave no es software gratuiro. La versión actual, URL o sólo el nombre. Para facilitar las cosas, se utiliza el
4.1, está disponible en http://www.hyperwave.com/. Se segundo método. El objeto Hyperwave de nombre
puede solicitar gratuitamente una versión limitada (30 'mi_objeto' es mapeado a 'http://host/mi_objeto' sin
días). importar dónde reside dentro de la jerarquía de
Hyperwave es un sistema de información similar a una Hyperwave. Un objeto con el nombre 'padre/mi_objeto'
base de datos (HIS, Hyperwave Information Server - podría ser el hijo de 'mi_objeto' en la jerarquía
Servidor Hyperwave de Información). Su objetivo es el Hyperwave, aunque en el espacio de nombres web
almacenamiento y manipulación de documentos. Un aparezca justamente lo opuesto y el usuario pueda ser
documento puede ser cualquier bloque posible de datos llevado a confusión. Esto sólo se puede evitar
que también puede ser almacenado en un archivo. Cada seleccionando nombres de objetos razonables.
documento se acompaña por su registro de objeto. El Hecha esta decisión surge un segundo problema. ¿Cómo
registro de objeto contiene metadatos para el implicar al PHP? el URL http://host/mi_objeto no llamará a
documento. Los metadatos son una lista de atributos que ningún script PHP a no ser que se le diga al servidor que
pueden ser extendidos por el usuario. Ciertos atributos lo transforme en p. ej. 'http://host/script_php3/mi_objeto'
siempre son fijados por el servidor Hyperwave, otros y que el 'script_php3' luego evalúe la variable
pueden ser modificados por el usuario. Un atributo es un $PATH_INFO y recupere el objeto con nombre 'mi_objeto'
par nombre/valor de la forma nombre=valor. El registro del servidor Hyperwave. Hay sólo un pequeño
completo del objeto tiene tantos de estos pares como inconveniente que se puede resolver fácilmente. Cuando
guste el usuario. El nombre de un atributo no tiene se reescribe cualquier URL no se permite el acceso a
porqué ser único, p. ej. un título puede aparecer varias ningún otro documento en el servidor web. Un script de
veces en el registro de un objeto. Esto tiene sentido si se PHP para buscar en el servidor Hyperwave sería
desea especificar un título en diferentes idiomas. En imposible. Por lo tanto se necesitará al menos una
dicho caso existe la convención de que cada valor de segunda regla de reescritura para que excluya ciertos
título esté precedido por la abreviatura de dos letras del URL, como los que empiecen p. ej. por
idioma, seguida por dos puntos, como p. ej. 'en:Title in http://host/Hyperwave. Básicamente esto sería compartir
English' o 'es:Título en Español'. Otros atributos tales un espacio de nombres entre el servidor web y el
como descripciones o palabras clave son canditatos servidor Hyperwave.
potenciales a esta diferenciación. También se pueden Los enlaces se insertan en los documentos basándose en
reemplazar las abreviaturas de idioma por cualquier otra el mecanismo citado más arriba.
cadena siempre y cuando estén separadas por los dos Se vuelve más complicado si el PHP no se está
puntos del resto del valor del atributo. ejecutando como módulo del servidor o como script CGI,
Cada registro de objeto tiene una representación nativa sino que se ejecuta como aplicación, p. ej. para volcar el
como cadena con cada par nombre/valor separado por contenido del servidor de Hyperwave a un CD-ROM. En
una línea nueva. La extensión Hyperwave también dicho caso tiene sentido mantener la jerarquía
conoce una segunda representación que consiste en un Hyperwave y mapearla en el sistema de archivos. Esto
array asociativo donde el nombre del atributo es la clave. entra conflicto con los nombres de los objetos si estos
Los valores de atributo multilingües en sí mismos forman reflejan su propia jerarquía (p. ej. eligiendo nombres que
otro array asociativo donde la clave es la abreviatura del comienzan por '/'). Por tanto, la '/' tendrá que ser
idioma. Realmente cualquier atributo múltiple forma una reemplazada por otro carácter, p. ej. '_' para continuar.
tabla asociativa donde la cadena a la izquierda de los dos El protocolo de red para comunicarse con el servidor
puntos en el valor de atributo es la clave. (Esto no se ha Hyperwave se denomina HG-CSP (Hyper-G Client/Server
implementado por completo. Sólo los atributos Title, Protocol, Protocolo Hyper-G Cliente/Servidor). Está
Description y Keyword son tratados adecuadamente.) basado en mensajes que inician ciertas acciones, p. ej.
Aparte de los documentos, todos los hiper-enlaces obtener el registro de un objeto. En versiones anteriores
contenidos en un documento son almacenados también del Servidor Hyperwave se distribuyeron dos clientes
como registros de objeto. Cuando el documento sea nativos (Harmony, Amadeus) para la comunicación con el
insertado en la base de datos, los hiper-enlaces que haya servidor. Ambos desaparecieron cuando se comercializó
en un documento serán borrados del mismo y el Hyperwave. Para sustituírlo se proporcionó el llamado
almacenados como objetos individuales. El registro de wavemaster. El wavemaster es como un conversor de
objeto del enlace contiene información acerca de dónde protocolo de HTTP a HG-CSP. La idea es realizar toda la
comienza y dónde termina. Para recuperar el documento administración de la base de datos y la visualización de
original se deberá recuperar el documento sin los documentos con una interfaz web. El wavemaster
enlaces y la lista de los mismos para reinsertarla (Las implementa una serie de posicionadores para acciones
funciones hw_pipedocument() y hw_gettext() hacen que permiten personalizar la interfaz. Dicho conjunto de
esto para usted). La ventaja de separar los enlaces del posicionadores se denomina el Lenguaje PLACE. El PLACE
documento es obvia. Una vez un documento al que no posee muchas de las características de un lenguaje
apunta un enlace cambia de nombre, el enlace puede de programación real y las extensiones al mismo
únicamente alargan la lista de posicionadores. Esto ha La extensión Hyperwave se utiliza mejor cuando el PHP
obligado al uso de JavaScript que, en mi opinión, no hace se compila como un módulo de Apache. En tal caso el
la vida más fácil. servidor Hyperwave subyacente puede ser ocultado casi
Añadir soporte de Hyperwave al PHP rellenaría el espacio por completo de los usuarios si el Apache utiliza su motor
que deja la falta de un lenguaje de programación que de re-escritura. Las siguientes instrucciones explicarán
permita personalizar la interfaz. El PHP implementa todos esto.
los mensajes definidos en el HG-CSP pero además Como el PHP con soporte Hyperwave incluído en el
proporciona comandos más poderosos, p. ej. recuperar Apache se ha diseñado para sustituir la solución nativa
documentos completos. de Hyperwave basada en Wavemaster, asumiré que el
El Hyperwave tiene su propia terminología para dar servidor Apache sólo sirve como interfaz web para el
nombre a ciertos tipos de información. Esta ha sido Hyperwave. Esto no es necesario, pero simplifica la
ampliamente extendida y anulada. Casi todas las configuración. El concepto es bastante sencillo.
funciones operan en uno de los siguientes tipos de datos. Primeramente necesita un script PHP que evalúe la
variable PATH_INFO y que trate su valor como el nombre
de un objeto Hyperwave. Llamemos a este script
• ID de objeto: Un valor entero único paara cada 'Hyperwave'. El URL
objeto del servidor Hyperwave. También es http://nombre.servidor/Hyperwave/nombre_de_objeto
uno de los atributos del registro de objeto devolvería entonces el objeto Hyperwave llamado
(ObjectID). Los ID de objeto se usan 'nombre_de_objeto'. Dependiendo del tipo del objeto, así
generalmente como parámetros de entrada reaccionará el script. Si es una colección, probablemente
que especifican a un objeto. devolverá un lista de hijos. Si es un documento devolverá
el tipo MIME y el contenido. Se puede mejorar
• registro de objeto: Una cadena con pares ligeramente si se usa el motor de re-escritura del
atributo-valor con la forma atributo=valos. Los Apache. Desde el punto de vista del usuario será más
pares están separados unos de otros por un sencillo si el URL http://nombre.servidor/nombre de
retorno de carro. Un registro de objeto puede objeto devuelve el objeto. La regla de reescritura es muy
convertirse fácilmente en una tabla (array) de sencilla:
objetos usando hw_object2array(). Varias
funciones devuelven registros de objeto. Los RewriteRule ^/(.*)
nombres de dichas funciones terminan en obj. /usr/local/apache/htdocs/HyperWave/$1 [L]

• tabla de objetos: Una tabla asociativa con Ahora todo URL apunta a un objeto en el servidor
todos los atributos de un objeto. La clave es el Hyperwave. Esto provoca un problema sencillo de
nombre del atributo. Si un atributo aparece resolver. No hay forma de ejecutar otro script, p. ej. para
más de una vez en un registro de objeto será buscar, salvo el script 'Hyperwave'. Esto se puede
convertido en otra tabla asociativa o indizada. solucionar con otra regla de reescritura como la
Los atributos que dependen del idioma (como siguiente:
el título, claves o descripción) se convertirán RewriteRule ^/hw/(.*)
en una tabla asociativa con la abreviatura del /usr/local/apache/htdocs/hw/$1 [L]
idioma como clave. El resto de los atributos
múltiples crearán una tabla indizada. Las Esta reservará el directorio /usr/local/apache/htdocs/hw
funciones de PHP nunca devuelven tablas de para script adicionales y otros archivos. Sólo hay que
objetos. asegurarse que esta regla se evalúa antes de la otra.
Sólo hay un pequeño inconveniente: todos los objetos
• hw_document: Este es un nuevo tipo de datos Hyperwave cuyo nombre comienza por 'hw/' serán
que almacena el documento actual, p. ej. ocultados. así que asegúrese que no utiliza dichos
HTML, PDF, etc. Está algo optimizado para nombres. Si necesita más directorios, p. ej. para
documentos HTML pero puede usarse para imágenes, simplemente añada más reglas o sitúe los
cualquier formato. archivos en un solo directorio. Por último, no olvide
conectar el motor de re-escritura con
Varias funciones que devuelven una tabla de registros de RewriteEngin
objeto también devuelven una tabla asociativa con e on
información estadística sobre los mismos. La tabla es el Mi experiencia me ha demostrado que necesitará los
último elemento del registro de objeto. La tabla siguientes scripts:
estadística contiene los siguientes elementos:
Hidden
Número de registros de objeto con el atributo
PresentationHints puesto a Hidden.
• para devolver el script en sí
CollectionHead • para permitir las búsquedas
Número de registros de objeto con el atributo
PresentationHints puesto a CollectionHead.
• para identificarse
FullCollectionHead • para ajustar su perfil
Número de registros de objeto con el atributo
PresentationHints puesto a FullCollectionHead.
• uno para cada función adicional como mostrar
los atributos del objeto, mostrar información
CollectionHeadNr
sobre usuarios, mostrar el estado del servidor,
Índice a una tabla de regitros de objeto con el
etc.
atributo PresentationHints puesto a
CollectionHead.
FullCollectionHeadNr
Índice a una tabla de regitros de objeto con el
atributo PresentationHints puesto a Pendientes
FullCollectionHead.
Total
Total: Número de registros de objeto. Aún hay varias cosas pendientes:

Integración con Apache • hw_InsertDocument debe dividirse en


hw_InsertObject() y hw_PutDocument().
hw_InsDoc -- insertar documento
• Los nombres de algunas funciones aún no
hw_insertanchors -- Inserts only anchors into text
están fijados.
hw_InsertDocument -- subir cualquier objeto
• Muchas funciones precisan la conexión actual hw_InsertObject -- inserta un registro de objeto
como primer parámetro. Esto obliga a escribir hw_mapid -- Mapea in id global a un id virtual local
mucho, lo cual no es con frecuencia necesario hw_Modifyobject -- modifica el registro de objeto
si sólo hay una conexión abierta. Una conexión hw_Mv -- mueve objetos
por defecto mejoraría esto. hw_New_Document -- crear nuevo documento
hw_Objrec2Array -- convierte atributos de registro de
• La conversión de registro de objeto a tabla de
objeto a tabla de objetos
objeto necesita manipular cualquier atributo
hw_Output_Document -- prints hw_document
múltiple.
hw_pConnect -- hacer una conexión de base de datos
permanente
Tabla de contenidos hw_PipeDocument -- recupera cualquier documento
hw_Array2Objrec -- convierte atributos de tabla de objeto hw_Root -- ID del objeto raíz
a registro de objeto hw_setlinkroot -- Set the id to which links are calculated
hw_changeobject -- Changes attributes of an object hw_stat -- Returns status string
(obsolete) hw_Unlock -- desbloquea objeto
hw_Children -- id de objeto de los hijos hw_Who -- Lista de los usuarios actualmente conectados
hw_ChildrenObj -- registros de objeto de los hijos
hw_Close -- cierra la conexión Hyperwave
hw_Array2Objrec
hw_Connect -- abre una conexión
hw_connection_info -- Prints information about the
connection to Hyperwave server (PHP 3>= 3.0.4, PHP 4 )
hw_Cp -- copia objetos hw_Array2Objrec -- convierte atributos de tabla de objeto
hw_Deleteobject -- borra objetos a registro de objeto
hw_DocByAnchor -- id del objeto al que pertenece un
enlace
hw_DocByAnchorObj -- registro de objeto al que Descripción
pertenece un enlace
hw_Document_Attributes -- object record of
hw_document strin hw_array2objrec ( array tabla_objetos)
hw_Document_BodyTag -- body tag of hw_document
hw_Document_Content -- returns content of Convierte una tabla_objetos en un registro de objeto. Los
hw_document atributos múltiples como 'Título' en distintos idiomas son
hw_Document_SetContent -- sets/replaces content of tratados correctamente.
hw_document Vea también hw_objrec2array().
hw_Document_Size -- size of hw_document
hw_dummy -- Hyperwave dummy function
hw_EditText -- recupera documento de texto hw_changeobject
hw_Error -- número de error
hw_ErrorMsg -- devuelve un mensaje de error
(PHP 3>= 3.0.3, PHP 4 )
hw_Free_Document -- libera un documento_hw
hw_changeobject -- Changes attributes of an object
hw_GetAnchors -- id de objeto de los enlaces de un
(obsolete)
documento
hw_GetAnchorsObj -- registros de objeto de los enlaces
de un documento Description
hw_GetAndLock -- devuelve registro de objeto y lo
bloquea
hw_GetChildColl -- id de objeto de colecciones hijas void hw_changeobject ( int link, int objid, array
hw_GetChildCollObj -- registros de objeto de colecciones attributes)
hijas
hw_GetChildDocColl -- id de objeto de documentos hijos
de una colección Aviso
hw_GetChildDocCollObj -- registros de objeto de Esta función no está documentada actualmente, solamente
documentos hijos de una colección se encuentra disponible la lista de parametros.
hw_GetObject -- registro de objeto
hw_GetObjectByQuery -- buscar objeto
hw_GetObjectByQueryColl -- buscar objeto en colección
hw_Children
hw_GetObjectByQueryCollObj -- buscar objeto en
colección
hw_GetObjectByQueryObj -- buscar objeto (PHP 3>= 3.0.3, PHP 4 )
hw_GetParents -- id de objeto de los padres hw_Children -- id de objeto de los hijos
hw_GetParentsObj -- registros de objeto de los padres
hw_getrellink -- Get link from source to dest relative to
rootid Descripción
hw_GetRemote -- Obtiene un documento remoto
hw_GetRemoteChildren -- Obtiene el hijo del documento
remoto array hw_children ( int conexión, int IDobjeto)
hw_GetSrcByDestObj -- Devuelve los enlaces que
apuntan al objeto Devuelve una tabla de id de objeto. Cada uno de ellos
hw_GetText -- obtiene un documento de texto pertenece a un hijo de la colección cuyo ID es IDobjeto.
hw_Username -- nombre del usuario actualmente La tabla contiene tanto los documentos como las
conectado colecciones hijas.
hw_Identify -- identificarse como usuario
hw_InCollections -- comprueba si los id de objeto están
en las colecciones hw_ChildrenObj
hw_Info -- información sobre conexión
hw_InsColl -- insertar colección
(PHP 3>= 3.0.3, PHP 4 )
hw_ChildrenObj -- registros de objeto de los hijos hw_Cp -- copia objetos

Descripción Descripción

array hw_childrenobj ( int conexión, int IDobjeto) int hw_cp ( int conexión, array tabla_id_objeto, int id
destino)
Devuelve una tabla de registros de objeto. Cada uno de
ellos pertenece a un hijo de la colección cuyo ID es Copia los objetos cuyos id se especifican en el segundo
IDobjeto. La tabla contiene tanto los documentos como parámetro a la colección identificada como id destino.
las colecciones hijas. El valor devuelto es el número de objetos copiados.
Vea también hw_mv().

hw_Close
hw_Deleteobject

(PHP 3>= 3.0.3, PHP 4 )


hw_Close -- cierra la conexión Hyperwave (PHP 3>= 3.0.3, PHP 4 )
hw_Deleteobject -- borra objetos

Descripción
Descripción

int hw_close ( int conexión)


int hw_deleteobject ( int conexión, int objeto_a_borrar)
Devuelve FALSE si la conexión no es un índice válido de
conexión, y TRUE en caso contrario. Cierra la conexión Borra el objeto con el id dado como segundo parámetro.
dada con el servidor de Hyperwave. Borrará todas las instancias del mismo.
Devuelve TRUE si no hay error o FALSE en caso
contrario.
hw_Connect Vea también hw_mv().

(PHP 3>= 3.0.3, PHP 4 ) hw_DocByAnchor


hw_Connect -- abre una conexión

(PHP 3>= 3.0.3, PHP 4 )


Descripción hw_DocByAnchor -- id del objeto al que pertenece un
enlace
int hw_connect ( string servidor, int puerto, string
usuario, string clave) Descripción

Abre una conexión con un servidor Hyperwave y


int hw_docbyanchor ( int conexión, int IDenlace)
devuelve un índice de conexión si hay éxito, o FALSE si
la conexión no se pudo realizar. Cada argumento debe
ser una cadena entrecomillada salvo el número de Devuelve el id de objeto del documento al que pertenece
puerto. Los argumentos de usuario y clave son el IDenlace.
opcionales y pueden omitirse. En tal caso no se realizará
identificación alguna con el servidor. Es similar a
identificarse como el usuario 'anonymous'. Esta función hw_DocByAnchorObj
devuelve un índice de conexión que se necesita para
otras funciones Hyperwave. Puede tener varias (PHP 3>= 3.0.3, PHP 4 )
conexiones abiertas a la vez. Recuerde que la clave no
hw_DocByAnchorObj -- registro de objeto al que
está encriptada. pertenece un enlace
Vea también hw_pConnect().

Descripción
hw_connection_info

string hw_docbyanchorobj ( int conexión, int IDenlace)


(PHP 3>= 3.0.3, PHP 4 )
hw_connection_info -- Prints information about the
connection to Hyperwave server Devuelve el registro de objeto del documento al que
pertenece el IDenlace.

Description
hw_Document_Attributes

void hw_connection_info ( int link)


(PHP 3>= 3.0.3, PHP 4 )
hw_Document_Attributes -- object record of
Aviso hw_document
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. Description

hw_Cp string hw_document_attributes ( int hw_document)

(PHP 3>= 3.0.3, PHP 4 ) Returns the object record of the document.
For backward compatibility, hw_documentattributes() Description
is also accepted. This is deprecated, however.
See also hw_document_bodytag(), and
hw_document_size(). int hw_document_size ( int hw_document)

Returns the size in bytes of the document.


hw_Document_BodyTag
See also hw_document_bodytag(), and
hw_document_attributes().
(PHP 3>= 3.0.3, PHP 4 ) For backward compatibility, hw_documentsize() is also
hw_Document_BodyTag -- body tag of hw_document accepted. This is deprecated, however.

Description hw_dummy

string hw_document_bodytag ( int hw_document) (PHP 3>= 3.0.3, PHP 4 )


hw_dummy -- Hyperwave dummy function

Returns the BODY tag of the document. If the document


is an HTML document the BODY tag should be printed Description
before the document.
See also hw_document_attributes(), and
hw_document_size(). string hw_dummy ( int link, int id, int msgid)
For backward compatibility, hw_documentbodytag() is
also accepted. This is deprecated, however.
Aviso
Esta función no está documentada actualmente, solamente
hw_Document_Content se encuentra disponible la lista de parametros.

(PHP 3>= 3.0.3, PHP 4 )


hw_Document_Content -- returns content of hw_EditText
hw_document
(PHP 3>= 3.0.3, PHP 4 )
Description hw_EditText -- recupera documento de texto

string hw_document_content ( int hw_document) Descripción

Returns the content of the document. If the document is int hw_edittext ( int conexión, int documento_hw)
an HTML document the content is everything after the
BODY tag. Information from the HEAD and BODY tag is in
Envía el documento de texto al servidor. El registro de
the stored in the object record.
objeto del documento no puede ser modificado mientras
See also hw_document_attributes(),
el documento es editado. Esta función sólo funcionará
hw_document_size(), and
para objetos puros de texto. No abrirá ninguna conexión
hw_document_setcontent().
especial de datos y por tanto bloquea la conexión de
control durante la transferencia.
hw_Document_SetContent Vea también hw_PipeDocument(),
hw_FreeDocument(), hw_DocumentBodyTag(),
hw_DocumentSize(), hw_OutputDocument(),
(PHP 4 ) hw_GetText().
hw_Document_SetContent -- sets/replaces content of
hw_document
hw_Error

Description
(PHP 3>= 3.0.3, PHP 4 )
hw_Error -- número de error
string hw_document_setcontent ( int hw_document,
string content)
Descripción
Sets or replaces the content of the document. If the
document is an HTML document the content is int hw_error ( int conexión)
everything after the BODY tag. Information from the
HEAD and BODY tag is in the stored in the object record.
Devuelve el último número de error. Si el valor devuelto
If you provide this information in the content of the
es 0 no ha habido errores. El error está relacionado con
document too, the Hyperwave server will change the
el último comando.
object record accordingly when the document is inserted.
Probably not a very good idea. If this functions fails the
document will retain its old content. hw_ErrorMsg
See also hw_document_attributes(),
hw_document_size(), and hw_document_content().
(PHP 3>= 3.0.3, PHP 4 )
hw_ErrorMsg -- devuelve un mensaje de error
hw_Document_Size

Descripción
(PHP 3>= 3.0.3, PHP 4 )
hw_Document_Size -- size of hw_document
string hw_errormsg ( int conexión)
Devuelve una cadena que contiene el último mensaje de Descripción
error o 'No Error'. Si devuelve FALSE es que la función
fracasó. El mensaje está relacionado con el último
comando. array hw_getchildcoll ( int conexión, int IDobjeto)

Devuelve una tabla de id de objeto. Cada ID de objeto


hw_Free_Document
pertenece a una colección hija de la colección con ID
IDobjeto. La función no devolverá documentos hijos.
(PHP 3>= 3.0.3, PHP 4 ) Vea también hw_GetChildren(),
hw_Free_Document -- libera un documento_hw hw_GetChildDocColl().

Descripción hw_GetChildCollObj

int hw_free_document ( int documento_hw) (PHP 3>= 3.0.3, PHP 4 )


hw_GetChildCollObj -- registros de objeto de colecciones
hijas
Libera la memoria ocupada por el documento
Hyperwave.
Descripción

hw_GetAnchors
array hw_getchildcollobj ( int conexión, int IDobjeto)

(PHP 3>= 3.0.3, PHP 4 )


hw_GetAnchors -- id de objeto de los enlaces de un Devuelve una tabla de registros de objeto. Cada uno de
documento ellos pertenece a una colección hija de la colección con
ID IDobjeto. La función no devolverá documentos hijos.
Vea también hw_ChildrenObj(),
Descripción hw_GetChildDocCollObj().

array hw_getanchors ( int conexión, int IDobjeto) hw_GetChildDocColl

Devuelve una tabla de id de objeto con los enlaces del (PHP 3>= 3.0.3, PHP 4 )
documento cuyo ID es IDobjeto. hw_GetChildDocColl -- id de objeto de documentos hijos
de una colección
hw_GetAnchorsObj
Descripción
(PHP 3>= 3.0.3, PHP 4 )
hw_GetAnchorsObj -- registros de objeto de los enlaces array hw_getchilddoccoll ( int conexión, int IDobjeto)
de un documento

Devuelve una tabla de id de objeto para los documentos


Descripción hijos de una colección.
Vea también hw_GetChildren(), hw_GetChildColl().
array hw_getanchorsobj ( int conexión, int IDobjeto)
hw_GetChildDocCollObj
Devuelve una tabla de registros de objeto con los
enlaces del documento cuyo ID es IDobjeto. (PHP 3>= 3.0.3, PHP 4 )
hw_GetChildDocCollObj -- registros de objeto de
documentos hijos de una colección
hw_GetAndLock

Descripción
(PHP 3>= 3.0.3, PHP 4 )
hw_GetAndLock -- devuelve registro de objeto y lo
bloquea array hw_getchilddoccollobj ( int conexión, int
IDobjeto)
Descripción
Devuelve una tabla de registros de objeto para los
documentos hijos de una colección.
string hw_getandlock ( int conexión, int IDobjeto) Vea también hw_ChildrenObj(),
hw_GetChildCollObj().
Devuelve el registro de objeto para el objeto con ID
IDobjeto. También bloqueará el objeto, de modo que
hw_GetObject
otros usuarios no podrán acceder al mismo hasta que
sea desbloqueado.
Vea también hw_Unlock(), hw_GetObject(). (PHP 3>= 3.0.3, PHP 4 )
hw_GetObject -- registro de objeto
hw_GetChildColl
Descripción
(PHP 3>= 3.0.3, PHP 4 )
hw_GetChildColl -- id de objeto de colecciones hijas array hw_getobject ( int conexión, [int|array] IDobjeto,
string consulta)
Devuelve el registro de objeto para el objeto cuyo ID es Busca objetos en la colección cuyo ID es IDobjeto y
IDobjeto si el segundo parámetro es un entero. Si es una devuelve una tabla de registros de objeto. El número
tabla la función devolverá una tabla de registros de máximo de resultados será max_resultados. Si
objeto. En tal caso, el último parámetro, que es una max_resultados vale -1, el número máximo de resultados
cadena de consulta, también es evaluado. es ilimitado.
La cadena de consulta tiene la sintáxis siguiente: La consulta funcionará sólo con atributos indizados.
<expr> ::= "(" <expr> ")" | Vea también hw_GetObjectByQueryColl().
"!" <expr> | /* NO */
<expr> "||" <expr> | /* O */
<expr> "&&" <expr> | /* Y */ hw_GetObjectByQueryObj
<atributo> <operador> <valor>
<atributo> ::= /* cualquier atributo (Título, Autor,
(PHP 3>= 3.0.3, PHP 4 )
TipoDocumento ...) */ hw_GetObjectByQueryObj -- buscar objeto
<operador> ::= "=" | /* igual */
"<" | /* menor que (comparación de cadenas) */
">" | /* mayor que (comparación de cadenas) */ Descripción
"~" /* expresión regular */
La consulta permite seleccionar elementos de la lista de
objetos dada. Al contrario de otras funciones de array hw_getobjectbyqueryobj ( int conexión, string
búsqueda, esta consulta no puede utilizar atributos consulta, int max_resultados)
indizados. El número de registros de objeto devueltos
depende de la consulta y de si está permitido el acceso Busca objetos en todo el servidor y devuelve una tabla
al objeto. de registros de objeto. El número máximo de resultados
Vea también hw_GetAndLock(), será max_resultados. Si max_resultados vale -1, el
hw_GetObjectByQuery(). número máximo de resultados es ilimitado.
La consulta funcionará sólo con atributos indizados.
hw_GetObjectByQuery Vea también hw_GetObjectByQuery().

(PHP 3>= 3.0.3, PHP 4 ) hw_GetParents


hw_GetObjectByQuery -- buscar objeto
(PHP 3>= 3.0.3, PHP 4 )
Descripción hw_GetParents -- id de objeto de los padres

array hw_getobjectbyquery ( int conexión, string Descripción


consulta, int max_resultados)
array hw_getparentsobj ( int conexión, int IDobjeto)
Busca objetos en todo el servidor y devuelve una tabla
de id de objeto. El número máximo de resultados será Devuelve una tabla indizada de id de objeto. Cada una
max_resultados. Si max_resultados vale -1, el número pertenece a un padre del objeto con ID IDobjeto.
máximo de resultados es ilimitado.
La consulta funcionará sólo con atributos indizados.
Vea también hw_GetObjectByQueryObj(). hw_GetParentsObj

hw_GetObjectByQueryColl (PHP 3>= 3.0.3, PHP 4 )


hw_GetParentsObj -- registros de objeto de los padres
(PHP 3>= 3.0.3, PHP 4 )
hw_GetObjectByQueryColl -- buscar objeto en colección Descripción

Descripción array hw_getparentsobj ( int conexión, int IDobjeto)

array hw_getobjectbyquerycoll ( int conexión, int Devuelve una tabla indizada de registros de objeto junto
IDobjeto, string consulta, int max_resultados) a una tabla asociativa con información estadística sobre
estos. La tabla asociativa es el último elemento de la
tabla devuelta. Cada registro de objeto pertenece a un
Busca objetos en la colección cuyo ID es IDobjeto y padre del objeto con ID IDobjeto.
devuelve una tabla de ID de objeto. El número máximo
de resultados será max_resultados. Si max_resultados
vale -1, el número máximo de resultados es ilimitado. hw_getrellink
La consulta funcionará sólo con atributos indizados.
Vea también hw_GetObjectByQueryCollObj().
(PHP 3>= 3.0.3, PHP 4 )
hw_getrellink -- Get link from source to dest relative to
hw_GetObjectByQueryCollObj rootid

(PHP 3>= 3.0.3, PHP 4 ) Description


hw_GetObjectByQueryCollObj -- buscar objeto en
colección
string hw_getrellink ( int link, int rootid, int sourceid, int
destid)
Descripción

Aviso
array hw_getobjectbyquerycollobj ( int conexión, int
IDobjeto, string consulta, int max_resultados) Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. array hw_getsrcbydestobj ( int conexión, int IDobjeto)

Devuelve los registros de objeto de todos los enlaces que


hw_GetRemote apuntan al objeto con ID IDobjeto. El objeto puede ser
tanto un documento como un enlace de tipo destino.
Vea también hw_GetAnchors().
(PHP 3>= 3.0.3, PHP 4 )
hw_GetRemote -- Obtiene un documento remoto
hw_GetText

Descripción
(PHP 3>= 3.0.3, PHP 4 )
hw_GetText -- obtiene un documento de texto
int hw_getremote ( int conexión, int IDobjeto)

Descripción
Devuelve un documento remoto. Los documentos
remotos en la notación de Hyperwave son los obtenidos
de una fuente externa. Los documentos remotos típicos int hw_gettext ( int conexión, int IDobjeto [, mixed
son páginas web externas o consultas a bases de datos. IDraiz/prefijo])
Para poder acceder a las fuentes externas a través de
documentos remotos, el Hyperwave presenta el HGI
(Hyperwave Gateway Interface - Interfaz de Pasarela de Devuelve el documento con ID de objeto IDobjeto. Si el
Hyperwave) que es similar al CGI. Actualmente, sólo se documento tiene enlaces que pueden ser insertados,
puede acceder a servidores ftp y http y a algunas bases serán insertados ahora. El parámetro opcional
de datos. Llamar a hw_GetRemote() devuelve el IDraiz/prefijo puede ser una cadena o un entero. Si es un
documento de la fuente externa. Si desea usar esta entero determina la forma en que los enlaces se insertan
función debe familiarizarse con los HGI. Debería en el documento. Por defecto es 0 y los enlaces se crean
considerar el usar PHP en lugar del Hyperwave para a partir del nombre del objeto de destino de los mismos.
acceder a fuentes externas. Añadir soporte de bases de Esto es útil para aplicaciones web. Si un enlace apunta a
datos a través de una pasarela Hyperwave sería más un objeto con nombre 'pelicula_internet' el enlace HTML
difícil que hacerlo en PHP. será <A HREF="/pelicula_internet">. La posición actual
Vea también hw_GetRemoteChildren(). del objeto de destino en la jerarquía de documentos es
despreciada. Tendrá que ajustar su navegador web para
que reescriba dicho URL a, por ejemplo,
hw_GetRemoteChildren '/mi_script.php3/pelicula_internet'. 'mi_script.php3'
deberá evaluar $PATH_INFO y recuperar el documento.
Todos los enlaces tendrán el prefijo '/mi_script.php3'. Si
(PHP 3>= 3.0.3, PHP 4 ) no desea este efecto puede fijar el parámetro opcional
hw_GetRemoteChildren -- Obtiene el hijo del documento IDraiz/prefijo al prefijo que desee en su lugar. En este
remoto caso deberá ser una cadena.
Si el IDraiz/prefijo es un entero distinto de 0, el enlace se
construye con todos los nombres de objeto comenzando
Descripción
con el objeto de id IDraiz/prefijo, separado por una barra
relativa al objeto actual. Si por ejemplo el documento
int hw_getremotechildren ( int conexión, string anterior 'pelicula_internet' está situado en 'a-b-c-
registro de objeto) pelicula_internet' donde '-' es el separador entre niveles
jerárquicos en el servidor Hyperwave y el documento
fuente está situado en 'a-b-d-fuente', el enlace HTML
Devuelve el hijo de un documento remoto. Los hijos de resultante sería: <A HREF="../c/pelicula_internet">. Esto
documentos remotos son en sí mismos documentos es útil cuando desea bajarse el contenido completo del
remotos. Esto tiene sentido cuando se afina una consulta servidor al disco y mapear la jerarquía de documentos en
de bases de datos y se explica en la Guía de el sistema de archivos.
Programación de Hyperwave. Si el número de hijos es 1 Esta función sólo trabajará en documentos de texto
la función devolverá el documento en sí mismo puros. No se abrirá una conexión de datos especial y por
formateado con la Interfaz de Pasarela de Hyperwave tanto bloqueará la conexión de control durante la
(HGI). Si el número de hijos es mayor de 1 devolverá una transferencia.
tabla de registros de objeto, con cada uno posible Vea también hw_PipeDocument(),
candidato para otra llamada a hw_FreeDocument(), hw_DocumentBodyTag(),
hw_GetRemoteChildren(). Dichos registros de objeto hw_DocumentSize(), hw_OutputDocument().
son virtuales y no existen en el servidor Hyperwave, y
por lo tanto no poseen un ID de objeto válido. La
apariencia exacta de dicho registro de objeto depende hw_Username
del HGI. Si desea usar esta función deberá estar muy
familiarizado con los HGI. También debería considerar el
uso del PHP en lugar de Hyperwave para acceder a (no version information, might be only in CVS)
fuentes externas. Añadir soporte de bases de datos a hw_Username -- nombre del usuario actualmente
través de una pasarela de Hyperwave resulta más difícil conectado
que hacerlo en PHP.
Vea también hw_GetRemote().
Descripción

hw_GetSrcByDestObj
string hw_getusername ( int conexión)

(PHP 3>= 3.0.3, PHP 4 ) Devuelve el nombre de usuario de la conexión.


hw_GetSrcByDestObj -- Devuelve los enlaces que
apuntan al objeto
hw_Identify

Descripción
(PHP 3>= 3.0.3, PHP 4 )
hw_Identify -- identificarse como usuario Inserta una nueva colección con los atributos de la
tabla_objetos en la colección cuyo ID de objeto es
IDobjeto.
Descripción

hw_InsDoc
int hw_identify ( string nombre, string clave)

(PHP 3>= 3.0.3, PHP 4 )


Le identifica como el usuario nombre y clave. La
hw_InsDoc -- insertar documento
identificación sólo es válida para la sesión actual. No
pienso que esta función sea necesaria con mucha
frecuancia. En muchos casos será más fácil identificarse Descripción
al abrir la conexión.
Vea también hw_Connect().
int hw_insdoc ( int conexión, int IDpadre, string
registro_de_objeto, string texto)
hw_InCollections

Inserta un nuevo documento con los atributos del


(PHP 3>= 3.0.3, PHP 4 ) registro_de_objeto en la colección cuyo ID de objeto es
hw_InCollections -- comprueba si los id de objeto están IDpadre. Esta función inserta tanto un registro de objeto
en las colecciones sólo como un registro de objeto y el texto puro en ASCII
dado en texto si este es especificado. si desea insertar
un documento general de cualquier tipo, utilice en su
Descripción lugar hw_insertdocument().
Vea también hw_InsertDocument(), hw_InsColl().
array hw_incollections ( int conexión, array
tabla_id_objeto, array tabla_id_colecciones, int hw_insertanchors
colecciones_devueltas)

(PHP 4 >= 4.0.4)


Comprueba si el conjunto de objetos (documentos o
hw_insertanchors -- Inserts only anchors into text
colecciones) especificado por el parámetro
tabla_id_objeto es parte de las colecciones enumeradas
en tabla_id_colecciones. Cuando el cuarto parámetro Description
colecciones_devueltas es 0, el subconjunto de id de
objeto que es parte de las colecciones (es decir, los
documentos o colecciones hijos de una o más string hw_insertanchors ( int hwdoc, array anchorecs,
colecciones de id de colecciones o de sus array dest [, array urlprefixes])
subcolecciones, recursivamente) es devuelto en forma
de tabla. Cuando el cuarto parámetro es 1, sin embargo,
el conjunto de colecciones que tienen uno o más objetos Aviso
de este subconjunto como hijos es devuelto como tabla. Esta función no está documentada actualmente, solamente
Esta opción permite a un cliente, p. ej., remarcar en una se encuentra disponible la lista de parametros.
visualización gráfica la parte de la jerarquía de
colecciones que contiene las coincidencias de una
consulta previa.
hw_InsertDocument

hw_Info
(PHP 3>= 3.0.3, PHP 4 )
hw_InsertDocument -- subir cualquier objeto
(PHP 3>= 3.0.3, PHP 4 )
hw_Info -- información sobre conexión
Descripción

Descripción
int hw_insertdocument ( int conexión, int id_padre, int
documento_hw)
string hw_info ( int conexión)
Sube un documento a la colección dada por id_padre. El
Devuelve información sobre la conexión actual. La documento debe ser creado antes con la función
cadena devuelta tiene el siguiente formato: hw_NewDocument(). Asegúrese que el registro de
<Cadenaservidor>, <Anfitrión>, <Puerto>, <Usuario>, objeto del nuevo documento contenga al menos los
<Puerto del Usuario>, <Intercambio de bytes> atributos: Type, DocumentType, Title y Name (así, en
inglés). Posiblemente desee fijar también el MimeType.
La función devuelve la id de objeto del nuevo
hw_InsColl documento, o FALSE.
Vea también hw_PipeDocument().
(PHP 3>= 3.0.3, PHP 4 )
hw_InsColl -- insertar colección hw_InsertObject

Descripción (PHP 3>= 3.0.3, PHP 4 )


hw_InsertObject -- inserta un registro de objeto
int hw_inscoll ( int conexión, int IDobjeto, array
tabla_objetos) Descripción
int hw_insertobject ( int conexión, string reg de objeto, alguna en el atributo. Esto es necesario se desea añadir
string parametro) un atributo completamente nuevo, no solamente un
nuevo valor para un atributo existente. Si la tabla
eliminar contuviera una cadena vacía para dicho
Inserta un objeto en el servidor. Este puede consistir en
atributo, este se intentaría suprimir, lo que fallaría
cualquier objeto hyperwave válido. Vea la
porque este no existe. La siguiente adición de un nuevo
documentación sobre el HG-CSP si desea información
valor para dicho atributo también fallará. Fijando el valor
detallada sobre cuáles tienen que ser los parámetros.
para dicho atributo p. ej. a 0 hará que ni siquiera se
Nota: Si se desea insertar un enlace, el atributo Position
intente eliminar, pero funcionará la adición del mismo.
siempre se fijará a un valor comienzo/final o a 'invisible'.
Si desea cambiar el atributo 'Nombre' con el valor actual
Las posiciones invisibles se necesitan si la anotación no
'libros' por el de 'artículos' deberá crear dos tablas y
tiene enlace correspondiente en el texto anotado.
llamar a hw_modifyobject().
Vea también hw_PipeDocument(),
Ejemplo 1. modificando un atributo
hw_InsertDocument(), hw_InsDoc(), hw_InsColl().

hw_mapid // $conexion es una conexión con el servidor


Hyperwave
// $idobj es la ID del objeto a modificar
(PHP 3>= 3.0.13, PHP 4 ) $tablasupr = array("Nombre" => "libros");
hw_mapid -- Mapea in id global a un id virtual local $tablaanad = array("Nombre" =>
"artículos");
$hw_modifyobject($conexion, $idobj,
Descripción
$tablasupr, $tablaanad);
Para borrar/añadir un par nombre=valor de/a el registro
int hw_mapid ( int conexión, int id servidor, int id objeto) de objeto, simplemente pase la tabla eliminar/añadir y
fije el último/tercer parámetro a tabla vacía. Si el atributo
Mapea un id de objeto global en un servidor hyperwave, es el primero con dicho nombre que se añade, fije el
incluso con aquellos a los que no se ha conectado con valor del atributo en la tabla eliminar a un valor entero.
hw_connect(), sobre un id virtual de objeto. Este id Ejemplo 2. añadiendo un atributo completamente
virtual se puede utilizar como cualquier otro id de objeto, nuevo
p. ej. para obtener el registro de objeto por medio de
hw_getobject(). El id de servidor es la primera parte del
id global de objeto (GOid) de aquel que es realmene el // $conexion es una conexión con el servidor
número IP expresado como entero. Hyperwave
Nota: Para usar esta función deberá activar el indicador // $idobj es la ID del objeto a modificar
F_DISTRIBUTED, que actualmenes sólo se puede fijar en $tablasupr = array("Nombre" => 0);
tiempo de compilación desde hg_comm.c. Por defecto $tablaanad = array("Nombre" =>
está inactivo. Lea el comentario al principio de "artículos");
hg_comm.c $hw_modifyobject($conexion, $idobj,
$tablasupr, $tablaanad);

hw_Modifyobject
Nota: Los atributos plurilingües, p.
(PHP 3>= 3.0.7, PHP 4 ) ej. 'Título', se pueden modificar de
hw_Modifyobject -- modifica el registro de objeto dos maneras. O bien proporcionando
los valores de los atributos en su
forma nativa 'lenguaje':'título', bien
Descripción proporcionando una tabla con los
elementos para cada lenguaje según
se describe más arriba. El ejemplo
int hw_modifyobject ( int conexión, int anterior podría quedar entonces:
objeto_a_cambiar, array eliminar, array añadir, int modo)

Ejemplo 3. modificando el atributo Título


Este comando permite eliminar, añadir, o modificar
atributos individuales de un registro de objeto. El objeto
está especificado por el ID de objeto objeto_a_cambiar.
La primera tabla, eliminar, es la lista de atributos a $tablasupr = array("Título" => "es:Libros");
eliminar. La segunda tabla, añadir, es la lista de atributos $tablaanad = array("Título" =>
a añadir. Para modificar un atributo, hay que borrar el "es:Artículos");
antiguo y añadir uno nuevo. hw_modifyobject() $hw_modifyobject($conexion, $idobj,
siempre eliminará los atributos antes de añadir los $tablasupr, $tablaanad);
nuevos excepto si el valor del atributo a eliminar no es o
una cadena o una tabla. Ejemplo 4. modificando el atributo Título
El último parámetro determina si la modificación se
realiza de manera recursiva. 1 quiere decir que sea
recursiva. Si alguno de los objetos no se puede modificar, $tablasupr = array("Título" => array("es" =>
será ignorado sin avisar. Incluso hw_error() podría no "Libros"));
indicar un error aunque alguno de los objetos no pueda $tablaanad = array("Título" => array("es" =>
ser modificado. "Artículos", "ge"=>"Artikel"));
Las claves de ambas tablas son los nombres de los $hw_modifyobject($conexion, $idobj, $tablasupr,
atributos. El valor de cada elemento de la tabla puede $tablaanad);
ser una tabla, una cadena o cualquier otra cosa. Si es
una tabla, cada valor de atributo se construye como la Esto elimina el título español 'Libros' y añade el título
clave de cada elemento más dos puntos y el valor de español 'Artículos' y el título alemán 'Artikel'.
cada elemento. Si es una cadena se toma como valor del Ejemplo 5. eliminando atributos
atributo. Una cadena vacía producirá la supresión
completa del atributo. Si el valor no es ni cadena ni tabla,
sino otra cosa, p. ej. un entero, no se realizará operación $tablasupr = array("Título" => "");
int hw_new_document ( string registro_de_objeto,
$tablaanad = array("Tñitulo" =>
string datos_documento, int tama_documento)
"es:Artículos");
$hw_modifyobject($conexion, $idobj,
$tablasupr, $tablaanad); Devuelve un nuevo documento Hyperwave en el que los
datos del documento están fijados a datos_documento y
el registro de objeto a registro_de_objeto. La longitud de
Nota: Esto eliminará todos los los datos_documento debe pasarse en tama_documento.
atributos con el nombre 'Título' y Esta función no inserta el documento en el servidor
añadirá un nuevo atributo 'Título'. Hyperwave.
Esto es útil cuando se desea eliminar Vea también hw_FreeDocument(),
atributos de forma recursiva. hw_DocumentSize(), hw_DocumentBodyTag(),
hw_OutputDocument(), hw_InsertDocument().

Nota: Si necesita eliminar todos los


atributos con un cierto nombre hw_Objrec2Array
tendrá que pasar una cadena vacía
como el valor del atributo.
(PHP 3>= 3.0.3, PHP 4 )
hw_Objrec2Array -- convierte atributos de registro de
Nota: Sólo los atributos 'Title', objeto a tabla de objetos
'Description' y 'Keyword' (así, en
inglés) manejarán de forma
Descripción
apropiada el prefijo de idioma. Si
estos atributos no llevaran prefijo de
idioma, se les asignariá el prefijo array hw_objrec2array ( string registro_de_objeto)
'xx'.

Convierte un registro_de_objeto en una tabla de objetos.


Nota: El atributo 'Name' es bastante Las claves de la tabla resultante son los nombres de los
especial. En algunos casos no puede atributos. Los atributos múltiples como 'Título' en
ser completamente eliminado. distintos idiomas forman su propia tabla. Las claves de
Obtendrá un mensaje de error esta tabla son las partes a la izquierda de los dos puntos
'Change of base attribute' ('Cambio del valor del atributo. Actualmente, sólo los atributos
de atributo base', no está muy claro 'Title', 'Description' y 'Keyword' (así, en inglés) son
cuando ocurre). Por tanto, tendrá correctamente tratados. Otros atributos múltiples
siempre que añadir un nuevo generan una tabla indizada. Actualmente, sólo el atributo
atributo Name primero y luego 'Group' es tratado correctamente.
eliminar el anterior. Vea también hw_array2objrec().

Nota: No debe rodear esta función hw_Output_Document


de llamadas a hw_getandlock() ni
a hw_unlock(). hw_modifyobject()
ya lo hace internamente. (PHP 3>= 3.0.3, PHP 4 )
hw_Output_Document -- prints hw_document

Devuelve TRUE si no hay error o FALSE en caso


contrario. Description

hw_Mv int hw_output_document ( int hw_document)

Prints the document without the BODY tag.


(PHP 3>= 3.0.3, PHP 4 )
For backward compatibility, hw_outputdocument() is
hw_Mv -- mueve objetos
also accepted. This is deprecated, however.

Descripción
hw_pConnect

int hw_mv ( int conexión, array tabla de id de objeto, int


(PHP 3>= 3.0.3, PHP 4 )
id origen, int id destino)
hw_pConnect -- hacer una conexión de base de datos
permanente
Mueve los objetos cuyas id se especifican en el segundo
parámetro desde la colección con id id origen hasta la
colección con el id id destino. Si el id de destino es 0, los Descripción
objetos serán disociados de la colección origen. Si esta
fuese la última instancia del objeto, este sería borrado. Si
int hw_pconnect ( string servidor, int puerto, string
desea borrar todas las instancias de una vez, utilice
usuario, string clave)
hw_deleteobject().
El valor devuelto es el número de objetos movidos.
Vea también hw_cp(), hw_deleteobject(). Devuelve un índice de conexión si hay éxito, o FALSE si
la conexión no puede hacerse. Abre una conexión
permanente a un servidor Hyperwave. Cada uno de los
hw_New_Document argumentos debe ser una cadena entrecomillada
excepto el número de puerto. El argumento usuario y la
clave son opcionales y pueden omitirse. En tal caso no se
(PHP 3>= 3.0.3, PHP 4 )
realizará ninguna identificación con el servidor. Es similar
hw_New_Document -- crear nuevo documento
a la identificación anónima del usuario. Esta función
devuelve un índice de conexión que se necesita para
Descripción
otras funciones de Hyperwave. Se pueden tener varias hw_Unlock
conexiones permanentes abiertas a la vez.
Vea también hw_Connect().
(PHP 3>= 3.0.3, PHP 4 )
hw_Unlock -- desbloquea objeto
hw_PipeDocument

Descripción
(PHP 3>= 3.0.3, PHP 4 )
hw_PipeDocument -- recupera cualquier documento
int hw_unlock ( int conexión, int IDobjeto)

Descripción
Desbloquea un documento para que otros usuarios
puedan acceder al mismo de nuevo.
int hw_pipedocument ( int conexión, int IDobjeto) Vea también hw_GetAndLock().

Devuelve el documento Hyperwave cuyo ID de objeto es hw_Who


IDobjeto. Si el documento tiene enlaces que pueden ser
insertados, deberán haberse insertado ya. El documento
será transferido a través de una conexión de datos (PHP 3>= 3.0.3, PHP 4 )
especial que no bloquea la conexión de control. hw_Who -- Lista de los usuarios actualmente conectados
Vea también hw_GetText() para saber más sobre
inserción de enlaces, hw_FreeDocument(), Descripción
hw_DocumentSize(), hw_DocumentBodyTag(),
hw_OutputDocument().
int hw_who ( int conexión)
hw_Root
Devuelve una tabla de los usuarios actualmente
conectados al servidor Hyperwave. Cada elemento de
(PHP 3>= 3.0.3, PHP 4 ) esta tabla contiene en sí mismo los elementos ID,
hw_Root -- ID del objeto raíz nombre, sistema, onSinceDate (conectadoDesdeFecha),
onSinceTime (conectadoDesdeHora), TotalTime
(TiempoTotal) y self (propio). 'self' es 1 si esta línea
Descripción
corresponde al usuario que realizó la petición.

int hw_root ( )
XXXIX. Hyperwave API functions

Devuelve la ID de objeto de la colección hiper-raíz.


Actualmente siempre vale 0. La colección hija de la Introducción
hiper-raíz es la colección raíz del servidor al que se ha
conectado.
Hyperwave has been developed at IICM in Graz. It started
with the name Hyper-G and changed to Hyperwave when
hw_setlinkroot it was commercialised (in 1996).
Hyperwave is not free software. The current version, 5.5,
is available at http://www.hyperwave.com/. A time
(PHP 3>= 3.0.3, PHP 4 ) limited version can be ordered for free (30 days).
hw_setlinkroot -- Set the id to which links are calculated See also the Hyperwave module.
Hyperwave is an information system similar to a
database (HIS, Hyperwave Information Server). Its focus
Description is the storage and management of documents. A
document can be any possible piece of data that may as
well be stored in file. Each document is accompanied by
void hw_setlinkroot ( int link, int rootid)
its object record. The object record contains meta data
for the document. The meta data is a list of attributes
Aviso which can be extended by the user. Certain attributes
are always set by the Hyperwave server, other may be
Esta función no está documentada actualmente, solamente modified by the user.
se encuentra disponible la lista de parametros.

Requerimientos
hw_stat
Since 2001 there is a Hyperwave SDK available. It
(PHP 3>= 3.0.3, PHP 4 ) supports Java, JavaScript and C++. This PHP Extension is
hw_stat -- Returns status string based on the C++ interface. In order to activate the
hwapi support in PHP you will have to install the
Hyperwave SDK first.
Description

Instalación
string hw_stat ( int link)

After installing the Hyperwave SDK, configure PHP with


Aviso --with-hwapi[=DIR].
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Integration with Apache
The integration with Apache and possible other servers is
already described in the Hyperwave module which has
• attributeSelector Any array of strings, each
containing a name of an attribute. This is used
been the first extension to connect a Hyperwave Server.
if you retrieve the object record and want to
include certain attributes.
Configuración en tiempo de ejecución • objectQuery A query to select certain object
out of a list of objects. This is used to reduce
the number of objects which was delivered by
The behaviour of these functions is affected by settings a function like hw_api->children() or
in php.ini. hw_api->find().
Tabla 1. Hyperwave API configuration options
Defa
Name Changeable Tabla de contenidos
ult
hw_api_attribute->key -- Returns key of the attribute
hwapi.allow_pers PHP_INI_SYSTE hw_api_attribute->langdepvalue -- Returns value for a
"0"
istent M given language
For further details and definition of the PHP_INI_* hw_api_attribute->value -- Returns value of the attribute
constants see ini_set(). hw_api_attribute->values -- Returns all values of the
attribute
hw_api_attribute -- Creates instance of class
Tipos de recursos hw_api_attribute
hw_api->checkin -- Checks in an object
hw_api->checkout -- Checks out an object
Esta extensión no define ningún tipo de recurso. hw_api->children -- Returns children of an object
hw_api_content->mimetype -- Returns mimetype
hw_api_content->read -- Read content
Constantes predefinidas hw_api->content -- Returns content of an object
hw_api->copy -- Copies physically
hw_api->dbstat -- Returns statistics about database
Esta extensión no define ninguna constante.
server
hw_api->dcstat -- Returns statistics about document
Classes cache server
hw_api->dstanchors -- Returns a list of all destination
anchors
The API provided by the HW_API extension is fully object hw_api->dstofsrcanchors -- Returns destination of a
oriented. It is very similar to the C++ interface of the source anchor
Hyperwave SDK. It consist of the following classes. hw_api_error->count -- Returns number of reasons
hw_api_error->reason -- Returns reason of error
hw_api->find -- Search for objects
• HW_API hw_api->ftstat -- Returns statistics about fulltext server
hwapi_hgcsp -- Returns object of class hw_api
• HW_API_Object hw_api->hwstat -- Returns statistics about Hyperwave
• HW_API_Attribute server
hw_api->identify -- Log into Hyperwave Server
• HW_API_Error hw_api->info -- Returns information about server
• HW_API_Content configuration
hw_api->insert -- Inserts a new object
• HW_API_Reason hw_api->insertanchor -- Inserts a new object of type
anchor
hw_api->insertcollection -- Inserts a new object of type
Some basic classes like HW_API_String, collection
HW_API_String_Array, etc., which exist in the hw_api->insertdocument -- Inserts a new object of type
Hyperwave SDK have not been implemented since PHP document
has powerful replacements for them. hw_api->link -- Creates a link to an object
Each class has certain method, whose names are hw_api->lock -- Locks an object
identical to its counterparts in the Hyperwave SDK. hw_api->move -- Moves object between collections
Passing arguments to this function differs from all the hw_api_content -- Create new instance of class
other PHP extensions but is close to the C++ API of the hw_api_content
HW SDK. Instead of passing serval parameters they are hw_api_object->assign -- Clones object
all put into an associated array and passed as one hw_api_object->attreditable -- Checks whether an
paramter. The names of the keys are identical to those attribute is editable
documented in the HW SDK. The common parameters hw_api_object->count -- Returns number of attributes
are listed below. If other parameters are required they hw_api_object->insert -- Inserts new attribute
will be documented if needed. hw_api_object -- Creates a new instance of class
hw_api_object
hw_api_object->remove -- Removes attribute
• objectIdentifier The name or id of an object, hw_api_object->title -- Returns the title attribute
e.g. "rootcollection", "0x873A8768 hw_api_object->value -- Returns value of attribute
0x00000002". hw_api->object -- Retrieve attribute information
• parentIdentifier The name or id of an object hw_api->objectbyanchor -- Returns the object an anchor
which is considered to be a parent. belongs to
hw_api->parents -- Returns parents of an object
• object An instance of class HW_API_Object. hw_api_reason->description -- Returns description of
• parameters An instance of class reason
HW_API_Object. hw_api_reason->type -- Returns type of reason
hw_api->remove -- Delete an object
• version The version of an object. hw_api->replace -- Replaces an object
• mode An integer value determine the way an hw_api->setcommitedversion -- Commits version other
operation is executed. than last version
hw_api->srcanchors -- Returns a list of all source anchors
hw_api->srcsofdst -- Returns source of a destination object attribute ( [string name [, string value]])
object
hw_api->unlock -- Unlocks a locked object
Creates a new instance of hw_api_attribute with the
hw_api->user -- Returns the own user object
given name and value.
hw_api->userlist -- Returns a list of all logged in users

hw_api->checkin
hw_api_attribute->key

(no version information, might be only in CVS)


(no version information, might be only in CVS)
hw_api->checkin -- Checks in an object
hw_api_attribute->key -- Returns key of the attribute

Description
Description

object checkin ( array parameter)


string key ( void )

This function checks in an object or a whole hiearchie of


Returns the name of the attribute.
objects. The parameters array contains the required
See also hwapi_attribute_value().
element 'objectIdentifier' and the optional element
'version', 'comment', 'mode' and 'objectQuery'. 'version'
hw_api_attribute->langdepvalue sets the version of the object. It consists of the major and
minor version separated by a period. If the version is not
set, the minor version is incremented. 'mode' can be one
(no version information, might be only in CVS) of the following values:
hw_api_attribute->langdepvalue -- Returns value for a HW_API_CHECKIN_NORMAL
given language Checks in and commits the object. The object
must be a document.
HW_API_CHECKIN_RECURSIVE
Description If the object to check in is a collection, all
children will be checked in recursively if they
string langdepvalue ( string language) are documents. Trying to check in a collection
would result in an error.
HW_API_CHECKIN_FORCE_VERSION_CONTROL
Returns the value in the given language of the attribute. Checks in an object even if it is not under
See also hwapi_attribute_value(). version control.
HW_API_CHECKIN_REVERT_IF_NOT_CHANGED
Check if the new version is different from the
hw_api_attribute->value last version. Unless this is the case the object
will be checked in.
(no version information, might be only in CVS) HW_API_CHECKIN_KEEP_TIME_MODIFIED
hw_api_attribute->value -- Returns value of the attribute Keeps the time modified from the most recent
object.
HW_API_CHECKIN_NO_AUTO_COMMIT
Description The object is not automatically commited on
checkin.
See also hwapi_checkout().
string value ( void )

hw_api->checkout
Returns the value of the attribute.
See also hwapi_attribute_key(),
hwapi_attribute_values(). (no version information, might be only in CVS)
hw_api->checkout -- Checks out an object
hw_api_attribute->values
Description
(no version information, might be only in CVS)
hw_api_attribute->values -- Returns all values of the object checkout ( array parameter)
attribute
This function checks out an object or a whole hiearchie of
Description objects. The parameters array contains the required
element 'objectIdentifier' and the optional element
'version', 'mode' and 'objectQuery'. 'mode' can be one of
array values ( void ) the following values:
HW_API_CHECKIN_NORMAL
Returns all values of the attribute as an array of strings. Checks out an object. The object must be a
See also hwapi_attribute_value(). document.
HW_API_CHECKIN_RECURSIVE
If the object to check out is a collection, all
hw_api_attribute children will be checked out recursively if they
are documents. Trying to check out a collection
would result in an error.
(no version information, might be only in CVS) See also hwapi_checkin().
hw_api_attribute -- Creates instance of class
hw_api_attribute
hw_api->children
Description
(no version information, might be only in CVS) Description
hw_api->children -- Returns children of an object

object copy ( array parameter)


Description
This function will make a physical copy including the
array children ( array parameter) content if it exists and returns the new object or an error
object. The parameter array contains the required
elements 'objectIdentifier' and
Retrieves the children of a collection or the attributes of 'destinationParentIdentifier'. The optional parameter is
a document. The children can be further filtered by 'attributeSelector'`
specifying an object query. The parameter array contains See also hwapi_move(), hwapi_link().
the required elements 'objectIdentifier' and the optional
elements 'attributeSelector' and 'objectQuery'.
The return value is an array of objects of type hw_api->dbstat
HW_API_Object or HW_API_Error.
See also hwapi_parents().
(no version information, might be only in CVS)
hw_api->dbstat -- Returns statistics about database
hw_api_content->mimetype server

(no version information, might be only in CVS) Description


hw_api_content->mimetype -- Returns mimetype

object dbstat ( array parameter)


Description
See also hwapi_dcstat(), hwapi_hwstat(),
string mimetype ( void ) hwapi_ftstat().

Returns the mimetype of the content. hw_api->dcstat

hw_api_content->read (no version information, might be only in CVS)


hw_api->dcstat -- Returns statistics about document
cache server
(no version information, might be only in CVS)
hw_api_content->read -- Read content
Description

Description
object dcstat ( array parameter)

string read ( string buffer, integer len)


See also hwapi_hwstat(), hwapi_dbstat(),
hwapi_ftstat().
Reads len bytes from the content into the given buffer.

hw_api->dstanchors
hw_api->content

(no version information, might be only in CVS)


(no version information, might be only in CVS) hw_api->dstanchors -- Returns a list of all destination
hw_api->content -- Returns content of an object anchors

Description Description

object content ( array parameter) object dstanchors ( array parameter)

This function returns the content of a document as an Retrieves all destination anchors of an object. The
object of type hw_api_content. The parameter array parameter array contains the required element
contains the required elements 'objectidentifier' and the 'objectIdentifier' and the optional elements
optional element 'mode'. The mode can be one of the 'attributeSelector' and 'objectQuery'.
constants HW_API_CONTENT_ALLLINKS, See also hwapi_srcanchors().
HW_API_CONTENT_REACHABLELINKS or
HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS
means to insert all anchors even if the destination is not hw_api->dstofsrcanchors
reachable. HW_API_CONTENT_REACHABLELINKS tells
hw_api_content() to insert only reachable links and
HW_API_CONTENT_PLAIN will lead to document without (no version information, might be only in CVS)
any links. hw_api->dstofsrcanchors -- Returns destination of a
source anchor

hw_api->copy
Description

(no version information, might be only in CVS)


hw_api->copy -- Copies physically object dstofsrcanchors ( array parameter)
Retrieves the destination object pointed by the specified See also hwapi_dcstat(), hwapi_dbstat(),
source anchors. The destination object can either be a hwapi_hwstat().
destination anchor or a whole document. The parameters
array contains the required element 'objectIdentifier' and
the optional element 'attributeSelector'. hwapi_hgcsp
See also hwapi_srcanchors(), hwapi_dstanchors(),
hwapi_objectbyanchor(). (no version information, might be only in CVS)
hwapi_hgcsp -- Returns object of class hw_api
hw_api_error->count
Description
(no version information, might be only in CVS)
hw_api_error->count -- Returns number of reasons
object hwapi_hgcsp ( string hostname [, int port])

Description Opens a connection to the Hyperwave server on host


hostname. The protocol used is HGCSP. If you do not
pass a port number, 418 is used.
int count ( void )
See also hwapi_hwtp().

Returns the number of error reasons.


See also hwapi_error_reason(). hw_api->hwstat

hw_api_error->reason (no version information, might be only in CVS)


hw_api->hwstat -- Returns statistics about Hyperwave
server
(no version information, might be only in CVS)
hw_api_error->reason -- Returns reason of error
Description

Description
object hwstat ( array parameter)

object reason ( void )


See also hwapi_dcstat(), hwapi_dbstat(),
hwapi_ftstat().
Returns the first error reason.
See also hwapi_error_count().
hw_api->identify

hw_api->find
(no version information, might be only in CVS)
hw_api->identify -- Log into Hyperwave Server
(no version information, might be only in CVS)
hw_api->find -- Search for objects
Description

Description
object identify ( array parameter)

array find ( array parameter)


Logs into the Hyperwave Server. The parameter array
must contain the elements 'username' und 'password'.
This functions searches for objects either by executing a The return value will be an object of type HW_API_Error
key or/and full text query. The found objects can further if identification failed or TRUE if it was successful.
be filtered by an optional object query. They are sorted
by their importance. The second search operation is
relatively slow and its result can be limited to a certain hw_api->info
number of hits. This allows to perform an incremental
search, each returning just a subset of all found (no version information, might be only in CVS)
documents, starting at a given index. The parameter
hw_api->info -- Returns information about server
array contains the 'keyquery' or/and 'fulltextquery' configuration
depending on who you would like to search. Optional
parameters are 'objectquery', 'scope', 'lanugages' and
'attributeselector'. In case of an incremental search the Description
optional parameters 'startIndex', numberOfObjectsToGet'
and 'exactMatchUnit' can be passed.
object info ( array parameter)

hw_api->ftstat
See also hwapi_dcstat(), hwapi_dbstat(),
hwapi_ftstat(), hwapi_hwstat().
(no version information, might be only in CVS)
hw_api->ftstat -- Returns statistics about fulltext server
hw_api->insert

Description
(no version information, might be only in CVS)
hw_api->insert -- Inserts a new object
object ftstat ( array parameter)
Description
object insert ( array parameter) hw_api->insertdocument -- Inserts a new object of type
document
Insert a new object. The object type can be user, group,
document or anchor. Depending on the type other object Description
attributes has to be set. The parameter array contains
the required elements 'object' and 'content' (if the object
is a document) and the optional parameters object insertdocument ( array parameter)
'parameters', 'mode' and 'attributeSelector'. The 'object'
must contain all attributes of the object. 'parameters' is
This function is a shortcut for hwapi_insert(). It inserts
an object as well holding futher attributes like the an object with content and sets some of the attributes
destination (attribute key is 'Parent'). 'content' is the
required for a document. The parameter array contains
content of the document. 'mode' can be a combination of the required elements 'object', 'parentIdentifier' and
the following flags:
'content' and the optional elements 'mode', 'parameter'
HW_API_INSERT_NORMAL and 'attributeSelector'. See hwapi_insert() for the
The object in inserted into the server.
meaning of each element.
HW_API_INSERT_FORCE-VERSION-CONTROL See also hwapi_insert() hwapi_insertanchor(),
HW_API_INSERT_AUTOMATIC-CHECKOUT
hwapi_insertcollection().
HW_API_INSERT_PLAIN
HW_API_INSERT_KEEP_TIME_MODIFIED
HW_API_INSERT_DELAY_INDEXING hw_api->link
See also hwapi_replace().

(no version information, might be only in CVS)


hw_api->insertanchor hw_api->link -- Creates a link to an object

(no version information, might be only in CVS) Description


hw_api->insertanchor -- Inserts a new object of type
anchor
object link ( array parameter)

Description
Creates a link to an object. Accessing this link is like
accessing the object to links points to. The parameter
object insertanchor ( array parameter) array contains the required elements 'objectIdentifier'
and 'destinationParentIdentifier'.
'destinationParentIdentifier' is the target collection.
This function is a shortcut for hwapi_insert(). It inserts The function returns TRUE on success or an error object.
an object of type anchor and sets some of the attributes
See also hwapi_copy().
required for an anchor. The parameter array contains the
required elements 'object' and 'documentIdentifier' and
the optional elements 'destinationIdentifier', 'parameter', hw_api->lock
'hint' and 'attributeSelector'. The 'documentIdentifier'
specifies the document where the anchor shall be
inserted. The target of the anchor is set in (no version information, might be only in CVS)
'destinationIdentifier' if it already exists. If the target hw_api->lock -- Locks an object
does not exists the element 'hint' has to be set to the
name of object which is supposed to be inserted later.
Once it is inserted the anchor target is resolved Description
automatically.
See also hwapi_insertdocument(), object lock ( array parameter)
hwapi_insertcollection(), hwapi_insert().

Locks an object for exclusive editing by the user calling


hw_api->insertcollection this function. The object can be only unlocked by this
user or the sytem user. The parameter array contains the
required element 'objectIdentifier' and the optional
(no version information, might be only in CVS) parameters 'mode' and 'objectquery'. 'mode' determines
hw_api->insertcollection -- Inserts a new object of type how an object is locked. HW_API_LOCK_NORMAL means,
collection an object is locked until it is unlocked.
HW_API_LOCK_RECURSIVE is only valid for collection and
Description locks all objects within th collection und possible
subcollections. HW_API_LOCK_SESSION means, an object
is locked only as long as the session is valid.
object insertcollection ( array parameter) See also hwapi_unlock().

This function is a shortcut for hwapi_insert(). It inserts hw_api->move


an object of type collection and sets some of the
attributes required for a collection. The parameter array
contains the required elements 'object' and (no version information, might be only in CVS)
'parentIdentifier' and the optional elements 'parameter' hw_api->move -- Moves object between collections
and 'attributeSelector'. See hwapi_insert() for the
meaning of each element.
See also hwapi_insertdocument(), Description
hwapi_insertanchor(), hwapi_insert().
object move ( array parameter)
hw_api->insertdocument
See also hw_objrec2array().
(no version information, might be only in CVS)
hw_api_content Description

(no version information, might be only in CVS) object hw_api_object ( array parameter)
hw_api_content -- Create new instance of class
hw_api_content
See also hwapi_lock().

Description
hw_api_object->remove

string content ( string content, string mimetype)


(no version information, might be only in CVS)
hw_api_object->remove -- Removes attribute
Creates a new content object from the string content.
The mimetype is set to mimetype.
Description

hw_api_object->assign
bool remove ( string name)

(no version information, might be only in CVS)


Removes the attribute with the given name. Returns
hw_api_object->assign -- Clones object
TRUE on success and otherwise FALSE.
See also hwapi_object_insert().
Description
hw_api_object->title
object assign ( array parameter)
(no version information, might be only in CVS)
Clones the attributes of an object. hw_api_object->title -- Returns the title attribute

hw_api_object->attreditable Description

(no version information, might be only in CVS) string title ( array parameter)
hw_api_object->attreditable -- Checks whether an
attribute is editable
hw_api_object->value

Description
(no version information, might be only in CVS)
hw_api_object->value -- Returns value of attribute
bool attreditable ( array parameter)

Description
hw_api_object->count

string value ( string name)


(no version information, might be only in CVS)
hw_api_object->count -- Returns number of attributes
Returns the value of the attribute with the given name or
FALSE if an error occured.
Description
hw_api->object
int count ( array parameter)
(no version information, might be only in CVS)
hw_api_object->insert hw_api->object -- Retrieve attribute information

(no version information, might be only in CVS) Description


hw_api_object->insert -- Inserts new attribute
object hw_api->object ( array parameter)
Description
This function retrieves the attribute information of an
object of any version. It will not return the document
bool insert ( object attribute)
content. The parameter array contains the required
elements 'objectIdentifier' and the optional elements
Adds an attribute to the object. Returns TRUE on success 'attributeSelector' and 'version'.
and otherwise FALSE. The returned object is an instance of class
See also hwapi_object_remove(). HW_API_Object on success or HW_API_Error if an error
occured.
This simple example retrieves an object and checks for
hw_api_object errors.
Ejemplo 1. Retrieve an object
(no version information, might be only in CVS)
hw_api_object -- Creates a new instance of class
hw_api_object <?php
function handle_error($error) {
$reason = $error->reason(0);
'objectidentifier' and the optional elements
echo "Type: <B>";
'attributeselector' and 'objectquery'.
switch($reason->type()) {
The return value is an array of objects of type
case 0:
HW_API_Object or HW_API_Error.
echo "Error";
See also hwapi_children().
break;
case 1:
echo "Warning"; hw_api_reason->description
break;
case 2:
echo "Message"; (no version information, might be only in CVS)
break; hw_api_reason->description -- Returns description of
} reason
echo "</B><BR>\n";
echo "Description: ".$reason-
>description("en")."<BR>\n"; Description
}
string description ( void )
function list_attr($obj) {
echo "<TABLE>\n";
$count = $obj->count(); Returns the description of a reason
for($i=0; $i<$count; $i++) {
$attr = $obj->attribute($i);
printf(" <TR><TD ALIGN=right hw_api_reason->type
bgcolor=#c0c0c0><B>%s</B></TD><TD
bgcolor=#F0F0F0>%s</TD>\n", (no version information, might be only in CVS)
$attr->key(), $attr->value()); hw_api_reason->type -- Returns type of reason
}
echo "</TABLE>\n";
} Description

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection, object type ( void )
"attributeSelector"=>array("Title", "Name",
"DocumentType")); Returns the type of a reason.
$root = $hwapi->object($parms);
if(get_class($root) == "HW_API_Error") {
handle_error($root); hw_api->remove
exit;
}
list_attr($root); (no version information, might be only in CVS)
?> hw_api->remove -- Delete an object

See also hwapi_content().


Description

hw_api->objectbyanchor
object remove ( array parameter)

(no version information, might be only in CVS)


hw_api->objectbyanchor -- Returns the object an anchor This function removes an object from the specified
belongs to parent. Collections will be removed recursively. You can
pass an optional object query to remove only those
objects which match the query. An object will be deleted
Description physically if it is the last instance. The parameter array
contains the required elements 'objectidentifier' and
'parentidentifier'. If you want to remove a user or group
object objectbyanchor ( array parameter) 'parentidentifier' can be skiped. The optional parameter
'mode' determines how the deletion is performed. In
This function retrieves an object the specified anchor normal mode the object will not be removed physically
belongs to. The parameter array contains the required until all instances are removed. In physical mode all
element 'objectIdentifier' and the optional element instances of the object will be deleted imediately. In
'attributeSelector'. removelinks mode all references to and from the objects
See also hwapi_dstofsrcanchor(), will be deleted as well. In nonrecursive the deletion is not
hwapi_srcanchors(), hwapi_dstanchors(). performed recursive. Removing a collection which is not
empty will cause an error.
See also hwapi_move().
hw_api->parents

hw_api->replace
(no version information, might be only in CVS)
hw_api->parents -- Returns parents of an object
(no version information, might be only in CVS)
hw_api->replace -- Replaces an object
Description

Description
array parents ( array parameter)

object replace ( array parameter)


Retrieves the parents of an object. The parents can be
further filtered by specifying an object query. The
parameter array contains the required elements
Replaces the attributes and the content of an object The 'objectQuery'. The function returns an array of objects or
parameter array contains the required elements an error.
'objectIdentifier' and 'object' and the optional parameters See also hwapi_dstofsrcanchor().
'content', 'parameters', 'mode' and 'attributeSelector'.
'objectIdentifier' contains the object to be replaced.
'object' contains the new object. 'content' contains the hw_api->unlock
new content. 'parameters' contain extra information for
HTML documents. HTML_Language is the letter
(no version information, might be only in CVS)
abbreviation of the language of the title. HTML_Base sets hw_api->unlock -- Unlocks a locked object
the base attribute of the HTML document. 'mode' can be
a combination of the following flags:
HW_API_REPLACE_NORMAL Description
The object on the server is replace with the
object passed.
HW_API_REPLACE_FORCE_VERSION_CONTROL object unlock ( array parameter)
HW_API_REPLACE_AUTOMATIC_CHECKOUT
HW_API_REPLACE_AUTOMATIC_CHECKIN Unlocks a locked object. Only the user who has locked
HW_API_REPLACE_PLAIN the object and the system user may unlock an object.
HW_API_REPLACE_REVERT_IF_NOT_CHANGED The parameter array contains the required element
HW_API_REPLACE_KEEP_TIME_MODIFIED 'objectIdentifier' and the optional parameters 'mode' and
See also hwapi_insert(). 'objectquery'. The meaning of 'mode' is the same as in
function hwapi_lock().
hw_api->setcommitedversion Returns TRUE on success or an object of class
HW_API_Error.
See also hwapi_lock().
(no version information, might be only in CVS)
hw_api->setcommitedversion -- Commits version other
than last version hw_api->user

Description (no version information, might be only in CVS)


hw_api->user -- Returns the own user object

object setcommitedversion ( array parameter)


Description

Commits a version of a docuemnt. The commited version


is the one which is visible to users with read access. By object user ( array parameter)
default the last version is the commited version.
See also hwapi_checkin(), hwapi_checkout(), See also hwapi_userlist().
hwapi_revert().

hw_api->userlist
hw_api->srcanchors

(no version information, might be only in CVS)


(no version information, might be only in CVS) hw_api->userlist -- Returns a list of all logged in users
hw_api->srcanchors -- Returns a list of all source anchors

Description
Description

object userlist ( array parameter)


object srcanchors ( array parameter)

See also hwapi_user().


Retrieves all source anchors of an object. The parameter
array contains the required element 'objectIdentifier' and
the optional elements 'attributeSelector' and XL. iconv functions
'objectQuery'.
See also hwapi_dstanchors().
Introducción

hw_api->srcsofdst
This module contains an interface to the iconv library
functions. The iconv library functions convert strings
(no version information, might be only in CVS) between various character sets encodings. The
hw_api->srcsofdst -- Returns source of a destination supported character sets depend on the iconv()
object implementation on your system. Note that the iconv()
function on some systems may not work as well as you
expect. In this case, you should install the libiconv
Description library.

object srcsofdst ( array parameter)


Requerimientos

Retrieves all the source anchors pointing to the specified


destination. The destination object can either be a Your systems standard C library must provide the iconv()
destination anchor or a whole document. The parameters function or you must have libiconv installed on your
array contains the required element 'objectIdentifier' and system. The libiconv library is available from
the optional element 'attributeSelector' and http://www.gnu.org/software/libiconv/.
Instalación ob_iconv_handler -- Convert character encoding as
output buffer handler

To be able to use the functions defined in this module


you must compile your PHP interpreter using the iconv_get_encoding
configure line --with-iconv[=DIR].

(PHP 4 >= 4.0.5)


Note to Win32 Users: In order to iconv_get_encoding -- Get current setting for character
enable this module on a Windows encoding conversion
environment, you must copy iconv-
1.3.dll from the DLL folder of the
PHP/Win32 binary package to the Description
SYSTEM32 folder of your windows
machine. (Ex: C:\WINNT\SYSTEM32 array iconv_get_encoding ( [string type])
or C:\WINDOWS\SYSTEM32). Starting
with PHP 4.2.1 the name changed to
iconv.dll It returns the current settings of ob_iconv_handler() as
array or FALSE on failure. The value of the optinal type
can be:
all
input_encodin
Configuración en tiempo de ejecución
g
output_encodi
The behaviour of these functions is affected by settings ng
in php.ini. internal_enco
Tabla 1. Iconv configuration options ding
Changeabl If type is omitted or not 'all' iconv_get_encoding()
Name Default returns the current settings of ob_iconv_handler() as
e
string.
iconv.input_encod ICONV_INPUT_ENCODIN PHP_INI_AL Ejemplo 1. iconv_get_encoding() example:
ing G L
iconv.output_enc ICONV_OUTPUT_ENCODI PHP_INI_AL
oding NG L <pre>
<?php
iconv.internal_enc ICONV_INTERNAL_ENCO PHP_INI_AL
iconv_set_encoding("internal_encoding",
oding DING L
"UTF-8");
For further details and definition of the PHP_INI_* iconv_set_encoding("output_encoding",
constants see ini_set(). "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
Tipos de recursos </pre>

Esta extensión no define ningún tipo de recurso.


The printout of the above program will be:

Constantes predefinidas
Array

Since PHP 4.3.0 it is possible to identify at runtime which (


iconv implementation is adopted by this extension.
Tabla 2. iconv constants [input_encoding] =>
typ ISO-8859-1
constant description
e
[output_encoding] =>
strin The implementation ISO-8859-1
ICONV_IMPL
g name
ICONV_VERSI strin The implementation [internal_encoding] =>
ON g version UTF-8

)
Nota: Writing implementation- See also: iconv_set_encoding() and
dependent scripts with these ob_iconv_handler().
constants should be discouraged.

iconv_set_encoding

Ver tambien (PHP 4 >= 4.0.5)


iconv_set_encoding -- Set current setting for character
encoding conversion
See also the GNU Recode functions.
Tabla de contenidos
iconv_get_encoding -- Get current setting for character Description
encoding conversion
iconv_set_encoding -- Set current setting for character
encoding conversion bool iconv_set_encoding ( string type, string charset)
iconv -- Convert string to requested character encoding
It changes the value of type to charset. Devuelve TRUE Si tiene PHP compilado con --enable-exif puede trabajar
si todo fue bien, FALSE en caso de fallo. con la información guardada en las cabeceras de las
The value of type can be: imágenes JPEG y TIFF. Estas funciones no requieren la
input_encodin biblioteca GD.
g Los formatos de imágenes que puede manipular
output_encodi dependen de la versión de GD que instale y de cualquier
ng otra biblioteca que GD pueda necesitar para acceder a
esos formatos de imagen. Las versiones de GD anteriores
internal_enco
a la GD-1.6 soportan imágenes en formato gif y no
ding
soportan png, mientras que las versiones superiores a la
Ejemplo 1. iconv_set_encoding() example:
GD-1.6 soportan el formato png y no el gif.
Antes de poder leer y escribir imágenes en formato jpeg,
deberá obtener e instalar jpeg-6b (disponible en
iconv_set_encoding("internal_encoding", ftp://ftp.uu.net/graphics/jpeg/), y después recompilar GD
"UTF-8"); para poder hacer uso de jpeg-6b. También tendrá que
iconv_set_encoding("output_encoding", compilar PHP con la opción --with-jpeg-dir=/ruta/a/jpeg-
"ISO-8859-1"); 6b.
See also: iconv_get_encoding() and Para añadir el soporte de fuentes Type 1, puede instalar
ob_iconv_handler(). t1lib (disponible en
ftp://sunsite.unc.edu/pub/Linux/libs/graphics/), y
entonces añadir la opción --with-t1lib[=dir] al recompilar.
iconv Tabla de contenidos
exif_imagetype -- Determine the type of an image
exif_read_data -- Read the EXIF headers from JPEG or
(PHP 4 >= 4.0.5) TIFF. This way you can read meta data generated by
iconv -- Convert string to requested character encoding digital cameras.
exif_thumbnail -- Retrieve the embedded thumbnail of a
Description TIFF or JPEG image
gd_info -- Retrieve information about the currently
installed GD library
string iconv ( string in_charset, string out_charset, string GetImageSize -- Obtiene el tamaño de una imagen GIF,
str) JPG o PNG
image_type_to_mime_type -- Get Mime-Type for image-
type returned by getimagesize, exif_read_data,
It converts the string str encoded in in_charset to the
exif_thumbnail, exif_imagetype
string encoded in out_charset. It returns the converted
image2wbmp -- Output image to browser or file
string or FALSE, if it fails.
imagealphablending -- Set the blending mode for an
Ejemplo 1. iconv() example:
image
ImageArc -- Dibuja una elipse parcial
ImageChar -- Dibuja un carácter horizontalmente
echo iconv("ISO-8859-1","UTF- ImageCharUp -- Dibuja un carácter vertical
8","This is a test."); ImageColorAllocate -- Reserva un color para una imagen
imagecolorallocatealpha -- Allocate a color for an image
ImageColorAt -- Obtiende el índice del color de un pixel
ob_iconv_handler ImageColorClosest -- Obtiene el índice del color más
cercano al color especificado
imagecolorclosestalpha -- Get the index of the closest
(PHP 4 >= 4.0.5) color to the specified color + alpha
ob_iconv_handler -- Convert character encoding as imagecolorclosesthwb -- Get the index of the color which
output buffer handler has the hue, white and blackness nearest to the given
color
Description imagecolordeallocate -- De-allocate a color for an image
ImageColorExact -- Devuelve el índice del color
especificado
array ob_iconv_handler ( string contents, int status) imagecolorexactalpha -- Get the index of the specified
color + alpha
ImageColorResolve -- Devuelve el índice del color
It converts the string encoded in internal_encoding to
especificado o su posible alternativa más cercana
output_encoding.
imagecolorresolvealpha -- Get the index of the specified
internal_encoding and output_encoding should be
color + alpha or its closest possible alternative
defined by iconv_set_encoding() or in the configuration
ImageColorSet -- Establece el color para el índice de la
file php.ini.
paleta especificado
Ejemplo 1. ob_iconv_handler() example:
ImageColorsForIndex -- Obtiene los colores de un índice
ImageColorsTotal -- Encuentra el número de colores de la
paleta de una imagen
ob_start("ob_iconv_handler"); // start ImageColorTransparent -- Define un color como
output buffering transparente
See also: iconv_get_encoding(), imagecopy -- Copy part of an image
iconv_set_encoding(), and output-control functions. imagecopymerge -- Copy and merge part of an image
imagecopymergegray -- Copy and merge part of an
image with gray scale
XLI. Funciones para imágenes imagecopyresampled -- Copia y reescala parte de una
imagen con remuestreo
ImageCopyResized -- Copia y redimensiona parte de una
Puede usar las funciones para imágenes en PHP para imagen
obtener el tamaño de imágenes JPEG, GIF, PNG, SWF, ImageCreate -- Crea una nueva imagen
TIFF y JPEG2000, y si tiene instalada la biblioteca GD imagecreatefromgd2 -- Create a new image from GD2 file
(disponible en http://www.boutell.com/gd/) también or URL
podrá crear y manipular imágenes.
imagecreatefromgd2part -- Create a new image from a ImageTTFBBox -- Devuelve un caja que rodea al texto
given part of GD2 file or URL usando fuentes TypeType
imagecreatefromgd -- Create a new image from GD file ImageTTFText -- Escribe texto en la imagen usando
or URL fuentes TrueType
ImageCreateFromGif -- Crea una nueva imagen desde un imagetypes -- Return the image types supported by this
fichero o una URL PHP build
imagecreatefromjpeg -- Crea una imagen nueva desde imagewbmp -- Output image to browser or file
un archivo o URL iptcembed -- Embed binary IPTC data into a JPEG image
imagecreatefrompng -- Crea una imagen nueva desde un iptcparse -- Parse a binary IPTC http://www.iptc.org/
fichero o URL block into single tags.
imagecreatefromstring -- Create a new image from the jpeg2wbmp -- Convert JPEG image file to WBMP image
image stream in the string file
imagecreatefromwbmp -- Create a new image from file or png2wbmp -- Convert PNG image file to WBMP image file
URL read_exif_data -- Reads header information stored in TIFF
imagecreatefromxbm -- Create a new image from file or and JPEG images
URL
imagecreatefromxpm -- Create a new image from file or
URL exif_imagetype
imagecreatetruecolor -- Crea una imagen nueva en color
real (true color)
(PHP 4 >= 4.3.0)
ImageDashedLine -- Dibuja una línea discontinua exif_imagetype -- Determine the type of an image
ImageDestroy -- Destruye una imagen
imageellipse -- Draw an ellipse
ImageFill -- Relleno Description
imagefilledarc -- Draw a partial ellipse and fill it
imagefilledellipse -- Draw a filled ellipse
ImageFilledPolygon -- Dibuja un polígono relleno int|false exif_imagetype ( string filename)
ImageFilledRectangle -- dibuja un rectángulo relleno
ImageFillToBorder -- Relleno de un color especifico exif_imagetype() reads the first bytes of an image and
ImageFontHeight -- Devuelve la altura de una fuente checks its signature. When a correct signature is found a
ImageFontWidth -- Devuelve la anchura de una fuente constant will be returned otherwise the return value is
imageftbbox -- Give the bounding box of a text using FALSE. The return value is the same value that
fonts via freetype2 getimagesize() returns in index 2 but this function is
imagefttext -- Write text to the image using fonts using much faster.
FreeType 2 The following constants are defined: 1 = IMAGETYPE_GIF,
imagegammacorrect -- Apply a gamma correction to a 2 = IMAGETYPE_JPEG, 3 = IMAGETYPE_PNG, 4 =
GD image IMAGETYPE_SWF, 5 = IMAGETYPE_PSD, 6 =
imagegd2 -- Output GD2 image to browser or file IMAGETYPE_BMP, 7 = IMAGETYPE_TIFF_II (intel byte
imagegd -- Output GD image to browser or file order), 8 = IMAGETYPE_TIFF_MM (motorola byte order), 9
ImageGif -- Envía una imagen al navegador o a un fichero = IMAGETYPE_JPC, 10 = IMAGETYPE_JP2, 11 =
ImageInterlace -- Activa o desactiva el entrelazado IMAGETYPE_JPX, 12 = IMAGETYPE_SWC.
imagejpeg -- Output image to browser or file This function can be used to avoid calls to other exif
ImageLine -- Dibuja una línea functions with unsupported file types or in conjunction
ImageLoadFont -- Carga una fuente nueva with $_SERVER['HTTP_ACCEPT'] to check whether or not
imagepalettecopy -- Copy the palette from one image to the viewer is able to see a specific image in his browser.
another
imagepng -- Output a PNG image to either the browser or
a file Nota: This function is only available
ImagePolygon -- Dibuja un polígono in PHP 4 compiled using --enable-
ImagePSBBox -- Devuelve el borde que rodea un exif.
rectángulo de texto usando fuentes PostScript Type1
ImagePSCopyFont -- hace una copia de una fuente ya
cargada para futuras modificaciones This function does not require the
ImagePSEncodeFont -- Cambia el vector de codificación GD image library.
de caracteres de una fuente
imagepsextendfont -- Extend or condense a font
See also getimagesize().
ImagePSFreeFont -- Libera la memoria usada por un
fuente PostScript Type 1
ImagePSLoadFont -- Carga una fuente PostScript Type 1 exif_read_data
desde un fichero
imagepsslantfont -- Slant a font
ImagePSText -- Para dibujar una cadena de texto sobre (PHP 4 >= 4.2.0)
una imagen usando fuentes PostScript Type1 exif_read_data -- Read the EXIF headers from JPEG or
ImageRectangle -- Dibuja un rectángulo TIFF. This way you can read meta data generated by
imagerotate -- Rotate an image with a given angle digital cameras.
imagesetbrush -- Set the brush image for line drawing
ImageSetPixel -- Dibuja un pixel
imagesetstyle -- Set the style for line drawing Description
imagesetthickness -- Set the thickness for line drawing
imagesettile -- Set the tile image for filling array exif_read_data ( string filename [, string sections
ImageString -- Dibuja una cadena de texto [, bool arrays [, bool thumbnail]]])
horizintalmente
ImageStringUp -- Dibuja una cadena de texto
verticalmente The exif_read_data() function reads the EXIF headers
ImageSX -- Obtiene la anchura de la imagen from a JPEG or TIFF image file. It returns an associative
ImageSY -- Obtiene la altura de la imagen array where the indexes are the header names and the
imagetruecolortopalette -- Convert a true color image to values are the values associated with those headers. If
a palette image no data can be returned the result is FALSE.
filename is the name of the file to read. This cannot be a
Edited by M.Boerger.
url.
COMPUTED.Copyright.Photographer: Photo (c)
sections a comma separated list of sections that need to
M.Boerger
be present in file to produce a result array.
COMPUTED.Copyright.Editor: Edited by
FILE FileName, FileSize, FileDateTime, SectionsFound M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
COMPUTE html, Width, Height, IsColor and some more if
IFD0.UserComment: ASCII
D available.
THUMBNAIL.JPEGInterchangeFormat: 134
Any information that has a Tag e.g. IFD0, THUMBNAIL.JPEGInterchangeFormatLength: 523
ANY_TAG
EXIF, ... COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
All tagged data of IFD0. In normal imagefiles this
IFD0 COMMENT.2: Comment #3end
contains image size and so forth.
A file is supposed to contain a thumbnail if it has THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNA
a second IFD. All tagged information about the THUMBNAIL.Thumbnail.Height: 1
IL
embedded thumbnail is stored in this section. THUMBNAIL.Thumbnail.Height: 1
COMMENT Comment headers of JPEG images.
The EXIF section is a sub section of IFD0. It Nota: If the image contains any
contains more detailed information about an IFD0 data then COMPUTED contains
EXIF
image. Most of these entries are digital camera the entry ByteOrderMotorola which
related. is 0 for little-endian (intel) and 1 for
arrays specifies whether or not each section becomes an big-endian (motorola) byte order.
array. The sections FILE, COMPUTED and THUMBNAIL This was added in PHP 4.3.
allways become arrays as they may contain values
whose names are conflict with other sections.
When an Exif header contains a
thumbnail whether or not to read the thumbnail itself and
Copyright note this itself can contain
not only its tagged data.
two values. As the solution is
inconsitent in the Exif 2.10 standard
Nota: Exif headers tend to be the COMPUTED section will return
present in JPEG/TIFF images both entries Copyright.Photographer
generated by digital cameras, but and Copyright.Editor while the IFD0
unfortunately each digital camera sections contains the byte array with
maker has a different idea of how to the NULL character that splits both
actually tag their images, so you entries. Or just the first entry if the
can't always rely on a specific Exif datatype was wrong (normal
header being present. behaviour of Exif). The COMPUTED
will contain also an entry Copyright
Which is either the original copyright
Ejemplo 1. exif_read_data() example string or it is a comma separated list
of photo and editor copyright.

<?php
echo "test1.jpg:<br />\n"; Nota: The tag UserComment has
$exif = exif_read_data ('tests/test1.jpg','IFD0'); the same problem as the Copyright
echo $exif===false ? "No header data found.<br />\n" tag. It can store two values first the
: "Image contains headers<br />"; encoding used and second the value
$exif = exif_read_data ('tests/test2.jpg',0,true); itself. If so the IFD section only
echo "test2.jpg:<br />\n"; contains the encoding or a byte
foreach($exif as $key=>$section) { array. The COMPUTED section will
foreach($section as $name=>$val) { store both in the entries
echo "$key.$name: $val<br />\n"; UserCommentEncoding and
} UserComment. The entry
}?> UserComment is available in both
cases so it should be used in
preference to the value in IFD0
section.
The first call fails because the image has no header
information.
If the user comment uses Unicode or
JIS encoding and the module
test1.jpg: mbstring is available this encoding
No header data found. will automatically changed according
test2.jpg: to the exif ini settings. This was
FILE.FileName: test2.jpg added in PHP 4.3.
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2 Nota: Height and Width are
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, computed the same way
COMMENT getimagesize() does so their
COMPUTED.html: width="1" height="1" values must not be part of any
COMPUTED.Height: 1 header returned. Also html is a
COMPUTED.Width: 1 height/width text string to be used
COMPUTED.IsColor: 1 inside normal HTML.
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image. Nota: Starting from PHP 4.3 the
COMPUTED.UserCommentEncoding: ASCII function can read all embedded IFD
COMPUTED.Copyright: Photo (c) M.Boerger, data including arrays (returned as
such). Also the size of an embedded Starting from version PHP 4.3 the function
thumbnail is returned in THUMBNAIL exif_thumbnail() can return thumbnails in TIFF format.
subarray and the function
exif_read_data() can return
thumbnails in TIFF format. Last but Nota: This function is only available
not least there is no longer a in PHP 4 compiled using --enable-
maximum legth for returned values exif. Its functionality and behaviour
(not until memory limit is reached). has changed in PHP 4.2

Nota: This function is only available This function does not require the
in PHP 4 compiled using --enable- GD image library.
exif. Its functionality and behaviour
has changed in PHP 4.2. Earlier
See also exif_read_data() and
versions are very unstable. image_type_to_mime_type().

Since PHP 4.3 user comment can


gd_info
automatically change encoding if
PHP 4 was compiled using --enable-
mbstring. (PHP 4 >= 4.3.0)
gd_info -- Retrieve information about the currently
installed GD library
This function does not require the
GD image library.
Description
See also exif_thumbnail() and
getimagesize(). array gd_info ( void)

exif_thumbnail Returns an associative array describing the version and


capabilities of the installed GD library.
Tabla 1. Elements of array returned by gd_info()
(PHP 4 >= 4.2.0)
exif_thumbnail -- Retrieve the embedded thumbnail of a Attribut
Meaning
TIFF or JPEG image e
GD string value describing the installed libgd
Version version.
Description
Freetype boolean value. TRUE if Freetype Support is
Support installed.
string exif_thumbnail ( string filename [, int &width [,
int &height [, int &imagetype]]]) string value describing the way in which
Freetype was linked. Expected values are: 'with
Freetype
freetype', 'with TTF library', and 'with unknown
exif_thumbnail() reads the embedded thumbnail of a Linkage
library'. This element will only be defined if
TIFF or JPEG image. If the image contains no thumbnail Freetype Support evaluated to TRUE.
FALSE will be returned.
The parameters width, height and imagetype are T1Lib boolean value. TRUE if T1Lib support is
available since PHP 4.3 and return the size of the Support included.
thumbnail as well as its type. It is possible that GIF Read boolean value. TRUE if support for reading GIF
exif_thumbnail() cannot create an image but determine Support images is included.
its size. In this case the return value is FALSE but width
and height are set. GIF
boolean value. TRUE if support for creating GIF
If you want to deliver thumbnails through this function Create
images is included.
you should send the mimetype information using Support
header() function. The following example demonstrates JPG
this: boolean value. TRUE if JPG support is included.
Support
Ejemplo 1. exif_thumbnail() example
PNG
boolean value. TRUE if PNG support is included.
Support
<?php WBMP boolean value. TRUE if WBMP support is
if (array_key_exists('file',$_REQUEST)) { Support included.
$image =
XBM
exif_thumbnail($_REQUEST['file'], $width, $height, boolean value. TRUE if XBM support is included.
Support
$type);
} else { Ejemplo 1. Using gd_info()
$image = false;
}
if ($image!==false) { <?php
header("Content-type: var_dump(gd_info());
".image_type_to_mime_type($type));
echo $image; /* Typical Output
exit; ==============
} else {
// no thumbnail available, handle the error here array(9) {
echo "No thumbnail available"; ["GD Version"]=>
} string(24) "bundled (2.0
?> compatible)"
["FreeType Support"]=>
Nota: Esta función no requiere la
bool(false)
libreria de imagenes GD.
["T1Lib Support"]=>
bool(false)
["GIF Read Support"]=> image_type_to_mime_type
bool(true)
["GIF Create Support"]=>
bool(false) (PHP 4 >= 4.3.0)
["JPG Support"]=> image_type_to_mime_type -- Get Mime-Type for image-
bool(false) type returned by getimagesize, exif_read_data,
["PNG Support"]=> exif_thumbnail, exif_imagetype
bool(true)
["WBMP Support"]=>
bool(true) Description
["XBM Support"]=>
bool(false) string image_type_to_mime_type ( int imagetype)
}

*/ The image_type_to_mime_type() function will


?> determine the Mime-Type for an IMAGETYPE constant.
Ejemplo 1. image_type_to_mime_type (file)
See also: imagepng(), imagejpeg(), imagegif(),
imagewbmp(), and imagetypes().
<?php
GetImageSize header ("Content-type: ".image_type_to_mime_type
(IMAGETYPE_PNG));
?>
(PHP 3, PHP 4 )
GetImageSize -- Obtiene el tamaño de una imagen GIF,
JPG o PNG Nota: This function does not require
the GD image library.
Descripción
See also getimagesize(),
array getimagesize ( string filename [, array exif_imagetype(),
imageinfo]) exif_read_data() and
exif_thumbnail().

La función GetImageSize() determinará el tamaño de


cualquier fichero de imagen GIF, JPG o PNG y devolverá image2wbmp
sus dimensiones junto al tipo de fichero en una cadena
de texto que pueda ser usada en una marca HTML IMG
normal. (PHP 4 >= 4.0.5)
Devuelve una matriz con 4 elementos. El índice 0 image2wbmp -- Output image to browser or file
contiene la anchura de la imagen en pixels. El índice 1
contiene la altura. El índice 2 es una marca indicando el Description
tipo de imagen. 1 = GIF, 2 = JPG, 3 = PNG. El índice 3 es
una cadena de texto con el string correcto "height=xxx
width=xxx" para ser usado directamente en una marca int image2wbmp ( resource image [, string filename [,
IMG. int threshold]])
Ejemplo 1. GetImageSize
image2wbmp() creates the WBMP file in filename from
the image image. The image argument is the return from
<?php $size = imagecreate().
GetImageSize("img/flag.jpg"); ?> The filename argument is optional, and if left off, the raw
<IMG SRC="img/flag.jpg" <?php echo image stream will be output directly. By sending an
$size[3]; ?>> image/vnd.wap.wbmp content-type using header(), you
El parámetro opcional imageinfo permite extraer can create a PHP script that outputs WBMP images
información adicional del fichero de imagen. Actualmente directly.
esto devolverá las diferentes marcas APP de los JPG en
una matriz asociada. Algunos programas usan estas
marcas APP para incluir información textual en las Nota: WBMP support is only
available if PHP was compiled
imagenes. Uno bastante común incluye información IPTC
http://www.iptc.org/ en la marca APP13. Puede usar la against GD-1.8 or later.
función iptcparse() para convertir la marca binaria
APP13 en algo leible. See also imagewbmp().
Ejemplo 2. GetImageSize devolviendo IPTC

imagealphablending
<?php
$size =
(PHP 4 >= 4.0.6)
GetImageSize("testimg.jpg",&$inf
imagealphablending -- Set the blending mode for an
o);
image
if (isset($info["APP13"])) {
$iptc =
iptcparse($info["APP13"]); Description
var_dump($iptc);
}
?>
int imagealphablending ( resource image, bool Vea también imageloadfont().
blendmode)

ImageColorAllocate
imagealphablending() allows for two different modes
of drawing on truecolor images. In blending mode, the
alpha channel component of the color supplied to all (PHP 3, PHP 4 )
drawing function, such as imagesetpixel() determines ImageColorAllocate -- Reserva un color para una imagen
how much of the underlying color should be allowed to
shine through. As a result, gd automatically blends the
existing color at that point with the drawing color, and Descripción
stores the result in the image. The resulting pixel is
opaque. In non-blending mode, the drawing color is int imagecolorallocate ( int im, int red, int green, int
copied literally with its alpha channel information, blue)
replacing the destination pixel. Blending mode is not
available when drawing on palette images. If blendmode
is TRUE, then blending mode is enabled, otherwise ImageColorAllocate devuelve un identificador del color
disabled. representado por la mezcla de los componentes RGB
dados. El parámetro im es el resultado de la función
imagecreate(). ImageColorAlocate tiene que ser
Nota: This function was added in invocada para crear cada color que va a ser usado por la
PHP 4.0.6 and requires GD 2.0.1 imagen que representa im.
$white = ImageColorAllocate($im,
ImageArc 255,255,255);
$black = ImageColorAllocate($im,
0,0,0);
(PHP 3, PHP 4 )
ImageArc -- Dibuja una elipse parcial
imagecolorallocatealpha
Descripción
(no version information, might be only in CVS)
int imagearc ( int im, int cx, int cy, int w, int h, int s, int imagecolorallocatealpha -- Allocate a color for an image
e, int col)
Description
ImageArc dibuja una elipse parcial centrada en cx, cy (la
esquina superior izquierda es 0,0) en la imagen que
representa im. w y h especifican la anchura y altura int imagecolorallocatealpha ( resource image, int red,
respectivamente mientras que los puntos de inicio y final int green, int blue, int alpha)
vienen indicados por los parámetros s y e en grados.
imagecolorallocatealpha() behaves identically to
imagecolorallocate() with the addition of the
ImageChar transparency parameter alpha which may have a value
between 0 and 127. 0 indicates completely opaque while
(PHP 3, PHP 4 ) 127 indicates completely transparent.
ImageChar -- Dibuja un carácter horizontalmente Returns FALSE if the allocation failed.

Descripción ImageColorAt

int imagechar ( int im, int font, int x, int y, string c, int (PHP 3, PHP 4 )
col) ImageColorAt -- Obtiende el índice del color de un pixel

ImageChar dibuja el primer carácter de c en la imagen Descripción


identificada como id con su esquina superior izquierda en
x, y (arriba izquierda es 0,0) con el color col. Si la fuente
es 1, 2, 3, 4 o 5 se usa una fuente predefinida (números int imagecolorat ( int im, int x, int y)
mayores corresponden con tamaños mayores).
Vea también imageloadfont(). Devuelve el índice del color del pixel especificado en la
posición de la imagen.
Vea también imagecolorset() y
ImageCharUp imagecolorsforindex().

(PHP 3, PHP 4 ) ImageColorClosest


ImageCharUp -- Dibuja un carácter vertical

(PHP 3, PHP 4 )
Descripción ImageColorClosest -- Obtiene el índice del color más
cercano al color especificado
int imagecharup ( int im, int font, int x, int y, string c,
int col) Descripción

ImageCharUp dibuja el caracter c verticalmente en la


imagen identificado como im en las coordenadas x, y int imagecolorclosest ( int im, int red, int green, int
(arriba izquierda es 0,0) con el color col. Si la fuente es 1, blue)
2, 3, 4 o 5 se usa una fuente predefinida.
Devuelve el índice del color de la paleta de la imagen Descripción
que sea más "cercano" al valor RGB especificado.
La "distancia" entre el color deseado y cada color de la
paleta es calculada como si los valores RGB int imagecolorexact ( int im, int red, int green, int blue)
representasen puntos en un espacio tridimensional.
Vea también imagecolorexact(). Devuelve el índice del color especificado de la paleta de
la imagen.
Si el color no existe en la paleta de la imagen, se
imagecolorclosestalpha
devuelve el valor -1.
Vea también imagecolorclosest().
(PHP 4 >= 4.0.6)
imagecolorclosestalpha -- Get the index of the closest
imagecolorexactalpha
color to the specified color + alpha

(PHP 4 >= 4.0.6)


Description
imagecolorexactalpha -- Get the index of the specified
color + alpha
int imagecolorclosestalpha ( resource image, int red,
int green, int blue, int alpha)
Description

Returns the index of the color in the palette of the image


which is "closest" to the specified RGB value and alpha int imagecolorexactalpha ( resource image, int red, int
level. green, int blue, int alpha)
See also imagecolorexactalpha().
Returns the index of the specified color+alpha in the
palette of the image.
Nota: This function was added in
If the color does not exist in the image's palette, -1 is
PHP 4.0.6 and requires GD 2.0.1
returned.
See also imagecolorclosestalpha().
imagecolorclosesthwb
Nota: This function was added in
(PHP 4 >= 4.0.1) PHP 4.0.6 and requires GD 2.0.1 or
imagecolorclosesthwb -- Get the index of the color which later
has the hue, white and blackness nearest to the given
color
ImageColorResolve

Description
(PHP 3>= 3.0.2, PHP 4 )
ImageColorResolve -- Devuelve el índice del color
int imagecolorclosesthwb ( resource image, int red, int especificado o su posible alternativa más cercana
green, int blue)
Descripción
Aviso
Esta función no está documentada actualmente, solamente int imagecolorresolve ( int im, int red, int green, int
se encuentra disponible la lista de parametros. blue)

Esta función garantiza el resultado de un índice de color


imagecolordeallocate para un color solicitado, ya sea el color exacto o su
alternativa más cercana.
Vea también imagecolorclosest().
(PHP 3>= 3.0.6, PHP 4 )
imagecolordeallocate -- De-allocate a color for an image
imagecolorresolvealpha
Description
(PHP 4 >= 4.0.6)
imagecolorresolvealpha -- Get the index of the specified
int imagecolordeallocate ( resource image, int color) color + alpha or its closest possible alternative

The imagecolordeallocate() function de-allocates a


color previously allocated with the Description
imagecolorallocate() function.
$white = imagecolorallocate ($im, int imagecolorresolvealpha ( resource image, int red,
255, 255, 255); int green, int blue, int alpha)
imagecolordeallocate ($im, $white);
This function is guaranteed to return a color index for a
requested color, either the exact color or the closest
ImageColorExact possible alternative.
See also imagecolorclosestalpha().
(PHP 3, PHP 4 )
ImageColorExact -- Devuelve el índice del color Nota: This function was added in
especificado PHP 4.0.6 and requires GD 2.0.1
ImageColorSet (PHP 3>= 3.0.6, PHP 4 )
imagecopy -- Copy part of an image

(PHP 3, PHP 4 )
ImageColorSet -- Establece el color para el índice de la Description
paleta especificado

int imagecopy ( resource dst_im, resource src_im, int


Descripción dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)

bool imagecolorset ( int im, int index, int red, int green, Copy a part of src_im onto dst_im starting at the x,y
int blue) coordinates src_x, src_y with a width of src_w and a
height of src_h. The portion defined will be copied onto
the x,y coordinates, dst_x and dst_y.
Establece el índice especificado de la paleta con el color
introduciod. Esto es útil para crear efectos de rellenado
en imagenes con paletas sin la sobrecarga de tener que imagecopymerge
realizar el rellenado.
Vea también imagecolorat().
(PHP 4 >= 4.0.1)
imagecopymerge -- Copy and merge part of an image
ImageColorsForIndex

Description
(PHP 3, PHP 4 )
ImageColorsForIndex -- Obtiene los colores de un índice
int imagecopymerge ( resource dst_im, resource
src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w,
Descripción int src_h, int pct)

array imagecolorsforindex ( int im, int index) Copy a part of src_im onto dst_im starting at the x,y
coordinates src_x, src_y with a width of src_w and a
height of src_h. The portion defined will be copied onto
Devuelve una matriz asociativa con las claves red, green the x,y coordinates, dst_x and dst_y. The two images will
y blue que contienen los valores apropiados para el color be merged according to pct which can range from 0 to
especificado en el índice. 100. When pct = 0, no action is taken, when 100 this
Vea también imagecolorat() y imagecolorexact(). function behaves identically to imagecopy().

ImageColorsTotal Nota: This function was added in


PHP 4.0.6
(PHP 3, PHP 4 )
ImageColorsTotal -- Encuentra el número de colores de la imagecopymergegray
paleta de una imagen

(PHP 4 >= 4.0.6)


Descripción imagecopymergegray -- Copy and merge part of an
image with gray scale
int imagecolorstotal ( int im)
Description
Encuentra el número de colores de la paleta de una
imagen.
int imagecopymergegray ( resource dst_im, resource
Vea también imagecolorat() y imagecolorsforindex().
src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w,
int src_h, int pct)
ImageColorTransparent
imagecopymergegray() copy a part of src_im onto
dst_im starting at the x,y coordinates src_x, src_y with a
(PHP 3, PHP 4 )
width of src_w and a height of src_h. The portion defined
ImageColorTransparent -- Define un color como
will be copied onto the x,y coordinates, dst_x and dst_y.
transparente
The two images will be merged according to pct which
can range from 0 to 100. When pct = 0, no action is
Descripción taken, when 100 this function behaves identically to
imagecopy().
This function is identical to imagecopymerge() except
int imagecolortransparent ( int im [, int col]) that when merging it preservese the hue of the source by
converting the destination pixels to gray scale before the
ImageColorTransparent establece como color copy operation.
transparente a col en la imagen im. im es el identificador
de imagen devuelto por imagecreate() y col es el Nota: This function was added in
identificador de color devuelto por PHP 4.0.6
imagecolorallocate().
Se devuelve el identificador del color transparente (o el
actual, si no se especifica ninguno). imagecopyresampled

imagecopy (PHP 4 >= 4.0.6)


imagecopyresampled -- Copia y reescala parte de una
imagen con remuestreo
Descripción resource imagecreatefromgd2 ( string filename)

int imagecopyresampled ( resource img_dst, resource Aviso


img_org, int Xdst, int Ydst, int Xorg, int Yorg, int
ancho_dst, int alto_dst, int ancho_org, int alto_org) Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

imagecopyresampled() copia una porción rectangular


de una imagen sobre otra, suavizando los valores de los Sugerencia: Puede usar una URL
píxeles mediante interpolación, de forma que al reducir como nombre de archivo con esta
el tamaño de una imagen aún mantiene una buena función si los "fopen wrappers" han
claridad. img_dst es la imagen de destino, img_org es el sido activados. Consulte fopen()
identificador de la imagen de origen. Si las coordenadas para más detalles.
de origen y destino y ancho y alto son diferentes, se
encogerá o agrandará el fragmento de imagen según sea
necesario. Las coordenadas son relativas a la esquina
Aviso
superior izquierda. Esta función se puede usar para
copiar regiones dentro de la misma imagen (si img_dst La versión actual de PHP para Windows, no soporta el
es la misma que img_org) pero si las regiones se acceso remoto a ficheros en esta función, no funcionará
superponen, los resultados serán impredecibles. incluso activando allow_url_fopen.
Vea también imagecopyresized().

imagecreatefromgd2part
Nota: Esta función fue añadida en
PHP 4.0.6 y requiere GD 2.0.1 o
superior (PHP 4 >= 4.1.0)
imagecreatefromgd2part -- Create a new image from a
given part of GD2 file or URL
ImageCopyResized

Description
(PHP 3, PHP 4 )
ImageCopyResized -- Copia y redimensiona parte de una
imagen resource imagecreatefromgd2part ( string filename,
int srcX, int srcY, int width, int height)
Descripción
Aviso
int imagecopyresized ( int dst_im, int src_im, int dstX, Esta función no está documentada actualmente, solamente
int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int se encuentra disponible la lista de parametros.
srcH)

ImageCopyResize copia una porción rectangular de una Sugerencia: Puede usar una URL
imagen hacia otra imagen. dst_im es la imagen de como nombre de archivo con esta
destino, src_im es el identificador de la imagen origen. Si función si los "fopen wrappers" han
la altura y anchura de las coordenadas de origen y sido activados. Consulte fopen()
destino difieren se realizará un estrechamiento o un para más detalles.
estiramiento apropiado del fragmento de la imagen. Las
coordenadas van localizadas sobre la esquina superior
izquierda. Esta función se puede usar para copiar Aviso
regiones dentro de la misma imagen (si dst_im es igual La versión actual de PHP para Windows, no soporta el
que src_im) pero si las regiones se solapan los resultados acceso remoto a ficheros en esta función, no funcionará
seran impredecibles. incluso activando allow_url_fopen.

ImageCreate
imagecreatefromgd

(PHP 3, PHP 4 )
ImageCreate -- Crea una nueva imagen (PHP 4 >= 4.1.0)
imagecreatefromgd -- Create a new image from GD file
or URL
Descripción

Description
int imagecreate ( int x_size, int y_size)

resource imagecreatefromgd ( string filename)


ImageCreate devuelve un identificador de imagen
representando una imagen en blanco de tamaño x_size
por y_size. Aviso
Esta función no está documentada actualmente, solamente
imagecreatefromgd2 se encuentra disponible la lista de parametros.

(PHP 4 >= 4.1.0) Sugerencia: Puede usar una URL


imagecreatefromgd2 -- Create a new image from GD2 file como nombre de archivo con esta
or URL función si los "fopen wrappers" han
sido activados. Consulte fopen()
Description para más detalles.
Aviso durante la creación (cortesía de vic@zymsys.com )

La versión actual de PHP para Windows, no soporta el


acceso remoto a ficheros en esta función, no funcionará function CargarJpeg ($nombreimg) {
incluso activando allow_url_fopen. $im = @imagecreatefromjpeg ($nombreimg); /*
Intento de apertura */
if (!$im) { /* Comprobar si ha fallado */
ImageCreateFromGif $im = imagecreate (150, 30); /* Crear una
imagen en blanco */
$bgc = imagecolorallocate ($im, 255, 255,
(PHP 3, PHP 4 ) 255);
ImageCreateFromGif -- Crea una nueva imagen desde un $tc = imagecolorallocate ($im, 0, 0, 0);
fichero o una URL imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
/* Mostrar un mensaje de error */
Descripción imagestring ($im, 1, 5, 5, "Error cargando
$nombreimg", $tc);
}
int imagecreatefromgif ( string filename) return $im;
}
imagecreatefromgif() devuelve un identificador de
imagen representando la imagen obtenida del nombre
del fichero dado. imagecreatefrompng
imagecreatefromgif() devuelve una cadena vacia si
hay algun fallo. Además muestra un mensaje de error, (PHP 3>= 3.0.13, PHP 4 )
que desafortunadamente se representa como un link roto imagecreatefrompng -- Crea una imagen nueva desde un
en un navegador. Para depurarlo fácilmente el siguiente fichero o URL
ejemplo producirá un error de GIF:
Ejemplo 1. Ejemplo de control de un error durante
la creación (cortesía vic@zymsys.com ) Descripción

function LoadGif($imgname) resource imagecreatefrompng ( string


{ nombre_archivo)
$im = @imagecreatefromgif($imgname); /* Attempt
to open */ imagecreatefrompng() devuelve un identificador de
if ($im == "") { /* See if it failed */ imagen que representa a la imagen obtenida a partir del
$im = ImageCreate(150,30); /* Create a blank nombre de archivo indicado.
image */ imagecreatefrompng() devuelve una cadena vacía si
$bgc = ImageColorAllocate($im,255,255,255); ha fallado. También escribe un mensaje de error, que
$tc = ImageColorAllocate($im,0,0,0); desafortunadamente se muestra en el navegador como
ImageFilledRectangle($im,0,0,150,30,$bgc); un enlace roto. Para depurar con mayor comodidad, el
ImageString($im,1,5,5,"Error loading $imgname", ejemplo siguiente producirá un JPEG erróneo:
$tc); /* Output an errmsg */ Ejemplo 1. Ejemplo de cómo manipular un error
} durante la creación (cortesía de vic@zymsys.com )
return $im;
}
function CargarJpeg ($nombreimg) {
$im = @imagecreatefrompng ($nombreimg); /*
Nota: Desde que todo el soporte a Intento de apertura */
GIFs ha sido eliminado en la libreria if (!$im) { /* Comprobar si ha fallado */
GD a partir de la versión 1.6, esta $im = imagecreate (150, 30); /* Crear una
función no está disponible si está imagen en blanco */
usando esa versión de la libreria GD. $bgc = imagecolorallocate ($im, 255, 255,
255);
$tc = imagecolorallocate ($im, 0, 0, 0);
imagecreatefromjpeg imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
/* Mostrar un mensaje de error */
(PHP 3>= 3.0.16, PHP 4 ) imagestring ($im, 1, 5, 5, "Error cargando
imagecreatefromjpeg -- Crea una imagen nueva desde $nombreimg", $tc);
un archivo o URL }
return $im;
}
Descripción

imagecreatefromstring
resource imagecreatefromjpeg ( string
nombre_archivo)
(PHP 4 >= 4.0.4)
imagecreatefromjpeg() devuelve un identificador de imagecreatefromstring -- Create a new image from the
imagen que representa a la imagen obtenida a partir del image stream in the string
nombre de archivo indicado.
imagecreatefromjpeg() devuelve una cadena vacía si Description
ha fallado. También escribe un mensaje de error, que
desafortunadamente se muestra en el navegador como
un enlace roto. Para depurar con mayor comodidad, el resource imagecreatefromstring ( string image)
ejemplo siguiente producirá un JPEG erróneo:
Ejemplo 1. Ejemplo de cómo manipular un error
imagecreatefromstring() returns an image identifier imagecreatefromxbm() returns an image identifier
representing the image obtained from the given string. representing the image obtained from the given
filename.

imagecreatefromwbmp
Sugerencia: Puede usar una URL
como nombre de archivo con esta
(PHP 4 >= 4.0.1) función si los "fopen wrappers" han
imagecreatefromwbmp -- Create a new image from file or sido activados. Consulte fopen()
URL para más detalles.

Description
Aviso
La versión actual de PHP para Windows, no soporta el
resource imagecreatefromwbmp ( string filename)
acceso remoto a ficheros en esta función, no funcionará
incluso activando allow_url_fopen.
imagecreatefromwbmp() returns an image identifier
representing the image obtained from the given
filename. imagecreatefromxpm
imagecreatefromwbmp() returns an empty string on
failure. It also outputs an error message, which
unfortunately displays as a broken link in a browser. To (PHP 4 >= 4.0.1)
ease debugging the following example will produce an imagecreatefromxpm -- Create a new image from file or
error WBMP: URL
Ejemplo 1. Example to handle an error during
creation (courtesy vic@zymsys.com)
Description

function LoadWBMP ($imgname) { resource imagecreatefromxpm ( string filename)


$im = @imagecreatefromwbmp ($imgname); /*
Attempt to open */
if (!$im) { /* See if it failed */ imagecreatefromxpm() returns an image identifier
$im = imagecreate (20, 20); /* Create a representing the image obtained from the given
blank image */ filename.
$bgc = imagecolorallocate ($im, 255, 255,
255); Sugerencia: Puede usar una URL
$tc = imagecolorallocate ($im, 0, 0, 0); como nombre de archivo con esta
imagefilledrectangle ($im, 0, 0, 10, 10, función si los "fopen wrappers" han
$bgc); sido activados. Consulte fopen()
/* Output an errmsg */ para más detalles.
imagestring ($im, 1, 5, 5, "Error loading
$imgname", $tc);
} Aviso
return $im;
} La versión actual de PHP para Windows, no soporta el
acceso remoto a ficheros en esta función, no funcionará
incluso activando allow_url_fopen.
Nota: WBMP support is only
available if PHP was compiled
against GD-1.8 or later. imagecreatetruecolor

Sugerencia: Puede usar una URL (PHP 4 >= 4.0.6)


como nombre de archivo con esta imagecreatetruecolor -- Crea una imagen nueva en color
función si los "fopen wrappers" han real (true color)
sido activados. Consulte fopen()
para más detalles.
Descripción

Aviso resource imagecreatetruecolor ( int anchura, int


La versión actual de PHP para Windows, no soporta el altura)
acceso remoto a ficheros en esta función, no funcionará
incluso activando allow_url_fopen. imagecreatetruecolor() devuelve un identificador de
imagen representando una imagen en blanco de tamaño
anchura por altura.
imagecreatefromxbm

Nota: Esta función fue añadida en


(PHP 4 >= 4.0.1) PHP 4.0.6 y requiere GD 2.0.1 o
imagecreatefromxbm -- Create a new image from file or superior
URL

ImageDashedLine
Description

(PHP 3, PHP 4 )
resource imagecreatefromxbm ( string filename) ImageDashedLine -- Dibuja una línea discontinua
Descripción int imagefilledarc ( resource image, int cx, int cy, int w,
int h, int s, int e, int col, int style)

int imagedashedline ( int im, int x1, int y1, int x2, int
y2, int col) imagefilledarc() draws a partial ellipse centered at cx,
cy (top left is 0, 0) in the image represented by image. W
and h specifies the ellipse's width and height respectively
ImageLine dibuja una línea discontinua desde x1,y1 while the start and end points are specified in degrees
hasta x2, y2 (arriba izquierda es 0.0) en la imagen im indicated by the s and e arguments. style is a bitwise OR
con el color col. of the following possibilities:
Vea también imageline().

ImageDestroy 1. IMG_ARC_PIE

2. IMG_ARC_CHORD
(PHP 3, PHP 4 )
ImageDestroy -- Destruye una imagen 3. IMG_ARC_NOFILL

4. IMG_ARC_EDGED
Descripción
IMG_ARC_PIE and IMG_ARC_CHORD are mutually
int imagedestroy ( int im) exclusive; IMG_ARC_CHORD just connects the starting
and ending angles with a straight line, while
IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL
ImageDestroy libera la memoria asociada a la imagen indicates that the arc or chord should be outlined, not
im. im es la imagen devuelta por la función filled. IMG_ARC_EDGED, used together with
imagecreate(). IMG_ARC_NOFILL, indicates that the beginning and
ending angles should be connected to the center - this is
a good way to outline (rather than fill) a 'pie slice'.
imageellipse

Nota: This function was added in


(PHP 4 >= 4.0.6)
PHP 4.0.6 and requires GD 2.0.1
imageellipse -- Draw an ellipse

imagefilledellipse
Description

(PHP 4 >= 4.0.6)


int imageellipse ( resource image, int cx, int cy, int w,
imagefilledellipse -- Draw a filled ellipse
int h, int col)

imageellipse() draws an ellipse centered at cx, cy (top Description


left is 0, 0) in the image represented by image. W and h
specifies the ellipse's width and height respectively. The
int imagefilledellipse ( resource image, int cx, int cy,
color of the ellipse is specified by color.
int w, int h, int col)

Nota: This function was added in imagefilledellipse() draws an ellipse centered at cx, cy
PHP 4.0.6 and requires GD 2.0.2 or (top left is 0, 0) in the image represented by image. W
later which can be obtained at and h specifies the ellipse's width and height
http://www.boutell.com/gd/ respectively. The ellipse is filled using color

See also imagearc(). Nota: This function was added in


PHP 4.0.6 and requires GD 2.0.1 or
later
ImageFill

See also imagefilledarc().


(PHP 3, PHP 4 )
ImageFill -- Relleno
ImageFilledPolygon
Descripción
(PHP 3, PHP 4 )
ImageFilledPolygon -- Dibuja un polígono relleno
int imagefill ( int im, int x, int y, int col)

ImageFill realiza un relleno empezando en la coordenada Descripción


x,y (arriba izquierda es 0,0) con el color col en la imagen
im.
int imagefilledpolygon ( int im, array points, int
num_points, int col)
imagefilledarc
ImageFilledPolygon crea un polígono relleno en la
imagen im, points es una matriz PHP conteniendo los
(PHP 4 >= 4.0.6)
vértices del poligono, por ejemplo. points[0] = x0,
imagefilledarc -- Draw a partial ellipse and fill it
points[1] = y0, points[2] = x1, points[3] = y1, etc.
num_points es el número total de vértices.
Description
ImageFilledRectangle array imageftbbox ( int size, int angle, string font_file,
string text [, array extrainfo])

(PHP 3, PHP 4 )
ImageFilledRectangle -- dibuja un rectángulo relleno Aviso
Esta función no está documentada actualmente, solamente
Descripción se encuentra disponible la lista de parametros.

int imagefilledrectangle ( int im, int x1, int y1, int x2, imagefttext
int y2, int col)

ImageFilledRectangle crea un rectángulo relleno con (PHP 4 >= 4.1.0)


color col en la imagen im comenzando con las imagefttext -- Write text to the image using fonts using
coordenadas superiores izquierdas x1, y1 y finalizando FreeType 2
en las coordenadas inferiores derechas x2, y2. 0,0 es la
esquina superior izquierda de la imagen. Description

ImageFillToBorder array imagefttext ( resource image, int size, int angle,


int x, int y, int col, string font_file, string text [, array
(PHP 3, PHP 4 ) extrainfo])
ImageFillToBorder -- Relleno de un color especifico
Aviso
Descripción Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
int imagefilltoborder ( int im, int x, int y, int border, int
col)
imagegammacorrect

ImageFillToBorder realiza un relleno hasta el color del


borde que está definido por border. El punto de inicio (PHP 3>= 3.0.13, PHP 4 )
para el relleno es x,y (arriba izquierda es 0,0) y la región imagegammacorrect -- Apply a gamma correction to a
se rellena con el color col. GD image

ImageFontHeight Description

(PHP 3, PHP 4 ) int imagegammacorrect ( resource image, float


ImageFontHeight -- Devuelve la altura de una fuente inputgamma, float outputgamma)

Descripción The imagegammacorrect() function applies gamma


correction to a gd image stream (image) given an input
gamma, the parameter inputgamma and an output
int imagefontheight ( int font) gamma, the parameter outputgamma.

Devuelve la altura en pixels de un carácter en un fuente imagegd2


específica.
Vea también imagefontwidth() y imageloadfont().
(PHP 4 >= 4.1.0)
imagegd2 -- Output GD2 image to browser or file
ImageFontWidth

Description
(PHP 3, PHP 4 )
ImageFontWidth -- Devuelve la anchura de una fuente
int imagegd2 ( resource image [, string filename [, int
chunk_size [, string type]]])
Descripción

Aviso
int imagefontwidth ( int font)
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Devuelve la anchura en pixels de un carácter en un
fuente específica. The optional type parameter is either raw or compressed.
Vea también imagefontheight() y imageloadfont().
Nota: The optional chunk_size and
imageftbbox type parameters became available in
PHP 4.3.1.

(PHP 4 >= 4.1.0)


imageftbbox -- Give the bounding box of a text using imagegd
fonts via freetype2
(PHP 4 >= 4.1.0)
Description imagegd -- Output GD image to browser or file
Description The filename argument is optional, and if left off, the raw
image stream will be output directly. To skip the filename
argument in order to provide a quality argument just use
int imagegd ( resource image [, string filename]) an empty string (''). By sending an image/jpeg content-
type using header(), you can create a PHP script that
outputs JPEG images directly.
Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. Nota: JPEG support is only available
if PHP was compiled against GD-1.8
or later.
ImageGif
quality is optional, and ranges from 0 (worst quality,
smaller file) to 100 (best quality, biggest file). The default
(PHP 3, PHP 4 )
is the default IJG quality value (about 75).
ImageGif -- Envía una imagen al navegador o a un fichero
If you want to output Progressive JPEGs, you need to set
interlacing on with imageinterlace().
Descripción See also imagepng(), imagegif(), imagewbmp(),
imageinterlace() and imagetypes().

int imagegif ( int im, string filename)


ImageLine
imagegif() crea el fichero GIF en filename a partir de la
imagen im. El parámetro im es el resultado de usar la (PHP 3, PHP 4 )
función imagecreate(). ImageLine -- Dibuja una línea
El formato de la imagen será GIF87a a menos que la
imagen se halla hecho transparente con
imagecolortransparent(), en cuyo caso el formato de Descripción
la imagen será GIF89a.
El parametro del nombre del fuichero es opcional, y si se
int imageline ( int im, int x1, int y1, int x2, int y2, int
deja en blanco, la imagen será mostrada directamente.
col)
Enviando un tipo de imagen/gif usando la función
header(), puede crear un script PHP que muestre
imagenes GIF directamente. ImageLine dibuja una línea desde x1,y1 hasta x2,y2
(arriba izquierda es 0,0) en la imagen im con el color col.
Vea también imagecreate() y imagecolorallocate().
Nota: Desde que todo el soporte a
GIFs ha sido eliminado en la libreria
GD a partir de la versión 1.6, esta ImageLoadFont
función no está disponible si está
usando esa versión de la libreria GD.
(PHP 3, PHP 4 )
ImageLoadFont -- Carga una fuente nueva
ImageInterlace
Descripción
(PHP 3, PHP 4 )
ImageInterlace -- Activa o desactiva el entrelazado
int imageloadfont ( string file)

Descripción ImageLoadFont carga una fuente de bitmaps definida por


el usuario y devuelve un identificador para esa fuente
int imageinterlace ( int im [, int interlace]) (que siempre es mayor de 5, de forma que no pueda
entrar en conflicto con las fuentes predefinidas)..
El formato del fichero de la fuente es actualmente binario
ImageInterlace() activa o desactiva el bit de y dependiente de la arquitectura. Esto significa que tiene
entrelazado. Si interlace es 1 la imagen im será que generar los ficheros de las fuentes en el mismo tipo
entrelazada, y si interlace es 0 el bit de entrelazado se de CPU que la que tiene la máquina que está ejecutando
desactiva. PHP.
Esta función devuelve como ha cambiado el estado del Tabla 1. Formato del fichero de fuentes
bit de entralazado de la imagen.
tipo
Posición de
Descripción
imagejpeg en bytes datos
C

(PHP 3>= 3.0.16, PHP 4 ) byte 0-3 int número de carácteres en la fuente
imagejpeg -- Output image to browser or file valor del primer carácter de la fuente
byte 4-7 int
(normalmente 32 para el espacio)
Description byte 8-11 int Anchura en pixels de cada carácter
byte 12-
int Altura en pixels de cada carácter
int imagejpeg ( resource image [, string filename [, int 15
quality]]) matriz con los datos del carácter, un
byte por pixel en cada carácter,
byte 16- char
imagejpeg() creates the JPEG file in filename from the haciendo un total de (número
image image. The image argument is the return from the carácteres* altura*anchura) bytes.
imagecreate() function. Vea también ImageFontWidth() y
ImageFontHeight().
imagepalettecopy space perimte cambiar el valor por defecto de un espacio
en una fuentes. Este valor es añadido al valor normal y
puede ser negativo.
(PHP 4 >= 4.0.1) tightness permite controlar la cantidad de espacio en
imagepalettecopy -- Copy the palette from one image to blanco entre carácteres. Este valor se añade a la anchura
another normal del carácter y puede ser negativo.
angle viene dado en grados.
Los parámetros space y tightness vienen expresados en
Description
unidades de espacio de carácteres, donde una unidad es
1/1000 el borde de una M.
int imagepalettecopy ( resource destination, resource Los parámetros space, tightness y angle son opcionales.
source) El borde es calculado usando la información disponible
de las métricas del carácter, y desafortunadamente
tiende a diferir ligeramente de los resultados obtenidos
imagepalettecopy() copies the palette from the source de digitalizar el texto. Si el ángulo es de 0 grados, puede
image to the destination image. esperar que el texto necesite un pixel más en cada
dirección.
imagepng Esta función devuelve un array conteniuendo los
siguientes elementos:
coordenada x inferior
(PHP 3>= 3.0.13, PHP 4 ) 0
izquierda
imagepng -- Output a PNG image to either the browser or
a file coordenada y inferior
1
izquierda

Description coordenada x superior


2
derecha
coordenada y superior
int imagepng ( resource image [, string filename]) 3
derecha
Vea también imagepstext().
The imagepng() outputs a GD image stream (image) in
PNG format to standard output (usually the browser) or,
if a filename is given by the filename it outputs the ImagePSCopyFont
image to the file.
<?php (PHP 3>= 3.0.9, PHP 4 )
$im = imagecreatefrompng ImagePSCopyFont -- hace una copia de una fuente ya
("test.png"); cargada para futuras modificaciones
imagepng ($im);
?>
See also imagegif(), imagewbmp(), imagejpeg(), Descripción
imagetypes().
int imagepscopyfont ( int fontindex)
ImagePolygon
Use esta función si necesita hacer modificaciones en la
fuente, por ejemplo expander/condensar, inclinarla o
(PHP 3, PHP 4 ) cambiar su vector de codificación de caracteres, pero
ImagePolygon -- Dibuja un polígono también necesita mantener la fuente original. Note que
la fuente que quiera copiar debe haber sido obtenida
Descripción usando imagepsloadfont(), no una fuente que sea una
copia de otra. Aunque puede hacer modificaciones antes
de copiarla.
int imagepolygon ( int im, array points, int num_points, Si usa esta función, debe liberar las fuentes obtenidas de
int col) esta manera. De otra forma su script se colgará.
En el caso de que todo vaya bien, devolverá un índice de
fuente válido que puede ser usado para futuos
ImagePolygon crea un polígono en la imagen id. points es
propósitos. De otra forma la función devolverá FALSE e
un array PHP conteniendo los vértices del polígono. de la
imprimirá un mensaje indicando que es lo que ha ido
siguiente forma points[0] = x0, points1 = y0, points[2] =
mal.
x1, points[3] = y1, etc. num_points es el número total de
Vea también imageploadpsfont().
vértices.
Vea también imagecreate().
ImagePSEncodeFont
ImagePSBBox
(PHP 3>= 3.0.9, PHP 4 )
ImagePSEncodeFont -- Cambia el vector de codificación
(PHP 3>= 3.0.9, PHP 4 )
de caracteres de una fuente
ImagePSBBox -- Devuelve el borde que rodea un
rectángulo de texto usando fuentes PostScript Type1
Descripción
Descripción
int imagepsencodefont ( string encodingfile)
array imagepsbbox ( string text, int font, int size, int
space, int width, float angle) Carga un vector de codificación de caracteres desde un
archivo y cambia el vector de codificación de las fuentes
a él. Loads a character encoding vector from from a file
size representa pixels.
and changes the fonts encoding vector to it. En las
fuentes PostScript normalmente faltan muchos ImagePSText
caracteres por encima de 127, seguramente quiera
cambiar esto si emplea u idioma distinto del inglés.El
formato exacto de este archivo está descrito en la (PHP 3>= 3.0.9, PHP 4 )
documentación de T1libs. T1lib viene con dos archivos ImagePSText -- Para dibujar una cadena de texto sobre
listos para usar, IsoLatin1.enc y IsoLatin2.enc. una imagen usando fuentes PostScript Type1
Si se encuentra usando esta función todo el tiempo, una
forma mucho mejor de definir la codificación es
Descripción
establecer ps.default_encoding en el archivo de
configuración para que apunte al archivo de codificación
correcto y todas las fuentes que cargue tendrán de array imagepstext ( int image, string text, int font, int
forma automática la codificación correcta. size, int foreground, int background, int x, int y [, int
space [, int tightness [, float angle [, int
antialias_steps]]]])
imagepsextendfont

size viene expresado en pixels.


(PHP 3>= 3.0.9, PHP 4 ) foreground es el color en el cual el texto será pintado.
imagepsextendfont -- Extend or condense a font background es el color en el que el texto tratará de
resaltar con antialiaing. Los pixels con el color
background no se pintan, de forma que la imagen de
Description
fondo no necesita ser de un color sólido.
Las coordenadas dadas por x, y definirán el origen (o
bool imagepsextendfont ( int font_index, float extend) punto de referencia) del primer carácter (la esquina
superior izquierda del carácter). Esto es diferente de la
función ImageString(), donde x, y definen la esquina
Extend or condense a font (font_index), if the value of superiro derecha del primer carácter. Consulte la
the extend parameter is less than one you will be documentación de PostScript sobre fuentes y su sistema
condensing the font. de medidas si tiene algún problema entendiendo como
funcion.
space permite cambiar el valor por defecto de un espacio
ImagePSFreeFont
en la fuente. Esta cantidad es sumada al valor normal y
puede ser negativa.
(PHP 3>= 3.0.9, PHP 4 ) tightness permite controlar la cantidad de espacio en
ImagePSFreeFont -- Libera la memoria usada por un blanco entre caracteres. Esta cantidad es sumada al
fuente PostScript Type 1 valor normal y puede ser negativa.
angle viene en grados.
antialias_steps permite controlar el número de colores
Descripción usados para el antialising del texto. Los valores
permitidos son 4 y 16. El valor superior está
recomendado para textos con tamaños inferiores a 20,
void imagepsfreefont ( int fontindex) donde el efecto en la calidad del texto es bastante
visible. Con tamaños superiores use 4. Hace un menor
Vea también imagepsloadfont(). uso de cálculo.
Parameters space y tightness están expresados en
unidades de espacio de caracteres, donde 1 unidad es
ImagePSLoadFont 1/1000 de una M mayúscula.
Los parámetros space, tightness, angle y antialias son
opcionales.
(PHP 3>= 3.0.9, PHP 4 )
Esta función devuelve una matriz conteniendo los
ImagePSLoadFont -- Carga una fuente PostScript Type 1
siguientes elementos:
desde un fichero
coordenada x inferior
0
izquierda
Descripción
coordenada y inferior
1
izquierda
int imagepsloadfont ( string filename)
coordenada x superior
2
derecha
En el caso de que todo vaya bien, tiene que devolver un
coordenada y superior
índice de fuente correcto que puede ser usado para 3
derecha
futuras operaciones. En caso contrario la función
devuelve FALSE e imprime un mensaje describiendo Vea también imagepsbbox().
donde ha fallado
Vea también imagepsfreefont().
ImageRectangle

imagepsslantfont
(PHP 3, PHP 4 )
ImageRectangle -- Dibuja un rectángulo
(PHP 3>= 3.0.9, PHP 4 )
imagepsslantfont -- Slant a font
Descripción

Description
int imagerectangle ( int im, int x1, int y1, int x2, int y2,
int col)
bool imagepsslantfont ( int font_index, float slant)
ImageRectangle crea un rectángulo de color col en la
Slant a font given by the font_index parameter with a imagen im comenzando en la coordenada superior
slant of the value of the slant parameter. izquierda x1,y1 y finalizando en la coordenada inferior
derecha x2,y2. 0,0 es la esquina superior izquierda de la imagesetstyle() sets the style to be used by all line
imagen. drawing functions (such as imageline() and
imagepolygon()) when drawing with the special color
IMG_COLOR_STYLED or lines of images with color
imagerotate IMG_COLOR_STYLEDBRUSHED.
The style parameter is an array of pixels. Following
example script draws a dashed line from upper left to
(PHP 4 >= 4.3.0)
lower right corner of the canvas:
imagerotate -- Rotate an image with a given angle
Ejemplo 1. imagesetstyle() example

Description
<?php
header ("Content-type: image/jpeg");
ressource imagerotate ( resource src_im, float angle, int $im = imagecreate (100, 100);
bgd_color) $w = imagecolorallocate ($im, 255, 255, 255);
$red = imagecolorallocate ($im, 255, 0, 0);
Rotates the src_im image using a given angle in degree.
bgd_color specifies the color of the uncovered zone after /* Draw a dashed line, 5 red pixels, 5 white pixels */
the rotation. $style = array ($red,$red,$red,$red,$red,$w,$w,$w,
$w,$w);
imagesetstyle ($im, $style);
imagesetbrush imageline ($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush()


(PHP 4 >= 4.0.6) with imagesetstyle */
imagesetbrush -- Set the brush image for line drawing $style = array ($w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$w,
$w,$red);
Description imagesetstyle ($im, $style);

$brush = imagecreatefrompng
int imagesetbrush ( resource image, resource brush) ("http://www.libpng.org/pub/png/images/smile.happy.p
ng");
$w2 = imagecolorallocate($brush,255,255,255);
imagesetbrush() sets the brush image to be used by all
imagecolortransparent ($brush, $w2);
line drawing functions (such as imageline() and
imagesetbrush ($im, $brush);
imagepolygon()) when drawing with the special colors
imageline ($im, 100, 0, 0, 100,
IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.
IMG_COLOR_STYLEDBRUSHED);

Nota: You need not take special imagejpeg ($im);


action when you are finished with a imagedestroy ($im);
brush, but if you destroy the brush ?>
image, you must not use the See also imagesetbrush(), imageline().
IMG_COLOR_BRUSHED or
IMG_COLOR_STYLEDBRUSHED colors
until you have set a new brush Nota: This function was added in
image! PHP 4.0.6

Nota: This function was added in imagesetthickness


PHP 4.0.6
(PHP 4 >= 4.0.6)
ImageSetPixel imagesetthickness -- Set the thickness for line drawing

(PHP 3, PHP 4 ) Description


ImageSetPixel -- Dibuja un pixel
void imagesetthickness ( resource image, int
Descripción thickness)

int imagesetpixel ( int im, int x, int y, int col) imagesetthickness() sets the thickness of the lines
drawn when drawing rectangles, polygons, ellipses etc.
etc. to thickness pixels.
ImageSetPixel dibuja un pixel x,y (arriba izquierda 0,0)
en la imagen im con color col.
Vea también imagecreate() y imagecolorallocate(). Nota: This function was added in
PHP 4.0.6 and requires GD 2.0.1 or
later
imagesetstyle

imagesettile
(PHP 4 >= 4.0.6)
imagesetstyle -- Set the style for line drawing
(PHP 4 >= 4.0.6)
imagesettile -- Set the tile image for filling
Description

Description
int imagesetstyle ( resource image, array style)
int imagesettile ( resource image, resource tile) Vea también imagecreate() y imagesy().

imagesettile() sets the tile image to be used by all ImageSY


region filling functions (such as imagefill() and
imagefilledpolygon()) when filling with the special
color IMG_COLOR_TILED. (PHP 3, PHP 4 )
A tile is an image used to fill an area with a repeated ImageSY -- Obtiene la altura de la imagen
pattern. Any GD image can be used as a tile, and by
setting the transparent color index of the tile image with
imagecolortransparent(), a tile allows certain parts of Descripción
the underlying area to shine through can be created.
int imagesy ( int im)
Nota: You need not take special
action when you are finished with a ImageSY devuelve la altura de la imagen identificada por
tile, but if you destroy the tile image, im.
you must not use the Vea también imagecreate() y imagesx().
IMG_COLOR_TILED color until you
have set a new tile image!
imagetruecolortopalette

Nota: This function was added in


PHP 4.0.6 (PHP 4 >= 4.0.6)
imagetruecolortopalette -- Convert a true color image to
a palette image
ImageString

Description
(PHP 3, PHP 4 )
ImageString -- Dibuja una cadena de texto
horizintalmente void imagetruecolortopalette ( resource image, bool
dither, int ncolors)

Descripción
imagetruecolortopalette() converts a truecolor image
to a palette image. The code for this function was
int imagestring ( int im, int font, int x, int y, string s, int originally drawn from the Independent JPEG Group library
col) code, which is excellent. The code has been modified to
preserve as much alpha channel information as possible
in the resulting palette, in addition to preserving colors
ImageString dibuja la cadena s en la imagen identificada
as well as possible. This does not work as well as might
por im en las coordenadas x,y (arriba izquierda es 0,0) be hoped. It is usually best to simply produce a truecolor
en el color col. Si la fuente es 1, 2, 3, 4 o 5, se emplea
output image instead, which guarantees the highest
una fuente interna. output quality.
Vea también imageloadfont().
dither indicates if the image should be dithered - if it is
TRUE then dithering will be used which will result in a
ImageStringUp more speckled image but with better color
approximation.
ncolors sets the maximum number of colors that should
(PHP 3, PHP 4 ) be retained in the palette.
ImageStringUp -- Dibuja una cadena de texto
verticalmente
Nota: This function was added in
PHP 4.0.6 and requires GD 2.0.1 or
Descripción later

int imagestringup ( int im, int font, int x, int y, string s, ImageTTFBBox
int col)

(PHP 3>= 3.0.1, PHP 4 )


ImageStringUp dibuja la cadena s verticalmente en la ImageTTFBBox -- Devuelve un caja que rodea al texto
imagen identificada por im en las coordenadas x,y (arriba usando fuentes TypeType
izquierda es 0,0) en el color col. Si la fuente es 1, 2, 3, 4
o 5, se usa una fuente interna.
Vea también imageloadfont(). Descripción

ImageSX array ImageTTFBBox ( int size, int angle, string fontfile,


string text)

(PHP 3, PHP 4 )
ImageSX -- Obtiene la anchura de la imagen Esta función calcula y devuelve un rectángulo en pixels
que encierra un texto con TrueType.
text
Descripción La cadena que ha de ser medida.
size
El tamaño de la fuente.
int imagesx ( int im) fontfile
El nombre del archivo de fuente TrueType.
ImageSX devuelva la anchura de la imagen identificado (Puede ser también una URL.)
por im. angle
Ángulo en grados en el text que va a ser Ejemplo 1. ImageTTFText
medido.
ImageTTFBBox() devuelve una matriz con 8 elementos
representando cuatro puntos que hacen una caja <?php
rodeando al texto: Header("Content-type: image/gif");
esquina inferior izquierda, $im = imagecreate(400,30);
0 $black = ImageColorAllocate($im, 0,0,0);
posición X
$white = ImageColorAllocate($im, 255,255,255);
esquina inferior izquierda, ImageTTFText($im, 20, 0, 10, 20, $white,
1
posición Y "/path/arial.ttf", "Testing... Omega: &#937;");
esquina inferior derecha, ImageGif($im);
2 ImageDestroy($im);
posición X
?>
esquina inferior derecha,
3 Esta función requiere la libreria GD y la libreria FreeType.
posición Y
Vea también ImageTTFBBox().
esquina superior derecha,
4
posición X
imagetypes
esquina superior derecha,
5
posición Y
esquina superior izquierda, (PHP 3 CVS only, PHP 4 >= 4.0.2)
6 imagetypes -- Return the image types supported by this
posición X
PHP build
esquina superior izquierda,
7
posición Y
Description
Los puntos son relativos a text a pesar del ángulo, de
forma que "superior izquierda" significa la esquina
superior izquierda viendo el texto horizontalmente. int imagetypes ( void)
Esta función requiere tanto la libreria GD como la libreria
Freetype.
Vea también ImageTTFText(). This function returns a bit-field corresponding to the
image formats supported by the version of GD linked into
PHP. The following bits are returned, IMG_GIF | IMG_JPG |
ImageTTFText IMG_PNG | IMG_WBMP. To check for PNG support, for
example, do this:
Ejemplo 1. imagetypes
(PHP 3, PHP 4 )
ImageTTFText -- Escribe texto en la imagen usando
fuentes TrueType <?php
if (imagetypes() &
Descripción IMG_PNG) {
echo "PNG Support is
enabled";
array ImageTTFText ( int im, int size, int angle, int x, int }
y, int col, string fontfile, string text) ?>

ImageTTFText escribe la cadenatext en la imagen


identificada por im, comenzando en las coordenadas x,y imagewbmp
(arriba izquierda es 0,0), con un ángulo de angle en el
color col, usando el ficheor de fuente TrueType (PHP 3>= 3.0.15, PHP 4 >= 4.0.1)
identificado por fontfile. imagewbmp -- Output image to browser or file
Las coordenadas dadas por x,y definirán el punto base
del primer carácter. (la esquina inferior izquierda del
carácter). Esto es diferente de la función ImageString(), Description
donde x,y definen la esquina superior derecha del primer
carácter.
El angle viene dado en grados, donde 0 grados int imagewbmp ( resource image [, string filename [, int
representa el texto de izquierda a derecha (dirección las foreground]])
3 en punto), y valores superiores representan una
rotación en el sentido de las agujas de un reloj. (ej. un imagewbmp() creates the WBMP file in filename from
valor de 90 representaría un texto que fuese de abajo the image image. The image argument is the return from
hacia arriba). the imagecreate() function.
fontfile es la ruta hacia la fuente TrueType que desee The filename argument is optional, and if left off, the raw
usar. image stream will be output directly. By sending an
text es la cadena de texto que puede incluir secuencias image/vnd.wap.wbmp content-type using header(), you
de caracteres UTF-8 (de la forma: &123; ) para acceder a can create a PHP script that outputs WBMP images
caracteres de la fuente más allá de los primeros 255. directly.
col es el índice de color. El uso de un índice de color
negativo tiene el efecto de desactivar el antialiasing.
ImageTTFText() devuelve una matriz con 8 elementos Nota: WBMP support is only
representando cuatro puntos que hace una caja que available if PHP was compiled
cubre el texto.El orden de los puntos en arriba izquierda, against GD-1.8 or later.
arriba derecha, abajo derecha, abajo izquierda. Los
puntos son relativos al texto a pesar del ángulo, por lo
que "arriba izquierda" significa en la esquina superior Using the optional foreground parameter, you can set the
izquierda cuando ve el texto horizontalmente. foreground color. Use an identifier obtained from
Este script de ejemplo producirá un GIF negro de 400x30 imagecolorallocate(). The default foreground color is
pixels, con las palabras "Testing..." en blanco con la black.
fuente Arial.
See also image2wbmp(), imagepng(), imagegif(), Converts the pngname PNG file to WBMP format, and
imagejpeg(), imagetypes(). saves it as wbmpname. With the d_height and d_width
you specify the height and width of the destination
image.
iptcembed

Nota: WBMP support is only


(PHP 3>= 3.0.7, PHP 4 ) available if PHP was compiled
iptcembed -- Embed binary IPTC data into a JPEG image against GD-1.8 or later.

Description See also jpeg2wbmp().

array iptcembed ( string iptcdata, string jpeg_file_name read_exif_data


[, int spool])

(PHP 4 >= 4.0.1)


Aviso read_exif_data -- Reads header information stored in TIFF
Esta función no está documentada actualmente, solamente and JPEG images
se encuentra disponible la lista de parametros.
Description

iptcparse
array exif_read_data ( string filename, string sections,
bool arrays, bool thumbnail)
(PHP 3>= 3.0.6, PHP 4 )
iptcparse -- Parse a binary IPTC http://www.iptc.org/
block into single tags. Nota: The read_exif_data()
function is an alias for
exif_read_data().
Description

See also exif_thumbnail().


array iptcparse ( string iptcblock)

XLII. Funciones IMAP


This function parses a binary IPTC block into its single
tags. It returns an array using the tagmarker as an index
and the value as the value. It returns FALSE on error or Para hacer funcionar estas funciones, debe compilar PHP
if no IPTC data was found. See getimagesize() for a con --with-imap. Esto requiere que la libreria c-client esté
sample. instalada. Obtenga la última versión de
ftp://ftp.cac.washington.edu/imap/ y compílela. Luego
copie c-client/c-client.a al directorio /usr/local/lib o a
jpeg2wbmp
cualquier otro directorio de su LINK path y copie c-
client/rfc822.h, mail.h y linkage.h al directorio
(PHP 4 >= 4.0.5) /usr/local/include o a cualquier otro de su INCLUDE path.
jpeg2wbmp -- Convert JPEG image file to WBMP image Decir que estas funciones no están limitadas al protocolo
file IMAP, a pesar de sus nombres. La librería subyacente c-
client también soporta NNTP, POP3 y métodos de acceso
local a buzones de correo. Vea imap_open() para una
Description mayor información.
Tabla de contenidos
imap_8bit -- Convierte una cadena de 8bit a una cadena
int jpeg2wbmp ( string jpegname, string wbmpname, int quoted-printable
d_height, int d_width, int threshold) imap_alerts -- Esta función devuelve todos los mensajes
de alerta IMAP (si hubo) que han ocurrido durante la
Converts the jpegname JPEG file to WBMP format, and petición de la pagina o desde que la pila de alertas fue
saves it as wbmpname. With the d_height and d_width inicializada.
you specify the height and width of the destination imap_append -- Agrega una cadena de mensaje al buzón
image. especificado
imap_base64 -- Decodifica texto codificado en BASE64
imap_binary -- Convierte una cadena de 8bit a una
Nota: WBMP support is only cadena base64
available if PHP was compiled imap_body -- Lee el cuerpo del mensaje
against GD-1.8 or later. imap_bodystruct -- Read the structure of a specified
body section of a specific message
imap_check -- Comprueba el estado del buzón actual
See also png2wbmp(). imap_clearflag_full -- Limpia los flags de los mensajes
imap_close -- Cierra una sesión IMAP
png2wbmp imap_createmailbox -- Crea un buzón nuevo
imap_delete -- Marca un mensaje para ser borrado en el
buzón actual
(PHP 4 >= 4.0.5) imap_deletemailbox -- Elimina un buzón
png2wbmp -- Convert PNG image file to WBMP image file imap_errors -- Esta función devuelve todos los errores
IMAP (si hubo) que han occurrido durante la petición de
la página o desde que la pila de errores se inicializó.
Description imap_expunge -- Elimina todos los mensajes marcados
como borrados
imap_fetch_overview -- Read an overview of the
int png2wbmp ( string pngname, string wbmpname, int
information in the headers of the given message
d_height, int d_width, int threshold)
imap_fetchbody -- Localiza una sección particular en el imap_8bit
cuerpo del mensaje
imap_fetchheader -- Devuelve la cabecera del mensaje
imap_fetchstructure -- Lee la estructuta de un mensaje (PHP 3, PHP 4 )
concreto imap_8bit -- Convierte una cadena de 8bit a una cadena
imap_get_quota -- Retrieve the quota level settings, and quoted-printable
usage statics per mailbox
imap_get_quotaroot -- Retrieve the quota settings per
Descripción
user
imap_getmailboxes -- Lee la lista de buzones,
devolviendo informacón detallada de cada uno string imap_8bit ( string string)
imap_getsubscribed -- Lista todos los buzones subscritos
imap_header -- Lee la cabecera del mensaje
imap_headerinfo -- Read the header of the message Convierte una cadena de 8bit a una cadena quoted-
imap_headers -- Returns headers for all messages in a printable.
mailbox Devuelve una cadena quoted-printable
imap_last_error -- Esta función devuelve el último error
IMAP (si se produjo) que ocurrió durante la petición de imap_alerts
esta página.
imap_list -- Read the list of mailboxes
imap_listmailbox -- Lee la lista de buzones (PHP 3>= 3.0.12, PHP 4 )
imap_listscan -- Read the list of mailboxes, takes a string imap_alerts -- Esta función devuelve todos los mensajes
to search for in the text of the mailbox de alerta IMAP (si hubo) que han ocurrido durante la
imap_listsubscribed -- Lista todos los buzones subscritos petición de la pagina o desde que la pila de alertas fue
imap_lsub -- List all the subscribed mailboxes inicializada.
imap_mail_compose -- Create a MIME message based on
given envelope and body sections
imap_mail_copy -- Copia los mensajes especificados a un Descripción
buzón
imap_mail_move -- Mueve los mensajes especificados a
array imap_alerts ( void)
un buzón
imap_mail -- Send an email message
imap_mailboxmsginfo -- Obtiene información acerca del Esta función devuelve un array con todos los mensajes
buzón actual de alerta IMAP generados desde la última llamada a
imap_mime_header_decode -- Decode MIME header imap_alerts(), o el comienzo de la pagina. Cuando se
elements llama a imap_alerts(), la pila de alerta es inicializada.
imap_msgno -- Esta función devuelve el número de La especificación IMAP requiere que estos mensajes sean
secuencia del mensaje para el UID dado. pasados al usuario.
imap_num_msg -- Informa del número de mensajes en el
buzón actual
imap_num_recent -- Informa el número de mensajes imap_append
recientes en el buzón actual
imap_open -- Abre una sesión IMAP (PHP 3, PHP 4 )
imap_ping -- Comprueba si la sesión IMAP está aún activa imap_append -- Agrega una cadena de mensaje al buzón
imap_qprint -- Convierte una cadena quoted-printable a especificado
una cadena de 8 bit
imap_renamemailbox -- Renombra un buzón
imap_reopen -- Reabre una sesión IMAP a un nuevo Descripción
buzón
imap_rfc822_parse_adrlist -- Examina la cadena dirección
imap_rfc822_parse_headers -- Parse mail headers from a int imap_append ( int imap_stream, string mbox, string
string message, string flags)
imap_rfc822_write_address -- Devuleve una dirección de
correo correctamente formateada dado el buzón, host, e Devuelve TRUE si no hay error y FALSE en caso
información personal. contrario.
imap_scanmailbox -- Lee la lista de buzones y toma una imap_append() agrega una cadena de mensaje al
cadena para buscar en el texto del buzón buzón especificado mbox. Si se especifica el parámetro
imap_search -- Esta función devuelve un array de flags, escribe las opciones o condiciones establecidas en
mensajes que coinciden con el criterio de busqueda el parámetro flags al buzón.
dado. Cuando conecte con el servidor Cyrus IMAP, debe usar
imap_set_quota -- Sets a quota for a given mailbox "\r\n" como finalizador de linea en vez de "\n" o la
imap_setacl -- Sets the ACL for a giving mailbox operación fallará.
imap_setflag_full -- Activa flags en los mensajes
imap_sort -- Ordena un array de cabeceras de mensajes
imap_status -- Esta función devuelve el información de imap_base64
estado de otro buzón distinto al actual.
imap_subscribe -- Subscribe to a mailbox
imap_thread -- Return threaded by REFERENCES tree (PHP 3, PHP 4 )
imap_uid -- Esta función devuelve el UID del número de imap_base64 -- Decodifica texto codificado en BASE64
secuencia del mensaje dado
imap_undelete -- Desmarca los mensajes que están
Descripción
marcados como borrados
imap_unsubscribe -- Unsubscribe from a mailbox
imap_utf7_decode -- Decodes a modified UTF-7 encoded string imap_base64 ( string text)
string.
imap_utf7_encode -- Converts 8bit data to modified UTF-
7 text. imap_base64() decodifica texto codificado en BASE-64.
imap_utf8 -- Converts text to UTF8 El mensaje decodificado es devuelto como una cadena.
imap_binary
Date : fecha del mensaje
Driver : controlador
(PHP 3>= 3.0.2, PHP 4 ) Mailbox : nombre del buzón
imap_binary -- Convierte una cadena de 8bit a una Nmsgs : número de mensajes
cadena base64 Recent : número de mensajes recientes

Descripción
imap_clearflag_full
string imap_binary ( string string)
(PHP 3>= 3.0.3, PHP 4 )
Convierte una cadena de 8bit a una cadena base64. imap_clearflag_full -- Limpia los flags de los mensajes
Devuleve una cadena base64.
Descripción
imap_body
string imap_clearflag_full ( int stream, string sequence,
(PHP 3, PHP 4 ) string flag, string options)
imap_body -- Lee el cuerpo del mensaje
Esta funcion elimina el flag especificado del conjunto de
flags activos para los mensajes en la secuencia
Descripción
especificada.
Las opciones son una máscara de bit con uno o más de
string imap_body ( int imap_stream, int msg_number, los siguientes:
int flags)
ST_UID El argumento sequence contiene UIDs
en vez de
imap_body() devuelve el cuerpo del mensaje, numerado números secuenciales
msg_number del buzón actual. Los flags opcionales son
una máscara de bit con una o mas de las siguientes:

imap_close
• FT_UID - El msgno es un UID
• FT_PEEK - No activar \Seen flag si no está ya (PHP 3, PHP 4 )
activa imap_close -- Cierra una sesión IMAP
• FT_INTERNAL - La cadena devuelta está en
formato interno, no canoniza a CRLF. Descripción

imap_bodystruct int imap_close ( int imap_stream, int flags)

(PHP 3>= 3.0.4, PHP 4 ) Cierra una sesión imap. Toma un parámetro flag
imap_bodystruct -- Read the structure of a specified opcional, CL_EXPUNGE, el cual purgará el buzón de forma
body section of a specific message trasparente antes de cerrarla.

Description imap_createmailbox

object imap_bodystruct ( resource stream_id, int (PHP 3, PHP 4 )


msg_no, int section) imap_createmailbox -- Crea un buzón nuevo

Aviso Descripción
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. int imap_createmailbox ( int imap_stream, string
mbox)

imap_check imap_createmailbox() crea un buzón nuevo


especificado por mbox (ver imap_open() para el
(PHP 3, PHP 4 ) formato del parámetro mbox).
imap_check -- Comprueba el estado del buzón actual Devuelve TRUE si no hay error y FALSE en caso
contrario.
Ver También imap_renamemailbox() y
Descripción imap_deletemailbox().

object imap_check ( int imap_stream) imap_delete

Devuelve información acerca del buzón actual. Devuelve (PHP 3, PHP 4 )


FALSE si falla. imap_delete -- Marca un mensaje para ser borrado en el
La función imap_check() comprueba el estado del buzón actual
buzón actual en el servidor y devuelve la información en
un objeto con las siguientes propiedades.
Descripción
int imap_delete ( int imap_stream, int msg_number) This function fetches mail headers for the given
sequence and returns an overview of their contents.
sequence will contain a sequence of message indices or
Devuelve TRUE.
UIDs, if flags contains FT_UID. The returned value is an
La función imap_delete() marca el mensaje
array of objects describing one message header each:
referenciado por msg_number para su eliminación. El
borrado físico de los mensajes es realizado por
imap_expunge().
• subject - the messages subject

imap_deletemailbox
• from - who sent it
• date - when was it sent
(PHP 3, PHP 4 ) • message_id - Message-ID
imap_deletemailbox -- Elimina un buzón • references - is a reference to this message id
• size - size in bytes
Descripción
• uid - UID the message has in the mailbox

int imap_deletemailbox ( int imap_stream, string


• msgno - message sequence number in the
maibox
mbox)
• recent - this message is flagged as recent
imap_deletemailbox() elimina el buzón especificado • flagged - this message is flagged
(ver imap_open() para el formato del mbox).
Devuelve TRUE si no hay error y FALSE en caso
• answered - this message is flagged as
answered
contrario.
Ver También imap_createmailbox() y • deleted - this message is flagged for deletion
imap_reanmemailbox().
• seen - this message is flagged as already read
• draft - this message is flagged as being a draft
imap_errors

Ejemplo 1. imap_fetch_overview() example


(PHP 3>= 3.0.12, PHP 4 )
imap_errors -- Esta función devuelve todos los errores
IMAP (si hubo) que han occurrido durante la petición de
$mbox =
la página o desde que la pila de errores se inicializó.
imap_open("{your.imap.host:143}","username","p
assword")
Descripción or die("can't connect: ".imap_last_error());

$overview =
array imap_errors ( void) imap_fetch_overview($mbox,"2,4:6",0);

Esta función devuelve un array de todos los mensajes de if(is_array($overview)) {


error IMAP generados desde la última llamada a reset($overview);
imap_errors(), o el principio de la página. Cuando se while( list($key,$val) = each($overview)) {
llama a imap_errors(), la pila de errores se inicializa. print $val->msgno
ATENCIàN: esta función no esta disponible aún en PHP4. . " - " . $val->date
. " - " . $val->subject
. "\n";
imap_expunge }
}

(PHP 3, PHP 4 ) imap_close($mbox);


imap_expunge -- Elimina todos los mensajes marcados
como borrados
imap_fetchbody
Descripción
(PHP 3, PHP 4 )
int imap_expunge ( int imap_stream) imap_fetchbody -- Localiza una sección particular en el
cuerpo del mensaje

imap_expunge() elimina todos los mensajes marcados


por la función imap_delete(). Descripción
Devuleve TRUE.
string imap_fetchbody ( int imap_stream, int
imap_fetch_overview msg_number, string part_number, flags flags)

(PHP 3>= 3.0.4, PHP 4 ) Esta función busca una sección particular en el cuerpo de
imap_fetch_overview -- Read an overview of the los mensajes especificados, como una cadena de texto y
information in the headers of the given message devuleve esa cadena. La especificación de la sección es
una cadena de enteros delimitados por comas,los cuales
indexan las partes del cuerpo como indica la
Description especificación IMAP4. Partes del cuerpo no son
decodificadas por esta función.
Las opciones para imap_fetchbody () son una máscara
array imap_fetch_overview ( resource imap_stream, de bit con una o más de las siguientes
string sequence [, int options])
• FT_UID - El msgono es un UID lines Número de lineas
• FT_PEEK - No activar \Seen flag si no esta ya bytes Número de bytes
activa ifdisposition TRUE si hay una cadena de configuración
• FT_INTERNAL - La cadena devuelta está en
disposition Cadena de configuración
formato "interno", sin ningún intento por
canonizar CRLF ifdparameters TRUE si el array dparameters existe
dparameters [a] Array de parametro de configuración
imap_fetchheader ifparameters TRUE si el array de parámetros existe
parameters [b] MIME parameters array
(PHP 3>= 3.0.3, PHP 4 )
Array de objetos describiendo cada parte
imap_fetchheader -- Devuelve la cabecera del mensaje parts [c]
del mensaje
Notas:
Descripción a. dparameters es un array de objetos donde cada objeto
tiene un "atributo" y una propiedad "valor".
b. parameter es un array de objetos donde cada objetor
string imap_fetchheader ( int imap_stream, int msgno,
tiene un "atributo" y una propiedad "valor".
int flags)
c. parts es un array de objetos identico en estructura al
objeto del primer nivel, con la limitación de que este no
Esta función localiza el formato de la cabecera RFC 822 puede contener más objetos 'parts'.
del mensaje especificado como una cadena de texto y
Tabla 2. Tipo primario del cuerpo
devuelve esa cadena de texto.
The options are: 0 texto
multipart
FT_UID El argumento msgno es un UID 1
e
FT_INTERNAL La cadena devuelta esta en formato
"interno", 2 mensaje
sin ningún intento de canonizar CRLF aplicació
3
n
FT_PREFETCHTEXT The RFC822.TEXT should be pre-
fetched at the 4 audio
same time. Esto evita un extra RTT en un 5 imagen
a
conexión IMAP si se desea un mensaje co 6 video
mpleto de 7 otro
texto (e.g. en una operación de
"guardar a un fichero local") Tabla 3. Codificacion para tranferencia
0 7BIT
1 8BIT
imap_fetchstructure
2 BINARY
3 BASE64
(PHP 3, PHP 4 )
imap_fetchstructure -- Lee la estructuta de un mensaje QUOTED-
4
concreto PRINTABLE
5 OTRO
Descripción

imap_get_quota
object imap_fetchstructure ( int imap_stream, int
msg_number [, int flags])
(PHP 4 >= 4.0.5)
imap_get_quota -- Retrieve the quota level settings, and
Esta función busca toda la información estructurada en el usage statics per mailbox
mensaje especificado. El parámetro opcional flags sólo
tiene una opcion, FT_UID, la cual indica a la función que
trate el argumento msg_number como un UID. El objeto Description
devuelto incluye el sobre, la fecha interna, el tama¤o,
flags y la estructura del cuerpo con un objeto similar por
cada mime adjunto al mensaje. La estructura de los array imap_get_quota ( resource imap_stream, string
objetos devueltos es como sigue: quota_root)
Tabla 1. Objetos Devueltos para
imap_fetchstructure() Returns an array with integer values limit and usage for
type Tipo primario del cuerpo the given mailbox. The value of limit represents the total
amount of space allowed for this mailbox. The usage
encoding Body transfer encoding value represents the mailboxes current level of capacity.
ifsubtype TRUE si hay una cadena de subtipo Will return FALSE in the case of failure.
This function is currently only available to users of the c-
subtype MIME subtype client2000 or greater library.
ifDescripción TRUE si hay una cadena de Descripción NOTE: For this function to work, the mail stream is
required to be opened as the mail-admin user. For a non-
Description Conenido de la cadena de Descripción admin user version of this function, please see the
ifid TRUE si hay una cadena de identificación imap_get_quotaroot() function of PHP.
imap_stream should be the value returned from an
id Cadena de Identificación imap_open() call. NOTE: This stream is required to be
opened as the mail admin user for the get_quota function
to work. quota_root should normally be in the form of value represents the user's current total mailbox
user.name where name is the mailbox you wish to capacity. This function will return FALSE in the case of
retrieve information about. call failure, and an array of information about the
Ejemplo 1. imap_get_quota() example connection upon an un-parsable response from the
server.
This function is currently only available to users of the c-
$mbox = client2000 or greater library.
imap_open("{your.imap.host}","mailadmin","password imap_stream should be the value returned from an
",OP_HALFOPEN) imap_open() call. This stream should be opened as the
or die("can't connect: ".imap_last_error()); user whose mailbox you wish to check. quota_root should
normally be in the form of which mailbox (i.e. INBOX).
$quota_value = imap_get_quota($mbox, Ejemplo 1. imap_get_quotaroot() example
"user.kalowsky");
if(is_array($quota_value)) {
print "Usage level is: " . $quota_value['usage']; $mbox =
print "Limit level is: " . $quota_value['limit']; imap_open("{your.imap.host}","kalowsky","password",
} OP_HALFOPEN)
or die("can't connect: ".imap_last_error());
imap_close($mbox);
$quota = imap_get_quotaroot($mbox, "INBOX");
As of PHP version 4.3, the function more properly reflects
if(is_array($quota)) {
the functionality as dictated by the RFC 2087. The array
$storage = $quota_values['STORAGE'];
return value has changed to support an unlimited
print "STORAGE usage level is: " . $storage['usage'];
number of returned resources (i.e. messages, or sub-
print "STORAGE limit level is: " . $storage['limit'];
folders) with each named resource receiving an
individual array key. Each key value then contains an
$message = $quota_values['MESSAGE'];
another array with the usage and limit values within it.
print "MESSAGE usage level is: " .
The example below shows the updated returned output.
$message['usage'];
For backwards compatibility reasons, the originial access
print "MESSAGE usage level is: " . $message['limit'];
methods are still available for use, although it is
suggested to update.
/* ... */
Ejemplo 2. imap_get_quota() 4.3 or greater
example
}

imap_close($mbox);
$mbox =
imap_open("{your.imap.host}","mailadmin","password See also imap_open(), imap_set_quota(),
",OP_HALFOPEN) imap_get_quota().
or die("can't connect: ".imap_last_error());
imap_getmailboxes
$quota_values = imap_get_quota($mbox,
"user.kalowsky");
if(is_array($quota_values)) { (PHP 3>= 3.0.12, PHP 4 )
$storage = $quota_values['STORAGE']; imap_getmailboxes -- Lee la lista de buzones,
print "STORAGE usage level is: " . $storage['usage']; devolviendo informacón detallada de cada uno
print "STORAGE limit level is: " . $storage['limit'];

$message = $quota_values['MESSAGE']; Descripción


print "MESSAGE usage level is: " .
$message['usage'];
print "MESSAGE usage level is: " . $message['limit']; array imap_getmailboxes ( int imap_stream, string ref,
string pat)
/* ... */
} Devuelve un array de objetos coneniendo información
del buzón. Cada objeto tiene los atributos name,
imap_close($mbox); especificando el nombre completo del buzón; delimiter,
See also imap_open(), imap_set_quota(), que es el delimitador jerárquico para la parte de la
imap_get_quotaroot(). jerarquía dónde está este buzón; y attributes. Attributes
es una máscara de bits contra la que se puede probar:

imap_get_quotaroot
• LATT_NOINFERIORS - Este buzón no tiene
"hijos" (No ha buzones por debajo de él)
(PHP 4 >= 4.3.0)
imap_get_quotaroot -- Retrieve the quota settings per • LATT_NOSELECT - Esto es sólo un contenedor,
user no un buzón - No puede abrirlo.
• LATT_MARKED - Este buzón está marcado.
Description Unicamente usado por UW-IMAPD.
• LATT_UNMARKED - Este buzón no está
array imap_get_quotaroot ( resource imap_stream, marcado. Unicamente usado por UW-IMAPD.
string quota_root)
ref normalmente debería ser solo el servidor IMAP, de la
Returns an array of integer values pertaining to the forma: {imap_server:imap_port}, y pattern especifica,
specified user mailbox. All values contain a key based dónde en la estructura jerárquica del buzón, para
upon the resource name, and a corresponding array with comenzar a buscar. Si quiere todo los buzones, pase el
the usage and limit values within. parámetro pattern como una cadena vacía.
The limit value represents the total amount of space Hay dos caracteres especiales que puede pasar como
allowed for this user's total mailbox usage. The usage parte del parámetro pattern: '*' and '%'. '*' significa que
devuelva todos los buzones. Si pasa el parámetro pattern
como '*', obtendrá una lista con la jerarquía completa del from[] (devuelve un array de objetos a partir de la linea F
buzón. %' significa que devuelva sólo el nivel actual. rom, conteniendo:)
Pasar '%' en el parámetro pattern devolverá sólo el nivel personal
más alto de los buzones; '~/mail/%' en UW_IMAPD adl
devolverá cada buzón del directorio ~/mail, pero ninguno mailbox
de los subdirectorios de ese directorio. host

ccaddress (la linea cc: al completo, hasta 1024 caractere


imap_getsubscribed s)
cc[] (devuelve un array de objetos a partir de la linea Cc:,
conteniendo:)
(PHP 3>= 3.0.12, PHP 4 )
personal
imap_getsubscribed -- Lista todos los buzones subscritos
adl
mailbox
Descripción host

bccaddress (la linea bcc al completo, hasta 1024 caracter


array imap_getsubscribed ( int imap_stream, string ref, es)
string pattern) bcc[] (devuelve un array de objetos a partir de la linea Bc
c, conteniendo:)
Esta función es idéntica a imap_getmailboxes(), personal
excepto que esta sólo devuelve los buzones a los que adl
está subscrito el usuario. mailbox
host

imap_header reply_toaddress (la linea reply_to: al completo, hasta 102


4 caracteres)
reply_to[] (devuelve un array de objetos a partir de la lin
(PHP 3, PHP 4 ) ea Reply_to,
imap_header -- Lee la cabecera del mensaje conteniendo:)
personal
adl
Descripción
mailbox
host
object imap_header ( int imap_stream, int msg_number
[, int fromlength [, int subjectlength [, string senderaddress (la linea sender: al completo, hasta 1024
defaulthost]]]) caracteres)
sender[] (devuelve un array de objetos a partir de la line
a sender, conteniendo:)
Esta función devuelve un objeto con varios elementos de personal
la cabecera. adl
mailbox
remail, date, Date, subject, Subject, in_reply_to, mes host
sage_id,
newsgroups, followup_to, references return_path (la linea return-path: al completo, hasta 102
4 caracteres)
message flags: return_path[] (devuelve un array de objetos a partir de la
Recent - 'R' si es reciente y ha sido leido, linea return_path,
'N' si es reciente y no ha sido leido, conteniendo:)
' ' si no es reciente personal
Unseen - 'U' si no ha sido leido Y no es reciente, adl
' ' si ha sido leido O no y es reciente mailbox
Answered -'A' si ha sido contestado, host
' ' si no ha sido contestado
Deleted - 'D' si ha sido borrado, udate (fecha del mensaje en formato unix)
' ' si no ha sido borrado
Draft - 'X' if draft, fetchfrom (la linea from formateada hasta ajustarse a los
' ' if not draft caracteres
Flagged - 'F' si esta if flagged, indicados en fromlength)
' ' if not flagged
fetchsubject (la linea subject formateada hasta ajustarse
OBSERVE que el comportamiento Recent/Unseen es un p a los caracteres
oco extra¤o. Si quiere conocer indicados en subjectlength)
si un mensaje es Unseen, debe comprobarlo asi

Unseen == 'U' || Recent == 'N'

toaddress (la linea to: al completo, hasta 1024 caractere imap_headerinfo


s)

to[] (devuelve un array de objetos a partir de la linea To, (PHP 3, PHP 4 )


conteniendo:) imap_headerinfo -- Read the header of the message
personal
adl
Description
mailbox
host

fromaddress (la linea from: al completo, hasta 1024 cara


cteres)
object imap_headerinfo ( resource imap_stream, int personal
msg_number [, int fromlength [, int subjectlength [, string adl
defaulthost]]]) mailbox
host
This function returns an object of various header
return_path (full return-path: line, up to 1024 characters)
elements.
return_path[] (returns an array of objects from the return
_path line,
remail, date, Date, subject, Subject, in_reply_to, mes
containing):
sage_id,
personal
newsgroups, followup_to, references
adl
mailbox
message flags:
host
Recent - 'R' if recent and seen,
'N' if recent and not seen,
udate (mail message date in unix time)
' ' if not recent
Unseen - 'U' if not seen AND not recent,
fetchfrom (from line formatted to fit fromlength
' ' if seen OR not seen and recent
characters)
Answered -'A' if answered,
' ' if unanswered
fetchsubject (subject line formatted to fit subjectlength c
Deleted - 'D' if deleted,
haracters)
' ' if not deleted
Draft - 'X' if draft,
' ' if not draft
Flagged - 'F' if flagged, imap_headers
' ' if not flagged

NOTE that the Recent/Unseen behavior is a little odd. If y (PHP 3, PHP 4 )


ou want to imap_headers -- Returns headers for all messages in a
know if a message is Unseen, you must check for mailbox

Unseen == 'U' || Recent == 'N'


Descripción
toaddress (full to: line, up to 1024 characters)
array imap_headers ( int imap_stream)
to[] (returns an array of objects from the To line, containi
ng):
personal Devuelve un array de cadenas formateadas con
adl informacion de la cabecera. Un elemento por mensaje de
mailbox correo.
host

fromaddress (full from: line, up to 1024 characters) imap_last_error

from[] (returns an array of objects from the From line, co (PHP 3>= 3.0.12, PHP 4 )
ntaining): imap_last_error -- Esta función devuelve el último error
personal IMAP (si se produjo) que ocurrió durante la petición de
adl esta página.
mailbox
host
Descripción
ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containi
ng): string imap_last_error ( void)
personal
adl Esta función devuelve el texto completo del último error
mailbox IMAP que ocurrió en la pagina actual. La plia de errores
host The error stack is untouched; llamando despues a la
función imap_last_error(), sin que se produzca un error,
bccaddress (full bcc line, up to 1024 characters) devolverá el mismo error.
bcc[] (returns an array of objects from the Bcc line, conta ATENCIàN: esta función no esta disponible aún en PHP4.
ining):
personal
adl imap_list
mailbox
host
(PHP 3>= 3.0.4, PHP 4 )
reply_toaddress (full reply_to: line, up to 1024 characters imap_list -- Read the list of mailboxes
)
reply_to[] (returns an array of objects from the Reply_to l Description
ine,
containing):
personal array imap_list ( resource imap_stream, string ref, string
adl pattern)
mailbox
host
Returns an array containing the names of the mailboxes.
See imap_getmailboxes() for a description of ref and
senderaddress (full sender: line, up to 1024 characters)
pattern.
sender[] (returns an array of objects from the sender line
Ejemplo 1. imap_list() example
, containing):
imap_lsub -- List all the subscribed mailboxes

Description
$mbox =
imap_open("{your.imap.host}","username","password
",OP_HALFOPEN) array imap_lsub ( resource imap_stream, string ref,
or die("can't connect: ".imap_last_error()); string pattern)

$list = imap_list($mbox,"{your.imap.host}","*");
if(is_array($list)) { Returns an array of all the mailboxes that you have
reset($list); subscribed. This is almost identical to
while (list($key, $val) = each($list)) imap_listmailbox(), but will only return mailboxes the
print imap_utf7_decode($val)."<br>\n"; user you logged in as has subscribed.
} else
print "imap_list failed: ".imap_last_error()."\n";
imap_mail_compose
imap_close($mbox);
(PHP 3>= 3.0.5, PHP 4 )
imap_mail_compose -- Create a MIME message based on
imap_listmailbox given envelope and body sections

(PHP 3, PHP 4 ) Description


imap_listmailbox -- Lee la lista de buzones
string imap_mail_compose ( array envelope, array
Descripción body)

array imap_listmailbox ( int imap_stream, string ref, Ejemplo 1. imap_mail_compose() example


string pat)

<?php
Devuelve un array que contiene los nombres de los
buzones.
$envelope["from"]="musone@afterfiv
e.com";
imap_listscan $envelope["to"]="musone@darkstar";
$envelope["cc"]="musone@edgeglob
al.com";
(no version information, might be only in CVS)
imap_listscan -- Read the list of mailboxes, takes a string $part1["type"]=TYPEMULTIPART;
to search for in the text of the mailbox $part1["subtype"]="mixed";

$filename="/tmp/imap.c.gz";
Description $fp=fopen($filename,"r");
$contents=fread($fp,filesize($filenam
e));
array imap_listscan ( resource imap_stream, string ref,
string pattern, string content) fclose($fp);

$part2["type"]=TYPEAPPLICATION;
Returns an array containing the names of the mailboxes $part2["encoding"]=ENCBINARY;
that have content in the text of the mailbox. This $part2["subtype"]="octet-stream";
function is similar to imap_listmailbox(), but it will $part2["description"]=basename($file
additionally check for the presence of the string content name);
inside the mailbox data. See imap_getmailboxes() for a $part2["contents.data"]=$contents;
description of ref and pattern.
$part3["type"]=TYPETEXT;
$part3["subtype"]="plain";
imap_listsubscribed $part3["description"]="description3";
$part3["contents.data"]="contents.dat
(PHP 3, PHP 4 ) a3\n\n\n\t";
imap_listsubscribed -- Lista todos los buzones subscritos
$body[1]=$part1;
$body[2]=$part2;
Descripción $body[3]=$part3;

echo
array imap_listsubscribed ( int imap_stream, string ref, nl2br(imap_mail_compose($envelope,
string pattern) $body));

Devuelve un array de todos los buzones que usted tiene ?>


subscritos. Los parámetros ref y pattern especifican la
localización desde donde comenzará a buscar y el patrón
que el nombre del buzón debe encontrar. imap_mail_copy

imap_lsub (PHP 3, PHP 4 )


imap_mail_copy -- Copia los mensajes especificados a un
buzón
(PHP 3>= 3.0.4, PHP 4 )
Descripción La función imap_mailboxmsginfo() comprueba el
estado del buzón actual en el servidor y devuelve la
información en un objeto con las siguientes propiedades.
int imap_mail_copy ( int imap_stream, string msglist,
string mbox, int flags) Date : fecha del mensaje
Driver : driver
Devuelve TRUE si no hay error y FALSE en caso Mailbox : nombre del buzón
contrario. Nmsgs : número de mensajes
Copia los mensajes especificados por msglist a un buzón Recent : número de los mensajes recientes
especificado. msglist es un rango no números de Unread : número de los mensajes no leidos
mensajes. Size : tama¤o del buzon
Flags es una máscara de bit de uno o más

imap_mime_header_decode
• CP_UID - los números de secuencia contienen
UIDS
(PHP 3>= 3.0.17, PHP 4 )
• CP_MOVE - Elimina los mensajes del buzon
imap_mime_header_decode -- Decode MIME header
actual despues de copiarlos
elements

imap_mail_move
Description

(PHP 3, PHP 4 )
array imap_mime_header_decode ( string text)
imap_mail_move -- Mueve los mensajes especificados a
un buzón
imap_mime_header_decode() function decodes MIME
message header extensions that are non ASCII text (see
Descripción RFC2047) The decoded elements are returned in an array
of objects, where each object has two properties,
"charset" & "text". If the element hasn't been encoded,
int imap_mail_move ( int imap_stream, string msglist,
and in other words is in plain US-ASCII,the "charset"
string mbox)
property of that element is set to "default".
Ejemplo 1. imap_mime_header_decode() example
Mueve los mensajes especificados por msglist al buzón
especicifado. msglist es un rango no números de
mensajes. $text="=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?=
Devuelve TRUE si no hay error y FALSE en caso <keld@dkuug.dk>";
contrario.
$elements=imap_mime_header_decode($text);
for($i=0;$i<count($elements);$i++) {
imap_mail
echo "Charset: {$elements[$i]->charset}\n";
echo "Text: {$elements[$i]->text}\n\n";
(PHP 3>= 3.0.14, PHP 4 ) }
imap_mail -- Send an email message In the above example we would have two elements,
whereas the first element had previously been encoded
with ISO-8859-1, and the second element would be plain
Description
US-ASCII.

string imap_mail ( string to, string subject, string


imap_msgno
message [, string additional_headers [, string cc [, string
bcc [, string rpath]]]])
(PHP 3>= 3.0.3, PHP 4 )
This function allows sending of emails with correct imap_msgno -- Esta función devuelve el número de
handling of Cc and Bcc receivers. The parameters to, cc secuencia del mensaje para el UID dado.
and bcc are all strings and are all parsed as rfc822
address lists. The receivers specified in bcc will get the
Descripción
mail, but are excluded from the headers. Use the rpath
parameter to specify return path. This is useful when
using php as a mail client for multiple users. int imap_msgno ( int imap_stream, int uid)

imap_mailboxmsginfo Esta función devuelve el número de secuencia del


mensaje para el UID dado. Esta función es la inversa a
imap_uid().
(PHP 3>= 3.0.2, PHP 4 )
imap_mailboxmsginfo -- Obtiene información acerca del
buzón actual imap_num_msg

Descripción (PHP 3, PHP 4 )


imap_num_msg -- Informa del número de mensajes en el
buzón actual
object imap_mailboxmsginfo ( int imap_stream)

Descripción
Devuelve información acerca del buzón actual. Devuelve
FALSE en caso de fallo.
int imap_num_msg ( int imap_stream)
Devuelve el número de mensajes en el buzón actual. int imap_ping ( int imap_stream)

imap_num_recent Devuelve TRUE si la sesión está activa, FALSE en caso


contrario.
La función imap_ping() pings the stream to see it is still
(PHP 3, PHP 4 ) active. Esto puede descubrir que hay correo nuevo; este
imap_num_recent -- Informa el número de mensajes es el método preferido para hacer una comprobación
recientes en el buzón actual periodica del buzón, asi como para mantener activa
sesiones en servidores que tienen inactivity timeout.
Descripción
imap_qprint
int imap_num_recent ( int imap_stream)
(PHP 3, PHP 4 )
imap_qprint -- Convierte una cadena quoted-printable a
Devuleve el número de mensajes recientes en el buzón
una cadena de 8 bit
actual.

Descripción
imap_open

string imap_qprint ( string string)


(PHP 3, PHP 4 )
imap_open -- Abre una sesión IMAP
Convierte una cadena quoted-printable a una cadena de
8 bit
Descripción Devuelve una cadena de 8 bit (binary)

int imap_open ( string mailbox, string username, string imap_renamemailbox


password, int flags)

(PHP 3, PHP 4 )
Devuleve la sesion IMAP si no hay error y FALSE en caso
imap_renamemailbox -- Renombra un buzón
contrario. Esta función también puede ser usada para
abrir sesiones con servidores POP3 y NNTP. Para
conectarse a un servidor IMAP escuchando por el puerto Descripción
143 en una máquina local, haga lo siguiente:
$mbox =
int imap_renamemailbox ( int imap_stream, string
imap_open("{localhost:143}INBOX","user_id","pa
old_mbox, string new_mbox)
ssword");
Para conectarse a un servidor POP3 escuchando por el
Esta función renombra un buzon (ver imap_open() para
puerto 110, use:
el formato del parámetro mbox).
$mbox = Devuelve TRUE si no hay error y FALSE en caso
imap_open("{localhost/pop3:110}INBOX","user_id","p contrario.
assword"); Ver También imap_createmailbox() and
Para conectarse a un servidor NNTP escuchando por el imap_deletemailbox().
puerto 119, use:
$nntp = imap_reopen
imap_open("{localhost/nntp:119}comp.te
st","","");
(PHP 3, PHP 4 )
Para conectarse a un servidor remoto sustituya imap_reopen -- Reabre una sesión IMAP a un nuevo
"localhost", por el nombre o dirección IP del servidor al buzón
cual quiere conectarse.
Las opciones son una máscara de bit con una o más de
los siguientes: Descripción

int imap_reopen ( string imap_stream, string mailbox [,


• OP_READONLY - Abre el buzón en modo de string flags])
sólo lectura
• OP_ANONYMOUS - No usa o actualiza un Devuelve TRUE si no hay error y FALSE en caso
.newsrc para las noticias contrario.
• OP_HALFOPEN - Para nombres IMAP y NNTP, Esta funció reabre la sesión especificada con un nuevo
abre una conexión pero no abre un buzón buzón.
Las opciones son máscaras de bit con una o más de las
• CL_EXPUNGE - Purga automaticamente el siguientes:
buzón antes de cerrar la sesión

imap_ping • OP_READONLY - Abre el buzón en modo de


sólo lectura

(PHP 3, PHP 4 )
• OP_ANONYMOUS - No usa o actualiza .newsrc
imap_ping -- Comprueba si la sesión IMAP está aún activa para noticias
• OP_HALFOPEN - Para nombres IMAP y NNTP,
abre una conexión pero no abre el buzon.
Descripción
Devuelve un array que contiene los nombres de los
• CL_EXPUNGE - Expurga automaticamente el
buzones que tienen el parámetro string en el texto del
buzon antes de cerra la sesión
buzón.

imap_rfc822_parse_adrlist
imap_search

(PHP 3>= 3.0.2, PHP 4 )


(PHP 3>= 3.0.12, PHP 4 )
imap_rfc822_parse_adrlist -- Examina la cadena dirección
imap_search -- Esta función devuelve un array de
mensajes que coinciden con el criterio de busqueda
Descripción dado.

string imap_rfc822_parse_adrlist ( string address, Descripción


string default_host)
array imap_search ( int imap_stream, string criteria, int
Esta función examina la cadena dirección y para cada flags)
dirección, devuelve un array de objetos. Los 4 objetos
son:
Esta función realiza una busqueda en el buzón
actualmente abierto indicado por imap_stream. criteria
mailbox - el nombre del buzón (username)
es una cadena, delimitada por espacios, en la cual las
host - el nombre del ordenador
siguientes palabras claves son permitidas. Cualquier
personal - el nombre personal
argumento múltiple (ej. FROM "joey smith") debe estar
adl - ruta del dominio
entre comillas.

imap_rfc822_parse_headers • ALL - devuelve todos los mensajes que


coinciden con el resto del criterio

(PHP 4 ) • ANSWERED - busca mensajes con el flag


imap_rfc822_parse_headers -- Parse mail headers from a \\ANSWERED activado
string • BCC "string" - busca mensajes con "cadena" en
el campo Bcc:
Description • BEFORE "date" - busca mensajes con Date:
antes de "date"
object imap_rfc822_parse_headers ( string headers [, • BODY "string" - busca mensajes con "cadena"
string defaulthost]) en el cuerpo del mensaje
• CC "string" - busca mensajes con "cadena" en
This function returns an object of various header el campo Cc:
elements, similar to imap_header(), except without the • DELETED - busca mensajes eliminados
flags and other elements that come from the IMAP
server. • FLAGGED - busca mensajes con el flag
\\FLAGGED (sometimes referred to as
Important or Urgent) activado
imap_rfc822_write_address
• FROM "string" - busca mensajes con "cadena"
en el campo From:
(PHP 3>= 3.0.2, PHP 4 )
imap_rfc822_write_address -- Devuleve una dirección de
• KEYWORD "string" - busca mensajes con
"cadena" como una palabra clave
correo correctamente formateada dado el buzón, host, e
información personal. • NEW - busca mensajes nuevos
• OLD - busca mensajes viejos
Descripción • ON "date" - busca mensajes con "date" igual a
Date:
string imap_rfc822_write_address ( string mailbox, • RECENT - busca mensajes con el flag \\RECENT
string host, string personal) activado
• SEEN - busca mensajes que han sido leidos (la
Devuelve una dirección de correo correctamente opcion \\SEEN activada)
formateada, dado el buzón, host, e información personal.
• SINCE "date" - busca mensajes conwith Date:
after "date"
imap_scanmailbox • SUBJECT "string" - busca mensajes con "string"
en el campo Subject:
(PHP 3, PHP 4 ) • TEXT "string" - busca mensajes con el texto
imap_scanmailbox -- Lee la lista de buzones y toma una "string"
cadena para buscar en el texto del buzón
• TO "string" - busca mensajes con "string" en el
campo To:
Descripción
• UNANSWERED - busca mensajes que no han
sido respondidos
array imap_scanmailbox ( int imap_stream, string • UNDELETED - busca mensajes que no han sido
string) eliminados
imap_setflag_full
• UNFLAGGED - busca mensajes que no estan
flagged
• UNKEYWORD "string" - busca mensajes que no (PHP 3>= 3.0.3, PHP 4 )
coinciden con la palabra clave "string" imap_setflag_full -- Activa flags en los mensajes

• UNSEEN - busca mensajes que no han sido


leidos aún Descripción

Por ejemplo, para buscar todos los mensajes no string imap_setflag_full ( int stream, string sequence,
contestados enviados por Mamá, usaría: "UNANSWERED string flag, string options)
FROM mamá". La busqueda parece ser no sensitiva. Esta
lista de criterios está tomada del codigo fuente del UW c- Esta función a¤ade el flag especificado al conjunto de
client y puede que este incompleta o sea inexacta. flags activos para los mensajes en la secuencia
Valores validos para los flags son SE_UID, que provoca especificada.
que el array devuelto contenga UIDs en vez de los Los flags que puede seleccionar son "\\Seen",
numeros de secuencia de los mensajes "\\Answered", "\\Flagged", "\\Deleted", "\\Draft", y
"\\Recent" ( definidos en el RFC2060)
imap_set_quota Las opciones son una máscara de bit con uno o más de
los siguientes:

(PHP 4 >= 4.0.5) ST_UID El argumento sequence contiene UIDs


imap_set_quota -- Sets a quota for a given mailbox en vez de
números secuenciales

Description

imap_sort
bool imap_set_quota ( resource imap_stream, string
quota_root, int quota_limit)
(PHP 3>= 3.0.3, PHP 4 )
imap_sort -- Ordena un array de cabeceras de mensajes
Sets an upper limit quota on a per mailbox basis. This
function requires the imap_stream to have been opened
as the mail administrator account. It will not work if Descripción
opened as any other user.
This function is currently only available to users of the c-
client2000 or greater library. string imap_sort ( int stream, int criteria, int reverse, int
imap_stream is the stream pointer returned from a options)
imap_open() call. This stream must be opened as the
mail administrator, other wise this function will fail. Devuelve un array de números de mensajes ordenados
quota_root is the mailbox to have a quota set. This por los parametros dados
should follow the IMAP standard format for a mailbox, Rev es 1 para una ordenación inversa.
'user.name'. quota_limit is the maximum size (in KB) for Criteria puede ser uno (y sólo uno) de los siguientes:
the quota_root.
Returns TRUE on success and FALSE on error. SORTDATE Fecha del mensaje
Ejemplo 1. imap_set_quota() example SORTARRIVAL Fecha de llegada
SORTFROM mailbox in first From address
SORTSUBJECT Asunto del mensaje
$mbox = imap_open ("{your.imap.host:143}", SORTTO mailbox in first To address
"mailadmin", "password"); SORTCC mailbox in first cc address
SORTSIZE tama¤o del mensaje en bytes
if(!imap_set_quota($mbox, "user.kalowsky", 3000))
{ Las opciones son una máscara de bit con uno o más de
print "Error in setting quota\n"; los siguientes:
return;
} SE_UID Devuelve UIDs en vez de números sec
uenciales
imap_close($mbox); SE_NOPREFETCH No preselecciona los mensajes b
See also imap_open(), imap_set_quota(). uscados.

imap_setacl
imap_status

(PHP 4 >= 4.1.0)


imap_setacl -- Sets the ACL for a giving mailbox (PHP 3>= 3.0.4, PHP 4 )
imap_status -- Esta función devuelve el información de
estado de otro buzón distinto al actual.
Description

Descripción
bool imap_setacl ( resource stream_id, string mailbox,
string id, string rights)
object imap_status ( int imap_stream, string mailbox,
int options)
Aviso
Esta función no está documentada actualmente, solamente Esta función devuelve un objeto que contiene
se encuentra disponible la lista de parametros. información de estado. Las opciones válidas son:
Descripción
• SA_MESSAGES - activa status->messages con
el número de mensajes en el buzon
• SA_RECENT - activa status->recent con el int imap_undelete ( int imap_stream, int msg_number)
número de mensajes recientes en el buzón
• SA_UNSEEN - activa status->unseen con el Esta funcion elimina la marca de borrado de un mensaje
número de mesajes no leidos (nuevos) en el especifico, puesta por la función imap_delete().
buzón Devuleve TRUE si no hay error y FALSE en caso
contrario.
• SA_UIDNEXT - activa status->uidnext con el
próximo uid a usar en el bizón
imap_unsubscribe
• SA_UIDVALIDITY - activa status->uidvalidity
con una constante que cambia cuando los uids
del buzon ya no son válidos (PHP 3, PHP 4 )
• SA_ALL - activa todos los de arriba imap_unsubscribe -- Unsubscribe from a mailbox

Descripción
status->flags contienen una máscara de bits la cual
puede ser comprobada contra cualquiera de las
propiedades de arriba. int imap_unsubscribe ( int imap_stream, string mbox)

imap_subscribe Da de baja el buzón especificado.


Devuelve TRUE si no hay error y FALSE en caso
contrario.
(PHP 3, PHP 4 )
imap_subscribe -- Subscribe to a mailbox
imap_utf7_decode
Descripción
(PHP 3>= 3.0.15, PHP 4 )
imap_utf7_decode -- Decodes a modified UTF-7 encoded
int imap_subscribe ( int imap_stream, string mbox) string.

Da de alta un nuevo buzón.


Description
Devuleve TRUE si no hay error y FALSE en caso
contrario.
string imap_utf7_decode ( string text)
imap_thread
Decodes modified UTF-7 text into 8bit data.
Returns the decoded 8bit data, or FALSE if the input
(PHP 4 >= 4.1.0) string was not valid modified UTF-7. This function is
imap_thread -- Return threaded by REFERENCES tree needed to decode mailbox names that contain
international characters outside of the printable ASCII
Description range. The modified UTF-7 encoding is defined in RFC
2060, section 5.1.3 (original UTF-7 was defned in
RFC1642).
array imap_thread ( resource stream_id [, int options])
imap_utf7_encode
Aviso
Esta función no está documentada actualmente, solamente (PHP 3>= 3.0.15, PHP 4 )
se encuentra disponible la lista de parametros. imap_utf7_encode -- Converts 8bit data to modified UTF-
7 text.

imap_uid
Description

(PHP 3>= 3.0.3, PHP 4 )


string imap_utf7_encode ( string data)
imap_uid -- Esta función devuelve el UID del número de
secuencia del mensaje dado
Converts 8bit data to modified UTF-7 text. This is needed
to encode mailbox names that contain international
Descripción characters outside of the printable ASCII range. The
modified UTF-7 encoding is defined in RFC 2060, section
5.1.3 (original UTF-7 was defned in RFC1642).
int imap_uid ( int imap_stream, int msgno)
Returns the modified UTF-7 text.

Esta función devuelve el UID del número de secuencia


del mensaje dado. Esta función es la inversa a imap_utf8
imap_msgno().
(PHP 3>= 3.0.13, PHP 4 )
imap_undelete imap_utf8 -- Converts text to UTF8

(PHP 3, PHP 4 ) Description


imap_undelete -- Desmarca los mensajes que están
marcados como borrados
string imap_utf8 ( string text) La conducta de columnas BLOB
puede ser modificada mediante
variables de configuración, las
Converts the given text to UTF8 (as defined in RFC2044).
cuales pueden ser definidas en
tiempo de ejecución mediante
XLIII. Funciones para Informix funciones.

El conector para Informix Online (ODS) 7.x, SE 7.x y variable de configuración:


Universal Server (IUS) 9.x se encuentra implementado en ifx.textasvarchar
"functions/ifx.ec" y "functions/php3_ifx.h". Para ODS 7.x
está completado, con total soporte para columnas de
variable de configuración:
tipo BYTE y TEXT. Para IUS 9.x está parcialmente
ifx.byteasvarchar
finalizado: los tipos de datos nuevos están allí (en el IUS
9.x), pero la funcionalidad para SLOB y CLOB se
encuentra bajo construcción todavía. funciones en tiempo de ejecución:

Notas de configuración: ifx_textasvarchar(0): usa


identificadores de blob para
columnas de tipo TEXT en las
Antes de ejecutar el guión (script)
consultas de selección
"configure", asegúrate que la
variable "INFORMIXDIR" ha sido
definida. ifx_byteasvarchar(0): usa
identificadores de blob para
columnas de tipo BYTE en las
Si ejecutas "configure
consultas de selección
--with_informix=yes" entonces el
guión de configuración detectará
automáticamente las librerías y los ifx_textasvarchar(1): devuelve
directorios include. Puedes obviar columnas de tipo TEXT como si
esta detección definiendo las fueran de tipo VARCHAR, sin tener
variables de entorno "IFX_LIBDIR", que usar identificadores de blob en
"IFX_LIBS" y "IFX_INCDIR". Definirás las consultas de selección
la variable de compilación
condicional "HAVE_IFX_IUS" si la
versión de Informix es 9.00 o ifx_byteasvarchar(1): devuelve
superior. columnas de tipo BYTE como si
fueran de tipo VARCHAR, sin tener
que usar identificadores de blob en
Algunas notas sobre el uso de las consultas de selección.
BLOBs (columnas de tipo TEXT y
BYTE):
variable de configuración:
ifx.blobinfile
BLOBs son normalmente
manipulados por enteros, los cuales
representan identificadores de BLOB. función en tiempo de ejecución:
Las consultas de selección
devuelven un "blob id" para
columnas de tipo BYTE y TEXT. Si ifx_blobinfile_mode(0): devuelve
eliges trabajar con los BLOBs en columnas de tipo BYTE en memoria,
memoria (con: "ifx_blobinfile(0);") el identificador de blob te permite
entonces puedes obtener el obtener el contenido.
contenido con "string_var =
ifx_get_blob($blob_id);". Si prefieres ifx_blobinfile_mode(1): devuelve
manipularlos en ficheros usa columnas de tipo BYTE en un fichero,
"ifx_blobinfile(1);" y el identificador te permite saber el
"ifx_get_blob($blob_id);" devolverá nombre de dicho archivo.
el nombre del archivo. En este caso,
utiliza las funciones habituales de
entrada y salida de ficheros para Si defines ifx_text/byteasvarchar a 1
obtener el contenido de los blob. entonces puedes usar columnas de
tipo TEXT y BYTE en las consultas de
selección como campos de tipo
Para consultas de inserción y VARCHAR, pero teniendo en cuenta
actualización debes crear estos que tendrán un mayor tamaño que
identificadores de blob con el habitual. Ya que en PHP todas las
"ifx_create_blob(..);". Entonces cadenas son posibles, esto permite
pondrás los identificadores de blob datos binarios. De esta forma, se
en un array y sustituirás en la pueden manejar correctamente. La
cadena de la consulta las columnas información devuelta puede
de tipo blob por una interrogación contener cualquier cosa, tú eres
(?). Para inserciones y responsable del contenido.
actualizaciones eres responsable de
definir el contenido de los blob con
ifx_update_blob(...). Si defines ifx_blobinfile a 1, utiliza el
nombre del archivo devuelto por
ifx_get_blob(..) para acceder a los
contenidos del blobs. En este caso,
ERES REPONSABLE DE ELIMINAR EL ifx_htmltbl_result -- Muestra todos los registros de una
ARCHIVO TEMPORAL GENERADO consulta en una tabla HTML
POR INFORMIX cuando accedas a los ifx_nullformat -- Define el valor por defecto cuando se
registros. Cada nueva fila obtenida leen valores nulos
creará un nuevo archivo temporal ifx_num_fields -- Devuelve el número de columnas en
para cada columna de tipo BYTE. una consulta
ifx_num_rows -- Cuenta los registros ya leídos de una
consulta
El directorio donde se guardan los ifx_pconnect -- Abre una conexión permanente con
archivos temporales puede ser Informix
definido por la variable de entorno ifx_prepare -- Prepara una sentencia SQL para su
blobdir, por defecto es ".", es decir, ejecución
el directorio actual. Así, ifx_query -- Envía una consulta a Informix
putenv(blobdir=tmpblob"); definirá ifx_textasvarchar -- Define el modo por defecto para los
un directorio donde se localizarán campos de tipo text
todos los ficheros temporales y ifx_update_blob -- Actualiza el contenido de un objeto
facilitará su borrado. Todos los blob
nombres de los archivos comienzan ifx_update_char -- Actualiza el contenido de un objeto
por "blb". char
ifxus_close_slob -- Cierra un objeto slob
ifxus_create_slob -- Crea un objeto slob y lo abre
Recortado (trimming)
ifx_free_slob -- Elimina un objeto slob
automático de datos de tipo
ifxus_open_slob -- Abre un objeto slob
"char" (SQLCHAR y SQLNCHAR):
ifxus_read_slob -- Lee un número de bytes (nbytes) de un
objeto slob
Puede ser definido con la variable de ifxus_seek_slob -- Define el fichero o posición en
configuración memoria
ifxus_tell_slob -- Devuelve el fichero actual o la posición
en memoria
ifx.charasvarchar: si se define a 1 ifxus_write_slob -- Escribe una cadena en un objeto slob
eliminará automáticamente los
espacios en blanco al final de la
cadena. ifx_affected_rows

Valores NULL: (PHP 3>= 3.0.3, PHP 4 )


ifx_affected_rows -- Obtiene el número de registros
procesados por una consulta
La variable de configuración
ifx.nullformat (y en tiempo de
ejecución ifx_nullformat()) cuando Descripción
sea definida a TRUE devolverá
columnas NULL como la cadena
int ifx_affected_rows ( int result_id)
"NULL", si es definida a FALSE
entonces la cadena vacía. Esto
permite distinguir entre columnas result_id es un identificador válido del resultado de
NULL y vacías. ifx_query() o ifx_prepare().
Devuelve el número de filas procesadas por una consulta
representada por un result_id (identificador de
Tabla de contenidos resultado).
ifx_affected_rows -- Obtiene el número de registros Para inserciones, actualizaciones y borrados el número
procesados por una consulta es exactamente los registros procesados (sqlerrd[2]).
ifx_blobinfile_mode -- Define el modo por defecto para los Para las consultas de selección es una estimación
blob en todas las consultas de selección (sqlerrd[0]). No confíes en él.
ifx_byteasvarchar -- Define el modo por defecto para los Es útil llamarla después de ejecutar ifx_prepare() pues
campos de tipo byte así podemos limitar las consultas a número razonable de
ifx_close -- Cierra una conexión con Informix registros.
ifx_connect -- Abre una conexión con un servidor Informix Examina también: ifx_num_rows()
ifx_copy_blob -- Duplica el objeto blob dado Ejemplo 1. Número de registros procesados por
ifx_create_blob -- Crea un objeto blob una consulta
ifx_create_char -- Crea un objeto char
ifx_do -- Ejecuta una sentencia SQL preparada
previamente
$rid = ifx_prepare ("select * from emp where name
ifx_error -- Devuelve el código de error de la última
like " . $name, $connid);
llamada a Informix
if (! $rid) {
ifx_errormsg -- Devuelve el mensaje de error de la última
... error ...
llamada a Informix
}
ifx_fetch_row -- Obtiene registros como un array (vector)
$rowcount = ifx_affected_rows ($rid);
enumerado
if ($rowcount > 1000) {
ifx_fieldproperties -- Indica las propiedades de los
printf ("Too many rows in result set (%d)\n<br>",
campos de una consulta SQL
$rowcount); // Demasiados registros en el resultado
ifx_fieldtypes -- Obtiene los campos de una consulta SQL
die ("Please restrict your query<br>\n");
ifx_free_blob -- Borra el objeto blob
// Por favor, restringe tu consulta
ifx_free_char -- Elimina un objeto char
}
ifx_free_result -- Libera los recursos de una consulta
ifx_get_blob -- Obtiene el contenido de un objeto blob
ifx_get_char -- Obtiene el contenido de un objeto char
ifx_getsqlca -- Después de una consulta, obtiene el ifx_blobinfile_mode
contenido de sqlca.sqlerrd[0..5]
(PHP 3>= 3.0.4, PHP 4 )
ifx_blobinfile_mode -- Define el modo por defecto para los ifx_connect() establece una conexión con un servidor
blob en todas las consultas de selección INFORMIX. Todos los argumentos son opcionales, y si no
se pasan, se toman los valores del fichero de
configuración (ifx.default_host para el ordenador donde
Descripción se encuentra el servidor (si no es definida, las librerías de
Infomix usarán la variable de entorno INFORMIXSERVER),
ifx.default_user para el usuario (userid),
void ifx_blobinfile_mode ( int mode)
ifx.default_password para la contraseña (password)
(ninguna, si no es definida).
Define el modo por defecto para los blob en todas las Para una segunda llamada a ifx_connect() con los
consultas de selección. El modo (mode) "0" quiere decir mismos argumentos, no se establecerá una nueva
que guarda en memoria los blobs de tipo BYTE y modo conexión, en vez de eso, el identificador de enlace de la
"1" significa guardarlos en un archivo. conexión abierta será devuelto.
La conexión con el servidor será cerrada tan pronto como
la ejecución del guión (script) finalice, a menos que
ifx_byteasvarchar anteriormente se haya llamando a ifx_close().
Examina también ifx_pconnect(), y ifx_close().
(PHP 3>= 3.0.4, PHP 4 ) Ejemplo 1. Conexión a una base de datos Informix
ifx_byteasvarchar -- Define el modo por defecto para los
campos de tipo byte
$conn_id = ifx_pconnect (mydb@ol_srv1,
"imyself", "mypassword");
Descripción

void ifx_byteasvarchar ( int mode) ifx_copy_blob

Define el modo por defecto para los campos de tipo byte (PHP 3>= 3.0.4, PHP 4 )
en todas las consultas de selección. Modo (mode) "0" ifx_copy_blob -- Duplica el objeto blob dado
devolverá un identificador de blob y "1" dará el
contenido en un campo de tipo varchar.
Descripción

ifx_close
int ifx_copy_blob ( int bid)

(PHP 3>= 3.0.3, PHP 4 ) Duplica el objeto blob dado. bid es el identificador del
ifx_close -- Cierra una conexión con Informix objeto blob a copiar.
Devuelve FALSE si hubo error, en otro caso el
Descripción identificador del nuevo objeto blob.

ifx_create_blob
int ifx_close ( [int link_identifier])

Devuelve: TRUE siempre. (PHP 3>= 3.0.4, PHP 4 )


ifx_close() cierra un enlace a una base de datos ifx_create_blob -- Crea un objeto blob
Informix que esté asociado con el identificador de enlace
(link_identifier). Si el identificador de enlace no es
Descripción
especificado, el último enlace abierto es asumido.
Observa que esto no es necesario habitualmente ya que
las conexiones no permanentes son cerradas int ifx_create_blob ( int type, int mode, string param)
automáticamente al finalizar el guión (script).
ifx_close() no cerrará enlaces persistentes generados
por ifx_pconnect(). Crea un objeto blob.
Examina también: ifx_connect(), y ifx_pconnect(). type (tipo): 1 = TEXT, 0 = BYTE
Ejemplo 1. Cierre de una conexión a Informix mode (modo): 0 = el contenido del objeto blob es
conservado en memoria, 1 = el contenido del objeto blob
es mantenido en un archivo.
param: si mode = 0: apunta al contenido en memoria, si
$conn_id = ifx_connect (mydb@ol_srv,
mode = 1: contiene el nombre del fichero.
"itsme", "mypassword");
Devuelve FALSE si hubo error, en otro caso el
... algunas consultas y código ...
identificador del nuevo objeto blob.
ifx_close($conn_id);

ifx_create_char
ifx_connect

(PHP 3>= 3.0.6, PHP 4 )


(PHP 3>= 3.0.3, PHP 4 ) ifx_create_char -- Crea un objeto char
ifx_connect -- Abre una conexión con un servidor Informix

Descripción
Descripción

int ifx_create_char ( string param)


int ifx_connect ( [string database [, string userid [,
string password]]])
Crea un objeto char. param será el contenido del char.

Si tuvo éxito, devuelve un identificador de conexión en


otro caso FALSE. ifx_do
(PHP 3>= 3.0.4, PHP 4 ) ifx_fetch_row
ifx_do -- Ejecuta una sentencia SQL preparada
previamente
(PHP 3>= 3.0.3, PHP 4 )
ifx_fetch_row -- Obtiene registros como un array (vector)
Descripción enumerado

int ifx_do ( int result_id) Descripción

Devuelve TRUE si se realizó, FALSE si hubo algún error. array ifx_fetch_row ( int result_id [, mixed position])
Ejecuta una consulta preparada anteriormente o abre un
cursor para ella.
No libera result_id si hubo un error. Devuelve un array (vector) correspondiente a la fila leída
También define el número real de registros procesados o FALSE si no hay más registros.
para consultas que no sean de selección y se puede Las columnas blob son devueltas como identificadores de
obtener mediante ifx_affected_rows(). blob enteros (integer) para usarlos con ifx_get_blob() a
Examina también: ifx_prepare() (hay un ejemplo). menos que hayas usado ifx_textasvarchar(1) o
ifx_byteasvarchar(1), en cuyo caso los blobs son
devueltos como cadenas de texto. Devuelve FALSE si
ifx_error hubo error.
result_id es un identificador válido del resultado de
ifx_query() o ifx_prepare() (sólo para consultas de
(PHP 3>= 3.0.3, PHP 4 ) selección).
ifx_error -- Devuelve el código de error de la última position es un parámetro opcional para una operación de
llamada a Informix lectura sobre un cursor de tipo "scroll": "NEXT"
(siguiente), "PREVIOUS" (anterior), "CURRENT" (actual),
"FIRST" (primero), "LAST" (último) o un número. Si se
Descripción
especifica un número, un registro concreto es leído. Este
parámetro opcional es sólo válido para cursores de tipo
string ifx_error ( void) scroll.
ifx_fetch_row() lee el contenido de un registro de la
consulta representada por el identificador de resultado
Los códigos de error de Informix (SQLSTATE & SQLCODE) indicado. La fila (registro) es devuelta en un array. Cada
son representados como se especifica a continuación: columna es guarda en un array, empezando éste desde
x [SQLSTATE = aa bbb SQLCODE=cccc] cero.
donde x = un espacio : no hubo error Las llamadas posteriores a ifx_fetch_row() devolverán
E : hubo error el registro siguiente en el resultado de la consulta, o
N : no hay más datos FALSE si no hay más filas.
W : aviso Ejemplo 1. Leer registros
? : no definido
Si el carácter "x" es cualquier otra cosa diferente a un
espacio, SQLSTATE y SQLCODE describen el error con
$rid = ifx_prepare ("select * from emp where name
mayor detalle.
like " . $name,
Examina el manual de Informix para el significado de
$connid, IFX_SCROLL);
SQLSTATE y SQLCODE.
if (! $rid) {
Devuelve en una cadena un caracter describiendo el
... error ...
resultado de una sentencia y los valores SQLSTATE y
}
SQLCODE asociados con la última sentencia SQL
$rowcount = ifx_affected_rows($rid);
ejecutada. El formato de la cadena es "(char)
if ($rowcount > 1000) {
[SQLSTATE=(dos dígitos) (tres dígitos) SQLCODE=(un
printf ("Too many rows in result set (%d)\n<br>",
dígitos)]". El primer carácter puede ser ' ' (un espacio)
$rowcount); // Demasiados registros en el resultado
(no hubo error), 'W' (la sentencia provocó un aviso), 'E'
die ("Please restrict your query<br>\n");
(la consulta produjo un error) o 'N' (la sentencia no
// Por favor, restringe tu consulta
devolvió ningún dato).
}
Examina también: ifx_errormsg()
if (! ifx_do ($rid)) {
... error ...
ifx_errormsg }
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
(PHP 3>= 3.0.4, PHP 4 ) for(reset($row); $fieldname=key($row); next($row))
ifx_errormsg -- Devuelve el mensaje de error de la última {
llamada a Informix $fieldvalue = $row[$fieldname];
printf ("%s = %s,", $fieldname, $fieldvalue);
}
Descripción printf("\n<br>");
$row = ifx_fetch_row ($rid, "NEXT");
string ifx_errormsg ( [int errorcode]) }
ifx_free_result ($rid);

Devuelve el mensaje de error asociado con el error más


reciente de Informix. Si definismos el parámetro opcional ifx_fieldproperties
"errorcode" (código de error), nos dará el mensaje de
error correspondiente a ese código.
Examina también: ifx_error() (PHP 3>= 3.0.3, PHP 4 )
printf("%s\n<br>", ifx_fieldproperties -- Indica las propiedades de los
ifx_errormsg(-201)); campos de una consulta SQL

Descripción
array ifx_fieldproperties ( int result_id) (PHP 3>= 3.0.6, PHP 4 )
ifx_free_char -- Elimina un objeto char
Dada una consulta representada por result_id devuelve
un array con los nombres de campo como llaves y las Descripción
propiedades como datos. FALSE es devuelto si hubo
error.
Devuelve las propiedades SQL de cada campo como un int ifx_free_char ( int bid)
array. Las propiedades son codificadas así:
"SQLTYPE;longitud;precisión;escala;ISNULLABLE" siendo
Borra el objeto char representado por el identificador del
SQLTYPE el tipo de dato definido en Informix como puede char bid. Devuelve FALSE si se produjo un error, en otro
ser "SQLVCHAR" etc. e ISNULLABLE (puede ser nulo)
caso TRUE.
igual a "Y" sí o "N" no.
Ejemplo 1. Propiedades de los campos de una
consulta SQL ifx_free_result

$properties = ifx_fieldtypes ($resultid); (PHP 3>= 3.0.3, PHP 4 )


if (! isset($properties)) { ifx_free_result -- Libera los recursos de una consulta
... error ...
} Descripción
for ($i = 0; $i < count($properties); $i++) {
$fname = key ($properties);
printf ("%s:\t type = %s\n", $fname, int ifx_free_result ( int result_id)
$properties[$fname]);
next ($properties);
} Libera los recursos representados por el identificador
result_id de una consulta. Devuelve FALSE si hubo error.

ifx_fieldtypes ifx_get_blob

(PHP 3>= 3.0.3, PHP 4 ) (PHP 3>= 3.0.4, PHP 4 )


ifx_fieldtypes -- Obtiene los campos de una consulta SQL ifx_get_blob -- Obtiene el contenido de un objeto blob

Descripción Descripción

array ifx_fieldtypes ( int result_id) int ifx_get_blob ( int bid)

Dada una consulta representada por result_id devuelve Devuelve el contenido de un objeto blob representado
un array con los nombres de campo como llaves y los por su identificador bid.
tipos como datos. Si no tuvo éxito da FALSE.
Ejemplo 1. Nombres y tipos de campos de una
consulta SQL ifx_get_char

(PHP 3>= 3.0.6, PHP 4 )


$types = ifx_fieldtypes ($resultid); ifx_get_char -- Obtiene el contenido de un objeto char
if (! isset ($types)) {
... error ...
} Descripción
for ($i = 0; $i < count($types); $i++) {
$fname = key($types);
printf("%s :\t type = %s\n", $fname, int ifx_get_char ( int bid)
$types[$fname]);
next($types); Devuelve el contenido de un objeto char representado
} por su identificador bid.

ifx_free_blob ifx_getsqlca

(PHP 3>= 3.0.4, PHP 4 ) (PHP 3>= 3.0.8, PHP 4 )


ifx_free_blob -- Borra el objeto blob ifx_getsqlca -- Después de una consulta, obtiene el
contenido de sqlca.sqlerrd[0..5]

Descripción
Descripción

int ifx_free_blob ( int bid)


array ifx_getsqlca ( int result_id)
Elimina el objeto blob representado por el identificador
bid. Devuelve FALSE si se produjo error, en otro caso result_id es un identificador válido del resultado de
TRUE. ifx_query() o ifx_prepare().
Devuelve una seudo fila (array asociativo) con los valores
de sqlca.sqlerrd[0] a sqlca.sqlerrd[5] de una consulta
ifx_free_char ejecutada, representada ésta con un identificador de
resultado result_id.
Para inserciones, actualizaciones y borrados los valores Descripción
devueltos son aquellos definidos por el servidor después
de que la consulta sea ejecutada. Esto da acceso al
número de registros procesados y al valor de una void ifx_nullformat ( int mode)
columna de tipo serial en una consulta de inserción. Para
consultas de selección, los valores son guardados cuando Define el valor por defecto cuando se leen valores nulos.
se prepara la sentencia. También permite conocer el Modo (mode) "0" devuelve "", y modo "1" devuelve
número estimado de registros procesados. El uso de esta "NULL".
función evita el sobrecoste de ejecutar la consulta "select
dbinfo('sqlca.sqlerrdx')", como obtener los valores
guardados por el conector para Informix en el momento ifx_num_fields
apropiado.
Ejemplo 1. Obtener los valores sqlca.sqlerrd[x]
(PHP 3>= 3.0.3, PHP 4 )
ifx_num_fields -- Devuelve el número de columnas en
una consulta
/* suponiendo que la primera columna de la tabla
'sometable' es de tipo serial */
$qid = ifx_query("insert into sometable values(0, '2nd Descripción
column', 'another column' ", $connid);
if (! $qid) {
... error ... int ifx_num_fields ( int result_id)
}
$sqlca = ifx_getsqlca ($qid); Dada una consulta representada por result_id devuelve
$serial_value = $sqlca["sqlerrd1"]; el número de columnas o FALSE si se produjo un error.
echo "The serial value of the inserted row is : " . Después de preparar o ejecutar una consulta, una
$serial_value<br>\n"; // El valor de tipo serial del llamada a esta función te da el número de columnas en
registro insertado es: la consulta.

ifx_htmltbl_result ifx_num_rows

(PHP 3>= 3.0.3, PHP 4 ) (PHP 3>= 3.0.3, PHP 4 )


ifx_htmltbl_result -- Muestra todos los registros de una ifx_num_rows -- Cuenta los registros ya leídos de una
consulta en una tabla HTML consulta

Descripción Descripción

int ifx_htmltbl_result ( int result_id [, string int ifx_num_rows ( int result_id)


html_table_options])
Da el número de registros ya leídos de una consulta
Devuelve el número de registros leídos o FALSE si hubo representada por un result_id después de llamar a
error. ifx_query() o ifx_do().
Muestra todas las filas de la consulta result_id dentro de
una tabla html. El argumento segundo, opcional, es una
cadena de parámetros del tag <table> ifx_pconnect
Ejemplo 1. Mostrar resultado como una tabla HTML
(PHP 3>= 3.0.3, PHP 4 )
ifx_pconnect -- Abre una conexión permanente con
$rid = ifx_prepare ("select * from emp where name Informix
like " . $name,
$connid, IFX_SCROLL);
if (! $rid) { Descripción
... error ...
}
$rowcount = ifx_affected_rows ($rid); int ifx_pconnect ( [string database [, string userid [,
if ($rowcount > 1000) { string password]]])
printf ("Too many rows in result set (%d)\n<br>",
$rowcount); // Demasiados registros en el resultado Devuelve un identificador positivo de enlace persistente
die ("Please restrict your query<br>\n"); si hubo conexión, o FALSE si se produjo un error.
// Por favor, restringe tu consulta ifx_pconnect() actúa muy parecido a ifx_connect() con
} dos principales diferencias.
if (! ifx_do($rid) { Esta función se comporta exactamente igual que
... error ... ifx_connect() cuando PHP no es ejecutado como un
} módulo de Apache. La primera diferencia es cuando se
conecta, la función intentará encontrar un enlace
ifx_htmltbl_result ($rid, "border=\"2\""); (persistente) que exista con el mismo servidor, usuario y
contraseña. Si es hallado, el identificador del enlace será
ifx_free_result($rid); devuelto en vez de abrir una nueva conexión.
Segundo, la conexión al servidor no se cerrará cuando la
ejecución del guión (script) finalice. En vez de esto, la
ifx_nullformat conexión permanecerá abierta para usos futuros
(ifx_close() no cerrará el enlace creado por
ifx_pconnect()).
(PHP 3>= 3.0.4, PHP 4 ) Este tipo de enlace es, por tanto, llamado 'persistente'
ifx_nullformat -- Define el valor por defecto cuando se Examina también: ifx_connect().
leen valores nulos
ifx_prepare Para cualquier tipo de consulta el número (estimado o
real) de registros procesados es guardo y se puede
obtener mediante ifx_affected_rows().
(PHP 3>= 3.0.4, PHP 4 ) Si tienes columnas BLOB (BYTE o TEXT) en una consulta
ifx_prepare -- Prepara una sentencia SQL para su de actualización, puedes añadir un parámetro
ejecución blobidarray conteniendo los identificadores de blob y
sustituir los valores de esas columnas por una "?" en el
texto de la consulta.
Descripción
Si el contenido de la columna de tipo TEXT (o BYTE) lo
permite, también puedes usar "ifx_textasvarchar(1)" y
int ifx_prepare ( string query, int conn_id [, int "ifx_byteasvarchar(1)". Esto supone manejar columnas
cursor_def, mixed blobidarray]) de tipo TEXT (o BYTE) como si fueran columnas normales
de tipo VARCHAR (pero teniendo en cuenta que tendrán
un mayor tamaño que el habitual), para consultas de
Devuelve un entero (integer) result_id para usarlo con selección y no necesitas preocuparte por los
ifx_do(). Es definido "affected_rows" (registros identificadores de blob.
procesados) y se puede obtener mediante la función La opción por defecto ifx_textasvarchar(0) o
ifx_affected_rows(). ifx_byteasvarchar(0) devuelve identificadores de blob
Prepara una consulta (query) sobre una conexión (valores enteros) para las consultas de selección. Puedes
(link_identifier). Un cursor es definido y abierto para las obtener el contenido del blob como una cadena o un
consultas de selección. El parámetro opcional tipo de fichero con las funciones para blob (ver más adelante).
cursor (cursor_type) te permite que sea un cursor de tipo Examina también: ifx_connect().
"scroll" y/o "hold". Es una máscara y puede ser Ejemplo 1. Mostrar todos los registros de la tabla
IFX_SCROLL, IFX_HOLD o ambos. "orders" como una tabla html
Para cualquier tipo de consulta el número estimado de
registros afectados (procesados) es guardado y puede
ser obtenido mediante ifx_affected_rows().
ifx_textasvarchar(1); // usa "modo texto"
Si tienes columnas BLOB (BYTE o TEXT) en una consulta,
para blobs
puedes añadir un parámetro blobidarray conteniendo los
$res_id = ifx_query("select * from orders",
identificadores de blob y sustituir los valores de esas
$conn_id);
columnas por una "?" en el texto de la consulta.
if (! $res_id) {
Si el contenido de la columna de tipo TEXT (o BYTE) lo
printf("Can't select orders : %s\n<br>
permite, puedes también usar "ifx_textasvarchar(1)" y
%s<br>\n", ifx_error());
"ifx_byteasvarchar(1)". Esto supone manejar columnas
ifx_errormsg();
de tipo TEXT (o BYTE) como si fueran columnas normales
die;
de tipo VARCHAR (pero teniendo en cuenta que tendrán
}
un mayor tamaño que el habitual), para consultas de
ifx_htmltbl_result($res_id, "border=\"1\"");
selección y no necesitas preocuparte por los
ifx_free_result($res_id);
identificadores de blob.
La opción por defecto ifx_textasvarchar(0) o Ejemplo 2. Inserta valores en la tabla "catalog"
ifx_byteasvarchar(0) devuelve identificadores de blob
(valores enteros) para las consultas de selección. Puedes
obtener el contenido del blob como una cadena o un // crea identificadores de blob para una columna de
fichero con las funciones para blob (ver más adelante). tipo byte y otra text
Examina también: ifx_do(). $textid = ifx_create_blob(0, 0, "Text column in
memory");
$byteid = ifx_create_blob(1, 0, "Byte column in
ifx_query
memory");
// almacena los identificadores de blob
(PHP 3>= 3.0.3, PHP 4 ) en un array llamado blobid
ifx_query -- Envía una consulta a Informix $blobidarray[] = $textid;
$blobidarray[] = $byteid;
// lanza la consulta
Descripción $query = "insert into catalog (stock_num, manu_code,
".
"cat_descr,cat_picture) values(1,'HRO',?,?)";
int ifx_query ( string query [, int link_identifier [, int $res_id = ifx_query($query, $conn_id, $blobidarray);
cursor_type [, mixed blobidarray]]]) if (! $res_id) {
... error ...
Devuelve un identificador positivo de resultado si tuvo }
éxito, FALSE en otro caso. // libera el resultado
Un entero (integer) "result_id" usado por otras funciones ifx_free_result($res_id);
para obtener el resultado de la consulta. Es definido
"affected_rows" (registros procesados) y se puede
obtener mediante la función ifx_affected_rows(). ifx_textasvarchar
ifx_query() envía una consulta a la base de datos activa
actualmente en el servidor, la cual está representada por
el identificador de enlace especificado (link_identifier). Si (PHP 3>= 3.0.4, PHP 4 )
el identificador no es definido, el último enlace abierto es ifx_textasvarchar -- Define el modo por defecto para los
asumido. Si el enlace no se encuentra abierto, campos de tipo text
ifx_connect() es llamado y utilizado.
Ejecuta una consulta (query) sobre una conexión
Descripción
(link_identifier). Un cursor es definido y abierto para las
consultas de selección. El parámetro opcional tipo de
cursor (cursor_type) te permite que sea un cursor de tipo void ifx_textasvarchar ( int mode)
"scroll" y/o "hold". Es una máscara y puede ser
IFX_SCROLL, IFX_HOLD o ambos. Las consultas que no
son de selección son ejecutadas inmediatamente. Define el modo por defecto para los campos de tipo text
en todas las consultas de selección. Modo (mode) "0"
devolverá un identificador de blob y "1" dará el (no version information, might be only in CVS)
contenido en un campo de tipo varchar. ifx_free_slob -- Elimina un objeto slob

ifx_update_blob Descripción

(PHP 3>= 3.0.4, PHP 4 ) int ifxus_free_slob ( int bid)


ifx_update_blob -- Actualiza el contenido de un objeto
blob
Borra un objeto slob. bid es el identificador del objeto
slob. Devuelve FALSE si hubo error, TRUE en otro caso.
Descripción
ifxus_open_slob
ifx_update_blob ( int bid, string content)
(PHP 3>= 3.0.4, PHP 4 )
Actualiza el contenido de un objeto blob representado ifxus_open_slob -- Abre un objeto slob
por su identificador bid. content es una cadena con el
nuevo contenido. Devuelve FALSE si hubo error, en otro
caso TRUE. Descripción

ifx_update_char int ifxus_open_slob ( long bid, int mode)

Abre un objeto slob. bid será un identificador de slob que


(PHP 3>= 3.0.6, PHP 4 )
válido. Modos: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 =
ifx_update_char -- Actualiza el contenido de un objeto
LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 =
char
LO_NOBUFFER o una combinación de ellos. Devuelve
FALSE si hubo error, en otro caso el identificador del
Descripción nuevo objeto slob.

int ifx_update_char ( int bid, string content) ifxus_read_slob

Actualiza el contenido de un objeto char representado (PHP 3>= 3.0.4, PHP 4 )


por su identificador bid. content es una cadena con la ifxus_read_slob -- Lee un número de bytes (nbytes) de un
información nueva. Devuelve FALSE si se produjo un objeto slob
error, en otro caso TRUE.

Descripción
ifxus_close_slob

int ifxus_read_slob ( long bid, long nbytes)


(PHP 3>= 3.0.4, PHP 4 )
ifxus_close_slob -- Cierra un objeto slob
Lee un número de bytes (nbytes) de un objeto slob. bid
es un identificador de slob válido y nbytes es el número
Descripción de bytes a leer. Devuelve FALSE si hubo error, sino la
cadena.

int ifxus_close_slob ( int bid)


ifxus_seek_slob

Cierra un objeto slob representado por su identificador


de slob bid. Devuelve FALSE si hubo error, TRUE en otro (PHP 3>= 3.0.4, PHP 4 )
caso. ifxus_seek_slob -- Define el fichero o posición en
memoria

ifxus_create_slob
Descripción

(PHP 3>= 3.0.4, PHP 4 )


ifxus_create_slob -- Crea un objeto slob y lo abre int ifxus_seek_blob ( long bid, int mode, long offset)

Descripción Define el fichero o posición en memoria de un objeto slob


abierto, bid será un identificador de slob válido. Modos
(mode): 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 =
int ifxus_create_slob ( int mode) LO_SEEK_END y offset es el desplazamiento en bytes. Si
hubo error entonces da FALSE.
Crea un objeto slob y lo abre. Modos: 1 = LO_RDONLY, 2
= LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = ifxus_tell_slob
LO_BUFFER, 32 = LO_NOBUFFER o una combinación de
ellos. También puedes usar nombres de constantes
IFX_LO_RDONLY, IFX_LO_WRONLY, etc. Devuelve FALSE (PHP 3>= 3.0.4, PHP 4 )
si hubo error, en otro caso el identificador del nuevo ifxus_tell_slob -- Devuelve el fichero actual o la posición
objeto slob. en memoria

ifx_free_slob Descripción
int ifxus_tell_slob ( long bid) (PHP 3>= 3.0.7, PHP 4 )
ibase_blob_cancel -- Cancel creating blob
Devuelve el fichero actual o la posición en memoria de
un objeto slob abierto, bid será un identificador de slob Description
válido. Si hubo error entonces da FALSE.

int ibase_blob_cancel ( int blob_id)


ifxus_write_slob

Aviso
(PHP 3>= 3.0.4, PHP 4 )
ifxus_write_slob -- Escribe una cadena en un objeto slob Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

Descripción
ibase_blob_close
int ifxus_write_slob ( long bid, string content)
(PHP 3>= 3.0.7, PHP 4 )
Escribe una cadena en un objeto slob. bid es un ibase_blob_close -- Close blob
identificador de slob válido y content el contenido a
escribir. Devuelve FALSE si hubo error, sino el número
Description
de bytes escritos.

int ibase_blob_close ( int blob_id)


XLIV. Funciones InterBase

Tabla de contenidos Aviso


ibase_blob_add -- Add data into created blob Esta función no está documentada actualmente, solamente
ibase_blob_cancel -- Cancel creating blob se encuentra disponible la lista de parametros.
ibase_blob_close -- Close blob
ibase_blob_create -- Create blob for adding data
ibase_blob_echo -- Output blob contents to browser ibase_blob_create
ibase_blob_get -- Get len bytes data from open blob
ibase_blob_import -- Create blob, copy file in it, and
close it (PHP 3>= 3.0.7, PHP 4 )
ibase_blob_info -- Return blob length and other useful ibase_blob_create -- Create blob for adding data
info
ibase_blob_open -- Open blob for retrieving data parts
ibase_close -- Description
ibase_commit -- Commit a transaction
ibase_connect --
int ibase_blob_create ( [int link_identifier])
ibase_errmsg -- Returns error messages
ibase_execute --
ibase_fetch_object -- Get an object from a InterBase Aviso
database
ibase_fetch_row -- Esta función no está documentada actualmente, solamente
ibase_field_info -- Get information about a field se encuentra disponible la lista de parametros.
ibase_free_query --
ibase_free_result --
ibase_num_fields -- Get the number of fields in a result ibase_blob_echo
set
ibase_pconnect --
ibase_prepare -- (PHP 3>= 3.0.7, PHP 4 )
ibase_query -- ibase_blob_echo -- Output blob contents to browser
ibase_rollback -- Rolls back a transaction
ibase_timefmt --
Description
ibase_trans -- Begin a transaction

int ibase_blob_echo ( string blob_id_str)


ibase_blob_add

(PHP 3>= 3.0.7, PHP 4 ) Aviso


ibase_blob_add -- Add data into created blob Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description
ibase_blob_get
int ibase_blob_add ( int blob_id, string data)
(PHP 3>= 3.0.7, PHP 4 )
Aviso ibase_blob_get -- Get len bytes data from open blob

Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros. Description

string ibase_blob_get ( int blob_id, int len)


ibase_blob_cancel
Aviso Description

Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros. int ibase_commit ( [int link_identifier, int
trans_number])

ibase_blob_import Commits transaction trans_number which was created


with ibase_trans().
(PHP 3>= 3.0.7, PHP 4 )
ibase_blob_import -- Create blob, copy file in it, and ibase_connect
close it

(PHP 3>= 3.0.6, PHP 4 )


Description ibase_connect --

string ibase_blob_import ( [int link_identifier, int Descripcion


file_id])

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

(PHP 3>= 3.0.7, PHP 4 )


ibase_blob_info ibase_errmsg -- Returns error messages

(PHP 3>= 3.0.7, PHP 4 ) Description


ibase_blob_info -- Return blob length and other useful
info
string ibase_errmsg ( void)

Description Returns a string containing an error message.

object ibase_blob_info ( string blob_id_str) ibase_execute

Aviso (PHP 3>= 3.0.6, PHP 4 )


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

ibase_blob_open
ibase_execute ( )

(PHP 3>= 3.0.7, PHP 4 )


ibase_blob_open -- Open blob for retrieving data parts ibase_fetch_object

Description (PHP 3>= 3.0.7, PHP 4 )


ibase_fetch_object -- Get an object from a InterBase
database
int ibase_blob_open ( string blob_id)

Description
Aviso
Esta función no está documentada actualmente, solamente object ibase_fetch_object ( int result_id)
se encuentra disponible la lista de parametros.
Fetches a row as a pseudo-object from a result_id
obtained either by ibase_query() or ibase_execute().
ibase_close
<php
$dbh = ibase_connect ($host,
(PHP 3>= 3.0.6, PHP 4 ) $username, $password);
ibase_close -- $stmt = 'SELECT * FROM tblname';
$sth = ibase_query ($dbh, $stmt);
Descripcion while ($row = ibase_fetch_object ($sth))
{
print $row->email . "\n";
ibase_close ( ) }
ibase_close ($dbh);
?>
ibase_commit
Subsequent call to ibase_fetch_object() would return
the next row in the result set, or FALSE if there are no
(PHP 3>= 3.0.7, PHP 4 ) more rows.
ibase_commit -- Commit a transaction See also ibase_fetch_row().
ibase_fetch_row int ibase_num_fields ( int result_id)

(PHP 3>= 3.0.6, PHP 4 ) Returns an integer containing the number of fields in a
ibase_fetch_row -- result set.
<?php
$dbh = ibase_connect ($host,
Descripcion
$username, $password);
$stmt = 'SELECT * FROM tblname';
ibase_fetch_row ( ) $sth = ibase_query ($dbh, $stmt);

if (ibase_num_fields($sth) > 0) {
ibase_field_info while ($row = ibase_fetch_object
($sth)) {
print $row->email . "\n";
(PHP 3>= 3.0.7, PHP 4 ) }
ibase_field_info -- Get information about a field } else {
die ("No Results were found for your
Description query");
}

array ibase_field_info ( int result, int field number) ibase_close ($dbh);


?>
Returns an array with information about a field after a See also: ibase_field_info().
select query has been run. The array is in the form of
name, alias, relation, length, type.
ibase_pconnect
$rs=ibase_query("SELECT * FROM
tablename");
$coln = ibase_num_fields($rs); (PHP 3>= 3.0.6, PHP 4 )
for ($i=0; $i < $coln; $i++) { ibase_pconnect --
$col_info = ibase_field_info($rs,
$i);
echo "name: ". Descripcion
$col_info['name']."\n";
echo "alias: ". ibase_pconnect ( )
$col_info['alias']."\n";
echo "relation: ".
$col_info['relation']."\n"; ibase_prepare
echo "length: ".
$col_info['length']."\n";
echo "type: ". (PHP 3>= 3.0.6, PHP 4 )
$col_info['type']."\n"; ibase_prepare --
}
Descripcion

ibase_free_query
ibase_prepare ( )

(PHP 3>= 3.0.6, PHP 4 )


ibase_free_query -- ibase_query

Descripcion (PHP 3>= 3.0.6, PHP 4 )


ibase_query --

ibase_free_query ( )
Descripcion

ibase_free_result
ibase_query ( )

(PHP 3>= 3.0.6, PHP 4 )


ibase_free_result -- ibase_rollback

Descripcion (PHP 3>= 3.0.7, PHP 4 )


ibase_rollback -- Rolls back a transaction

ibase_free_result ( )
Description

ibase_num_fields
int ibase_rollback ( [int link_identifier, int
trans_number])
(PHP 3>= 3.0.7, PHP 4 )
ibase_num_fields -- Get the number of fields in a result
set Rolls back transaction trans_number which was created
with ibase_trans().

Description
ibase_timefmt
(PHP 3>= 3.0.6, PHP 4 ) ingres_field_nullable -- Test if a field is nullable.
ibase_timefmt -- ingres_field_precision -- Get the precision of a field.
ingres_field_scale -- Get the scale of a field.
ingres_field_type -- Get the type of a field in a query
Descripcion result.
ingres_num_fields -- Get the number of fields returned
by the last query
ibase_timefmt ( )
ingres_num_rows -- Get the number of rows affected or
returned by the last query
ibase_trans ingres_pconnect -- Open a persistent connection to an
Ingres II database.
ingres_query -- Send a SQL query to Ingres II
(PHP 3>= 3.0.7, PHP 4 ) ingres_rollback -- Roll back a transaction.
ibase_trans -- Begin a transaction

ingres_autocommit
Description

(PHP 4 >= 4.0.2)


int ibase_trans ( [int trans_args [, int link_identifier]]) ingres_autocommit -- Switch autocommit on or off.

Begins a transaction. Description

XLV. Ingres II functions bool ingres_autocommit ( [resource link])

Aviso ingres_autocommit() is called before opening a


transaction (before the first call to ingres_query() or
Este módulo es EXPERIMENTAL. Esto significa que el just after a call to ingres_rollback() or
comportamineto de estas funciones, nombre de funciones ingres_autocommit()) to switch the "autocommit"
y en definitiva TODO lo documentado aqui, puede cambiar mode of the server on or off (when the script begins the
en una futura version de PHP SIN AVISO. Quedas avisado, y autocommit mode is off).
utilizar este módulo es tu responsabiliad. When the autocommit mode is on, every query is
These functions allow you to access Ingres II database automaticaly commited by the server, as if
servers. ingres_commit() was called after every call to
In order to have these functions available, you must ingres_query().
compile php with Ingres support by using the --with- See also ingres_query(), ingres_rollback() and
ingres option. You need the Open API library and header ingres_commit().
files included with Ingres II. If the II_SYSTEM environment
variable isn't correctly set you may have to use --with-
ingres_close
ingres=DIR to specify your Ingres installation directory.
When using this extension with Apache, if Apache does
not start and complains with "PHP Fatal error: Unable to (PHP 4 >= 4.0.2)
start ingres_ii module in Unknown on line 0" then make ingres_close -- Close an Ingres II database connection
sure the environement variable II_SYSTEM is correctly
set. Adding "export II_SYSTEM="/home/ingres/II" in the
script that starts Apache, just before launching httpd, Description
should be fine.
bool ingres_close ( [resource link])
Nota: If you already used PHP
extensions to access other database Returns TRUE on success, or FALSE on failure.
servers, note that Ingres doesn't ingres_close() closes the connection to the Ingres
allow concurrent queries and/or server that's associated with the specified link. If the link
transaction over one connection, parameter isn't specified, the last opened link is used.
thus you won't find any result or ingres_close() isn't usually necessary, as it won't close
transaction handle in this extension. persistent connections and all non-persistent connections
The result of a query must be are automatically closed at the end of the script.
treated before sending another See also ingres_connect(), and ingres_pconnect().
query, and a transaction must be
commited or rolled back before
opening another transaction (which ingres_commit
is automaticaly done when sending
the first query).
(PHP 4 >= 4.0.2)
ingres_commit -- Commit a transaction.
Tabla de contenidos
ingres_autocommit -- Switch autocommit on or off.
ingres_close -- Close an Ingres II database connection Description
ingres_commit -- Commit a transaction.
ingres_connect -- Open a connection to an Ingres II
database. bool ingres_commit ( [resource link])
ingres_fetch_array -- Fetch a row of result into an array.
ingres_fetch_object -- Fetch a row of result into an object. ingres_commit() commits the currently open
ingres_fetch_row -- Fetch a row of result into an transaction, making all changes made to the database
enumerated array. permanent.
ingres_field_length -- Get the length of a field. This closes the transaction. A new one can be open by
ingres_field_name -- Get the name of a field in a query sending a query with ingres_query().
result.
You can also have the server commit automaticaly after data in associative indices, using the field names as
every query by calling ingres_autocommit() before keys.
opening the transaction. If two or more columns of the result have the same field
See also ingres_query(), ingres_rollback() and names, the last column will take precedence. To access
ingres_autocommit(). the other column(s) of the same name, you must use the
numeric index of the column or make an alias for the
column.
ingres_connect
ingres_query(select t1.f1 as foo t2.f1 as
bar from t1, t2);
(PHP 4 >= 4.0.2) $result = ingres_fetch_array();
ingres_connect -- Open a connection to an Ingres II $foo = $result["foo"];
database. $bar = $result["bar"];
result_type can be II_NUM for enumerated array,
Description II_ASSOC for associative array, or II_BOTH (default).
Speed-wise, the function is identical to
ingres_fetch_object(), and almost as quick as
resource ingres_connect ( [string database [, string ingres_fetch_row() (the difference is insignificant).
username [, string password]]]) Ejemplo 1. ingres_fetch_array() example

Returns a Ingres II link resource on success, or FALSE on


failure. <?php
ingres_connect() opens a connection with the Ingres ingres_connect ($database, $user,
database designated by database, which follows the $password);
syntax [node_id::]dbname[/svr_class].
If some parameters are missing, ingres_connect() uses ingres_query ("select * from table");
the values in php.ini for ingres.default_database, while ($row = ingres_fetch_array()) {
ingres.default_user and ingres.default_password. echo $row["user_id"]; # using
The connection is closed when the script ends or when associative array
ingres_close() is called on this link. echo $row["fullname"];
All the other ingres functions use the last opened link as echo $row[1]; # using
a default, so you need to store the returned value only if enumerated array
you use more than one link at a time. echo $row[2];
Ejemplo 1. ingres_connect() example }
?>
See also ingres_query(), ingres_num_fields(),
<?php ingres_field_name(), ingres_fetch_object() and
$link = ingres_connect ("mydb", ingres_fetch_row().
"user", "pass")
or die ("Could not connect");
print ("Connected successfully"); ingres_fetch_object
ingres_close ($link);
?>
(PHP 4 >= 4.0.2)
Ejemplo 2. ingres_connect() example using default ingres_fetch_object -- Fetch a row of result into an object.
link

Description
<?php
ingres_connect ("mydb", object ingres_fetch_object ( [int result_type [, resource
"user", "pass") link]])
or die ("Could not
connect");
print ("Connected ingres_fetch_object() Returns an object that
successfully"); corresponds to the fetched row, or FALSE if there are no
ingres_close (); more rows.
?> This function is similar to ingres_fetch_array(), with
one difference - an object is returned, instead of an
See also ingres_pconnect(), and ingres_close(). array. Indirectly, that means that you can only access the
data by the field names, and not by their offsets
(numbers are illegal property names).
ingres_fetch_array
The optional argument result_type is a constant and can
take the following values: II_ASSOC, II_NUM, and II_BOTH.
(PHP 4 >= 4.0.2) Speed-wise, the function is identical to
ingres_fetch_array -- Fetch a row of result into an array. ingres_fetch_array(), and almost as quick as
ingres_fetch_row() (the difference is insignificant).
Ejemplo 1. ingres_fetch_object() example
Description

array ingres_fetch_array ( [int result_type [, resource <?php


link]]) ingres_connect ($database, $user,
$password);
ingres_query ("select * from
ingres_fetch_array() Returns an array that corresponds table");
to the fetched row, or FALSE if there are no more rows. while ($row =
This function is an extended version of ingres_fetch_object()) {
ingres_fetch_row(). In addition to storing the data in echo $row->user_id;
the numeric indices of the result array, it also stores the echo $row->fullname;
}
ingres_field_name() returns the name of a field in a
?>
query result, or FALSE on failure.
See also ingres_query(), ingres_num_fields(), index is the number of the field and must be between 1
ingres_field_name(), ingres_fetch_array() and and the value given by ingres_num_fields().
ingres_fetch_row(). See also ingres_query(), ingres_fetch_array(),
ingres_fetch_object() and ingres_fetch_row().
ingres_fetch_row
ingres_field_nullable
(PHP 4 >= 4.0.2)
ingres_fetch_row -- Fetch a row of result into an (PHP 4 >= 4.0.2)
enumerated array. ingres_field_nullable -- Test if a field is nullable.

Description Description

array ingres_fetch_row ( [resource link]) bool ingres_field_nullable ( int index [, resource link])

ingres_fetch_row() returns an array that corresponds ingres_field_nullable() returns TRUE if the field can be
to the fetched row, or FALSE if there are no more rows. set to the NULL value and FALSE if it can't.
Each result column is stored in an array offset, starting at index is the number of the field and must be between 1
offset 1. and the value given by ingres_num_fields().
Subsequent call to ingres_fetch_row() would return the See also ingres_query(), ingres_fetch_array(),
next row in the result set, or FALSE if there are no more ingres_fetch_object() and ingres_fetch_row().
rows.
Ejemplo 1. ingres_fetch_row() example
ingres_field_precision

<?php (PHP 4 >= 4.0.2)


ingres_connect ($database, $user, ingres_field_precision -- Get the precision of a field.
$password);

ingres_query ("select * from Description


table");
while ($row = ingres_fetch_row()) {
echo $row[1]; int ingres_field_precision ( int index [, resource link])
echo $row[2];
} ingres_field_precision() returns the precision of a field.
?> This value is used only for decimal, float and money SQL
See also ingres_num_fields(), ingres_query(), data types. For detailed information, see the
ingres_fetch_array() and ingres_fetch_object(). Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1
and the value given by ingres_num_fields().
ingres_field_length See also ingres_query(), ingres_fetch_array(),
ingres_fetch_object() and ingres_fetch_row().
(PHP 4 >= 4.0.2)
ingres_field_length -- Get the length of a field. ingres_field_scale

Description (PHP 4 >= 4.0.2)


ingres_field_scale -- Get the scale of a field.
int ingres_field_length ( int index [, resource link])
Description
ingres_field_length() returns the length of a field. This
is the number of bytes used by the server to store the int ingres_field_scale ( int index [, resource link])
field. For detailed information, see the Ingres/OpenAPI
User Guide - Appendix C.
index is the number of the field and must be between 1 ingres_field_scale() returns the scale of a field. This
and the value given by ingres_num_fields(). value is used only for the decimal SQL data type. For
See also ingres_query(), ingres_fetch_array(), detailed information, see the Ingres/OpenAPI User Guide
ingres_fetch_object() and ingres_fetch_row(). - Appendix C.
index is the number of the field and must be between 1
and the value given by ingres_num_fields().
ingres_field_name See also ingres_query(), ingres_fetch_array(),
ingres_fetch_object() and ingres_fetch_row().
(PHP 4 >= 4.0.2)
ingres_field_name -- Get the name of a field in a query ingres_field_type
result.

(PHP 4 >= 4.0.2)


Description ingres_field_type -- Get the type of a field in a query
result.
string ingres_field_name ( int index [, resource link])
Description
string ingres_field_type ( int index [, resource link]) (PHP 4 >= 4.0.2)
ingres_pconnect -- Open a persistent connection to an
Ingres II database.
ingres_field_type() returns the type of a field in a query
result, or FALSE on failure. Examples of types returned
are "IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", Description
"IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE",
"IIAPI_VCH_TYPE". Some of these types can map to more
than one SQL type depending on the length of the field resource ingres_pconnect ( [string database [, string
(see ingres_field_length()). For example username [, string password]]])
"IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed
information, see the Ingres/OpenAPI User Guide -
Returns a Ingres II link resource on success, or FALSE on
Appendix C. failure.
index is the number of the field and must be between 1
See ingres_connect() for parameters details and
and the value given by ingres_num_fields(). examples. There are only 2 differences between
See also ingres_query(), ingres_fetch_array(),
ingres_pconnect() and ingres_connect() : First, when
ingres_fetch_object() and ingres_fetch_row(). connecting, the function will first try to find a (persistent)
link that's already opened with the same parameters. If
ingres_num_fields one is found, an identifier for it will be returned instead of
opening a new connection. Second, the connection to the
Ingres server will not be closed when the execution of
(PHP 4 >= 4.0.2) the script ends. Instead, the link will remain open for
ingres_num_fields -- Get the number of fields returned future use (ingres_close() will not close links
by the last query established by ingres_pconnect()). This type of link is
therefore called 'persistent'.
See also ingres_connect(), and ingres_close().
Description

ingres_query
int ingres_num_fields ( [resource link])

(PHP 4 >= 4.0.2)


ingres_num_fields() returns the number of fields in the
ingres_query -- Send a SQL query to Ingres II
results returned by the Ingres server after a call to
ingres_query()
See also ingres_query(), ingres_fetch_array(), Description
ingres_fetch_object() and ingres_fetch_row().

bool ingres_query ( string query [, resource link])


ingres_num_rows

Returns TRUE on success, or FALSE on failure.


(PHP 4 >= 4.0.2) ingres_query() sends the given query to the Ingres
ingres_num_rows -- Get the number of rows affected or server. This query must be a valid SQL query (see the
returned by the last query Ingres SQL reference guide)
The query becomes part of the currently open
transaction. If there is no open transaction,
Description ingres_query() opens a new transaction. To close the
transaction, you can either call ingres_commit() to
commit the changes made to the database or
int ingres_num_rows ( [resource link])
ingres_rollback() to cancel these changes. When the
script ends, any open transaction is rolled back (by
For delete, insert or update queries, ingres_num_rows() calling ingres_rollback()). You can also use
returns the number of rows affected by the query. For ingres_autocommit() before opening a new transaction
other queries, ingres_num_rows() returns the number to have every SQL query immediatly commited.
of rows in the query's result. Some types of SQL queries can't be sent with this
function :
Nota: This function is mainly meant
to get the number of rows modified
in the database. If this function is
• close (see ingres_close()).
called before using • commit (see ingres_commit()).
ingres_fetch_array(),
ingres_fetch_object() or • connect (see ingres_connect()).
ingres_fetch_row() the server will • disconnect (see ingres_close()).
delete the result's data and the
script won't be able to get them. • get dbevent
• prepare to commit
You should instead retrieve the • rollback (see ingres_rollback()).
result's data using one of these fetch
functions in a loop until it returns
• savepoint
FALSE, indicating that no more • set autocommit (see ingres_autocommit()).
results are available. • all cursor related queries are unsupported

See also ingres_query(), ingres_fetch_array(),


Ejemplo 1. ingres_query() example
ingres_fetch_object() and ingres_fetch_row().

ingres_pconnect <?php
ingres_connect ($database, $user,
Tipos de recursos
$password);

ingres_query ("select * from


table");
while ($row = ingres_fetch_row()) { Constantes predefinidas
echo $row[1];
echo $row[2];
} Esta extensión no define ninguna constante.
?> Tabla de contenidos
ircg_channel_mode -- Set channel mode flags for user
See also ingres_fetch_array(), ingres_fetch_object(), ircg_disconnect -- Close connection to server
ingres_fetch_row(), ingres_commit(), ircg_fetch_error_msg -- Returns the error from previous
ingres_rollback() and ingres_autocommit(). IRCG operation
ircg_get_username -- Get username for connection
ingres_rollback ircg_html_encode -- Encodes HTML preserving output
ircg_ignore_add -- Add a user to your ignore list on a
server
(PHP 4 >= 4.0.2) ircg_ignore_del -- Remove a user from your ignore list on
ingres_rollback -- Roll back a transaction. a server
ircg_is_conn_alive -- Check connection status
ircg_join -- Join a channel on a connected server
Description ircg_kick -- Kick a user out of a channel on server
ircg_lookup_format_messages -- Check for the existence
of a format message set
bool ingres_rollback ( [resource link])
ircg_msg -- Send message to channel or user on server
ircg_nick -- Change nickname on server
ingres_rollback() rolls back the currently open ircg_nickname_escape -- Encode special characters in
transaction, actualy canceling all changes made to the nickname to be IRC-compliant
database during the transaction. ircg_nickname_unescape -- Decodes encoded nickname
This closes the transaction. A new one can be open by ircg_notice -- Send a notice to a user on server
sending a query with ingres_query(). ircg_part -- Leave a channel on server
See also ingres_query(), ingres_commit() and ircg_pconnect -- Connect to an IRC server
ingres_autocommit(). ircg_register_format_messages -- Register a format
message set
ircg_set_current -- Set current connection for output
XLVI. IRC Gateway Functions ircg_set_file -- Set logfile for connection
ircg_set_on_die -- Set action to be executed when
Introducción connection dies
ircg_topic -- Set topic for channel on server
ircg_whois -- Query server for user information
With IRCG you can rapidly stream XML data to thousands
of concurrently connected users. This can be used to
build powerful, extensible interactive platforms such as ircg_channel_mode
online games and webchats. IRCG also features support
for a non-streaming mode where a helper application (PHP 4 >= 4.0.5)
reformats incoming data and supplies static file snippets ircg_channel_mode -- Set channel mode flags for user
in special formats such as cHTML (i-mode) or WML (WAP).
These static files are then delivered by the high-
performance web server. Description
Up to v3, IRCG runs under these platforms:

boolean ircg_channel_mode ( resource connection,


• AIX string channel, string mode_spec, string nick)

• FreeBSD
Set channel mode flags for channel on server connected
• HP-UX to by connection. Mode flags are passed in mode_spec
• Irix
and are applied to the user specified by nick.
Mode flags are set or cleared by specifying a mode
• Linux character and prepending it with a plus or minus
character, respectively. E.g. operator mode is granted by
• Solaris
'+o' and revoked by '-o', as passed as mode_spec.
• Tru64

ircg_disconnect

Instalación (PHP 4 >= 4.0.4)


ircg_disconnect -- Close connection to server

Detailed installation instructions can be found here. We


urge you to use the provided installation script. Description

Configuración en tiempo de ejecución boolean ircg_disconnect ( resource connection, string


reason)

Esta extensión no define ninguna directiva de ircg_disconnect() will close a connection to a server
configuración. previously established with ircg_pconnect().
See also: ircg_pconnect().
ircg_fetch_error_msg boolean ircg_ignore_add ( resource connection, string
nick)

(PHP 4 >= 4.1.0)


ircg_fetch_error_msg -- Returns the error from previous This function adds user nick to the ignore list of
IRCG operation connection connection. Afterwards, IRCG will suppress all
messages from this user through the associated
connection.
Description See also: ircg_ignore_del().

array ircg_fetch_error_msg ( resource connection) ircg_ignore_del

ircg_fetch_error_msg() returns the error from a failed (PHP 4 >= 4.0.5)


connection. ircg_ignore_del -- Remove a user from your ignore list on
a server
Nota: Error code is stored in first
array element, error text in second. Description
The error code is equivalent to IRC
reply codes as defined by RFC 2812.
boolean ircg_ignore_del ( resource connection, string
nick)
Ejemplo 1. ircg_fetch_error_msg() example

This function removes user nick from the IRCG ignore list
associated with connection.
if (!ircg_join ($id, "#php")) {
$error = See also: ircg_ignore_add().
ircg_fetch_error_msg($id);
print ("Can't join channel ircg_is_conn_alive
#php. Error code:
$error[0] Description:
$error[1]"); (PHP 4 >= 4.0.5)
} ircg_is_conn_alive -- Check connection status

Description
ircg_get_username

boolean ircg_is_conn_alive ( resource connection)


(PHP 4 >= 4.1.0)
ircg_get_username -- Get username for connection
ircg_is_conn_alive() returns TRUE if connection is still
alive and working or FALSE, if the connection has died
Description for some reason.

string ircg_get_username ( resource connection) ircg_join

Function ircg_get_username() returns the username


(PHP 4 >= 4.0.4)
for the specified connection connection. Returns FALSE
ircg_join -- Join a channel on a connected server
if connection died or is not valid.

Description
ircg_html_encode

boolean ircg_join ( resource connection, string channel


(PHP 4 >= 4.0.5)
[, string key])
ircg_html_encode -- Encodes HTML preserving output

Join the channel channel on the server connected to by


Description connection. IRCG will optionally pass the room key key.

boolean ircg_html_encode ( string html_string) ircg_kick

Encodes a HTML string html_string for output. This


(PHP 4 >= 4.0.5)
exposes the interface which the IRCG extension uses
ircg_kick -- Kick a user out of a channel on server
internally to reformat data coming from an IRC link. The
function causes IRC color/font codes to be encoded in
HTML and escapes certain entities. Description

ircg_ignore_add boolean ircg_kick ( resource connection, string channel,


string nick, string reason)
(PHP 4 >= 4.0.5)
ircg_ignore_add -- Add a user to your ignore list on a Kick user nick from channel on server connected to by
server connection. reason should give a short message
describing why this action was performed.
Description
ircg_lookup_format_messages
(PHP 4 >= 4.0.5) Description
ircg_lookup_format_messages -- Check for the existence
of a format message set
string ircg_nickname_unescape ( string nick)

Description
Function ircg_nickname_unescape() returns a decoded
nickname, which is specified in nick.
boolean ircg_lookup_format_messages ( string name) See also: ircg_nickname_escape()

Check for the existence of the format message set name. ircg_notice
Sets may be registered with
ircg_register_format_messages(), a default set
named ircg is always available. Returns TRUE, if the set (PHP 4 >= 4.0.5)
exists and FALSE otherwise. ircg_notice -- Send a notice to a user on server
See also: ircg_register_format_messages()
Description
ircg_msg
boolean ircg_notice ( resource connection, string , string
(PHP 4 >= 4.0.4) message)
ircg_msg -- Send message to channel or user on server
This function will send the message text to the user nick
on the server connected to by connection. IRC servers
Description
and other software will not automatically generate
replies to NOTICEs in contrast to other message types.
boolean ircg_msg ( resource connection, string
recipient, string message [, boolean suppress])
ircg_part

ircg_msg() will send the message to a channel or user


on the server connected to by connection. A recipient (PHP 4 >= 4.0.4)
starting with # or & will send the message to a channel, ircg_part -- Leave a channel on server
anything else will be interpreted as a username.
Setting the optional parameter suppress to a TRUE value
Description
will suppress output of your message to your own
connection. This so-called loopback is necessary,
because the IRC server does not echo PRIVMSG boolean ircg_part ( resource connection, string channel)
commands back to us.
Leave the channel channel on the server connected to by
ircg_nick connection.

(PHP 4 >= 4.0.5) ircg_pconnect


ircg_nick -- Change nickname on server
(PHP 4 >= 4.0.4)
Description ircg_pconnect -- Connect to an IRC server

boolean ircg_nick ( resource connection, string nick) Description

Change your nickname on the given connection to the resource ircg_pconnect ( string username [, string
one given in nick, if possible. server_ip [, int server_port [, string msg_format [, array
Will return TRUE on success and FALSE on failure. ctcp_messages [, array user_settings]]]]])

ircg_nickname_escape ircg_pconnect() will try to establish a connection to an


IRC server and return a connection resource handle for
further use.
(PHP 4 >= 4.0.6) The only mandatory parameter is username, this will set
ircg_nickname_escape -- Encode special characters in your initial nickname on the server. server_ip and
nickname to be IRC-compliant server_port are optional and default to 127.0.0.1 and
6667.
Description
Nota: For now parameter server_ip
will not do any hostname lookups
string ircg_nickname_escape ( string nick)
and will only accept IP addresses in
numerical form. DNS lookups are
Function ircg_nickname_escape() returns an encoded expensive and should be done in the
nickname specified by nick wich is IRC-compliant. context of IRCG.
See also: ircg_nickname_unescape()

You can customize the output of IRC messages and


ircg_nickname_unescape events by selecting a format message set previously
created with ircg_register_format_messages() by
specifying the set's name in msg_format.
(PHP 4 >= 4.0.6) If you want to handle CTCP messages such as ACTION
ircg_nickname_unescape -- Decodes encoded nickname (/me), you need to define a mapping from CTCP type
(e.g. ACTION) to a custom format string. Do this by
passing an associative array as ctcp_messages. The keys
• 1 - mod encode
of the array are the CTCP type and the respective value • 2 - nickname decode
is the format message.
You can define "ident", "password", and "realname"
tokens which are sent to the IRC server by setting these See also: ircg_lookup_format_messages().
in an associative array. Pass that array as user_settings.
See also: ircg_disconnect(), ircg_is_conn_alive(),
ircg_set_current
ircg_register_format_messages().

(PHP 4 >= 4.0.4)


ircg_register_format_messages
ircg_set_current -- Set current connection for output

(PHP 4 >= 4.0.5)


Description
ircg_register_format_messages -- Register a format
message set
boolean ircg_set_current ( resource connection)
Description
Select the current HTTP connection for output in this
execution context. Every output sent from the server
boolean ircg_register_format_messages ( string connected to by connection will be copied to standard
name, array messages) output while using default formatting or a format
message set specified by
With ircg_register_format_messages() you can ircg_register_format_messages().
customize the way your IRC output looks like or which See also: ircg_register_format_messages().
script functions are invoked on the client side.
ircg_set_file

• Plain channel message


(PHP 4 >= 4.2.0)
• Private message received
ircg_set_file -- Set logfile for connection
• Private message sent
• Some user leaves channel Description
• Some user enters channel
• Some user was kicked from the channel bool ircg_set_file ( resource connection, string path)
• Topic has been changed
Function ircg_set_file() specifies a logfile path in which
• Error all output from connection connection will be logged.
• Fatal error Returns TRUE on success, otherwise FALSE.
• Join list end(?)
ircg_set_on_die
• Self part(?)
• Some user changes his nick
(PHP 4 >= 4.2.0)
• Some user quits his connection ircg_set_on_die -- Set action to be executed when
• Mass join begin connection dies

• Mass join element


Description
• Mass join end
• Whois user
bool ircg_set_on_die ( resource connection, string host,
• Whois server int port, string data)
• Whois idle
• Whois channel In case of the termination of connection connection IRCG
will connect to host at port (Note: host must be an IPv4
• Whois end address, IRCG does not resolve host-names due to
blocking issues), send data to the new host connection
• Voice status change on user
and will wait until the remote part closes connection. This
• Operator status change on user can be used to trigger a PHP script for example.
This feature requires IRCG 3.
• Banlist
• Banlist end
ircg_topic

• %f - from (PHP 4 >= 4.0.5)


• %t - to ircg_topic -- Set topic for channel on server

• %c - channel
Description
• %r - plain message
• %m - encoded message
boolean ircg_topic ( resource connection, string
• %j - js encoded message channel, string new_topic)
Change the topic for channel channel on the server Defaul Changeabl
connected to by connection to new_topic. Name
t e
PHP_INI_AL
ircg_whois java.home NULL
L
java.library. PHP_INI_AL
NULL
(PHP 4 >= 4.0.5) path L
ircg_whois -- Query server for user information
JAVALI PHP_INI_AL
java.library
B L
Description For further details and definition of the PHP_INI_*
constants see ini_set().
boolean ircg_whois ( resource connection, string nick)
Tipos de recursos
Sends a query to the connected server connection to ask
for information about the specified user nick.
Esta extensión no define ningún tipo de recurso.

XLVII. PHP / Java Integration


Constantes predefinidas

Introducción
Esta extensión no define ninguna constante.

There are two possible ways to bridge PHP and Java: you
can either integrate PHP into a Java Servlet environment, Ejemplos
which is the more stable and efficient solution, or
integrate Java support into PHP. The former is provided
by a SAPI module that interfaces with the Servlet server, Ejemplo 1. Java Example
the latter by this Java extension.
The Java extension provides a simple and effective
means for creating and invoking methods on Java objects <?php
from PHP. The JVM is created using JNI, and everything // get instance of Java class java.lang.System in
runs in-process. PHP
$system = new Java('java.lang.System');
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el // demonstrate property access
comportamineto de estas funciones, nombre de funciones print 'Java version='.$system-
y en definitiva TODO lo documentado aqui, puede cambiar >getProperty('java.version').' <br>';
en una futura version de PHP SIN AVISO. Quedas avisado, y print 'Java vendor=' .$system-
utilizar este módulo es tu responsabiliad. >getProperty('java.vendor').' <br>';
print 'OS='.$system->getProperty('os.name').'
'.
Requerimientos $system->getProperty('os.version').' on
'.
$system->getProperty('os.arch').'
You need a Java VM installed on your machine to use this <br>';
extension.
// java.util.Date example
$formatter = new
Instalación Java('java.text.SimpleDateFormat',
"EEEE, MMMM dd, yyyy 'at'
h:mm:ss a zzzz");
To include Java support in your PHP build you must add
the option --with-java[=DIR] where DIR points to the base print $formatter->format(new
install directory of your JDK. This extension can only be Java('java.util.Date'));
built as a shared dl. More build instructions for this ?>
extension can be found in php4/ext/java/README.
Ejemplo 2. AWT Example

Note to Win32 Users: In order to


enable this module on a Windows <?php
environment, you must copy jvm.dll // This example is only intented to be run
from the DLL folder of the as a CGI.
PHP/Win32 binary package to the
SYSTEM32 folder of your windows $frame = new Java('java.awt.Frame',
machine. (Ex:C:\WINNT\SYSTEM32 or 'PHP');
C:\WINDOWS\SYSTEM32) $button = new Java('java.awt.Button',
'Hello Java World!');

$frame->add('North', $button);
Configuración en tiempo de ejecución $frame->validate();
$frame->pack();
$frame->visible = True;
The behaviour of these functions is affected by settings
in php.ini. $thread = new Java('java.lang.Thread');
Tabla 1. Java configuration options $thread->sleep(10000);
Defaul Changeabl
Name $frame->dispose();
t e
?> • PHP has a habit of changing the working
Notes: directory. sapi/servlet will eventually change it
back, but while PHP is running the servlet
engine may not be able to load any classes
from the CLASSPATH which are specified using
• new Java() will create an instance of a class if a a relative directory syntax, or find the work
suitable constructor is available. If no directory used for administration and JSP
parameters are passed and the default compilation tasks.
constructor is useful as it provides access to
classes like java.lang.System which expose
most of their functionallity through static Tabla de contenidos
methods. java_last_exception_clear -- Clear last Java exception
• Accessing a member of an instance will first java_last_exception_get -- Get last Java exception
look for bean properties then public fields. In
other words, print $date.time will first attempt java_last_exception_clear
to be resolved as $date.getTime(), then as
$date.time.
(PHP 4 >= 4.0.2)
• Both static and instance members can be
java_last_exception_clear -- Clear last Java exception
accessed on an object with the same syntax.
Furthermore, if the java object is of type
java.lang.Class, then static members of the Description
class (fields and methods) can be accessed.
• Exceptions raised result in PHP warnings, and
void java_last_exception_clear ( void)
NULL results. The warnings may be eliminated
by prefixing the method call with an "@" sign.
The following APIs may be used to retrieve and Aviso
reset the last error:
o java_last_exception_get() Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
o java_last_exception_clear() y en definitiva TODO lo documentado aqui, puede cambiar
• Overload resolution is in general a hard
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
problem given the differences in types
between the two languages. The PHP Java See java_last_exception_get() for an example.
extension employs a simple, but fairly
effective, metric for determining which
overload is the best match. java_last_exception_get

Additionally, method names in PHP are not (PHP 4 >= 4.0.2)


case sensitive, potentially increasing the java_last_exception_get -- Get last Java exception
number of overloads to select from.
Description
Once a method is selected, the parameters are
cooerced if necessary, possibly with a loss of exception java_last_exception_get ( void)
data (example: double precision floating point
numbers will be converted to boolean).
Aviso

• In the tradition of PHP, arrays and hashtables


Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
may pretty much be used interchangably. Note
y en definitiva TODO lo documentado aqui, puede cambiar
that hashtables in PHP may only be indexed by
en una futura version de PHP SIN AVISO. Quedas avisado, y
integers or strings; and that arrays of primitive
utilizar este módulo es tu responsabiliad.
types in Java can not be sparse. Also note that
these constructs are passed by value, so may The following example demonstrates the usage of Java's
be expensive in terms of memory and time. exception handler from within PHP:
Ejemplo 1. Java exception handler

<?php
Java Servlet SAPI
$stack = new
Java('java.util.Stack');
The Java Servlet SAPI builds upon the mechanism defined $stack->push(1);
by the Java extension to enable the entire PHP processor
to be run as a servlet. The primary advanatage of this // This should succeed
from a PHP perspective is that web servers which support $result = $stack->pop();
servlets typically take great care in pooling and reusing $ex =
JVMs. Build instructions for the Servlet SAPI module can java_last_exception_get();
be found in php4/sapi/README. Notes: if (!$ex) print "$result\n";

// This should fail (error


• While this code is intended to be able to run on suppressed by @)
$result = @$stack->pop();
any servlet engine, it has only been tested on
$ex =
Apache's Jakarta/tomcat to date. Bug reports,
java_last_exception_get();
success stories and/or patches required to get
if ($ex) print $ex->toString();
this code to run on other engines would be
appreciated.
// Clear last exception echo "El resultado de la conexión es ".$ds."<p>";
java_last_exception_clear();
?> if ($ds) {
echo "Autentificandose ...";
$r=ldap_bind($ds); // Autentificación anónima,
XLVIII. Funciones LDAP típicamente con
// acceso de lectura
echo "El resultado de la autentificación es ".
Introducción a LDAP $r."<p>";

echo "Buscando (sn=P*) ...";


LDAP es el protocolo de acceso a directorios ligero // Busqueda de entradas por apellidos
(Lightweight Directory Access Protocol), un protocolo $sr=ldap_search($ds,"o=Mi Compañia, c=ES",
usado para acceder a "Servidores de Directorio". El "sn=P*");
directorio es una clase especial de base de datos que echo "El resultado de la búsqueda es ".$sr."<p>";
contiene información estructurada en forma de árbol.
El concepto es similar a la estructura de directorios de echo "El número de entradas devueltas es
los discos duros, pero en este caso, el directorio raiz es ".ldap_count_entries($ds,$sr)."<p>";
"El Mundo" y los subdirectorios de primer nivel son los
"países". Niveles inferiores de la estructura de directorio echo "Recuperando entradas ...<p>";
contienen entradas para compañías, organizaciones o $info = ldap_get_entries($ds, $sr);
lugares, y en niveles aún inferiores se encuentran las echo "Devueltos datos de ".$info["count"]."
entradas para la gente, y quizás de equipos informáticos entradas:<p>";
y documentos.
Para referirse a un fichero en un subdirectorio del disco for ($i=0; $i<$info["count"]; $i++) {
duro se usa algo como echo "dn es: ". $info[$i]["dn"] ."<br>";
echo "La primera entrada cn es: ". $info[$i]["cn"]
/usr/local/misapps/docs [0] ."<br>";
echo "La primera entrada email es: ". $info[$i]
Las barras marcan cada división en la referencia al ["mail"][0] ."<p>";
fichero, y la secuencia es leida de izquierda a derecha. }
El equivalente a la referencia a un fichero en LDAP es el
"distinguished name" (nombre distinguible), abreviado echo "Cerrando conexión";
como "db". Un ejemplo de dn podría ser. ldap_close($ds);
cn=Pedro Pérez,ou=Contabilidad,o=Mi Compañía,c=E } else {
S echo "<h4>Ha sido imposible conectar al servidor
LDAP</h4>";
Las comas marcan cada división en la referencia, y la }
secuencia se lee de derecha a izquierda. Este dn se ?>
leería como ..

country = ES
organization = Mi Compañía Usando las llamadas LDAP de PHP
organizationalUnit = Contabilidad
commonName = Pedro Pérez
Es necesario conseguir y compilar la librerías cliente de
LDAP ya sea del paquete ldap-3.3 de la Universidad de
De la misma manera que no hay reglas estrictas sobre
Michigan o del Netscape Directory SDK. También es
como organizar la estructura de directorios de un disco
necesario recompilar PHP con soporte LDAP activado
duro, un administrador de un servidor de directorio
para que la funciones LDAP de PHP funcionen.
puede establecer cualquier estructura que sea útil para
Antes de usarse las llamadas LDAP se debe saber ..
sus propósitos. Sin embargo hay algunos acuerdos
tácitos que siempre deben seguirse. El mensaje es que
no se puede escribir código para acceder un directorio si
no se conoce algo de su estructura, igual que no se • El nombre o dirección del servidor de directorio
puede usar una base de datos sin algún conocimiento que se va a usar
sobre lo que está disponible en ella. • El "dn base" del servidor (la parte del directorio
global contenida en ese servidor, que puede
ser por ejemplo "o=Mi Compañia,c=ES")
Ejemplo de código completo
• Si es necesaria contraseña para acceder al
servidor (muchos servidores ofrecen acceso de
Recuperar informacion para todas las entradas donde el lectura para usuarios anónimos pero requieren
apellido empiece por "P" de un servidor de directorio, un password para cualquier otro acceso)
mostrando un extracto con el nombre y dirección de
correo electrónico.
Ejemplo 1. ejemplo de búsqueda LDAP La secuencia típica de llamadas LDAP suele
implementarse en aplicaciones que siguen el siguiente
patrón:
<?php
// La secuencia básica para trabajar con LDAP es ldap_connect() // establecer la conexión con el servido
conectar, autentificarse, r
// buscar, interpretar el resultado de la búsqueda y |
cerrar la conexión. ldap_bind() // login anónimo o autentificado
|
echo "<h3>Prueba de consulta LDAP</h3>"; Hacer búsquedas o actualizaciones en el directorio
echo "Conectando ..."; y mostrar los resultados
$ds=ldap_connect("localhost"); // Debe ser un |
servidor LDAP válido! ldap_close() // Cerrar la conexión
Más información ldap_8859_to_t61

Mucha información acerca de LDAP puede ser consultada (PHP 4 >= 4.0.2)
en ldap_8859_to_t61 -- Translate 8859 characters to t61
characters

• Netscape
Description
• Universidad de Michigan
• Proyecto OpenLDAP string ldap_8859_to_t61 ( string value)
• LDAP World
Aviso
El SDK de Netscape contiene una Guía de Programación Esta función no está documentada actualmente, solamente
muy útil en formato html. se encuentra disponible la lista de parametros.
Tabla de contenidos
ldap_8859_to_t61 -- Translate 8859 characters to t61
characters
ldap_add
ldap_add -- Añade entradas a un directorio LDAP
ldap_bind -- Autentifica en un directorio LDAP
ldap_close -- Cierra una conexión a un servidor LDAP (PHP 3, PHP 4 )
ldap_compare -- Compare value of attribute found in ldap_add -- Añade entradas a un directorio LDAP
entry specified with DN
ldap_connect -- Conecta con un servidor LDAP
ldap_count_entries -- Cuenta el número de entradas de Descripción
una búsqueda
ldap_delete -- Borra una entrada de un directorio
ldap_dn2ufn -- Convierte un dn al formato User Friendly int ldap_add ( int identificador_de_conexion, string dn,
Naming array entrada)
ldap_err2str -- Convierte un código numérico de error
LDAP en un mensaje. Devuelve verdadero cuando finaliza correctamente y
ldap_errno -- Devuelve el código numérico de error para falso se produce un error.
el último comando LDAP. La función ldap_add() se usa para añadir entradas o
ldap_error -- Devuelte el mensaje de error del último registros a un directorio LDAP. El DN ("distinguished
comando LDAP name", nombre distinguible, la referencia de cualquier
ldap_explode_dn -- Divide un DN en las partes que le entrada LDAP) es especificado por dn. El array entrada
componen especifica la información que quiere añadirse. Los
ldap_first_attribute -- Devuelte el primer atributo valores del array son indexados por sus propios
ldap_first_entry -- Devuelve el identificador del primer atributos. En caso de valores múltiples para un mismo
resultado atributo, son indexados usando enteros empezando con
ldap_first_reference -- Return first reference 0.
ldap_free_result -- Libera la memoria que almacena los
resultados entry["atributo1"] = valor
ldap_get_attributes -- Obtiene los atributos de una entry["atributo2"][0] = valor1
entrada de un resultado de búsqueda entry["atributo2"][1] = valor2
ldap_get_dn -- Obtiene el DN de una entrada de un Ejemplo 1. Ejemplo completo con login atentificado
resultado
ldap_get_entries -- Obtiene todas las entradas de un
resultado <?php
ldap_get_option -- Get the current value for given option $ds=ldap_connect("localhost"); // Asumimos que el
ldap_get_values_len -- Obtiene todos los valores binarios servidor LDAP está en el
de un atributo de una entrada // servidor local
ldap_get_values -- Obtiene todos los valores de un
atributo de una entrada if ($ds) {
ldap_list -- Búsqueda Single-level (Nivel Único) // autentificarse con el dn apropiado para tener
ldap_mod_add -- Añade valores de atributos permisos de modificación
ldap_mod_del -- Borra valores de atributos $r=ldap_bind($ds,"cn=root, o=Mi Compañia, c=ES",
ldap_mod_replace -- Reemplaza valores de atributos "secreto");
ldap_modify -- Modifica una entrada LDAP
ldap_next_attribute -- Obtiene el siguiente atributo de // prepare data
una entrada $info["cn"]="Pedro Pérez";
ldap_next_entry -- Obtiene la siguiente entrada de un $info["sn"]="Pedro";
resultado $info["mail"]="pedro.p@algun.sitio";
ldap_next_reference -- Get next reference $info["objectclass"]="persona";
ldap_parse_reference -- Extract information from
reference entry // add data to directory
ldap_parse_result -- Extract information from result $r=ldap_add($ds, "cn=Pedro Pérez, o=Mi
ldap_read -- Lee una entrada Compañia, c=ES", $info);
ldap_rename -- Modify the name of an entry
ldap_search -- Busca en un arbol LDAP ldap_close($ds);
ldap_set_option -- Set the value of the given option } else {
ldap_set_rebind_proc -- Set a callback function to do re- echo "Ha sido imposible conectar al servidor LDAP";
binds on referral chasing. }
ldap_sort -- Sort LDAP result entries ?>
ldap_start_tls -- Start TLS
ldap_t61_to_8859 -- Translate t61 characters to 8859
characters
ldap_bind
ldap_unbind -- Hace logout de un directorio LDAP
(PHP 3, PHP 4 )
ldap_bind -- Autentifica en un directorio LDAP
// compare value
$r=ldap_compare($ds, $dn, $attr, $value);
Descripción
if ($r === -1) {
echo "Error: ".ldap_error($ds);
int ldap_bind ( int identificador_de_conexion [, string } elseif ($r === TRUE) {
rdn_del_usuario [, string contraseña]]) echo "Password correct.";
} elseif ($r === FALSE) {
echo "Wrong guess! Password incorrect.";
Se conecta a un directorio LDAP con un RDN y su
}
contraseña. Devuelve verdadero cuando finaliza
correctamente y falso se produce un error.
} else {
ldap_bind() se conecta al directorio con un determinado
echo "Unable to bind to LDAP server.";
usuario. rdn_de_usuario y contraseña son opcionales. Si
}
no son especificados, se intenta el acceso anónimo.
ldap_close($ds);
ldap_close
} else {
echo "Unable to connect to LDAP server.";
(PHP 3, PHP 4 ) }
ldap_close -- Cierra una conexión a un servidor LDAP ?>

Aviso
Descripción
ldap_compare() can NOT be used to compare BINARY
values!
int ldap_close ( int identificador_de_conexion)

Devuelve verdadero cuando finaliza correctamente y Nota: This function was added in
falso se produce un error. 4.0.2.
ldap_close() cierra la conexión con el servidor LDAP
asociada con el identificador_de_conexion especificado. ldap_connect
Esta llamada es idéntica internamente a ldap_unbind().
La API LDAP usa la llamada ldap_unbind(), y por lo
tanto quizás deba usar esta llamada en lugar de (PHP 3, PHP 4 )
ldap_close(). ldap_connect -- Conecta con un servidor LDAP

ldap_compare Descripción

(PHP 4 >= 4.0.2) int ldap_connect ( [string nombre_host [, int puerto]])


ldap_compare -- Compare value of attribute found in
entry specified with DN
Devuelve un identificador de conexión positivo en caso
de éxito, ó falso si ocurre algún error.
Description ldap_connect() establece una conexión con el servidor
LDAP especificado en nombre_host y puerto. Ambos
argumentos son opcionales. Si no se especifican, el
bool ldap_compare ( resource link_identifier, string dn, identificador de la conexión LDAP actualmente abierta es
string attribute, string value) devuelto. Si sólo es especificado nombre_host el puerto
tomado por defecto es el 389.
Returns TRUE if value matches otherwise returns
FALSE. Returns -1 on error. ldap_count_entries
ldap_compare() is used to compare value of attribute to
value of same attribute in LDAP directory entry specified
with dn. (PHP 3, PHP 4 )
The following example demonstrates how to check ldap_count_entries -- Cuenta el número de entradas de
whether or not given password matches the one defined una búsqueda
in DN specified entry.
Ejemplo 1. Complete example of password check
Descripción

<?php int ldap_count_entries ( int identificador_de_conexion,


int identificador_de_resultado)
$ds=ldap_connect("localhost"); // assuming the LDAP
server is on this host
Devuelve el número de entradas del resultado o falso si
if ($ds) { ha ocurrido algún error.
ldap_count_entries() devuelce el número de entradas
// bind almacenadas en el resultado de operaciones de
if(ldap_bind($ds)) { búsqueda previas. identificador_de_resultado identifica el
resultado ldap interno al que hacemos referencia.
// prepare data
$dn = "cn=Matti Meikku, ou=My Unit, o=My
Company, c=FI"; ldap_delete
$value = "secretpassword";
$attr = "password"; (PHP 3, PHP 4 )
ldap_delete -- Borra una entrada de un directorio Esta función devuelve el código numérico de error, que
está estandarizado, producido por el último comando
LDAP y en la conexión especificada. Este número puede
Descripción ser convertido en un mensaje textual de error usando
ldap_err2str().
A menos que decremente el nivel de alerta en su fichero
int ldap_delete ( int identificador_de_conexion, string
php3.ini (ó php.ini) o anteponga a los comandos LDAP en
dn)
símbolo @ (arroba) para suprimir las alertas y warnings,
los errores producidos serán mostrados
Devuelve verdadero cuando finaliza correctamente y automáticamente en el código HTML generado.
falso se produce un error. Ejemplo 1. Generando y capturando un error
La función ldap_delete() borra la entrada particular dn
del directorio LDAP.
<?php
// Este ejemplo contiene un error, que será
ldap_dn2ufn
capturado.
$ld = ldap_connect("localhost");
(PHP 3, PHP 4 ) $bind = ldap_bind($ld);
ldap_dn2ufn -- Convierte un dn al formato User Friendly // error de sintaxis en la expresión del filtro
Naming (codigo
// de error 87). Debería ser "objectclass=*".
$res = @ldap_search($ld, "o=Mi Compañía,
Descripción c=ES", "objectclass");
if (!$res) {
printf("LDAP-Código Error: %s<br>\n",
string ldap_dn2ufn ( string dn) ldap_errno($ld));
printf("LDAP-Mensaje Error: %s<br>\n",
La función ldap_dn2ufn() es usada para convertir un DN ldap_error($ld));
en un formato más amigable para el usuario. die("Argh!<br>\n");
}
$info = ldap_get_entries($ld, $res);
ldap_err2str printf("%d entradas encontradas.<br>\n",
$info["count"]);
?>
(PHP 3>= 3.0.13, PHP 4 )
ldap_err2str -- Convierte un código numérico de error Ver también ldap_err2str() y ldap_error().
LDAP en un mensaje.
ldap_error
Descripción
(PHP 3>= 3.0.12, PHP 4 )
string ldap_err2str ( int numerr) ldap_error -- Devuelte el mensaje de error del último
comando LDAP
Devuelve una cadena con el mensaje de error.
Esta función devuelve una cadena con el mensaje de Descripción
error explicativo del código numérico de error numerr.
Aunque los códigos de error LDAP están estandarizados,
diferentes librerías devuelven mensajes textuales de string ldap_error ( int identificador_de_conexión)
error diferentes o incluso localizados. Nunca se debe
comprobar la existencia de un error específico por el Devuelve una cadena con el mensaje de error.
mensaje textual, sino por el código numérico. Esta función devuelve una cadena con el mensaje de
Var también ldap_errno() y ldap_error(). error explicativo del error generado por el último
Ejemplo 1. Enumerando todos los mensajes de comando LDAP en la conexión especificada. Aunque los
error LDAP códigos de error LDAP están estandarizados, diferentes
librerías devuelven mensajes textuales de error
diferentes o incluso localizados. Nunca se debe
<?php comprobar la existencia de un error específico por el
for($i=0; $i<100; $i++) { mensaje textual, sino por el código numérico.
printf("Error $i: %s<br>\n", A menos que decremente el nivel de alerta en su fichero
ldap_str2err($i)); php3.ini (ó php.ini) o anteponga a los comandos LDAP en
} símbolo @ (arroba) para suprimir las alertas y warnings,
?> los errores producidos serán mostrados
automáticamente en el código HTML generado.
Ver también ldap_err2str() y ldap_errno().
ldap_errno

ldap_explode_dn
(PHP 3>= 3.0.12, PHP 4 )
ldap_errno -- Devuelve el código numérico de error para
el último comando LDAP. (PHP 3, PHP 4 )
ldap_explode_dn -- Divide un DN en las partes que le
componen
Descripción

Descripción
int ldap_errno ( int identificador_de_conexión)

array ldap_explode_dn ( string dn, int con_atributos)


Devuelve el código de error del último comando LDAP
para la conexión especificada.
La función ldap_explode_dn() es usada para dividir un Aviso
DN devuelto por ldap_get_dn() en las partes que le
componen. Cada parte es conocida como Relative Esta función no está documentada actualmente, solamente
Distinguished Name (Nombre Relativo Distinguible) se encuentra disponible la lista de parametros.
abreviado como RDN. ldap_explode_dn() devuelve un
array con todos esos componentes. con_atributos sirve
para especificar si los RDN se devuelven sólo como ldap_free_result
valores o con sus atributos también (es decir, en un
formato atributo=valor). Hay que poner with_attrib a 0
para obtener también los atributos y a 1 para obtener (PHP 3, PHP 4 )
sólo los valores. ldap_free_result -- Libera la memoria que almacena los
resultados

ldap_first_attribute
Descripción

(PHP 3, PHP 4 )
ldap_first_attribute -- Devuelte el primer atributo int ldap_free_result ( int identificador_de_resultado)

Devuelve verdadero cuando finaliza correctamente y


Descripción
falso se produce un error.
ldap_free_result() libera la memoria reservada
string ldap_first_attribute ( int internamente para almacenar el resultado de búsquedas
identificador_de_conexion, int LDAP asociada al identificador
identificador_de_entrada_en_resultado, int identificador_de_resultado. Toda la memoria de
identificador_ber) resultados es automáticamente liberada al finalizarse la
ejecución de un script.
Normalmente la memoria reservada para resultados ldap
Devuelte el primer atributo en la entrada o falso si ocurre se libera al final del script. En caso de que el script
algún error. realice sucesivas búsquedas que devuelvan conjuntos de
De manera similar a leer entradas, los atributos también resultados grandes, puede utilizarse ldap_free_result()
son leidos de uno en uno de una entrada en particular para mantener bajo el uso de memoria del script durante
del directorio. ldap_first_attribute() devuelve el primer su ejecución.
atributo en la entrada a la que apunta el
identificador_de_entrada_en_resultado El resto de los
atributos son obtenidos llamanda a la función ldap_get_attributes
ldap_next_attribute() sucesivamente. El parámetro
indetificador_ber es el identificador del puntero interno a
memoria. Es pasado por referencia. El mismo (PHP 3, PHP 4 )
indetificador_ber es pasado a la función ldap_get_attributes -- Obtiene los atributos de una
ldap_next_attribute() que modifica dicho puntero. entrada de un resultado de búsqueda
Ver también ldap_get_attributes()
Descripción
ldap_first_entry
array ldap_get_attributes ( int
(PHP 3, PHP 4 ) identificador_de_conexion, int
ldap_first_entry -- Devuelve el identificador del primer identificador_de_entrada_de_resultado)
resultado
Devuelve una completa información de la entrada en un
array multidimensional o falso en caso de error.
Descripción
La función ldap_get_attributes() es usada para
simplificar el leer atributos y valores de una entrada de
int ldap_first_entry ( int identificador_de_conexion, int un resultado de búsqueda. El valor de retorno es un
identificador_de_resultado) array multidimensional de atributos y sus valores.
Teniendo localizado una entrada específica en el
directorio se puede conseguir la información que
Devuelve el identificador de la primera entrada del contiene dicha entrada usando esta llamada. Puede usar
resultado ó falso en caso de error. esta función para aplicaciones que naveguen por las
Las entradas en un resultado LDAP son leidas entradas del directorio y/o cuando no se conoce la
secuencialmente usando las funciones estructura de las entradas del directorio. En otras
ldap_first_entry() y ldap_next_entry(). aplicaciones se busca un atributo específico, como la
ldap_first_entry() devuelve el identificador de la dirección de email o los apellidos y no importa el resto de
primera entrada del resultado. Este identificador es información contenida..
entonces suministrado a la rutina lap_next_entry() pata
obtener sucesivas entradas del resultado. valor_devuelto["count"] = número de atributos en la entr
Ver también ldap_get_entries(). ada
valor_devuelto[0] = primer atributo
ldap_first_reference valor_devuelto[n] = enésimo atributo

valor_devuelto["atributo"]["count"] = número de vaslores


(PHP 4 >= 4.0.5) del atributo
ldap_first_reference -- Return first reference valor_devuelto["atributo"][0] = primer valor del atributo
valor_devuelto["atributo"][i] = iésimo valor del atributo
Ejemplo 1. Mostrar la lista de atributos contenida
Description en una entrada específica de un directorio

resource ldap_first_reference ( resource link, resource


result) // $ds es un identificador de conexión al directorio
valor_devuelto[i]["atributo"]["count"] = número de valore
// $sr es un resultado de búsqueda válido de una
s para "atributo"
llamada
en la entrada iésima
// anterior a una de las funciones de búsqueda en
valor_devuelto[i]["atributo"][j] = jésimo valor de "atribut
directorios
o" en la entrada
// ldap.
iésima
Ver también ldap_first_entry() y ldap_next_entry()
$entrada = ldap_first_entry($ds, $sr);

$atributos = ldap_get_attributes($ds, $entrada); ldap_get_option

echo $atributos["count"]." atributos contenidos en


esta entrada:<p>"; (PHP 4 >= 4.0.4)
ldap_get_option -- Get the current value for given option
for ($i=0; $i<$atributos["count"]; $i++)
echo $atributos[$i]."<br>";
Description
Ver también ldap_first_attribute() y
ldap_next_attribute()
bool ldap_get_option ( resource link_identifier, int
option, mixed retval)
ldap_get_dn
Sets retval to the value of the specified option. Devuelve
(PHP 3, PHP 4 ) TRUE si todo fue bien, FALSE en caso de fallo.
ldap_get_dn -- Obtiene el DN de una entrada de un The parameter option can be one of: LDAP_OPT_DEREF,
resultado LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT,
LDAP_OPT_PROTOCOL_VERSION,
LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS,
Descripción LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME,
LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN.
These are described in draft-ietf-ldapext-ldap-c-api-xx.txt
string ldap_get_dn ( int indentificador_de_conexion, int
indentificador_de_entrada_de_resultado)
Nota: This function is only available
Devuelve el DN de la entrada del resultado o falso en when using OpenLDAP 2.x.x OR
caso de error. Netscape Directory SDK x.x, and was
La función ldap_get_dn() se utiliza para obtener el DN added in PHP 4.0.4
de una entrada de un resultado de búsqueda.
Ejemplo 1. Check protocol version
ldap_get_entries

// $ds is a valid link identifier for a directory server


(PHP 3, PHP 4 ) if (ldap_get_option($ds,
ldap_get_entries -- Obtiene todas las entradas de un LDAP_OPT_PROTOCOL_VERSION, $version))
resultado echo "Using protocol version $version";
else
echo "Unable to determine protocol version";
Descripción
See also ldap_set_option().

array ldap_get_entries ( int indentificador_de_conexion,


int indentificador_de_resultado) ldap_get_values_len

Devuelve una completa información de un resultado de (PHP 3>= 3.0.13, PHP 4 )


búsqueda en un array multidimensional o falso en caso ldap_get_values_len -- Obtiene todos los valores binarios
de error. de un atributo de una entrada
La función ldap_get_entries() es usada para simplificar
el leer múltiples entradas de de un resultado y después
leer sus atributos y multiples valores. Toda la Description
información es devuelta por una llamada a una función
en forma de array multidimensional. La estructura del
array es como se muestra más abajo. array ldap_get_values_len ( int
Los indices de atributos son convertidos a minúsculas. indentificador_de_conexion, int
(Los atributos de servidores de directorios son indentificador_de_entrada_de_resultado, string atributo)
indiferentes a las mayusculas/minusculas, pero no
cuando son usados como indices de arrays) Devuelve un array de valores del atributo o falso en caso
de error.
valor_devuelto["count"] = número de entradas del result La función ldap_get_values_len() se utiliza para
ado obtener todos los valores de un atributo de una entrada
valor_devuelto[0] : contiene los detalles de la primera en de un resultado de búsqueda. La entrada es especificada
trada por el indentificador_de_entrada_de_resultado. El número
de valores se almacena en el índice "count" del array
valor_devuelto[i]["dn"] = DN de la entrada iésima del re devuelto. Los valores individuales se almacenan con
sultado índices enteros en el array. El primer índice es 0.
Esta función se utiliza exactamente como
valor_devuelto[i]["count"] = número de atributos de la e ldap_get_values() salvo que permite manejar datos
ntrada iésima binarios y no cadenas de caracteres.
valor_devuelto[i][j] = jésimo atributo de la iésima entrad
a del resultado
ldap_get_values int ldap_list ( int identificador_de_conexion, string
dn_base, string filtro [, array atributos])

(PHP 3, PHP 4 )
ldap_get_values -- Obtiene todos los valores de un Devuelve un identificador de resultado de búsqueda o
atributo de una entrada falso en caso de error.
ldap_list() realiza la búsqueda según el filtro
especificado en el directorio con el alcance
Descripción LDAP_SCOPE_ONELEVEL.
LDAP_SCOPE_ONELEVEL significa que la búsqueda solo
devuelve información que se encuentre en el nivel
array ldap_get_values ( int identificador_de_conexion, inmediatamente inferior al dn_base especificado en la
int identificador_de_entrada_de_resultado, string llamada a la función. (Equivalente a ejecutar "ls" en un
atributo) unix y obtener un listado de ficheros y carpetas en el
directorio de trabajo actual.)
Devuelve un array de valores del atributo o falso en caso Esta llamada toma un cuarto parámetro opcional, que es
de error. un array de los atributos requeridos. Consulte las notas
La función ldap_get_values() se utiliza para obtener de la función ldap_search().
todos los valores de un atributo de una entrada. La Ejemplo 1. Produce una lista de todas las unidades
entrada del resultado es especificada por el organizativas de una compañía
identificador_de_entrada_de_resultado. El número de
valores se almacena en el índice "count" del array
devuelto. Los valores individuales se almacenan con // $ds es un identificador de conexión
índices enteros en el array. El primer índice es 0. válido.
Esta llamada necesita un
identificador_de_entrada_de_resultado, por lo que $dnbase = "o=Mi Compañía, c=ES";
necesita ser precedida por una de las llamadas de $solonecesito = array("ou");
búsqueda ldap y una llamada para obtener una entrada
en particular del resultado. $sr=ldap_list($ds, $dnbase, "ou=*",
La aplicación debe ser o bien programada $solonecesito);
específicamente para buscar ciertos atributos (como
apellidos o email) o bien utilizar la función $info = ldap_get_entries($ds, $sr);
ldap_get_attributes() para averiguar que atributos
existen para una entrada dada, antes de llamar a for ($i=0; $i<$info["count"]; $i++)
ldap_get_values(). echo $info[$i]["ou"][0] ;
LDAP permite mas de un valor para cada atributo, por lo
que se puede, por ejemplo, almacenar varias direcciones
de email para una persona en el directorio y nombrar a ldap_mod_add
ese atributo como "email"

valor_devuelto["count"] = número de valores del atributo (PHP 3>= 3.0.8, PHP 4 )


valor_devuelto[0] = primer valor del atributo ldap_mod_add -- Añade valores de atributos
valor_devuelto[i] = iésimo valor del atributo
Ejemplo 1. Listar todos los valores del atributo
"email" de una entrada de un directorio Descripción

int ldap_mod_add ( int identificador_de_conexion, string


// $ds es un identificador de conexión al directorio dn, array entrada)

// $sr es un resultado de búsqueda válido de una


llamada Devuelve verdadero cuando finaliza correctamente y
// anterior a una de las funciones de búsqueda en falso se produce un error.
directorios Esta función añadir uno o varios atributos al dn
// ldap. especificado. Realiza la modificación al nivel de atributos,
en vez de hacerlo al nivel de objetos. Las modificaciones
// $entrada es un identificador de entrada válido a nivel de objeto son propocionadas por la función
de una llamada ldap_add().
// anterior a una de las funciones que devuelven
una entrada de ldap_mod_del
// directorio

$valores = ldap_get_values($ds, (PHP 3>= 3.0.8, PHP 4 )


$entrada,"email"); ldap_mod_del -- Borra valores de atributos

echo $valores["count"]." direcciones de email para


esta entrada.<p>"; Descripción

for ($i=0; $i < $valores["count"]; $i++)


int ldap_mod_del ( int identificador_de_conexion, string
echo $valores[$i]."<br>";
dn, array entrada)

ldap_list returns TRUE on success and FALSE on error.


Esta función elimina atributos del dn especificado.
Realiza la modificación a nivel de atributos, en vez de
(PHP 3, PHP 4 ) hacerlo a nivel de objetos. Las modificaciones a nivel de
ldap_list -- Búsqueda Single-level (Nivel Único) objeto son proporcionadas por la función ldap_del().

Descripción ldap_mod_replace
(PHP 3>= 3.0.8, PHP 4 ) Devuelve el identificador de la siguiente entrada del
ldap_mod_replace -- Reemplaza valores de atributos resultado. Las entradas deben haber sido leidas al
principio con ldap_first_entry(). Si no hay más entradas
en el resultado devuelve falso.
Descripción La función ldap_next_entry() se utiliza para obtener las
entradas almacenadas en un resultado. Llamadas
sucesivas a la función ldap_next_entry() devuelven las
int ldap_mod_replace ( int identificador_de_conexion,
entradas una a una hasta que ya no queden más
string dn, array entrada)
entradas. La primera llamada a ldap_next_entry() se
realiza después de llamar a ldap_first_entry().
Devuelve verdadero cuando finaliza correctamente y Ver también ldap_get_entries()
falso se produce un error.
Esta función reemplaza atributos del dn especificado.
Realiza la modificación a nivel de atributos, en vez de ldap_next_reference
hacerlo a nivel de objetos. Las modificaciones a nivel de
objeto son proporcionadas por la función ldap_modify().
(PHP 4 >= 4.0.5)
ldap_next_reference -- Get next reference
ldap_modify
Description
(PHP 3, PHP 4 )
ldap_modify -- Modifica una entrada LDAP
resource ldap_next_reference ( resource link, resource
entry)
Descripción
Aviso
int ldap_modify ( int identificador_de_conexion, string
Esta función no está documentada actualmente, solamente
dn, array entrada)
se encuentra disponible la lista de parametros.

Devuelve verdadero cuando finaliza correctamente y


falso se produce un error. ldap_parse_reference
La función ldap_modify() se utiliza para modificar
entradas existentes en un directorio LDAP. La estructura
de la entrada es igual a la de ldap_add(). (PHP 4 >= 4.0.5)
ldap_parse_reference -- Extract information from
reference entry
ldap_next_attribute

Description
(PHP 3, PHP 4 )
ldap_next_attribute -- Obtiene el siguiente atributo de
una entrada bool ldap_parse_reference ( resource link, resource
entry, array referrals)

Descripción
Aviso
string ldap_next_attribute ( int Esta función no está documentada actualmente, solamente
identificador_de_conexion, int se encuentra disponible la lista de parametros.
identificador_de_entrada_de_resultado, int
identificador_ber)
ldap_parse_result
Devuelve el siguiente atributo de una entrada o falso en
caso de error. (PHP 4 >= 4.0.5)
ldap_next_attribute() es llamado para recuperar los ldap_parse_result -- Extract information from result
atributos de una entrada. El estado interno del puntero
es mantenido por el identificador_ber, que es pasado por
referencia a la función. La primera llamada a Description
ldap_next_attribute() es realizada con el
identificador_de_entrada_de_resultado devuelto por la
función ldap_first_attribute(). bool ldap_parse_result ( resource link, resource result,
Ver también ldap_get_attributes() int errcode, string matcheddn, string errmsg, array
referrals)

ldap_next_entry
Aviso
Esta función no está documentada actualmente, solamente
(PHP 3, PHP 4 )
se encuentra disponible la lista de parametros.
ldap_next_entry -- Obtiene la siguiente entrada de un
resultado
ldap_read
Descripción
(PHP 3, PHP 4 )
int ldap_next_entry ( int identificador_de_conexion, int ldap_read -- Lee una entrada
identificador_de_entrada_de_resultado)
Descripción
int ldap_read ( int identificador_de_conexión, string independientemente de que tipos de atributos sean
dn_base, string filtro [, array atributos]) solicitados.
También es necesario resaltar que algunos servidores de
directorio están configurados para devolver un cierto
Devuelve un identificador de resultado de búsqueda o
número de entradas como máximo. Si esto ocurre, el
falso en caso de error.
servidor indicará que solo devuelve un conjunto de
ldap_read() realiza la búsqueda según el filtro
resultados parcial.
especificado con alcance LDAP_SCOPE_BASE, por lo que
El filtro de búsqueda puede ser simple o avanzado,
es equivalente a leer cualquier entrada del directorio.
usando operadores booleanos en el formato descrito en
No se permiten filtros vacios. Si se pretende obtener
la documentación sobre LDAP (Consulte el Netscape
absolutamente toda la información, se debe usar un filtro
Directory SDK para obtener completa información sobre
del tipo "objectClass=*". Si conoce que tipos de entradas
filtros).
son usadas en el servidor de directorio es conveniente
El ejemplo de abajo recupera la unidad organizativa (ou),
usar el filtro apropiado, como por ejemplo
apellidos nombre común y dirección de email para todas
"objectClass=inetOrgPerson".
las personas de "Mi Compañía" donde los apellidos o el
Esta llamada toma un cuarto parámetro opcional que es
nombre común contiene la subcadena $persona. Este
un array de los atributos requeridos. Consulte las notas
ejemplo usa un filtro booleano para indicar al servidor
de la función ldap_search().
que busque la información en más de un atributo.
Ejemplo 1. Búsqueda LDAP
ldap_rename

// $ds es un identificador de conexión válido


(PHP 4 >= 4.0.5)
ldap_rename -- Modify the name of an entry // $persona es todo o parte del nombre de una
persona, por ejemplo "Pe"
Description
$dn = "o=Mi Compañía, c=ES";
$filtro="(|(sn=$persona*)(givenname=$persona*))";
bool ldap_rename ( resource link_identifier, string dn, $solonecesito = array( "ou", "sn", "givenname",
string newrdn, string newparent, bool deleteoldrdn) "mail");

$sr=ldap_search($ds, $dn, $filtro, $solonecesito);


The entry specified by dn is renamed/moved. The new
RDN is specified by newrdn and the new parent/superior $info = ldap_get_entries($ds, $sr);
entry is specified by newparent. If the parameter
deleteoldrdn is TRUE the old RDN value(s) is removed, print $info["count"]." entradas devueltas<p>";
else the old RDN value(s) is retained as non-distinguished
values of the entry. Devuelve TRUE si todo fue bien,
FALSE en caso de fallo.
ldap_set_option

Nota: This function currently only


(PHP 4 >= 4.0.4)
works with LDAPv3. You may have to
ldap_set_option -- Set the value of the given option
use ldap_set_option() prior to
binding to use LDAPv3. This function
is only available when using Description
OpenLDAP 2.x.x OR Netscape
Directory SDK x.x, and was added in
PHP 4.0.5. bool ldap_set_option ( resource link_identifier, int
option, mixed newval)

ldap_search
Sets the value of the specified option to be newval.
Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
(PHP 3, PHP 4 ) on error.
ldap_search -- Busca en un arbol LDAP The parameter option can be one of: LDAP_OPT_DEREF,
LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT,
LDAP_OPT_PROTOCOL_VERSION,
Descripción LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS,
LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME,
int ldap_search ( int identificador_de_conexion, string LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN,
LDAP_OPT_SERVER_CONTROLS,
dn_base, string filtro [, array atributos])
LDAP_OPT_CLIENT_CONTROLS. Here's a brief description,
see draft-ietf-ldapext-ldap-c-api-xx.txt for details.
Devuelve un identificador de resultado de búsqueda o The options LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT,
falso en caso de error. LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION
ldap_search() realiza la búsqueda según el filtro and LDAP_OPT_ERROR_NUMBER have integer value,
especificado con alcance LDAP_SCOPE_SUBTREE. Esto es LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have
equivalente a buscar en el directorio entero. dn_base boolean value, and the options LDAP_OPT_HOST_NAME,
especifica el DN base para el directorio. LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN
Existe un cuarto parámetro opcional que puede ser have string value. The first example illustrates their use.
añadido para restringir los atributos y valores devueltos The options LDAP_OPT_SERVER_CONTROLS and
por el servidor a sólo los requeridos. Es mucho más LDAP_OPT_CLIENT_CONTROLS require a list of controls,
eficiente que la acción por defecto (que devolverá todos this means that the value must be an array of controls. A
los atributos y sus valores asociados). El uso del cuarto control consists of an oid identifying the control, an
parámetro debe ser por tanto considerado una práctica optional value, and an optional flag for criticality. In PHP
recomendable. a control is given by an array containing an element with
El cuerto parámetro es un array estándar de PHP con los the key oid and string value, and two optional elements.
atributos requeridos, por ejemplo The optional elements are key value with string value
array("email","sn","cn"). Nota: "dn" siempre es devuelto and key iscritical with boolean value. iscritical defaults to
FALSE if not supplied. See also the second example ldap_start_tls -- Start TLS
below.

Description
Nota: This function is only available
when using OpenLDAP 2.x.x OR
Netscape Directory SDK x.x, and was bool ldap_start_tls ( resource link)
added in PHP 4.0.4.
Aviso
Ejemplo 1. Set protocol version Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

// $ds is a valid link identifier for a directory


server ldap_t61_to_8859
if (ldap_set_option($ds,
LDAP_OPT_PROTOCOL_VERSION, 3))
echo "Using LDAPv3"; (PHP 4 >= 4.0.2)
else ldap_t61_to_8859 -- Translate t61 characters to 8859
echo "Failed to set protocol version to 3"; characters
Ejemplo 2. Set server controls
Description

// $ds is a valid link identifier for a directory server


// control with no value string ldap_t61_to_8859 ( string value)
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical"
=> TRUE);
// iscritical defaults to FALSE Aviso
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => Esta función no está documentada actualmente, solamente
"magic"); se encuentra disponible la lista de parametros.
// try to set both controls
if (!ldap_set_option($ds,
LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2))) ldap_unbind
echo "Failed to set server controls";
See also ldap_get_option().
(PHP 3, PHP 4 )
ldap_unbind -- Hace logout de un directorio LDAP
ldap_set_rebind_proc
Descripción
(PHP 4 >= 4.2.0)
ldap_set_rebind_proc -- Set a callback function to do re-
binds on referral chasing. int ldap_unbind ( int identificador_de_conexion)

Devuelve verdadero cuando finaliza correctamente y


Description falso se produce un error.
La función ldap_unbind() hace logout, desautentifica de
bool ldap_set_rebind_proc ( resource link, string un directorio LDAP.
callback)
XLIX. Funciones de Correo
Aviso
Esta función no está documentada actualmente, solamente The mail() Funciones que permiten enviar correo.
se encuentra disponible la lista de parametros. Tabla de contenidos
ezmlm_hash -- Calculate the hash value needed by
EZMLM
ldap_sort mail -- Envía correo

(PHP 4 >= 4.2.0) ezmlm_hash


ldap_sort -- Sort LDAP result entries
(PHP 3>= 3.0.17, PHP 4 >= 4.0.2)
Description ezmlm_hash -- Calculate the hash value needed by
EZMLM

bool ldap_sort ( resource link, resource result, string


sortfilter) Description

int ezmlm_hash ( string addr)


Aviso
Esta función no está documentada actualmente, solamente ezmlm_hash() calculates the hash value needed when
se encuentra disponible la lista de parametros. keeping EZMLM mailing lists in a MySQL database.
Ejemplo 1. Calculating the hash and subscribing a
user
ldap_start_tls

(PHP 4 >= 4.2.0) $user = "joecool@example.com";


mailparse_rfc822_parse_addresses -- Parse addresses
$hash = ezmlm_hash ($user);
and returns a hash containing that data
$query = sprintf ("INSERT INTO sample VALUES (%s,
mailparse_stream_encode -- Streams data from source
'%s')", $hash, $user);
file pointer, apply encoding and write to destfp
$db->query($query); // using PHPLIB db interface
mailparse_uudecode_all -- Scans the data from fp and
extract each embedded uuencoded file. Returns an array
listing filename information
mail

mailparse_determine_best_xfer_encoding
(PHP 3, PHP 4 )
mail -- Envía correo
(4.1.0 - 4.1.2 only)
mailparse_determine_best_xfer_encoding -- Figures out
Descripción the best way of encoding the content read from the file
pointer fp, which must be seek-able
bool mail ( string para, string sobre, string mensaje [,
string cabeceras_adicionales]) Description

mail() envía automáticamente el mensaje especificado


en mensage al destinatario especificado en para. Para int mailparse_determine_best_xfer_encoding
especificar múltiples destinatarios se puede hacer ( resource fp)
incluyendo una coma entre las direcciones en para.
Ejemplo 1. Enviando correo.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
mail("pepito@loquesea.es", "Sobre este tema", "Linea comportamineto de estas funciones, nombre de funciones
1\nLinea 2\nLinea 3"); y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Si se añadiera una cadena como cuarto argumento, esta utilizar este módulo es tu responsabiliad.
cadena sería enviada al final de la cabecera. Esto se usa
normalmente para enviar cabeceras extra en los Aviso
mensajes. Si se desea enviar varias cabeceras extra el
mecanismo será el mismo separándolas una linea. Esta función no está documentada actualmente, solamente
Ejemplo 2. Enviando correo con varias cabeceras. se encuentra disponible la lista de parametros.

mail("pepito@loquesea.es", "El tema", $message, mailparse_msg_create


"From: webmaster@$SERVER_NAME\nReply-To:
webmaster@$SERVER_NAME\nX-Mailer: PHP/" . (4.1.0 - 4.1.2 only)
phpversion()); mailparse_msg_create -- Returns a handle that can be
used to parse a message

L. mailparse functions
Description

Introducción
int mailparse_msg_create ( void)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Tabla de contenidos
mailparse_determine_best_xfer_encoding -- Figures out Aviso
the best way of encoding the content read from the file
Esta función no está documentada actualmente, solamente
pointer fp, which must be seek-able
se encuentra disponible la lista de parametros.
mailparse_msg_create -- Returns a handle that can be
used to parse a message
mailparse_msg_extract_part_file -- Extracts/decodes a
message section, decoding the transfer encoding mailparse_msg_extract_part_file
mailparse_msg_extract_part -- Extracts/decodes a
message section. If callbackfunc is not specified, the (4.1.0 - 4.1.2 only)
contents will be sent to "stdout" mailparse_msg_extract_part_file -- Extracts/decodes a
mailparse_msg_free -- Frees a handle allocated by message section, decoding the transfer encoding
mailparse_msg_crea
mailparse_msg_get_part_data -- Returns an associative
array of info about the message Description
mailparse_msg_get_part -- Returns a handle on a given
section in a mimemessage
mailparse_msg_get_structure -- Returns an array of mime string mailparse_msg_extract_part_file ( resource
section names in the supplied message rfc2045, string filename [, string callbackfunc])
mailparse_msg_parse_file -- Parse file and return a
resource representing the structure
mailparse_msg_parse -- Incrementally parse data into Aviso
buffer Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el
en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones
utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar
Aviso en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mailparse_msg_extract_part

(4.1.0 - 4.1.2 only) mailparse_msg_get_part


mailparse_msg_extract_part -- Extracts/decodes a
message section. If callbackfunc is not specified, the
(4.1.0 - 4.1.2 only)
contents will be sent to "stdout"
mailparse_msg_get_part -- Returns a handle on a given
section in a mimemessage
Description
Description
void mailparse_msg_extract_part ( resource rfc2045,
string msgbody [, string callbackfunc])
int mailparse_msg_get_part ( resource rfc2045, string
mimesection)
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Aviso
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y
Aviso utilizar este módulo es tu responsabiliad.

Esta función no está documentada actualmente, solamente Aviso


se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mailparse_msg_free
mailparse_msg_get_structure
(4.1.0 - 4.1.2 only)
mailparse_msg_free -- Frees a handle allocated by
(4.1.0 - 4.1.2 only)
mailparse_msg_crea
mailparse_msg_get_structure -- Returns an array of mime
section names in the supplied message
Description
Description
void mailparse_msg_free ( resource rfc2045buf)
array mailparse_msg_get_structure ( resource
Aviso rfc2045)

Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el
en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones
utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar
Aviso en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mailparse_msg_get_part_data

(4.1.0 - 4.1.2 only) mailparse_msg_parse_file


mailparse_msg_get_part_data -- Returns an associative
array of info about the message
(4.1.0 - 4.1.2 only)
mailparse_msg_parse_file -- Parse file and return a
Description resource representing the structure

array mailparse_msg_get_part_data ( resource Description


rfc2045)
resource mailparse_msg_parse_file ( string filename)
Aviso Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.

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

mailparse_msg_parse mailparse_uudecode_all

(4.1.0 - 4.1.2 only) (no version information, might be only in CVS)


mailparse_msg_parse -- Incrementally parse data into mailparse_uudecode_all -- Scans the data from fp and
buffer extract each embedded uuencoded file. Returns an array
listing filename information

Description
Description

void mailparse_msg_parse ( resource rfc2045buf,


string data) array mailparse_uudecode_all ( resource fp)

Aviso Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.

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

mailparse_rfc822_parse_addresses LI. Funciones matemáticas

(4.1.0 - 4.1.2 only) Introducción


mailparse_rfc822_parse_addresses -- Parse addresses
and returns a hash containing that data
Estas funciones matemáticas solo manejan valores
dentro de los rangos de los tipos long y double de su
Description ordenador. Si necesita manejar números mayores, pege
un vistazo a funciones matemáticas de precisión
arbitraria.
array mailparse_rfc822_parse_addresses ( string
addresses)
Constantes matemáticas
Aviso
Los siguientes valores estan definidos como constantes
Este módulo es EXPERIMENTAL. Esto significa que el
en PHP por la extensión matemática:
comportamineto de estas funciones, nombre de funciones
Tabla 1. Constantes matemáticas
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y Consta
Valor Descripción
utilizar este módulo es tu responsabiliad. nte

Aviso 3.14159265358979 El valor de ¶


M_PI
323846 (pi)
Esta función no está documentada actualmente, solamente
Tabla de contenidos
se encuentra disponible la lista de parametros.
abs -- Valor absoluto
acos -- Arco coseno
acosh -- Inverse hyperbolic cosine
mailparse_stream_encode asin -- Arco seno
asinh -- Inverse hyperbolic sine
(4.1.0 - 4.1.2 only) atan2 -- Arco tangente de dos variables
mailparse_stream_encode -- Streams data from source atan -- Arco tangente
file pointer, apply encoding and write to destfp atanh -- Inverse hyperbolic tangent
base_convert -- Convierte un número entre bases
arbitrarias
Description BinDec -- binario a decimal
ceil -- Redondea fracciones hacia arriba
cos -- coseno
bool mailparse_stream_encode ( resource sourcefp, cosh -- Hyperbolic cosine
resource destfp, string encoding) DecBin -- decimal a binario
DecHex -- decimal a hexadecimal (PHP 4 >= 4.1.0)
DecOct -- decimal a octal acosh -- Inverse hyperbolic cosine
deg2rad -- Converts the number in degrees to the radian
equivalent
exp -- e elevado a... Description
expm1 -- Returns exp(number) - 1, computed in a way
that is accurate even when the value of number is close float acosh ( float arg)
to zero
floor -- redondea fracciones hacia abajo
fmod -- Returns the floating point remainder (modulo) of Returns the inverse hyperbolic cosine of arg, i.e. the
the division of the arguments value whose hyperbolic cosine is arg.
getrandmax -- Muestra el mayor valor aleatorio posible
HexDec -- hexadecimal a decimal
hypot -- Returns sqrt( num1*num1 + num2*num2) Nota: Esta función no está
is_finite -- implementada en plataformas
is_infinite -- Windows.
is_nan --
lcg_value -- Combined linear congruential generator See also acos(), asinh() and atanh().
log10 -- Logaritmo en base-10
log1p -- Returns log(1 + number), computed in a way
that accurate even when the val ue of number is close to asin
zero
log -- Logaritmo natural
max -- encuentra el valor mayor (PHP 3, PHP 4 )
min -- encuentra el valor menor asin -- Arco seno
mt_getrandmax -- muestra el mayor valor aleatorio
posible
Descripción
mt_rand -- genera un valor aleatorio mejorado
mt_srand -- Introduce la semilla del generador de
números aleatorios mejorado float asin ( float arg)
OctDec -- octal a decimal
pi -- devuelve el valor de pi
pow -- expresión exponencial Devuelve el arco seno de arg en radianes.
rad2deg -- Converts the radian number to the equivalent Vea también acos() y atan().
number in degrees
rand -- genera un valor aleatorio asinh
round -- Redondea un float.
sin -- seno
sinh -- Hyperbolic sine (PHP 4 >= 4.1.0)
sqrt -- Raíz cuadrada asinh -- Inverse hyperbolic sine
srand -- introduce la semilla del generador de números
aleatorios
tan -- tangente Description
tanh -- Hyperbolic tangent
float asinh ( float arg)
abs
Returns the inverse hyperbolic sine of arg, i.e. the value
(PHP 3, PHP 4 ) whose hyperbolic sine is arg.
abs -- Valor absoluto
Nota: Esta función no está
Descripción implementada en plataformas
Windows.

mixed abs ( mixed number)


See also asin(), acosh() and atanh().

Devuelve el valor absoluto de un número. Si el número


del argumento es decimal, el tipo de retorno también es atan2
decimal, de otra manera devuelve un entero.
(PHP 3>= 3.0.5, PHP 4 )
acos atan2 -- Arco tangente de dos variables

(PHP 3, PHP 4 ) Descripción


acos -- Arco coseno
float atan2 ( float y, float x)
Descripción
Esta función calcula la arco tangente de las dos variables
float acos ( float arg) x e y. Es similar a el cálculo de la arco tangente de y / x,
excepto que los signos de ambos argumentos son usados
para determinar el cuadrante del resultado
Devuelve el arco coseno de arg en radianes. La función devuelve el resultado en radianes, el cual está
Vea también asin() y atan(). entre -PI y PI (inclusive).
Vea también acos() y atan().
acosh
atan
(PHP 3, PHP 4 ) BinDec convierte un número binario en un número
atan -- Arco tangente decimal. El mayor número que puede ser convertido son
31 bits de unos o 2147483647 en decimal.
Vea también la función decbin() .
Descripción

ceil
float atan ( float arg)

(PHP 3, PHP 4 )
Devuelve la arco tangente de arg en radianes.
ceil -- Redondea fracciones hacia arriba
Vea también acos() y atan().

Descripción
atanh

int ceil ( float number)


(PHP 4 >= 4.1.0)
atanh -- Inverse hyperbolic tangent
Devuelve el valor entero superior más cercano a number.
El uso de ceil() con enteros es una perdida de tiempo
Description absoluta.
NOTA: PHP/FI 2's ceil() devuelve un float. Use: $new =
(double)ceil($number); para tener el comportamiento
float atanh ( float arg)
antiguo.
Vea también floor() y round().
Returns the inverse hyperbolic tangent of arg, i.e. the
value whose hyperbolic tangent is arg.
cos

Nota: Esta función no está


implementada en plataformas (PHP 3, PHP 4 )
Windows. cos -- coseno

See also atan(), asinh() and acosh(). Descripción

base_convert float cos ( float arg)

Devuelve el coseno de arg en radianes.


(PHP 3>= 3.0.6, PHP 4 )
Vea también sin() y tan().
base_convert -- Convierte un número entre bases
arbitrarias
cosh
Descripción
(PHP 4 >= 4.1.0)
cosh -- Hyperbolic cosine
strin base_convert ( string number, int frombase, int
tobase)
Description
Devuelve una cadena conteniendo el number
representado en base tobase. La base en la cual number
float cosh ( float arg)
es dado viene especificada en frombase. Tanto frombase
y tobase tienen que estar entre 2 y 36, inclusive. Los
dígitos en números con una base mayor que 10 serán Returns the hyperbolic cosine of arg, defined as
representados con las letras a-z, a vale 10, b vale 11 y z (exp(arg) + exp(-arg))/2.
vale 36. See also cos(), acosh(), sin() and tan().
Ejemplo 1. base_convert()

DecBin
$binary =
base_convert($hexadecimal, 16, (PHP 3, PHP 4 )
2); DecBin -- decimal a binario

BinDec Descripción

(PHP 3, PHP 4 ) string decbin ( int number)


BinDec -- binario a decimal
Devuelve una cadena conteniendo la representación en
binario de el número dado en el argumento. El número
Descripción
mayor que puede ser convertido es 2147483647 en
decimal que resulta una cadena de 31 unos.
int bindec ( string binary_string) Vea también la función bindec() .

Devuelve el equivalente decimal del número binario DecHex


representado por el argumento binary_string.
(PHP 3, PHP 4 ) float expm1 ( float number)
DecHex -- decimal a hexadecimal

Aviso
Descripción
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
string dechex ( int number) 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 una cadena conteniendo la representación
hexadecimal del número dado en el argumento. El mayor Aviso
número que puede ser convertido es 2147483647 en
decimal resultando "7fffffff". Esta función no está documentada actualmente, solamente
Vea también la función hexdec() . se encuentra disponible la lista de parametros.

DecOct floor

(PHP 3, PHP 4 ) (PHP 3, PHP 4 )


DecOct -- decimal a octal floor -- redondea fracciones hacia abajo

Descripción Descripción

string decoct ( int number) float floor ( float number)

Devuelve una cadena conteniendo la representación Devuelve el valor entero inferior más cercano a number.
octal del número dado en el argumento. Returns a string El uso de floor() con enteros es una perdida de tiempo
containing an octal representation of the given number absoluta.
argument. El mayor número que puede ser ocnvertido es NOTA: PHP/FI 2's floor() devuelve un float. Use: $new =
2147483647 en decimal resultando "17777777777". Vea (double)floor($number); para tener el comportamiento
también octdec(). antiguo.
Vea también ceil() y round().
deg2rad
fmod
(PHP 3>= 3.0.4, PHP 4 )
deg2rad -- Converts the number in degrees to the radian (PHP 4 >= 4.2.0)
equivalent fmod -- Returns the floating point remainder (modulo) of
the division of the arguments
Description
Description
float deg2rad ( float number)
float fmod ( float x, float y)
This function converts number from degrees to the
radian equivalent. Returns the floating point remainder of dividing the
See also rad2deg(). dividend (x) by the divisor (y). The reminder (r) is defined
as: x = i * y + r, for some integer i. If y is non-zero, r has
the same sign as x and a magnitude less than the
exp
magnitude of y.
Ejemplo 1. Using fmod()
(PHP 3, PHP 4 )
exp -- e elevado a...
$x = 5.7;
$y = 1.3;
Descripción $r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3
+ 0.5 = 5.7
float exp ( float arg)

Devuelve el número e elevado a la potencia de arg. getrandmax


Vea también pow().

(PHP 3, PHP 4 )
expm1 getrandmax -- Muestra el mayor valor aleatorio posible

(PHP 4 >= 4.1.0) Descripción


expm1 -- Returns exp(number) - 1, computed in a way
that is accurate even when the value of number is close
to zero int getrandmax ( void)

Description Devuelve el valor máximo que puede devolver una


llamada a rand().
Vea también rand(), srand() mt_rand(), mt_srand() y
mt_getrandmax().
HexDec is_nan --

(PHP 3, PHP 4 ) Description


HexDec -- hexadecimal a decimal

bool is_nan ( float val)


Descripción
Returns TRUE if val is 'not a number', like the result of
int hexdec ( string hex_string) acos(1.01).

Devuelve el equivalente decimal de el número lcg_value


hexadecimal representado por el argumento hex_string.
HexDec convierte una cadena hexadecimal en un
número decimal. El número mayor que puede ser (PHP 4 )
convertido es 7fffffff o 2147483647 en decimal. lcg_value -- Combined linear congruential generator
Vea también la función dechex() .
Description
hypot
float lcg_value ( void)
(PHP 4 >= 4.1.0)
hypot -- Returns sqrt( num1*num1 + num2*num2) lcg_value() returns a pseudo random number in the
range of (0, 1). The function combines two CGs with
periods of 2^31 - 85 and 2^31 - 249. The period of this
Description
function is equal to the product of both primes.

float hypot ( float num1, float num2)


log10

Aviso (PHP 3, PHP 4 )


Este módulo es EXPERIMENTAL. Esto significa que el log10 -- Logaritmo en base-10
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
Descripción
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
float log10 ( float arg)
Aviso
Esta función no está documentada actualmente, solamente Devuelve el logaritmo en base-10 de arg.
se encuentra disponible la lista de parametros.

log1p
is_finite
(PHP 4 >= 4.1.0)
(PHP 4 >= 4.2.0) log1p -- Returns log(1 + number), computed in a way
is_finite -- that accurate even when the val ue of number is close to
zero

Description
Description

bool is_finite ( float val)


float log1p ( float number)
Returns TRUE if val is a legal finite number within the
allowed range for a PHP float on this platform. Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
is_infinite 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
(PHP 4 >= 4.2.0)
utilizar este módulo es tu responsabiliad.
is_infinite --
Aviso
Description Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
bool is_infinite ( float val)
log
Returns TRUE if val is infinite (positive or negative), like
the result of log(0) or any value too big to fit into a float
on this platform. (PHP 3, PHP 4 )
log -- Logaritmo natural

is_nan
Descripción

(PHP 4 >= 4.2.0)


float log ( float arg) Descripción

Devuelve el logaritmo de arg. int mt_rand ( [int min [, int max]])

max Muchos generadores de números aleatorios de libcs


antiguas tienen características dudosas o desconocidas y
son lentas. Por defecto, PHP usa el generador de
(PHP 3, PHP 4 ) números aleatorios de libc con la función rand(). La
max -- encuentra el valor mayor función mt_rand() es un reemplazo para esta. Usa un
generador de números aleatorios con características
conocidas, el Tornado de Mersenne, que es capaz de
Descripción
producir números aleatorios que incluso se pueden
emplear para propósitos criptográficos y es cuatro veces
mixed max ( mixed arg1, mixed arg2, mixed argn) más rápido que la media de los que provee libc. La
página principal del Tornado de Mersenne puede
encontrarse en
max() devuelve el número mayor de los valores de los http://www.math.keio.ac.jp/~matumoto/emt.html, y una
parámetros. versión optimizada del código del TM esta disponible en
Si el primer parámetro es un array, max() devuelve el http://www.scp.syr.edu/~marc/hawk/twister.html.
mayor valor en ese array. Si el primer parámetro es un Si es llamada sin los parámetros opcionales min y max
entero, string o double, necesita al menos dos mt_rand() devuelve un valor pseudo-aleatorio entre 0 y
parámetros y max() devuelve el mayor número de estos RAND_MAX. Si quiere un número aleatorio entre 5 y 15
valores. Puede comparar un número ilimitado de valores. (inclusive), use mt_rand(5,15).
Si uno o más de los valores es un double, todos los Recuerde introducir la semilla del generador de números
valores serán tratados como doubles, y devolverá un aleatorios antes de usar la instrucción con mt_srand().
double. Si ninguno de los valores es un double, todos Vea también mt_srand(), mt_getrandmax(), srand(),
ellos serán tratados como enteros, y se devolverá un rand() y getrandmax().
entero.

mt_srand
min

(PHP 3>= 3.0.6, PHP 4 )


(PHP 3, PHP 4 ) mt_srand -- Introduce la semilla del generador de
min -- encuentra el valor menor números aleatorios mejorado

Descripción Descripción

mixed min ( mixed arg1, mixed arg2, mixed argn) void mt_srand ( int seed)

min() returns the numerically lowest of the parameter Introduce la semilla seed en el generador de números
values. aleatorios mejorado.
Si el primer parámetro es un array, min() devuelve el
menor valor en ese array. Si el primer parámetro es un // seed son los microsegundos desde el último
entero, string o double, necesita al menos dos segundo "entero"
parámetros y min() devuelve el número menor de estos mt_srand((double)microtime()*1000000);
valores. Puede comparar un número ilimitado de valores. $randval = mt_rand();
Si uno o más de los valores es un double, todos los Vea también mt_rand(), mt_getrandmax(), srand(),
valores serán tratados como doubles, y devolverá un rand() y getrandmax().
double. Si ninguno de los valores es un double, todos
ellos serán tratados como enteros, y se devolverá un
entero. OctDec

mt_getrandmax (PHP 3, PHP 4 )


OctDec -- octal a decimal
(PHP 3>= 3.0.6, PHP 4 )
mt_getrandmax -- muestra el mayor valor aleatorio Descripción
posible

int octdec ( string octal_string)


Descripción
Devuelve el equivalente decimal del número octal
int mt_getrandmax ( void) representado por el argumento octal_string. OctDec
convierte una cadena octal en un número decimal. El
mayor número que puede ser convertido es
Devuelve el valor máximo que se puede obtener con una 17777777777 o 2147483647 en decimal.
llamada a mt_rand(). Vea también decoct().
Vea también mt_rand(), mt_srand() rand(), srand() y
getrandmax().
pi
mt_rand
(PHP 3, PHP 4 )
pi -- devuelve el valor de pi
(PHP 3>= 3.0.6, PHP 4 )
mt_rand -- genera un valor aleatorio mejorado
Descripción
$foo == 4.0
Vea también ceil() y floor().
double pi ( void)

sin
Devuelve una aproximación de pi.

(PHP 3, PHP 4 )
pow
sin -- seno

(PHP 3, PHP 4 )
Descripción
pow -- expresión exponencial

float sin ( float arg)


Descripción

Devuelve el seno de arg en radianes.


float pow ( float base, float exp) Vea también cos() y tan().

Devuelve base elevado a la potencia de exp.


sinh
Vea también exp().

(PHP 4 >= 4.1.0)


rad2deg
sinh -- Hyperbolic sine

(PHP 3>= 3.0.4, PHP 4 )


Description
rad2deg -- Converts the radian number to the equivalent
number in degrees
float sinh ( float arg)
Description
Returns the hyperbolic sine of arg, defined as (exp(arg) -
exp(-arg))/2.
float rad2deg ( float number) See also sin(), asinh(), cos() and tan().

This function converts number from radian to degrees.


sqrt
See also deg2rad().

(PHP 3, PHP 4 )
rand
sqrt -- Raíz cuadrada

(PHP 3, PHP 4 )
Descripción
rand -- genera un valor aleatorio

float sqrt ( float arg)


Descripción

Devuelve la raíz cuadrada de arg.


int rand ( [int min [, int max]])

srand
Si es llamada sin los argumentos opcionales min y max,
rand() devuelve un valor pseudo-aleatorio entre 0 y
RAND_MAX. Si quiere un número aleatorio entre 5 y 15 (PHP 3, PHP 4 )
(inclusive), por ejemplo, use rand(5,15). srand -- introduce la semilla del generador de números
Recuerde introducir la semilla del generador de números aleatorios
aleatorios antes de usar srand().
Vea también srand(), getrandmax(), mt_rand(),
mt_srand() y mt_getrandmax(). Descripción

round void srand ( int seed)

(PHP 3, PHP 4 ) Inicializa el generador de números aleatorios con seed.


round -- Redondea un float. // seed son los microsegundos desde el último
segundo "entero"
srand((double)microtime()*1000000);
Descripción $randval = rand();
Vea también rand(), getrandmax(), mt_rand(),
double round ( double val) mt_srand() y mt_getrandmax().

Devuelve el valor redondeado de val. tan


$foo = round( 3.4 ); //
$foo == 3.0
$foo = round( 3.5 ); // (PHP 3, PHP 4 )
$foo == 4.0 tan -- tangente
$foo = round( 3.6 ); //
Descripción character encoding and character
encoding issues.

float tan ( float arg)


Nota: If you use databases with
PHP, it is recommended that you use
Devuelve la tangente de arg en radianes.
the same character encoding for
Vea también sin() y cos().
both database and internal encoding
for ease of use and better
tanh performance.

(PHP 4 >= 4.1.0) If you are using PostgreSQL, it


tanh -- Hyperbolic tangent supports character encoding that is
different from backend character
encoding. See the PostgreSQL
Description manual for details.

float tanh ( float arg)

Instalación
Returns the hyperbolic tangent of arg, defined as
sinh(arg)/cosh(arg).
See also tan(), atanh(), sin() and cos(). mbstring is an extended module. You must enable the
module with the configure script. Refer to the Install
section for details.
LII. Multi-Byte String Functions
The following configure options are related to the
mbstring module.
Introducción

• --enable-mbstring: Enable mbstring functions.


There are many languages in which all characters can be This option is required to use mbstring
expressed by single byte. Multi-byte character codes are functions.
used to express many characters for many languages.
mbstring is developed to handle Japanese characters.
However, many mbstring functions are able to handle Nota: As of PHP 4.3.0, the
character encoding other than Japanese. option --enable-mbstring
A multi-byte character encoding represents single will be enabled by default
character with consecutive bytes. Some character and replaced with --with-
encoding has shift(escape) sequences to start/end multi- mbstring[=LANG] to
byte character strings. Therefore, a multi-byte character support Chinese, Korean
string may be destroyed when it is divided and/or and Russian language
counted unless multi-byte character encoding safe support. Japanese
method is used. This module provides multi-byte character encoding is
character safe string functions and other utility functions supported by default. If
such as conversion functions. --with-mbstring=cn is
Since PHP is basically designed for ISO-8859-1, some used, simplified chinese
multi-byte character encoding does not work well with encoding will be
PHP. Therefore, it is important to set supported. If --with-
mbstring.internal_encoding to a character encoding that mbstring=tw is used,
works with PHP. traditional chinese
PHP4 Character Encoding Requirements encoding will be
supported. If --with-
mbstring=kr is used,
• Per byte encoding korean encoding will be
supported. If --with-
• Single byte characters in range of 00h-7fh mbstring=ru is used,
which is compatible with ASCII russian encoding will be
• Multi-byte characters without 00h-7fh supported. If --with-
mbstring=all is added, all
supported character
These are examples of internal character encoding that encoding in mbstring will
works with PHP and does NOT work with PHP. be enabled, but the binary
Character encodings work with size of PHP will be
PHP: maximized because of
ISO-8859-*, EUC-JP, UTF-8 huge Unicode character
maps. Note that Chinese,
Character encodings do NOT Korean and Russian
work with PHP: encoding is experimentally
JIS, SJIS supported in PHP 4.3.0.

Character encoding, that does not work with PHP, may be


converted with mbstring's HTTP input/output conversion • --enable-mbstr-enc-trans : Enable HTTP input
feature/function. character encoding conversion using mbstring
conversion engine. If this feature is enabled,
Nota: SJIS should not be used for HTTP input character encoding may be
internal encoding unless the reader converted to mbstring.internal_encoding
is familiar with parser/compiler, automatically.
Nota: As of PHP 4.3.0, the overload, 1: Overload mail() function, 2:
option --enable-mbstr-enc- Overload str*() functions, 4: Overload ereg*()
trans will be eliminated functions.
and replaced with
mbstring.encoding_transla
tion. HTTP input character Web Browsers are supposed to use the same character
encoding conversion is encoding when submitting form. However, browsers may
enabled when this is set to not use the same character encoding. See
On (the default is Off). mb_http_input() to detect character encoding used by
browsers.
If enctype is set to multipart/form-data in HTML forms,
mbstring does not convert character encoding in POST
• --enable-mbregex: Enable regular expression
data. The user must convert them in the script, if
functions with multibyte character support.
conversion is needed.
Although, browsers are smart enough to detect character
encoding in HTML. charset is better to be set in HTTP
header. Change default_charset according to character
Configuración en tiempo de ejecución encoding.
Ejemplo 1. php.ini setting example

The behaviour of these functions is affected by settings


in php.ini. ; Set default language
Tabla 1. Multi-Byte String configuration options mbstring.language = English; Set default
Defa language to English (default)
Name Changeable mbstring.language = Japanese; Set default
ult
language to Japanese
mbstring.language NULL PHP_INI_ALL
mbstring.detect_order NULL PHP_INI_ALL ;; Set default internal encoding
;; Note: Make sure to use character encoding works
mbstring.http_input NULL PHP_INI_ALL with PHP
mbstring.http_output NULL PHP_INI_ALL mbstring.internal_encoding = UTF-8 ; Set internal
encoding to UTF-8
mbstring.internal_enc
NULL PHP_INI_ALL
oding ;; HTTP input encoding translation is enabled.
mbstring.script_encodi mbstring.encoding_translation = On
NULL PHP_INI_ALL
ng
;; Set default HTTP input character encoding
mbstring.substitute_c ;; Note: Script cannot change http_input setting.
NULL PHP_INI_ALL
haracter mbstring.http_input = pass ; No conversion.
mbstring.func_overloa PHP_INI_SYSTE mbstring.http_input = auto ; Set HTTP input to
"0" auto
d M
; "auto" is expanded to
mbstring.encoding_tra "ASCII,JIS,UTF-8,EUC-JP,SJIS"
"0" PHP_INI_ALL
nslation mbstring.http_input = SJIS ; Set HTTP2 input to
For further details and definition of the PHP_INI_* SJIS
constants see ini_set(). mbstring.http_input = UTF-8,SJIS,EUC-JP ;
Here is a short explanation of the configuration Specify order
directives.
;; Set default HTTP output character encoding
mbstring.http_output = pass ; No conversion
• mbstring.language defines default language mbstring.http_output = UTF-8 ; Set HTTP output
used in mbstring. Note that this option defines encoding to UTF-8
mbstring.interanl_encoding and
mbstring.interanl_encoding should be placed ;; Set default character encoding detection order
after mbstring.language in php.ini mbstring.detect_order = auto ; Set detect order
to auto
• mbstring.encoding_translation enables HTTP mbstring.detect_order = ASCII,JIS,UTF-8,SJIS,EUC-
input character encoding detection and JP ; Specify order
translation into internal chatacter encoding.
• mbstring.internal_encoding defines default ;; Set default substitute character
internal character encoding. mbstring.substitute_character = 12307 ; Specify
Unicode value
• mbstring.http_input defines default HTTP input mbstring.substitute_character = none ; Do not print
character encoding. character
• mbstring.http_output defines default HTTP mbstring.substitute_character = long ; Long
output character encoding. Example: U+3000,JIS+7E7E

• mbstring.detect_order defines default Ejemplo 2. php.ini setting for EUC-JP users


character code detection order. See also
mb_detect_order().
;; Disable Output Buffering
• mbstring.substitute_character defines output_buffering = Off
character to substitute for invalid character
encoding. ;; Set HTTP header charset
• mbstring.func_overloadoverload(replace) default_charset = EUC-JP
single byte functions by mbstring functions.
mail(), ereg(), etc. are overloaded by ;; Set default language to
mb_send_mail(), mb_ereg(), etc. Possible Japanese
values are 0, 1, 2, 4 or a combination of them. mbstring.language = Japanese
For example, 7 for overload everything. 0: No
data. If it is the case, strings are needed to be converted
to internal character encoding.
;; HTTP input encoding translation
is enabled.
mbstring.encoding_translation =
On • HTTP Input

;; Set HTTP input encoding


There is no way to control HTTP input
conversion to auto
character conversion from PHP script. To
mbstring.http_input = auto
disable HTTP input character conversion, it has
to be done in php.ini.
;; Convert HTTP output to EUC-JP
mbstring.http_output = EUC-JP
Ejemplo 4. Disable HTTP input conversion in php.ini
;; Set internal encoding to EUC-JP
mbstring.internal_encoding =
EUC-JP ;; Disable HTTP Input conversion
mbstring.http_input = pass
;; Do not print invalid characters ;; Disable HTTP Input conversion (PHP
mbstring.substitute_character = 4.3.0 or higher)
none mbstring.encoding_translation = Off
Ejemplo 3. php.ini setting for SJIS users

When using PHP as an Apache module, it is


;; Enable Output Buffering possible to override PHP ini setting per Virtual
output_buffering = On Host in httpd.conf or per directory with
.htaccess. Refer to the Configuration section
;; Set mb_output_handler to enable and Apache Manual for details.
output conversion
output_handler =
mb_output_handler • HTTP Output

;; Set HTTP header charset


default_charset = Shift_JIS There are several ways to enable output
character encoding conversion. One is using
;; Set default language to Japanese php.ini, another is using ob_start() with
mbstring.language = Japanese mb_output_handler() as ob_start callback
function.
;; Set http input encoding conversion to
auto
mbstring.http_input = auto Nota: For PHP3-i18n
users, mbstring's output
;; Convert to SJIS conversion differs from
mbstring.http_output = SJIS PHP3-i18n. Character
encoding is converted
;; Set internal encoding to EUC-JP using output buffer.
mbstring.internal_encoding = EUC-JP
Ejemplo 5. php.ini setting example
;; Do not print invalid characters
mbstring.substitute_character = none
;; Enable output character encoding conversion
for all PHP pages
Tipos de recursos
;; Enable Output Buffering
output_buffering = On
Esta extensión no define ningún tipo de recurso.
;; Set mb_output_handler to enable output
conversion
Constantes predefinidas
output_handler = mb_output_handler
Ejemplo 6. Script example
Estas constantes están definidas por esta extensión y
estarán disponibles solamente cuando la extensión ha
sido o bien compilada dentro de PHP o grabada <?php
dinamicamente en tiempo de ejecución.
MB_OVERLOAD_MAIL (integer) // Enable output character encoding conversion
MB_OVERLOAD_STRING (integer) only for this page
MB_OVERLOAD_REGEX (integer)
// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');
HTTP Input and Output
// Start buffering and specify
HTTP input/output character encoding conversion may "mb_output_handler" as
convert binary data also. Users are supposed to control // callback function
character encoding conversion if binary data is used for ob_start('mb_output_handler');
HTTP input/output.
If enctype for HTML form is set to multipart/form-data, ?>
mbstring does not convert character encoding in POST
Supported Character Encodings value of
original overloaded
mbstring.func_overloa
function function
Currently, the following character encoding is supported d
by the mbstring module. Character encoding may be strtoupper( mb_strtoupper(
specified for mbstring functions' encoding parameter. 2
) )
The following character encoding is supported in this PHP
extension: substr_coun mb_substr_cou
2
UCS-4, UCS-4BE, UCS-4LE, UCS-2, UCS-2BE, UCS-2LE, t() nt()
UTF-32, UTF-32BE, UTF-32LE, UCS-2LE, UTF-16, UTF- 4 ereg() mb_ereg()
16BE, UTF-16LE, UTF-8, UTF-7, ASCII, EUC-JP, SJIS, eucJP-
win, SJIS-win, ISO-2022-JP, JIS, ISO-8859-1, ISO-8859-2, 4 eregi() mb_eregi()
ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO- ereg_replac mb_ereg_repla
8859-7, ISO-8859-8, ISO-8859-9, ISO-8859-10, ISO-8859- 4
e() ce()
13, ISO-8859-14, ISO-8859-15, byte2be, byte2le,
byte4be, byte4le, BASE64, 7bit, 8bit and UTF7-IMAP. eregi_repla mb_eregi_repla
4
As of PHP 4.3.0, the following character encoding support ce() ce()
will be added experimentaly : EUC-CN, CP936, HZ, EUC- 4 split() mb_split()
TW, CP950, BIG-5, EUC-KR, UHC (CP949), ISO-2022-KR,
Windows-1251 (CP1251), Windows-1252 (CP1252),
CP866, KOI8-R.
Basics of Japanese multi-byte characters
php.ini entry, which accepts encoding name, accepts
"auto" and "pass" also. mbstring functions, which accepts
encoding name, and accepts "auto". Most Japanese characters need more than 1 byte per
If "pass" is set, no character encoding conversion is character. In addition, several character encoding
performed. schemas are used under a Japanese environment. There
If "auto" is set, it is expanded to "ASCII,JIS,UTF-8,EUC- are EUC-JP, Shift_JIS(SJIS) and ISO-2022-JP(JIS) character
JP,SJIS". encoding. As Unicode becomes popular, UTF-8 is used
See also mb_detect_order() also. To develop Web applications for a Japanese
environment, it is important to use the character set for
the task in hand, whether HTTP input/output, RDBMS and
Nota: "Supported character
E-mail.
encoding" does not mean that it
works as internal character code.

• Storage for a character can be up to six bytes


• A multi-byte character is usually twice of the
Overloading PHP string functions with multi byte width compared to single-byte characters.
string functions Wider characters are called "zen-kaku" -
meaning full width, narrower characters are
called "han-kaku" - meaning half width. "zen-
Because almost PHP application written for language kaku" characters are usually fixed width.
using single-byte character encoding, there are some
difficulties for multibyte string handling including
• Some character encoding defines shift(escape)
sequence for entering/exiting multi-byte
japanese. Almost PHP string functions such as substr() character strings.
do not support multibyte string.
Multibyte extension (mbstring) has some PHP string • ISO-2022-JP must be used for SMTP/NNTP.
functions with multibyte support (ex. substr() supports
mb_substr()).
• "i-mode" web site is supposed to use SJIS.
Multibyte extension (mbstring) also supports 'function
overloading' to add multibyte string functionality without
code modification. Using function overloading, some PHP
string functions will be oveloaded multibyte string References
functions. For example, mb_substr() is called instead of
substr() if function overloading is enabled. Function
overload makes easy to port application supporting only Multi-byte character encoding and its related issues are
single-byte encoding for multibyte application. very complex. It is impossible to cover in sufficient detail
mbstring.func_overload in php.ini should be set some here. Please refer to the following URLs and other
positive value to use function overloading. The value resources for further readings.
should specify the category of overloading functions,
sbould be set 1 to enable mail function overloading. 2 to
enable string functions, 4 to regular expression functions. • Unicode/UTF/UCS/etc
For example, if is set for 7, mail, strings, regex functions
should be overloaded. The list of overloaded functions
are shown in below. http://www.unicode.org/
Tabla 2. Functions to be overloaded
value of
mbstring.func_overloa
original overloaded • Japanese/Korean/Chinese character
function function information
d
1 mail() mb_send_mail()
ftp://ftp.ora.com/pub/examples/nutshell/ujip/do
2 strlen() mb_strlen() c/cjk.inf
2 strpos() mb_strpos()
2 strrpos() mb_strrpos() Tabla de contenidos
mb_convert_case -- Perform case folding on a string
2 substr() mb_substr()
mb_convert_encoding -- Convert character encoding
mb_strtolower( mb_convert_kana -- Convert "kana" one from another
2 strtolower()
) ("zen-kaku" ,"han-kaku" and more)
mb_convert_variables -- Convert character code in Description
variable(s)
mb_decode_mimeheader -- Decode string in MIME header
field string mb_convert_case ( string str, int mode [, string
mb_decode_numericentity -- Decode HTML numeric encoding])
string reference to character
mb_detect_encoding -- Detect character encoding mb_convert_case() returns case folded version of
mb_detect_order -- Set/Get character encoding detection string converted in the way specified by mode.
order mode can be one of MB_CASE_UPPER, MB_CASE_LOWER
mb_encode_mimeheader -- Encode string for MIME or MB_CASE_TITLE.
header encoding specifies the encoding of str; if omitted, the
mb_encode_numericentity -- Encode character to HTML internal character encoding value will be used.
numeric string reference The return value is str with the appropriate case folding
mb_ereg_match -- Regular expression match for applied.
multibyte string By contrast to the standard case folding functions such
mb_ereg_replace -- Replace regular expression with as strtolower() and strtoupper(), case folding is
multibyte support performed on the basis of the Unicode character
mb_ereg_search_getpos -- Returns start point for next properties. Thus the behaviour of this function is not
regular expression match affected by locale settings and it can convert any
mb_ereg_search_getregs -- Retrive the result from the characters that have 'alphabetic' property, such as A-
last multibyte regular expression match umlaut (Ä).
mb_ereg_search_init -- Setup string and regular For more information about the Unicode properties,
expression for multibyte regular expression match please see http://www.unicode.org/unicode/reports/tr21/.
mb_ereg_search_pos -- Return position and length of Ejemplo 1. mb_convert_case() example
matched part of multibyte regular expression for
predefined multibyte string
mb_ereg_search_regs -- Returns the matched part of $str = "mary had a Little lamb and she loved it so";
multibyte regular expression $str = mb_convert_case($str, MB_CASE_UPPER, "UTF-
mb_ereg_search_setpos -- Set start point of next regular 8");
expression match print $str; # Prints MARY HAD A LITTLE LAMB AND
mb_ereg_search -- Multibyte regular expression match SHE LOVED IT SO
for predefined multibyte string $str = mb_convert_case($str, MB_CASE_TITLE, "UTF-
mb_ereg -- Regular expression match with multibyte 8");
support print $str; # Prints Mary Had A Little Lamb And She
mb_eregi_replace -- Replace regular expression with Loved It So
multibyte support ignoring case
mb_eregi -- Regular expression match ignoring case with See also mb_strtolower(), mb_strtoupper(),
multibyte support strtolower(), strtoupper().
mb_get_info -- Get internal settings of mbstring
mb_http_input -- Detect HTTP input character encoding
mb_convert_encoding
mb_http_output -- Set/Get HTTP output character
encoding
mb_internal_encoding -- Set/Get internal character (PHP 4 >= 4.0.6)
encoding mb_convert_encoding -- Convert character encoding
mb_language -- Set/Get current language
mb_output_handler -- Callback function converts
character encoding in output buffer Description
mb_parse_str -- Parse GET/POST/COOKIE data and set
global variable
mb_preferred_mime_name -- Get MIME charset string string mb_convert_encoding ( string str, string to-
mb_regex_encoding -- Returns current encoding for encoding [, mixed from-encoding])
multibyte regex as string
mb_regex_set_options -- Set/Get the default options for mb_convert_encoding() converts character encoding
mbregex functions of string str from from-encoding to to-encoding.
mb_send_mail -- Send encoded mail. str : String to be converted.
mb_split -- Split multibyte string using regular expression from-encoding is specified by character code name
mb_strcut -- Get part of string before conversion. it can be array or string - comma
mb_strimwidth -- Get truncated string with specified separated enumerated list. If it is not specified, the
width internal encoding will be used.
mb_strlen -- Get string length Ejemplo 1. mb_convert_encoding() example
mb_strpos -- Find position of first occurrence of string in
a string
mb_strrpos -- Find position of last occurrence of a string /* Convert internal character encoding to SJIS */
in a string $str = mb_convert_encoding($str, "SJIS");
mb_strtolower -- Make a string lowercase
mb_strtoupper -- Make a string uppercase /* Convert EUC-JP to UTF-7 */
mb_strwidth -- Return width of string $str = mb_convert_encoding($str, "UTF-7", "EUC-JP");
mb_substitute_character -- Set/Get substitution character
mb_substr_count -- Count the number of substring /* Auto detect encoding from JIS, eucjp-win, sjis-win,
occurrences then convert str to UCS-2LE */
mb_substr -- Get part of string $str = mb_convert_encoding($str, "UCS-2LE", "JIS,
eucjp-win, sjis-win");
mb_convert_case
/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
(PHP 4 >= 4.3.0) See also: mb_detect_order().
mb_convert_case -- Perform case folding on a string

mb_convert_kana
(PHP 4 >= 4.0.6) mb_convert_variables() convert character encoding of
mb_convert_kana -- Convert "kana" one from another variables vars in encoding from-encoding to encoding to-
("zen-kaku" ,"han-kaku" and more) encoding. It returns character encoding before
conversion for success, FALSE for failure.
mb_convert_variables() join strings in Array or Object
Description to detect encoding, since encoding detection tends to fail
for short strings. Therefore, it is impossible to mix
encoding in single array or object.
string mb_convert_kana ( string str, string option [,
It from-encoding is specified by array or comma
mixed encoding])
separated string, it tries to detect encoding from from-
coding. When encoding is omitted, detect_order is used.
mb_convert_kana() performs "han-kaku" - "zen-kaku" vars (3rd and larger) is reference to variable to be
conversion for string str. It returns converted string. This converted. String, Array and Object are accepted.
function is only useful for Japanese. mb_convert_variables() assumes all parameters have
option is conversion option. Default value is "KV". the same encoding.
encoding is character encoding. If it is omitted, internal Ejemplo 1. mb_convert_variables() example
character encoding is used.
Applicable Conversion Options
/* Convert variables $post1, $post2 to internal
option : Specify with conversion of following options. encoding */
Default "KV" $interenc = mb_internal_encoding();
"r" : Convert "zen-kaku" alphabets to "han-kaku" $inputenc = mb_convert_variables($interenc,
"R" : Convert "han-kaku" alphabets to "zen-kaku" "ASCII,UTF-8,SJIS-win", $post1, $post2);
"n" : Convert "zen-kaku" numbers to "han-kaku"
"N" : Convert "han-kaku" numbers to "zen-kaku"
"a" : Convert "zen-kaku" alphabets and numbers to mb_decode_mimeheader
"han-kaku"
"A" : Convert "han-kaku" alphabets and numbers to
"zen-kaku" (PHP 4 >= 4.0.6)
(Characters included in "a", "A" options are mb_decode_mimeheader -- Decode string in MIME header
U+0021 - U+007E excluding U+0022, U+0027, field
U+005C, U+007E)
"s" : Convert "zen-kaku" space to "han-kaku" Description
(U+3000 -> U+0020)
"S" : Convert "han-kaku" space to "zen-kaku"
(U+0020 -> U+3000) string mb_decode_mimeheader ( string str)
"k" : Convert "zen-kaku kata-kana" to "han-kaku
kata-kana"
"K" : Convert "han-kaku kata-kana" to "zen-kaku mb_decode_mimeheader() decodes encoded-word
kata-kana" string str in MIME header.
"h" : Convert "zen-kaku hira-gana" to "han-kaku kata- It returns decoded string in internal character encoding.
kana" See also mb_encode_mimeheader().
"H" : Convert "han-kaku kata-kana" to "zen-kaku hira-
gana" mb_decode_numericentity
"c" : Convert "zen-kaku kata-kana" to "zen-kaku hira-
gana"
"C" : Convert "zen-kaku hira-gana" to "zen-kaku kata- (PHP 4 >= 4.0.6)
kana" mb_decode_numericentity -- Decode HTML numeric
"V" : Collapse voiced sound notation and convert string reference to character
them into a character. Use with "K","H"
Ejemplo 1. mb_convert_kana() example Description

/* Convert all "kana" to "zen-kaku" "kata- string mb_decode_numericentity ( string str, array
kana" */ convmap [, string encoding])
$str = mb_convert_kana($str, "KVC");
Convert numeric string reference of string str in specified
/* Convert "han-kaku" "kata-kana" to "zen- block to character. It returns converted string.
kaku" "kata-kana" array is array to specifies code area to convert.
and "zen-kaku" alpha-numeric to "han- encoding is character encoding. If it is omitted, internal
kaku" */ character encoding is used.
$str = mb_convert_kana($str, "KVa"); Ejemplo 1. convmap example

mb_convert_variables $convmap = array (


int start_code1, int end_code1, int
(PHP 4 >= 4.0.6) offset1, int mask1,
mb_convert_variables -- Convert character code in int start_code2, int end_code2, int
variable(s) offset2, int mask2,
........
int start_codeN, int end_codeN, int
Description offsetN, int maskN );
// Specify Unicode value for start_codeN
and end_codeN
string mb_convert_variables ( string to-encoding, // Add offsetN to value and take bit-wise
mixed from-encoding, mixed vars) 'AND' with maskN,
// then convert value to numeric string
Nota: UTF-8, UTF-7, ASCII, EUC-
reference.
JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-
See also: mb_encode_numericentity(). 2022-JP

mb_detect_encoding For ISO-8859-*, mbstring always


detects as ISO-8859-*.
(PHP 4 >= 4.0.6)
mb_detect_encoding -- Detect character encoding For UTF-16, UTF-32, UCS2 and UCS4,
encoding detection will fail always.
Description
Ejemplo 1. Useless detect order example
string mb_detect_encoding ( string str [, mixed
encoding-list])
; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8
mb_detect_encoding() detects character encoding in
string str. It returns detected character encoding. ; Always detect as UTF-8, since
encoding-list is list of character encoding. Encoding order ASCII/UTF-7 values are
may be specified by array or comma separated list ; valid for UTF-8
string. detect_order = UTF-8, ASCII, UTF-7
If encoding_list is omitted, detect_order is used.
Ejemplo 2. mb_detect_order() examples
Ejemplo 1. mb_detect_encoding() example

/* Set detection order by


/* Detect character encoding with current
enumerated list */
detect_order */
mb_detect_order("eucjp-win,sjis-
echo mb_detect_encoding($str);
win,UTF-8");
/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-
/* Set detection order by array */
JP,SJIS" */
$ary[] = "ASCII";
echo mb_detect_encoding($str, "auto");
$ary[] = "JIS";
$ary[] = "EUC-JP";
/* Specify encoding_list character encoding by
mb_detect_order($ary);
comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-
/* Display current detection order
win");
*/
echo implode(", ",
/* Use array to specify encoding_list */
mb_detect_order());
$ary[] = "ASCII";
$ary[] = "JIS"; See also mb_internal_encoding(), mb_http_input(),
$ary[] = "EUC-JP"; mb_http_output() mb_send_mail().
echo mb_detect_encoding($str, $ary);
See also: mb_detect_order(). mb_encode_mimeheader

mb_detect_order (PHP 4 >= 4.0.6)


mb_encode_mimeheader -- Encode string for MIME
header
(PHP 4 >= 4.0.6)
mb_detect_order -- Set/Get character encoding detection
order Description

Description string mb_encode_mimeheader ( string str [, string


charset [, string transfer-encoding [, string linefeed]]])
array mb_detect_order ( [mixed encoding-list])
mb_encode_mimeheader() converts string str to
encoded-word for header field. It returns converted string
mb_detect_order() sets automatic character encoding
in ASCII encoding.
detection order to encoding-list. It returns TRUE for
charset is character encoding name. Default is ISO-2022-
success, FALSE for failure.
JP.
encoding-list is array or comma separated list of
transfer-encoding is transfer encoding. It should be one
character encoding. ("auto" is expanded to "ASCII, JIS,
of "B" (Base64) or "Q" (Quoted-Printable). Default is "B".
UTF-8, EUC-JP, SJIS")
linefeed is end of line marker. Default is "\r\n" (CRLF).
If encoding-list is omitted, it returns current character
Ejemplo 1. mb_convert_kana() example
encoding detection order as array.
This setting affects mb_detect_encoding() and
mb_send_mail().
$name = ""; // kanji
$mbox = "kru";
Nota: mbstring currently $doma = "gtinn.mon";
implements following encoding $addr = mb_encode_mimeheader($name, "UTF-7",
detection filters. If there is a invalid "Q") . " <" . $mbox . "@" . $doma . ">";
byte sequence for following echo $addr;
encoding, encoding detection will
See also mb_decode_mimeheader().
fail.
mb_encode_numericentity Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
(PHP 4 >= 4.0.6) comportamineto de estas funciones, nombre de funciones
mb_encode_numericentity -- Encode character to HTML y en definitiva TODO lo documentado aqui, puede cambiar
numeric string reference en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Description mb_ereg_match() returns TRUE if string matches
regular expression pattern, FALSE if not.
The internal encoding or the character encoding
string mb_encode_numericentity ( string str, array specified in mb_regex_encoding() will be used as
convmap [, string encoding]) character encoding.

mb_encode_numericentity() converts specified Nota: This function is supported in


character codes in string str from HTML numeric PHP 4.2.0 or higher.
character reference to character code. It returns
converted string.
array is array specifies code area to convert. See also: mb_regex_encoding(), mb_ereg().
encoding is character encoding.
Ejemplo 1. convmap example
mb_ereg_replace

$convmap = array ( (4.2.0 - 4.3.0 only)


int start_code1, int end_code1, int offset1, int mb_ereg_replace -- Replace regular expression with
mask1, multibyte support
int start_code2, int end_code2, int offset2, int
mask2,
........ Description
int start_codeN, int end_codeN, int offsetN, int
maskN );
// Specify Unicode value for start_codeN and string mb_ereg_replace ( string pattern, string
end_codeN replacement, string string [, array option])
// Add offsetN to value and take bit-wise 'AND'
with maskN, then
// it converts value to numeric string reference. Aviso

Ejemplo 2. mb_encode_numericentity() example 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
/* Convert Left side of ISO-8859-1 to HTML numeric en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
character reference */
$convmap = array(0x80, 0xff, 0, 0xff); mb_ereg_replace() scans string for matches to pattern,
$str = mb_encode_numericentity($str, $convmap, then replaces the matched text with replacement and
"ISO-8859-1"); returns the result string or FALSE on error. Multibyte
character can be used in pattern.
/* Convert user defined SJIS-win code in block 95-104 Matching condition can be set by option parameter. If i is
to numeric specified for this parameter, the case will be ignored. If x
string reference */ is specified, white space will be ignored. If m is specified,
$convmap = array( match will be executed in multiline mode and line break
0xe000, 0xe03e, 0x1040, 0xffff, will be included in '.'. If p is specified, match will be
0xe03f, 0xe0bb, 0x1041, 0xffff, executed in POSIX mode, line break will be considered as
0xe0bc, 0xe0fa, 0x1084, 0xffff, normal character. If e is specified, replacement string will
0xe0fb, 0xe177, 0x1085, 0xffff, be evaluated as PHP expression.
0xe178, 0xe1b6, 0x10c8, 0xffff, The internal encoding or the character encoding
0xe1b7, 0xe233, 0x10c9, 0xffff, specified in mb_regex_encoding() will be used as
0xe234, 0xe272, 0x110c, 0xffff, character encoding.
0xe273, 0xe2ef, 0x110d, 0xffff,
0xe2f0, 0xe32e, 0x1150, 0xffff,
0xe32f, 0xe3ab, 0x1151, 0xffff ); Nota: This function is supported in
$str = mb_encode_numericentity($str, $convmap, PHP 4.2.0 or higher.
"sjis-win");
See also: mb_decode_numericentity(). See also: mb_regex_encoding(), mb_eregi_replace().

mb_ereg_match mb_ereg_search_getpos

(4.2.0 - 4.3.0 only) (4.2.0 - 4.3.0 only)


mb_ereg_match -- Regular expression match for mb_ereg_search_getpos -- Returns start point for next
multibyte string regular expression match

Description Description

bool mb_ereg_match ( string pattern, string string [, array mb_ereg_search_getpos ( void)


string option])

Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.
mb_ereg_search_getpos() returns the point to start mb_ereg_search_init() sets string and pattern for
regular expression match for mb_ereg_search(), multibyte regular expression. These values are used for
mb_ereg_search_pos(), mb_ereg_search_regs(). The mb_ereg_search(), mb_ereg_search_pos(),
position is represented by bytes from the head of string. mb_ereg_search_regs(). It returns TRUE for success,
The internal encoding or the character encoding FALSE for error.
specified in mb_regex_encoding() will be used as The internal encoding or the character encoding
character encoding. specified in mb_regex_encoding() will be used as
character encoding.

Nota: This function is supported in


PHP 4.2.0 or higher. Nota: This function is supported in
PHP 4.2.0 or higher.

See also: mb_regex_encoding(),


mb_ereg_search_setpos(). See also: mb_regex_encoding(),
mb_ereg_search_regs().

mb_ereg_search_getregs
mb_ereg_search_pos

(4.2.0 - 4.3.0 only)


mb_ereg_search_getregs -- Retrive the result from the (4.2.0 - 4.3.0 only)
last multibyte regular expression match mb_ereg_search_pos -- Return position and length of
matched part of multibyte regular expression for
predefined multibyte string
Description

Description
array mb_ereg_search_getregs ( void)

array mb_ereg_search_pos ( [string pattern [, string


Aviso option]])
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y Este módulo es EXPERIMENTAL. Esto significa que el
utilizar este módulo es tu responsabiliad. comportamineto de estas funciones, nombre de funciones
mb_ereg_search_getregs() returns an array including y en definitiva TODO lo documentado aqui, puede cambiar
the sub-string of matched part by last en una futura version de PHP SIN AVISO. Quedas avisado, y
mb_ereg_search(), mb_ereg_search_pos(), utilizar este módulo es tu responsabiliad.
mb_ereg_search_regs(). If there are some maches, the mb_ereg_search_pos() returns an array including
first element will have the matched sub-string, the position of matched part for multibyte regular
second element will have the first part grouped with expression. The first element of the array will be the
brackets, the third element will have the second part beggining of matched part, the second element will be
grouped with brackets, and so on. It returns FALSE on length (bytes) of matched part. It returns FALSE on
error; error.
The internal encoding or the character encoding The string for match is specified by
specified in mb_regex_encoding() will be used as mb_ereg_search_init(). It it is not specified, the
character encoding. previous one will be used.
The internal encoding or the character encoding
specified in mb_regex_encoding() will be used as
Nota: This function is supported in character encoding.
PHP 4.2.0 or higher.

Nota: This function is supported in


See also: mb_regex_encoding(), PHP 4.2.0 or higher.
mb_ereg_search_init().

See also: mb_regex_encoding(),


mb_ereg_search_init mb_ereg_search_init().

(4.2.0 - 4.3.0 only) mb_ereg_search_regs


mb_ereg_search_init -- Setup string and regular
expression for multibyte regular expression match
(4.2.0 - 4.3.0 only)
mb_ereg_search_regs -- Returns the matched part of
Description multibyte regular expression

array mb_ereg_search_init ( string string [, string Description


pattern [, string option]])

array mb_ereg_search_regs ( [string pattern [, string


Aviso option]])
Aviso mb_ereg_search() returns TRUE if the multibyte string
matches with the regular expression, FALSE for
Este módulo es EXPERIMENTAL. Esto significa que el otherwise. The string for matching is set by
comportamineto de estas funciones, nombre de funciones mb_ereg_search_init(). If pattern is not specified, the
y en definitiva TODO lo documentado aqui, puede cambiar previous one is used.
en una futura version de PHP SIN AVISO. Quedas avisado, y The internal encoding or the character encoding
utilizar este módulo es tu responsabiliad. specified in mb_regex_encoding() will be used as
mb_ereg_search_regs() executes the multibyte regular character encoding.
expression match, and if there are some matched part, it
returns an array including substring of matched part as Nota: This function is supported in
first element, the first grouped part with brackets as PHP 4.2.0 or higher.
second element, the second grouped part as third
element, and so on. It returns FALSE on error.
The internal encoding or the character encoding See also: mb_regex_encoding(),
specified in mb_regex_encoding() will be used as mb_ereg_search_init().
character encoding.

mb_ereg
Nota: This function is supported in
PHP 4.2.0 or higher.
(4.2.0 - 4.3.0 only)
mb_ereg -- Regular expression match with multibyte
See also: mb_regex_encoding(), support
mb_ereg_search_init().

Description
mb_ereg_search_setpos

int mb_ereg ( string pattern, string string [, array regs])


(4.2.0 - 4.3.0 only)
mb_ereg_search_setpos -- Set start point of next regular
expression match Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Description 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
array mb_ereg_search_setpos ( void) utilizar este módulo es tu responsabiliad.
mb_ereg() executes the regular expression match with
Aviso multibyte support, and returns 1 if matches are found. If
the optional third parameter was specified, the function
Este módulo es EXPERIMENTAL. Esto significa que el returns the byte length of matched part, and therarray
comportamineto de estas funciones, nombre de funciones regs will contain the substring of matched string. The
y en definitiva TODO lo documentado aqui, puede cambiar functions returns 1 if it matches with the empty string. It
en una futura version de PHP SIN AVISO. Quedas avisado, y no matche found or error happend, FALSE will be
utilizar este módulo es tu responsabiliad. returned.
mb_ereg_search_setpos() sets the starting point of The internal encoding or the character encoding
match for mb_ereg_search(). specified in mb_regex_encoding() will be used as
The internal encoding or the character encoding character encoding.
specified in mb_regex_encoding() will be used as
character encoding. Nota: This function is supported in
PHP 4.2.0 or higher.
Nota: This function is supported in
PHP 4.2.0 or higher. See also: mb_regex_encoding(), mb_eregi()

See also: mb_regex_encoding(), mb_eregi_replace


mb_ereg_search_init().

(4.2.0 - 4.3.0 only)


mb_ereg_search mb_eregi_replace -- Replace regular expression with
multibyte support ignoring case
(4.2.0 - 4.3.0 only)
mb_ereg_search -- Multibyte regular expression match Description
for predefined multibyte string

string mb_eregi_replace ( string pattern, string replace,


Description string string)

bool mb_ereg_search ( [string pattern [, string option]])


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y mb_ereg_replace() scans string for matches to pattern,
utilizar este módulo es tu responsabiliad. then replaces the matched text with replacement and
returns the result string or FALSE on error. Multibyte If type is specified for "http_output", "http_input",
character can be used in pattern. The case will be "internal_encoding", "func_overload", the specified
ignored. setting parameter will be returned.
The internal encoding or the character encoding See also mb_internal_encoding(), mb_http_output().
specified in mb_regex_encoding() will be used as
character encoding.
mb_http_input

Nota: This function is supported in


PHP 4.2.0 or higher. (PHP 4 >= 4.0.6)
mb_http_input -- Detect HTTP input character encoding

See also: mb_regex_encoding(), mb_ereg_replace().


Description

mb_eregi
string mb_http_input ( [string type])

(4.2.0 - 4.3.0 only)


mb_http_input() returns result of HTTP input character
mb_eregi -- Regular expression match ignoring case with
encoding detection.
multibyte support
type: Input string specifies input type. "G" for GET, "P" for
POST, "C" for COOKIE. If type is omitted, it returns last
Description input type processed.
Return Value: Character encoding name. If
mb_http_input() does not process specified HTTP input,
int mb_eregi ( string pattern, string string [, array regs]) it returns FALSE.
See also mb_internal_encoding(), mb_http_output(),
mb_detect_order().
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el mb_http_output
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 (PHP 4 >= 4.0.6)
utilizar este módulo es tu responsabiliad. mb_http_output -- Set/Get HTTP output character
mb_eregi() executes the regular expression match with encoding
multibyte support, and returns 1 if matches are found.
This function ignore case. If the optional third parameter Description
was specified, the function returns the byte length of
matched part, and therarray regs will contain the
substring of matched string. The functions returns 1 if it string mb_http_output ( [string encoding])
matches with the empty string. It no matche found or
error happend, FALSE will be returned.
The internal encoding or the character encoding If encoding is set, mb_http_output() sets HTTP output
specified in mb_regex_encoding() will be used as character encoding to encoding. Output after this
character encoding. function is converted to encoding. mb_http_output()
returns TRUE for success and FALSE for failure.
If encoding is omitted, mb_http_output() returns
Nota: This function is supported in current HTTP output character encoding.
PHP 4.2.0 or higher. See also mb_internal_encoding(), mb_http_input(),
mb_detect_order().

See also: mb_regex_encoding(), mb_ereg().


mb_internal_encoding

mb_get_info
(PHP 4 >= 4.0.6)
mb_internal_encoding -- Set/Get internal character
(PHP 4 >= 4.2.0) encoding
mb_get_info -- Get internal settings of mbstring

Description
Description

string mb_internal_encoding ( [string encoding])


string mb_get_info ( [string type])
mb_internal_encoding() sets internal character
Aviso encoding to encoding If parameter is omitted, it returns
current internal encoding.
Este módulo es EXPERIMENTAL. Esto significa que el encoding is used for HTTP input character encoding
comportamineto de estas funciones, nombre de funciones conversion, HTTP output character encoding conversion
y en definitiva TODO lo documentado aqui, puede cambiar and default character encoding for string functions
en una futura version de PHP SIN AVISO. Quedas avisado, y defined by mbstring module.
utilizar este módulo es tu responsabiliad. encoding: Character encoding name
mb_get_info() returns internal setting parameter of Return Value: If encoding is
mbstring. set,mb_internal_encoding() returns TRUE for success,
If type isn't specified or is specified to "all", an array otherwise returns FALSE. If encoding is omitted, it
having the elements "internal_encoding", "http_output", returns current character encoding name.
"http_input", "func_overload" will be returned. Ejemplo 1. mb_internal_encoding() example
Nota: If you want to output some
/* Set internal character encoding
binary data such as image from PHP
to UTF-8 */
script with PHP 4.3.0 or later,
mb_internal_encoding("UTF-8");
Content-Type: header must be send
using header() before any binary
/* Display current internal
data was send to client (e.g.
character encoding */
header("Content-Type: image/png")).
echo mb_internal_encoding();
If Content-Type: header was send,
See also mb_http_input(), mb_http_output(), output character encoding
mb_detect_order(). conversion will not be performed.

mb_language Note that if 'Content-Type: text/*'


was send using header(), the
sending data is regarded as text,
(PHP 4 >= 4.0.6) encoding conversion will be
mb_language -- Set/Get current language performed using character encoding
settings.
Description
If you want to output some binary
string mb_language ( [string language]) data such as image from PHP script
with PHP 4.2.x or earlier, you must
set output encoding to "pass" using
mb_language() sets language. If language is omitted, it mb_http_output().
returns current language as string.
language setting is used for encoding e-mail messages.
Valid languages are "Japanese", "ja","English","en" and See also ob_start().
"uni" (UTF-8). mb_send_mail() uses this setting to
encode e-mail.
Language and its setting is ISO-2022-JP/Base64 for mb_parse_str
Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted
printable for English. (PHP 4 >= 4.0.6)
Return Value: If language is set and language is valid, it mb_parse_str -- Parse GET/POST/COOKIE data and set
returns TRUE. Otherwise, it returns FALSE. When global variable
language is omitted, it returns language name as string.
If no language is set previously, it returns FALSE.
See also mb_send_mail(). Description

mb_output_handler boolean mb_parse_str ( string encoded_string [, array


result])
(PHP 4 >= 4.0.6)
mb_output_handler -- Callback function converts mb_parse_str() parses GET/POST/COOKIE data and sets
character encoding in output buffer global variables. Since PHP does not provide raw
POST/COOKIE data, it can only used for GET data for now.
It preses URL encoded data, detects encoding, converts
Description coding to internal encoding and set values to result array
or global variables.
encoded_string: URL encoded data.
string mb_output_handler ( string contents, int status) result: Array contains decoded and character encoding
converted values.
mb_output_handler() is ob_start() callback function. Return Value: It returns TRUE for success or FALSE for
mb_output_handler() converts characters in output failure.
buffer from internal character encoding to HTTP output See also mb_detect_order(),
character encoding. mb_internal_encoding().
4.1.0 or later version, this hanlder adds charset HTTP
header when following conditions are met:
mb_preferred_mime_name

• Does not set Content-Type by header() (PHP 4 >= 4.0.6)


• Default MIME type begins with text/ mb_preferred_mime_name -- Get MIME charset string

• http_output setting is other than pass


Description

contents : Output buffer contents


status : Output buffer status string mb_preferred_mime_name ( string encoding)
Return Value: String converted
Ejemplo 1. mb_output_handler() example mb_preferred_mime_name() returns MIME charset
string for character encoding encoding. It returns charset
string.
mb_http_output("UTF- Ejemplo 1. mb_preferred_mime_string() example
8");
ob_start("mb_output_h
andler"); $outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" .
boolean mb_send_mail ( string to, string subject, string
mb_preferred_mime_name($outputenc));
message [, string additional_headers [, string
additional_parameter]])
mb_regex_encoding
mb_send_mail() sends email. Headers and message are
converted and encoded according to mb_language()
(4.2.0 - 4.3.0 only) setting. mb_send_mail() is wrapper function of mail().
mb_regex_encoding -- Returns current encoding for See mail() for details.
multibyte regex as string to is mail addresses send to. Multiple recipients can be
specified by putting a comma between each address in
to. This parameter is not automatically encoded.
Description subject is subject of mail.
message is mail message.
string mb_regex_encoding ( [string encoding]) additional_headers is inserted at the end of the header.
This is typically used to add extra headers. Multiple extra
headers are separated with a newline ("\n").
Aviso additional_parameter is a MTA command line parameter.
It is useful when setting the correct Return-Path header
Este módulo es EXPERIMENTAL. Esto significa que el when using sendmail.
comportamineto de estas funciones, nombre de funciones Devuelve TRUE si todo fue bien, FALSE en caso de fallo.
y en definitiva TODO lo documentado aqui, puede cambiar See also mail(), mb_encode_mimeheader(), and
en una futura version de PHP SIN AVISO. Quedas avisado, y mb_language().
utilizar este módulo es tu responsabiliad.
mb_regex_encoding() returns the character encoding
used by multibyte regex functions. mb_split
If the optional parameter encoding is specified, it is set to
the character encoding for multibyte regex. The default (4.2.0 - 4.3.0 only)
value is the internal character encoding. mb_split -- Split multibyte string using regular expression

Nota: This function is supported in Description


PHP 4.2.0 or higher.

array mb_split ( string pattern, string string [, int limit])


See also: mb_internal_encoding(), mb_ereg()

Aviso
mb_regex_set_options
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
(PHP 4 4.3.0 only) y en definitiva TODO lo documentado aqui, puede cambiar
mb_regex_set_options -- Set/Get the default options for en una futura version de PHP SIN AVISO. Quedas avisado, y
mbregex functions utilizar este módulo es tu responsabiliad.
mb_split() split multibyte string using regular
Description expression pattern and returns the result as an array.
If optional parameter limit is specified, it will be split in
limit elements as maximum.
string mb_regex_set_options ( [string options]) The internal encoding or the character encoding
specified in mb_regex_encoding() will be used as
character encoding.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Nota: This function is supported in
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar PHP 4.2.0 or higher.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. See also: mb_regex_encoding(), mb_ereg().
mb_regex_set_options() sets the default options
described by options for multibyte regex functions.
Returns the previous options. If options is omitted, it mb_strcut
returns the string that describes the current options.
(PHP 4 >= 4.0.6)
Nota: This function is supported in mb_strcut -- Get part of string
PHP 4.3.0 or higher.
Description
See also: mb_split(), mb_ereg() mb_eregi()
string mb_strcut ( string str, int start [, int length [,
mb_send_mail string encoding]])

mb_strcut() returns the portion of str specified by the


(PHP 4 >= 4.0.6) start and length parameters.
mb_send_mail -- Send encoded mail. mb_strcut() performs equivalent operation as
mb_substr() with different method. If start position is
Description multi-byte character's second byte or larger, it starts
from first byte of multi-byte character.
It subtracts string from str that is shorter than length First character's position is 0. Second character position
AND character that is not part of multi-byte string or not is 1, and so on.
being middle of shift sequence. If encoding is omitted, internal character encoding is
encoding is character encoding. If it is not set, internal used. mb_strrpos() accepts string for needle where
character encoding is used. strrpos() accepts only character.
See also mb_substr(), mb_internal_encoding(). offset is search offset. If it is not specified, 0 is used.
encoding is character encoding name. If it is omitted,
internal character encoding is used.
mb_strimwidth See also mb_strpos(), mb_internal_encoding(),
strpos()
(PHP 4 >= 4.0.6)
mb_strimwidth -- Get truncated string with specified mb_strrpos
width

(PHP 4 >= 4.0.6)


Description mb_strrpos -- Find position of last occurrence of a string
in a string
string mb_strimwidth ( string str, int start, int width,
string trimmarker [, string encoding]) Description

mb_strimwidth() truncates string str to specified width.


int mb_strrpos ( string haystack, string needle [, string
It returns truncated string.
encoding])
If trimmarker is set, trimmarker is appended to return
value.
start is start position offset. Number of characters from mb_strrpos() returns the numeric position of the last
the beginning of string. (First character is 0) occurrence of needle in the haystack string. If needle is
trimmarker is string that is added to the end of string not found, it returns FALSE.
when string is truncated. mb_strrpos() performs multi-byte safe strrpos()
encoding is character encoding. If it is omitted, internal operation based on number of characters. needle
encoding is used. position is counted from the beginning of haystack. First
Ejemplo 1. mb_strimwidth() example character's position is 0. Second character position is 1.
If encoding is omitted, internal encoding is assumed.
mb_strrpos() accepts string for needle where strrpos()
$str = mb_strimwidth($str, accepts only character.
0, 40, "..>"); encoding is character encoding. If it is not specified,
internal character encoding is used.
See also: mb_strwidth(), mb_internal_encoding(). See also mb_strpos(), mb_internal_encoding(),
strrpos().
mb_strlen
mb_strtolower
(PHP 4 >= 4.0.6)
mb_strlen -- Get string length (PHP 4 >= 4.3.0)
mb_strtolower -- Make a string lowercase
Description
Description
string mb_strlen ( string str [, string encoding])
string mb_strtolower ( string str [, string encoding])
mb_strlen() returns number of characters in string str
having character encoding encoding. A multi-byte mb_strtolower() returns str with all alphabetic
character is counted as 1. characters converted to lowercase.
encoding is character encoding for str. If encoding is encoding specifies the encoding of str; if omitted, the
omitted, internal character encoding is used. internal character encoding value will be used.
See also mb_internal_encoding(), strlen(). For more information about the Unicode properties,
please see http://www.unicode.org/unicode/reports/tr21/.
mb_strpos By contrast to strtolower(), 'alphabetic' is determined
by the Unicode character properties. Thus the behaviour
of this function is not affected by locale settings and it
(PHP 4 >= 4.0.6) can convert any characters that have 'alphabetic'
mb_strpos -- Find position of first occurrence of string in property, such as A-umlaut (Ä).
a string Ejemplo 1. mb_strtolower() example

Description $str = "Mary Had A Little Lamb and She


LOVED It So";
int mb_strpos ( string haystack, string needle [, int $str = mb_strtolower($str);
offset [, string encoding]]) print $str; # Prints mary had a little lamb
and she loved it so

mb_strpos() returns the numeric position of the first See also strtolower(), mb_strtoupper(),
occurrence of needle in the haystack string. If needle is mb_convert_case().
not found, it returns FALSE.
mb_strpos() performs multi-byte safe strpos() mb_strtoupper
operation based on number of characters. needle
position is counted from the beginning of the haystack.
(PHP 4 >= 4.3.0)
mb_strtoupper -- Make a string uppercase Invalid characters may be substituted NULL(no output),
string or integer value (Unicode character code value).
This setting affects mb_detect_encoding() and
Description mb_send_mail().
substchar : Specify Unicode value as integer or specify as
string as follows
string mb_strtoupper ( string str [, string encoding])

mb_strtoupper() returns str with all alphabetic • "none" : no output


characters converted to uppercase.
encoding specifies the encoding of str; if omitted, the • "long" : Output character code value (Example:
internal character encoding value will be used. U+3000,JIS+7E7E)
By contrast to strtoupper(), 'alphabetic' is determined
by the Unicode character properties. Thus the behaviour
Return Value: If substchar is set, it returns TRUE for
of this function is not affected by locale settings and it
success, otherwise returns FALSE. If substchar is not set,
can convert any characters that have 'alphabetic'
it returns Unicode value or "none"/"long".
property, such as a-umlaut (ä).
Ejemplo 1. mb_substitute_character() example
For more information about the Unicode properties,
please see http://www.unicode.org/unicode/reports/tr21/.
Ejemplo 1. mb_strtoupper() example
/* Set with Unicode U+3013
(GETA MARK) */
mb_substitute_character(0x3013)
$str = "Mary Had A Little Lamb and She LOVED It
;
So";
$str = mb_strtoupper($str);
/* Set hex format */
print $str; # Prints MARY HAD A LITTLE LAMB AND
mb_substitute_character("long");
SHE LOVED IT SO
See also strtoupper(), mb_strtolower(), /* Display current setting */
mb_convert_case(). echo mb_substitute_character();

mb_strwidth
mb_substr_count

(PHP 4 >= 4.0.6)


(PHP 4 >= 4.3.0)
mb_strwidth -- Return width of string
mb_substr_count -- Count the number of substring
occurrences
Description
Description
int mb_strwidth ( string str [, string encoding])
int mb_substr_count ( string haystack, string needle [,
mb_strwidth() returns width of string str. string encoding])
Multi-byte character usually twice of width compare to
single byte character.
mb_substr_count() returns the number of times the
Character width needle substring occurs in the haystack string.
encoding specifies the encoding for needle and haystack.
U+0000 - If omitted, internal character encoding is used.
U+0019 0 Ejemplo 1. mb_substr_count() example
U+0020 -
U+1FFF 1
U+2000 - <?php
U+FF60 2 print mb_substr_count("This is a test",
U+FF61 - "is"); // prints out 2
U+FF9F 1 ?>
U+FFA0 -
2 See also substr_count(), mb_strpos(), mb_substr().

encoding is character encoding. If it is omitted, internal


encoding is used. mb_substr
See also: mb_strimwidth(), mb_internal_encoding().
(PHP 4 >= 4.0.6)
mb_substitute_character mb_substr -- Get part of string

(PHP 4 >= 4.0.6) Description


mb_substitute_character -- Set/Get substitution character
string mb_substr ( string str, int start [, int length [,
Description string encoding]])

mixed mb_substitute_character ( [mixed substrchar]) mb_substr() returns the portion of str specified by the
start and length parameters.
mb_substr() performs multi-byte safe substr()
mb_substitute_character() specifies substitution operation based on number of characters. Position is
character when input character encoding is invalid or counted from the beginning of str. First character's
character code is not exist in output character encoding. position is 0. Second character position is 1, and so on.
If encoding is omitted, internal encoding is assumed.
encoding is character encoding. If it is omitted, internal mcal_event_set_recur_none -- Sets the recurrence of the
character encoding is used. streams global event structure
See also mb_strcut(), mb_internal_encoding(). mcal_event_set_recur_weekly -- Sets the recurrence of
the streams global event structure
mcal_event_set_recur_yearly -- Sets the recurrence of
LIII. MCAL functions the streams global event structure
mcal_event_set_start -- Sets the start date and time of
the streams global event structure
MCAL stands for Modular Calendar Access Library.
mcal_event_set_title -- Sets the title of the streams
Libmcal is a C library for accessing calendars. It's written
global event structure
to be very modular, with plugable drivers. MCAL is the
mcal_expunge -- Deletes all events marked for being
calendar equivalent of the IMAP module for mailboxes.
expunged.
With mcal support, a calendar stream can be opened
mcal_fetch_current_stream_event -- Returns an object
much like the mailbox stream with the IMAP support.
containing the current streams event structure
Calendars can be local file stores, remote ICAP servers,
mcal_fetch_event -- Fetches an event from the calendar
or other formats that are supported by the mcal library.
stream
Calendar events can be pulled up, queried, and stored.
mcal_is_leap_year -- Returns if the given year is a leap
There is also support for calendar triggers (alarms) and
year or not
reoccuring events.
mcal_list_alarms -- Return a list of events that has an
With libmcal, central calendar servers can be accessed
alarm triggered at the given datetime
and used, removing the need for any specific database or
mcal_list_events -- Return a list of events between two
local file programming.
given datetimes
To get these functions to work, you have to compile PHP
mcal_next_recurrence -- Returns the next recurrence of
with --with-mcal. That requires the mcal library to be
the event
installed. Grab the latest version from
mcal_open -- Opens up an MCAL connection
http://mcal.chek.com/ and compile and install it.
mcal_popen -- Opens up a persistent MCAL connection
The following constants are defined when using the MCAL
mcal_rename_calendar -- Rename an MCAL calendar
module: MCAL_SUNDAY, MCAL_MONDAY,
mcal_reopen -- Reopens an MCAL connection
MCAL_TUESDAY, MCAL_WEDNESDAY, MCAL_THURSDAY,
mcal_snooze -- Turn off an alarm for an event
MCAL_FRIDAY, MCAL_SATURDAY, MCAL_RECUR_NONE,
mcal_store_event -- Modify an existing event in an MCAL
MCAL_RECUR_DAILY, MCAL_RECUR_WEEKLY,
calendar
MCAL_RECUR_MONTHLY_MDAY,
mcal_time_valid -- Returns TRUE if the given year,
MCAL_RECUR_MONTHLY_WDAY, MCAL_RECUR_YEARLY,
month, day is a valid time
MCAL_JANUARY, MCAL_FEBRUARY, MCAL_MARCH,
mcal_week_of_year -- Returns the week number of the
MCAL_APRIL, MCAL_MAY, MCAL_JUNE, MCAL_JULY,
given date
MCAL_AUGUGT, MCAL_SEPTEMBER, MCAL_OCTOBER,
MCAL_NOVEMBER, and MCAL_DECEMBER. Most of the
functions use an internal event structure that is unique mcal_append_event
for each stream. This alleviates the need to pass around
large objects between functions. There are convenience
functions for setting, initializing, and retrieving the event (PHP 4 )
structure values. mcal_append_event -- Store a new event into an MCAL
Tabla de contenidos calendar
mcal_append_event -- Store a new event into an MCAL
calendar
mcal_close -- Close an MCAL stream Description
mcal_create_calendar -- Create a new MCAL calendar
mcal_date_compare -- Compares two dates
int mcal_append_event ( int mcal_stream)
mcal_date_valid -- Returns TRUE if the given year,
month, day is a valid date
mcal_day_of_week -- Returns the day of the week of the mcal_append_event() Stores the global event into an
given date MCAL calendar for the given stream.
mcal_day_of_year -- Returns the day of the year of the Returns the uid of the newly inserted event.
given date
mcal_days_in_month -- Returns the number of days in
the given month mcal_close
mcal_delete_calendar -- Delete an MCAL calendar
mcal_delete_event -- Delete an event from an MCAL (PHP 3>= 3.0.13, PHP 4 )
calendar mcal_close -- Close an MCAL stream
mcal_event_add_attribute -- Adds an attribute and a
value to the streams global event structure
mcal_event_init -- Initializes a streams global event Description
structure
mcal_event_set_alarm -- Sets the alarm of the streams
global event structure int mcal_close ( int mcal_stream, int flags)
mcal_event_set_category -- Sets the category of the
streams global event structure Closes the given mcal stream.
mcal_event_set_class -- Sets the class of the streams
global event structure
mcal_event_set_description -- Sets the description of the mcal_create_calendar
streams global event structure
mcal_event_set_end -- Sets the end date and time of the
streams global event structure (PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_daily -- Sets the recurrence of the mcal_create_calendar -- Create a new MCAL calendar
streams global event structure
mcal_event_set_recur_monthly_mday -- Sets the Description
recurrence of the streams global event structure
mcal_event_set_recur_monthly_wday -- Sets the
recurrence of the streams global event structure string mcal_create_calendar ( int stream, string
calendar)
Creates a new calendar named calendar. mcal_days_in_month() Returns the number of days in
the given month, taking into account if the given year is
a leap year or not.
mcal_date_compare

mcal_delete_calendar
(PHP 3>= 3.0.13, PHP 4 )
mcal_date_compare -- Compares two dates
(PHP 3>= 3.0.13, PHP 4 )
mcal_delete_calendar -- Delete an MCAL calendar
Description

Description
int mcal_date_compare ( int a_year, int a_month, int
a_day, int b_year, int b_month, int b_day)
string mcal_delete_calendar ( int stream, string
calendar)
mcal_date_compare() Compares the two given dates,
returns <0, 0, >0 if a<b, a==b, a>b respectively
Deletes the calendar named calendar.

mcal_date_valid
mcal_delete_event

(PHP 3>= 3.0.13, PHP 4 )


mcal_date_valid -- Returns TRUE if the given year, (PHP 3>= 3.0.13, PHP 4 )
month, day is a valid date mcal_delete_event -- Delete an event from an MCAL
calendar

Description
Description

int mcal_date_valid ( int year, int month, int day)


int mcal_delete_event ( int uid)
mcal_date_valid() Returns TRUE if the given year,
month and day is a valid date, FALSE if not. mcal_delete_event() deletes the calendar event
specified by the uid.
Returns TRUE.
mcal_day_of_week

mcal_event_add_attribute
(PHP 3>= 3.0.13, PHP 4 )
mcal_day_of_week -- Returns the day of the week of the
given date (PHP 3>= 3.0.15, PHP 4 )
mcal_event_add_attribute -- Adds an attribute and a
value to the streams global event structure
Description

Description
int mcal_ ( int year, int month, int day)

void mcal_event_add_attribute ( int stream, string


mcal_day_of_week() returns the day of the week of the
attribute, string value)
given date

mcal_event_add_attribute() adds an attribute to the


mcal_day_of_year stream's global event structure with the value given by
"value" .
(PHP 3>= 3.0.13, PHP 4 )
mcal_day_of_year -- Returns the day of the year of the mcal_event_init
given date

(PHP 3>= 3.0.13, PHP 4 )


Description mcal_event_init -- Initializes a streams global event
structure
int mcal_ ( int year, int month, int day)
Description
mcal_day_of_year() returns the day of the year of the
given date
int mcal_event_init ( int stream)

mcal_days_in_month mcal_event_init() initializes a streams global event


structure. this effectively sets all elements of the
structure to 0, or the default settings.
(PHP 3>= 3.0.13, PHP 4 )
Returns TRUE.
mcal_days_in_month -- Returns the number of days in
the given month
mcal_event_set_alarm
Description
(PHP 3>= 3.0.13, PHP 4 )
int mcal_days_in_month ( int month, int leap year)
mcal_event_set_alarm -- Sets the alarm of the streams int mcal_event_set_end ( int stream, int year, int month
global event structure [, int day [, int hour [, int min [, int sec]]]])

Description mcal_event_set_end() sets the streams global event


structure's end date and time to the given values.
Returns TRUE.
int mcal_event_set_alarm ( int stream, int alarm)

mcal_event_set_recur_daily
mcal_event_set_alarm() sets the streams global event
structure's alarm to the given minutes before the event.
Returns TRUE. (PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_daily -- Sets the recurrence of the
streams global event structure
mcal_event_set_category

Description
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_category -- Sets the category of the
streams global event structure int mcal_event_set_recur_daily ( int stream, int year,
int month, int day, int interval)

Description
mcal_event_set_recur_daily() sets the streams global
event structure's recurrence to the given value to be
int mcal_event_set_category ( int stream, string reoccuring on a daily basis, ending at the given date.
category)

mcal_event_set_recur_monthly_mday
mcal_event_set_category() sets the streams global
event structure's category to the given string.
Returns TRUE. (PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_mday -- Sets the
recurrence of the streams global event structure
mcal_event_set_class

Description
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_class -- Sets the class of the streams
global event structure int mcal_event_set_recur_monthly_mday ( int stream,
int year, int month, int day, int interval)

Description
mcal_event_set_recur_monthly_mday() sets the
streams global event structure's recurrence to the given
int mcal_event_set_class ( int stream, int class) value to be reoccuring on a monthly by month day basis,
ending at the given date.
mcal_event_set_class() sets the streams global event
structure's class to the given value. The class is either 1 mcal_event_set_recur_monthly_wday
for public, or 0 for private.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_wday -- Sets the
mcal_event_set_description recurrence of the streams global event structure

(PHP 3>= 3.0.13, PHP 4 ) Description


mcal_event_set_description -- Sets the description of the
streams global event structure
int mcal_event_set_recur_monthly_wday ( int stream,
int year, int month, int day, int interval)
Description

mcal_event_set_recur_monthly_wday() sets the


int mcal_event_set_description ( int stream, string streams global event structure's recurrence to the given
description) value to be reoccuring on a monthly by week basis,
ending at the given date.
mcal_event_set_description() sets the streams global
event structure's description to the given string. mcal_event_set_recur_none
Returns TRUE.

(PHP 3>= 3.0.15, PHP 4 )


mcal_event_set_end mcal_event_set_recur_none -- Sets the recurrence of the
streams global event structure
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_end -- Sets the end date and time of the Description
streams global event structure

int mcal_event_set_recur_none ( int stream)


Description
mcal_event_set_recur_none() sets the streams global (no version information, might be only in CVS)
event structure to not recur (event->recur_type is set to mcal_expunge -- Deletes all events marked for being
MCAL_RECUR_NONE). expunged.

mcal_event_set_recur_weekly Description

(PHP 3>= 3.0.13, PHP 4 ) int mcal_expunge ( int stream)


mcal_event_set_recur_weekly -- Sets the recurrence of
the streams global event structure
mcal_expunge() Deletes all events which have been
previously marked for deletion.
Description
mcal_fetch_current_stream_event
int mcal_event_set_recur_weekly ( int stream, int
year, int month, int day, int interval, int weekdays)
(PHP 3>= 3.0.13, PHP 4 )
mcal_fetch_current_stream_event -- Returns an object
mcal_event_set_recur_weekly() sets the streams containing the current streams event structure
global event structure's recurrence to the given value to
be reoccuring on a weekly basis, ending at the given
date. Description

mcal_event_set_recur_yearly int mcal_fetch_current_stream_event ( int stream)

mcal_event_fetch_current_stream_event() returns
(PHP 3>= 3.0.13, PHP 4 )
the current stream's event structure as an object
mcal_event_set_recur_yearly -- Sets the recurrence of
containing:
the streams global event structure

Description • int id - ID of that event.


• int public - TRUE if the event if public, FALSE
int mcal_event_set_recur_yearly ( int stream, int year, if it is private.
int month, int day, int interval) • string category - Category string of the event.
• string title - Title string of the event.
mcal_event_set_recur_yearly() sets the streams
global event structure's recurrence to the given value to • string description - Description string of the
be reoccuring on a yearly basis,ending at the given date . event.
• int alarm - number of minutes before the event
mcal_event_set_start to send an alarm/reminder.
• object start - Object containing a datetime
entry.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_start -- Sets the start date and time of • object end - Object containing a datetime
the streams global event structure entry.
• int recur_type - recurrence type
Description • int recur_interval - recurrence interval
• datetime recur_enddate - recurrence end date
int mcal_event_set_start ( int stream, int year, int
month [, int day [, int hour [, int min [, int sec]]]])
• int recur_data - recurrence data

mcal_event_set_start() sets the streams global event All datetime entries consist of an object that contains:
structure's start date and time to the given values.
Returns TRUE.
• int year - year

mcal_event_set_title • int month - month


• int mday - day of month
(PHP 3>= 3.0.13, PHP 4 ) • int hour - hour
mcal_event_set_title -- Sets the title of the streams
global event structure
• int min - minutes
• int sec - seconds
Description • int alarm - minutes before event to send an
alarm

int mcal_event_set_title ( int stream, string title)


mcal_fetch_event
mcal_event_set_title() sets the streams global event
structure's title to the given string. (PHP 3>= 3.0.13, PHP 4 )
Returns TRUE. mcal_fetch_event -- Fetches an event from the calendar
stream
mcal_expunge
Description array mcal_list_events ( int mcal_stream [, int
begin_year [, int begin_month [, int begin_day [, int
end_year [, int end_month [, int end_day]]]]]])
object mcal_fetch_event ( int mcal_stream, int event_id
[, int options])
Returns an array of event ID's that has an alarm going off
between the start and end dates, or if just a stream is
mcal_fetch_event() fetches an event from the calendar given, uses the start and end dates in the global event
stream specified by id. structure.
Returns an event object consisting of: mcal_list_events() function takes in an optional
beginning date and an end date for a calendar stream.
An array of event id's that are between the given dates
• int id - ID of that event. or the internal event dates are returned.
• int public - TRUE if the event if public, FALSE
if it is private. mcal_list_events
• string category - Category string of the event.
• string title - Title string of the event. (PHP 3>= 3.0.13, PHP 4 )
mcal_list_events -- Return a list of events between two
• string description - Description string of the
given datetimes
event.
• int alarm - number of minutes before the event
to send an alarm/reminder. Description

• object start - Object containing a datetime


entry. array mcal_list_events ( int mcal_stream [, int
begin_year [, int begin_month [, int begin_day [, int
• object end - Object containing a datetime end_year [, int end_month [, int end_day]]]]]])
entry.
• int recur_type - recurrence type Returns an array of event ID's that are between the start
• int recur_interval - recurrence interval and end dates, or if just a stream is given, uses the start
and end dates in the global event structure.
• datetime recur_enddate - recurrence end date mcal_list_events() function takes in an optional
• int recur_data - recurrence data beginning date and an end date for a calendar stream.
An array of event id's that are between the given dates
or the internal event dates are returned.
All datetime entries consist of an object that contains:

mcal_next_recurrence
• int year - year
• int month - month (PHP 3>= 3.0.13, PHP 4 )
mcal_next_recurrence -- Returns the next recurrence of
• int mday - day of month the event
• int hour - hour
• int min - minutes Description
• int sec - seconds
• int alarm - minutes before event to send an int mcal_next_recurrence ( int stream, int weekstart,
alarm array next)

mcal_next_recurrence() returns an object filled with


mcal_is_leap_year the next date the event occurs, on or after the supplied
date. Returns empty date field if event does not occur or
(PHP 3>= 3.0.13, PHP 4 ) something is invalid. Uses weekstart to determine what
mcal_is_leap_year -- Returns if the given year is a leap day is considered the beginning of the week.
year or not
mcal_open
Description
(PHP 3>= 3.0.13, PHP 4 )
int mcal_is_leap_year ( int year) mcal_open -- Opens up an MCAL connection

mcal_is_leap_year() returns 1 if the given year is a leap Description


year, 1 if not.
int mcal_open ( string calendar, string username, string
mcal_list_alarms password, string options)

(PHP 3>= 3.0.13, PHP 4 ) Returns an MCAL stream on success, FALSE on error.
mcal_list_alarms -- Return a list of events that has an mcal_open() opens up an MCAL connection to the
alarm triggered at the given datetime specified calendar store. If the optional options is
specified, passes the options to that mailbox also. The
streams internal event structure is also initialized upon
Description connection.

mcal_popen
(PHP 3>= 3.0.13, PHP 4 ) mcal_store_event() Stores the modifications to the
mcal_popen -- Opens up a persistent MCAL connection current global event for the given stream.
Returns TRUE on success and FALSE on error.

Description
mcal_time_valid

int mcal_popen ( string calendar, string username,


string password [, int options]) (PHP 3>= 3.0.13, PHP 4 )
mcal_time_valid -- Returns TRUE if the given year,
month, day is a valid time
Returns an MCAL stream on success, FALSE on error.
mcal_popen() opens up an MCAL connection to the
specified calendar store. If the optional options is Description
specified, passes the options to that mailbox also. The
streams internal event structure is also initialized upon
connection. int mcal_time_valid ( int hour, int minutes, int seconds)

mcal_rename_calendar mcal_time_valid() Returns TRUE if the given hour,


minutes and seconds is a valid time, FALSE if not.

(PHP 3>= 3.0.13, PHP 4 )


mcal_rename_calendar -- Rename an MCAL calendar mcal_week_of_year

Description (PHP 4 )
mcal_week_of_year -- Returns the week number of the
given date
string mcal_rename_calendar ( int stream, string
old_name, string new_name)
Description

Renames the calendar old_name to new_name.


int mcal_week_of_year ( int day, int month, int year)

mcal_reopen
LIV. Funciones Criptográficas

(PHP 3>= 3.0.13, PHP 4 )


mcal_reopen -- Reopens an MCAL connection Estas funciones trabajan usando mcrypt.
Esta es una interfaz a la librería mcrypt, que soporta una
gran variedad de algoritmos de bloque como DES,
Description TripleDES, Blowfish (por defecto), 3-WAY, SAFER-SK64,
SAFER-SK128, TWOFISH, TEA, RC2 y GOST en los modos
de cifrado CBC, OFB, CFB y ECB. Adicionalmente, soporta
int mcal_reopen ( string calendar [, int options])
RC6 e IDEA que se consideran "no-libres".
Para usarlos, descarga libmcrypt-x.x.tar.gz de aquí y
Reopens an MCAL stream to a new calendar. sigue las instrucciones de instalación incluidas. Necesitas
mcal_reopen() reopens an MCAL connection to the compilar PHP con el parámetro --with-mcrypt para activar
specified calendar store. If the optional options is esta extensión.
specified, passes the options to that mailbox also. mcrypt puede usarse para encriptar y desencriptar
usando los cifrados mencionados arriba. Los cuatro
comandos importantes de mcrypt (mcrypt_cfb(),
mcal_snooze mcrypt_cbc(), mcrypt_ecb(), y mcrypt_ofb()) pueden
operar en ambos modos que se llaman
(PHP 3>= 3.0.13, PHP 4 ) MCRYPT_ENCRYPT y MCRYPT_DECRYPT, respectivamente.
mcal_snooze -- Turn off an alarm for an event Ejemplo 1. Encripta un valor de entrada con
TripleDES en modo ECB

Description
<?php
$key = "esta es una clave muy secreta";
int mcal_snooze ( int uid) $input = "Nos vemos a las 9 en punto en el lugar
secreto.";
mcal_snooze() turns off an alarm for a calendar event
specified by the uid. $encrypted_data = mcrypt_ecb(MCRYPT_TripleDES,
Returns TRUE. $key, $input, MCRYPT_ENCRYPT);
?>

mcal_store_event Este ejemplo devolverá los datos encriptados como una


cadena en $encrypted_data.
mcrypt puede operar en cuatro modos de cifrado (CBC,
(PHP 3>= 3.0.13, PHP 4 ) OFB, CFB y ECB). Perfilaremos el uso normal de cada uno
mcal_store_event -- Modify an existing event in an MCAL de estos modos. Para una mejor referencia y una
calendar discusión más completa ver Applied Cryptography by
Schneier (ISBN 0-471-11709-9).

Description
• ECB (electronic codebook o libro de códigos
int mcal_store_event ( int mcal_stream) electrónico) va bien para datos aleatorios,
tales como encriptar otras claves. Puesto que
los datos son cortos y aleatorios, las
desventajas de ECB tienen un efecto negativo mcrypt_decrypt -- Decrypts crypttext with given
favorable. parameters
mcrypt_ecb -- Encripta/desencripta datos en modo ECB
• CBC (cipher block chaining o cifrado en bloque
mcrypt_enc_get_algorithms_name -- Returns the name of
encadenado) es especialmente útil para
the opened algorithm
encriptar ficheros, donde incrementa
mcrypt_enc_get_block_size -- Returns the blocksize of the
significativamente la seguridad por encima de
opened algorithm
ECB.
mcrypt_enc_get_iv_size -- Returns the size of the IV of
• CFB (cipher feedback o cifrado realimentado) the opened algorithm
es el mejor modo de encriptar flujos de bytes mcrypt_enc_get_key_size -- Returns the maximum
donde cada byte debe ser encriptado. supported keysize of the opened mode
mcrypt_enc_get_modes_name -- Returns the name of the
• OFB (output feedback o salida realimentada)
opened mode
es comparable al CFB, pero puede usarse en
mcrypt_enc_get_supported_key_sizes -- Returns an array
aplicaciones donde la propagación de errores
with the supported keysizes of the opened algorithm
no puede tolerarse.
mcrypt_enc_is_block_algorithm_mode -- Checks whether
the encryption of the opened mode works on blocks
Actualmente PHP no soporta el encriptado/desencriptado mcrypt_enc_is_block_algorithm -- Checks whether the
de flujos de bits. Por ahora, sólo soporta el manejo de algorithm of the opened mode is a block algorithm
cadenas. mcrypt_enc_is_block_mode -- Checks whether the
Para una lista completa de los cifrados soportados, ver opened mode outputs blocks
las definiciones al final de mcrypt.h. La regla general es mcrypt_enc_self_test -- This function runs a self test on
que se puede acceder al cifrado desde PHP con the opened module
MCRYPT_nombredelcifrado. mcrypt_encrypt -- Encrypts plaintext with given
Aquí hay una pequeña lista de los cifrados que estan parameters
soportados actualmente por la extensión mcrypt. Si un mcrypt_generic_deinit -- This function deinitializes an
cifrado no está listado aquí, pero está listado por mcrypt encryption module
como soportado, puedes asumir con seguridad que ésta mcrypt_generic_end -- This function terminates
documentación está caduca. encryption
mcrypt_generic_init -- This function initializes all buffers
needed for encryption
• MCRYPT_BLOWFISH mcrypt_generic -- This function encrypts data
mcrypt_get_block_size -- Obtiene el tamaño de bloque
• MCRYPT_DES del cifrado indicado
• MCRYPT_TripleDES
mcrypt_get_cipher_name -- Obtiene el nombre del cifrado
especificado
• MCRYPT_ThreeWAY mcrypt_get_iv_size -- Returns the size of the IV belonging
to a specific cipher/mode combination
• MCRYPT_GOST
mcrypt_get_key_size -- Obtiene el tamaño de la clave de
• MCRYPT_CRYPT un cifrado
mcrypt_list_algorithms -- Get an array of all supported
• MCRYPT_DES_COMPAT
ciphers
• MCRYPT_SAFER64 mcrypt_list_modes -- Get an array of all supported modes
mcrypt_module_close -- Close the mcrypt module
• MCRYPT_SAFER128
mcrypt_module_get_algo_block_size -- Returns the
• MCRYPT_CAST128 blocksize of the specified algorithm
mcrypt_module_get_algo_key_size -- Returns the
• MCRYPT_TEAN
maximum supported keysize of the opened mode
• MCRYPT_RC2 mcrypt_module_get_supported_key_sizes -- Returns an
array with the supported keysizes of the opened
• MCRYPT_TWOFISH (para las antiguas versiones
algorithm
mcrypt 2.x) mcrypt_module_is_block_algorithm_mode -- This function
• MCRYPT_TWOFISH128 (TWOFISHxxx está returns if the the specified module is a block algorithm or
disponible en las versiones más nuevas 2.x) not
mcrypt_module_is_block_algorithm -- This function
• MCRYPT_TWOFISH192
checks whether the specified algorithm is a block
• MCRYPT_TWOFISH256 algorithm
mcrypt_module_is_block_mode -- This function returns if
• MCRYPT_RC6 the the specified mode outputs blocks or not
• MCRYPT_IDEA mcrypt_module_open -- This function opens the module
of the algorithm and the mode to be used
mcrypt_module_self_test -- This function runs a self test
Debes (en los modos CFB y OFB) o puedes (en el modo on the specified module
CBC) suministrar un vector de inicialización (IV) a la mcrypt_ofb -- Encripta/desencripta datos en modo OFB
correspondiente función de cifrado. El IV debe ser único y mdecrypt_generic -- This function decrypts data
debe ser el mismo cuando desencriptas o encriptas. Con
datos que son guardados encriptados, puedes cojer la
salida de una función de índice bajo la cual los datos son mcrypt_cbc
almacenados (ej. la clave MD5 de un fichero).
Alternativamente, puedes transmitir el IV junto con los
datos encriptados (ver capítulo 9.3 de Applied (PHP 3>= 3.0.8, PHP 4 )
Cryptography by Schneier (ISBN 0-471-11709-9) para mcrypt_cbc -- Encripta/desencripta datos en modo CBC
una discusión de éste asunto).
Tabla de contenidos Descripción
mcrypt_cbc -- Encripta/desencripta datos en modo CBC
mcrypt_cfb -- Encripta/desencripta datos en modo CFB
mcrypt_create_iv -- Crea un vector de inicialización (IV) a int mcrypt_cbc ( int cipher, string key, string data, int
partir de una fuente aleatoria mode [, string iv])
mcrypt_cbc() encripta o desencripta (dependiendo de (PHP 4 >= 4.0.2)
mode) los datos data con el cifrado cipher y la clave key mcrypt_decrypt -- Decrypts crypttext with given
en el modo de cifrado CBC y devuelve la cadena parameters
resultante.
El parámetro cipher es una de las constantes con nombre
MCRYPT_nombrecifrado. Description
key es la clave suministrada al algoritmo. Debe
guardarse en secreto.
string mcrypt_decrypt ( string cipher, string key, string
data son los datos que serán encriptados/desencriptados. data, string mode [, string iv])
mode es MCRYPT_ENCRYPT o MCRYPT_DECRYPT.
iv es el vector de inicialización opcional.
Ver también: mcrypt_cfb(), mcrypt_ecb(), mcrypt_decrypt() decrypts the data and returns the
mcrypt_ofb() unencrypted data.
Cipher is one of the MCRYPT_ciphername constants of
the name of the algorithm as string.
mcrypt_cfb Key is the key with which the data is encrypted. If it's
smaller that the required keysize, it is padded with '\0'.
Data is the data that will be decrypted with the given
(PHP 3>= 3.0.8, PHP 4 )
cipher and mode. If the size of the data is not n *
mcrypt_cfb -- Encripta/desencripta datos en modo CFB
blocksize, the data will be padded with '\0'.
Mode is one of the MCRYPT_MODE_modename constants
Descripción of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC,
CFB, OFB modes, and in some algorithms in STREAM
int mcrypt_cfb ( int cipher, string key, string data, int mode. If you do not supply an IV, while it is needed for an
mode, string iv) algorithm, the function issues a warning and uses an IV
with all bytes set to '\0'.
mcrypt_cfb() encripta o desencripta (dependiendo de
mode) los datos data con el cifrado cipher y la clave key mcrypt_ecb
en el modo de cifrado CFB y devuelve la cadena
resultante.
El parámetro cipher es una de las constantes con nombre (PHP 3>= 3.0.8, PHP 4 )
MCRYPT_nombrecifrado. mcrypt_ecb -- Encripta/desencripta datos en modo ECB
key es la clave suministrada al algoritmo. Debe
guardarse en secreto.
data son los datos que serán encriptados/desencriptados. Descripción
mode es MCRYPT_ENCRYPT o MCRYPT_DECRYPT.
iv es el vector de inicialización.
int mcrypt_ecb ( int cipher, string key, string data, int
Ver también: mcrypt_cbc(), mcrypt_ecb(), mode)
mcrypt_ofb()

mcrypt_ecb() encripta o desencripta (dependiendo de


mcrypt_create_iv mode) los datos data con el cifrado cipher y la clave key
en el modo de cifrado ECB y devuelve la cadena
resultante.
(PHP 3>= 3.0.8, PHP 4 )
El parámetro cipher es una de las constantes con nombre
mcrypt_create_iv -- Crea un vector de inicialización (IV) a
MCRYPT_nombrecifrado.
partir de una fuente aleatoria
key es la clave suministrada al algoritmo. Debe
guardarse en secreto.
Descripción data son los datos que serán encriptados/desencriptados.
mode es MCRYPT_ENCRYPT o MCRYPT_DECRYPT.
Ver también: mcrypt_cbc(), mcrypt_cfb(),
string mcrypt_create_iv ( int size, int source) mcrypt_ofb()

mcrypt_create_iv() se usa para crear un IV. mcrypt_enc_get_algorithms_name


mcrypt_create_iv() toma dos argumentos, size
determina el tamaño del IV, source especifica la fuente
del IV. (PHP 4 >= 4.0.2)
La fuente puede ser MCRYPT_RAND (generador de mcrypt_enc_get_algorithms_name -- Returns the name of
números aleatorios del sistema), MCRYPT_DEV_RANDOM the opened algorithm
(que lee datos de /dev/random) y
MCRYPT_DEV_URANDOM (que lee datos de
/dev/urandom). Si usas MCRYPT_RAND, asegurate de Description
llamar antes a srand() para inicializar el generador de
números aleatorios. string mcrypt_enc_get_algorithms_name ( resource
Ejemplo 1. Ejemplo de mcrypt_create_iv
td)

<?php This function returns the name of the algorithm.


$cipher = MCRYPT_TripleDES; Ejemplo 1. mcrypt_enc_get_algorithms_name()
$block_size = mcrypt_get_block_size($cipher); example
$iv = mcrypt_create_iv($block_size,
MCRYPT_DEV_RANDOM);
?> <?php
$td = mcrypt_module_open (MCRYPT_CAST_256, '',
MCRYPT_MODE_CFB, '');
mcrypt_decrypt echo mcrypt_enc_get_algorithms_name($td). "\n";
$td = mcrypt_module_open ('cast-256', '',
MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
?> <?php
$td = mcrypt_module_open (MCRYPT_CAST_256, '',
Prints: MCRYPT_MODE_CFB, '');
CAST-256 echo mcrypt_enc_get_modes_name($td). "\n";
CAST-256
$td = mcrypt_module_open ('cast-256', '', 'ecb', '');
echo mcrypt_enc_get_modes_name($td). "\n";
?>
mcrypt_enc_get_block_size
Prints:
(PHP 4 >= 4.0.2) CFB
mcrypt_enc_get_block_size -- Returns the blocksize of the ECB
opened algorithm

mcrypt_enc_get_supported_key_sizes
Description

(PHP 4 >= 4.0.2)


int mcrypt_enc_get_block_size ( resource td) mcrypt_enc_get_supported_key_sizes -- Returns an array
with the supported keysizes of the opened algorithm
This function returns the block size of the algorithm
specified by the encryption descriptor td in bytes.
Description

mcrypt_enc_get_iv_size
array mcrypt_enc_get_supported_key_sizes
( resource td)
(PHP 4 >= 4.0.2)
mcrypt_enc_get_iv_size -- Returns the size of the IV of Returns an array with the key sizes supported by the
the opened algorithm algorithm specified by the encryption descriptor. If it
returns an empty array then all key sizes between 1 and
mcrypt_enc_get_key_size() are supported by the
Description
algorithm.
Ejemplo 1. mcrypt_enc_get_supported_key_sizes()
int mcrypt_enc_get_iv_size ( resource td) example

This function returns the size of the iv of the algorithm


<?php
specified by the encryption descriptor in bytes. If it
$td = mcrypt_module_open ('rijndael-
returns '0' then the IV is ignored in the algorithm. An IV is
256', '', 'ecb', '');
used in cbc, cfb and ofb modes, and in some algorithms
var_dump
in stream mode.
(mcrypt_enc_get_supported_key_sizes($td)
);
mcrypt_enc_get_key_size ?>

This will print:


(PHP 4 >= 4.0.2)
mcrypt_enc_get_key_size -- Returns the maximum array(3) {
supported keysize of the opened mode [0]=>
int(16)
[1]=>
Description int(24)
[2]=>
int mcrypt_enc_get_key_size ( resource td) int(32)
}
?>
This function returns the maximum supported key size of
the algorithm specified by the encryption descriptor td in
bytes. mcrypt_enc_is_block_algorithm_mode

mcrypt_enc_get_modes_name (PHP 4 >= 4.0.2)


mcrypt_enc_is_block_algorithm_mode -- Checks whether
(PHP 4 >= 4.0.2) the encryption of the opened mode works on blocks
mcrypt_enc_get_modes_name -- Returns the name of the
opened mode Description

Description bool mcrypt_enc_is_block_algorithm_mode ( resource


td)
string mcrypt_enc_get_modes_name ( resource td)
This function returns TRUE if the mode is for use with
This function returns the name of the mode. block algorithms, otherwise it returns FALSE. (eg. FALSE
Ejemplo 1. mcrypt_enc_get_modes_name() example for stream, and TRUE for cbc, cfb, ofb).
mcrypt_enc_is_block_algorithm Mode is one of the MCRYPT_MODE_modename constants
of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC,
(PHP 4 >= 4.0.2) CFB, OFB modes, and in some algorithms in STREAM
mcrypt_enc_is_block_algorithm -- Checks whether the mode. If you do not supply an IV, while it is needed for an
algorithm of the opened mode is a block algorithm algorithm, the function issues a warning and uses an IV
with all bytes set to '\0'.
Ejemplo 1. mcrypt_encrypt() Example
Description

bool mcrypt_enc_is_block_algorithm ( resource td) <?php


$iv = mcrypt_create_iv (mcrypt_get_iv_size
(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB),
This function returns TRUE if the algorithm is a block
MCRYPT_RAND);
algorithm, or FALSE if it is a stream algorithm.
$key = "This is a very secret key";
$text = "Meet me at 11 o'clock behind the
mcrypt_enc_is_block_mode monument.";
echo strlen ($text)."\n";

(PHP 4 >= 4.0.2) $crypttext = mcrypt_encrypt


mcrypt_enc_is_block_mode -- Checks whether the (MCRYPT_RIJNDAEL_256, $key, $text,
opened mode outputs blocks MCRYPT_MODE_ECB, $iv);
echo strlen ($crypttext)."\n";
?>
Description

bool mcrypt_enc_is_block_mode ( resource td) The above example will print out:

This function returns TRUE if the mode outputs blocks of


42
bytes or FALSE if it outputs bytes. (eg. TRUE for cbc and
64
ecb, and FALSE for cfb and stream).
See also mcrypt_module_open() for a more advanced
API and an example.
mcrypt_enc_self_test

mcrypt_generic_deinit
(PHP 4 >= 4.0.2)
mcrypt_enc_self_test -- This function runs a self test on
the opened module (PHP 4 >= 4.1.1)
mcrypt_generic_deinit -- This function deinitializes an
encryption module
Description

Description
bool mcrypt_enc_self_test ( resource td)

bool mcrypt_generic_deinit ( resource td)


This function runs the self test on the algorithm specified
by the descriptor td. If the self test succeeds it returns
FALSE. In case of an error, it returns TRUE. This function terminates encryption specified by the
encryption descriptor (td). It clears all buffers, but does
not close the module. You need to call
mcrypt_encrypt mcrypt_module_close() yourself. (But PHP does this for
you at the end of the script. Returns FALSE on error, or
(PHP 4 >= 4.0.2) TRUE on success.
mcrypt_encrypt -- Encrypts plaintext with given See for an example mcrypt_module_open() and the
parameters entry on mcrypt_generic_init().

Description mcrypt_generic_end

string mcrypt_encrypt ( string cipher, string key, string (PHP 4 >= 4.0.2)
data, string mode [, string iv]) mcrypt_generic_end -- This function terminates
encryption

mcrypt_encrypt() encrypts the data and returns the


encrypted data. Description
Cipher is one of the MCRYPT_ciphername constants of
the name of the algorithm as string.
bool mcrypt_generic_end ( resource td)
Key is the key with which the data will be encrypted. If
it's smaller that the required keysize, it is padded with
'\0'. It is better not to use ASCII strings for keys. It is This function is deprecated, use
recommended to use the mhash functions to create a mcrypt_generic_deinit() instead. It can cause crashes
key from a string. when used with mcrypt_module_close() due to
Data is the data that will be encrypted with the given multiple buffer frees.
cipher and mode. If the size of the data is not n * This function terminates encryption specified by the
blocksize, the data will be padded with '\0'. The returned encryption descriptor (td). Actually it clears all buffers,
crypttext can be larger that the size of the data that is and closes all the modules used. Returns FALSE on
given by data. error, or TRUE on success.
mcrypt_generic_init (PHP 3>= 3.0.8, PHP 4 )
mcrypt_get_cipher_name -- Obtiene el nombre del cifrado
especificado
(PHP 4 >= 4.0.2)
mcrypt_generic_init -- This function initializes all buffers
needed for encryption Descripción

Description string mcrypt_get_cipher_name ( int cipher)

int mcrypt_generic_init ( resource td, string key, string mcrypt_get_cipher_name() se usa para obtener el
iv) nombre del cifrado especificado.
mcrypt_get_cipher_name() toma como argumento el
número de cifrado y devuelve el nombre del cifrado o
The maximum length of the key should be the one FALSE, si el cifrado no existe.
obtained by calling mcrypt_enc_get_key_size() and Ejemplo 1. Ejemplo de mcrypt_get_cipher_name
every value smaller than this is legal. The IV should
normally have the size of the algorithms block size, but
you must obtain the size by calling
<?php
mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV
$cipher = MCRYPT_TripleDES;
MUST exist in CFB, CBC, STREAM, nOFB and OFB modes.
It needs to be random and unique (but not secret). The
print
same IV must be used for encryption/decryption. If you
mcrypt_get_cipher_name($cip
do not want to use it you should set it to zeros, but this is
her);
not recommended. The function returns a negative value
?>
on error.
You need to call this function before every call to El ejemplo de más arriba da como resultado:
mcrypt_generic() or mdecrypt_generic(). TripleDE
See for an example mcrypt_module_open() and the S
entry on mcrypt_generic_deinit().

mcrypt_generic mcrypt_get_iv_size

(PHP 4 >= 4.0.2) (PHP 4 >= 4.0.2)


mcrypt_generic -- This function encrypts data mcrypt_get_iv_size -- Returns the size of the IV belonging
to a specific cipher/mode combination

Description
Description

string mcrypt_generic ( resource td, string data)


int mcrypt_get_iv_size ( resource td)
This function encrypts data. The data is padded with "\0" int mcrypt_get_iv_size ( string cipher, string mode)
to make sure the length of the data is n * blocksize. This
function returns the encrypted data. Note that the length
of the returned string can in fact be longer then the The first prototype is when linked against libmcrypt 2.2.x,
input, due to the padding of the data. the second when linked against libmcrypt 2.4.x or higher.
The encryption handle should alwayws be initialized with mcrypt_get_iv_size() returns the size of the
mcrypt_generic_init() with a key and an IV before Initialisation Vector (IV) in bytes. On error the function
calling this function. Where the encryption is done, you returns FALSE. If the IV is ignored in the specified
should free the encryption buffers by calling cipher/mode combination zero is returned.
mcrypt_generic_deinit(). See cipher is one of the MCRYPT_ciphername constants of the
mcrypt_module_open() for an example. name of the algorithm as string.
See also mdecrypt_generic(), mcrypt_generic_init() mode is one of the MCRYPT_MODE_modename constants
and mcrypt_generic_deinit(). of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
td is the resource that is returned by
mcrypt_module_open().
mcrypt_get_block_size Ejemplo 1. mcrypt_create_iv() example

(PHP 3>= 3.0.8, PHP 4 )


mcrypt_get_block_size -- Obtiene el tamaño de bloque <?php
del cifrado indicado $size = mcrypt_get_iv_size (MCRYPT_CAST_256,
MCRYPT_MODE_CFB);

Descripción $size = mcrypt_get_iv_size ('des', 'ecb');


?>

int mcrypt_get_block_size ( int cipher) See also: mcrypt_create_iv()

mcrypt_get_block_size() se usa para obtener el mcrypt_get_key_size


tamaño de bloque del cifrado indicado en cipher.
mcrypt_get_block_size() toma un argumento, el
(PHP 3>= 3.0.8, PHP 4 )
cifrado cipher y devuelve el tamaño en bytes.
mcrypt_get_key_size -- Obtiene el tamaño de la clave de
Ver también: mcrypt_get_key_size()
un cifrado

mcrypt_get_cipher_name
Descripción
int mcrypt_get_key_size ( int cipher)

algorithms in the default mode directory. If it is not set


mcrypt_get_key_size() se usa para obtener el tamaño with the ini directive mcrypt.modes_dir, the default
de la clave del cifrado indicado en cipher. directory of mcrypt is used (which is
mcrypt_get_key_size() toma un argumento, el cifrado /usr/local/lib/libmcrypt).
cipher y devuelve el tamaño de la clave en bytes.
Ver también: mcrypt_get_block_size()
mcrypt_module_close

mcrypt_list_algorithms
(PHP 4 >= 4.0.2)
mcrypt_module_close -- Close the mcrypt module
(PHP 4 >= 4.0.2)
mcrypt_list_algorithms -- Get an array of all supported
ciphers Description

Description bool mcrypt_module_close ( resource td)

array mcrypt_list_algorithms ( [string lib_dir]) This function closes the specified encryption handle.
See mcrypt_module_open() for an example.

mcrypt_list_algorithms() is used to get an array of all


supported algorithms in the lib_dir parameter. mcrypt_module_get_algo_block_size
mcrypt_list_algorithms() takes an optional lib_dir
parameter which specifies the directory where all
algorithms are located. If not specifies, the value of the (PHP 4 >= 4.0.2)
mcrypt.algorithms_dir php.ini directive is used. mcrypt_module_get_algo_block_size -- Returns the
Ejemplo 1. mcrypt_list_algorithms() Example blocksize of the specified algorithm

Description
<?php
$algorithms = mcrypt_list_algorithms
("/usr/local/lib/libmcrypt"); int mcrypt_module_get_algo_block_size ( string
algorithm [, string lib_dir])
foreach ($algorithms as $cipher) {
echo "$cipher<br />\n"; This function returns the block size of the algorithm
} specified in bytes. The optional lib_dir parameter can
?> contain the location where the mode module is on the
system.

The above example will produce a list with all supported


algorithms in the "/usr/local/lib/libmcrypt" directory. mcrypt_module_get_algo_key_size

mcrypt_list_modes (PHP 4 >= 4.0.2)


mcrypt_module_get_algo_key_size -- Returns the
maximum supported keysize of the opened mode
(PHP 4 >= 4.0.2)
mcrypt_list_modes -- Get an array of all supported modes
Description

Description
int mcrypt_module_get_algo_key_size ( string
algorithm [, string lib_dir])
array mcrypt_list_modes ( [string lib_dir])
This function returns the maximum supported key size of
mcrypt_list_modes() is used to get an array of all the algorithm specified in bytes. The optional lib_dir
supported modes in the lib_dir. parameter can contain the location where the mode
mcrypt_list_modes() takes as optional parameter a module is on the system.
directory which specifies the directory where all modes
are located. If not specifies, the value of the
mcrypt.modes_dir php.ini directive is used. mcrypt_module_get_supported_key_sizes
Ejemplo 1. mcrypt_list_modes() Example
(PHP 4 >= 4.0.2)
mcrypt_module_get_supported_key_sizes -- Returns an
<?php
array with the supported keysizes of the opened
$modes =
algorithm
mcrypt_list_modes ();

foreach ($modes as Description


$mode) {
echo "$mode <br
/>\n"; array mcrypt_module_get_supported_key_sizes
} ( string algorithm [, string lib_dir])
?>
Returns an array with the key sizes supported by the
specified algorithm. If it returns an empty array then all
The above example will produce a list with all supported key sizes between 1 and
mcrypt_module_get_algo_key_size() are supported by resource mcrypt_module_open ( string algorithm,
the algorithm. The optional lib_dir parameter can contain string algorithm_directory, string mode, string
the location where the mode module is on the system. mode_directory)
See also mcrypt_enc_get_supported_key_sizes()
which is used on open encryption modules.
This function opens the module of the algorithm and the
mode to be used. The name of the algorithm is specified
mcrypt_module_is_block_algorithm_mode in algorithm, eg. "twofish" or is one of the
MCRYPT_ciphername constants. The module is closed by
calling mcrypt_module_close(). Normally it returns an
(PHP 4 >= 4.0.2) encryption descriptor, or FALSE on error.
mcrypt_module_is_block_algorithm_mode -- This function The algorithm_directory and mode_directory are used to
returns if the the specified module is a block algorithm or locate the encryption modules. When you supply a
not directory name, it is used. When you set one of these to
the empty string (""), the value set by the
mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive
Description is used. When these are not set, the default directories
that are used are the ones that were compiled in into
bool mcrypt_module_is_block_algorithm_mode libmcrypt (usally /usr/local/lib/libmcrypt).
( string mode [, string lib_dir]) Ejemplo 1. mcrypt_module_open() Example

This function returns TRUE if the mode is for use with <?php
block algorithms, otherwise it returns FALSE. (eg. FALSE $td = mcrypt_module_open (MCRYPT_DES, '',
for stream, and TRUE for cbc, cfb, ofb). The optional MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');
lib_dir parameter can contain the location where the $td = mcrypt_module_open ('rijndael-256', '', 'ofb',
mode module is on the system. '');
?>
mcrypt_module_is_block_algorithm The first line in the example above will try to open the
DES cipher from the default directory and the EBC mode
from the directory /usr/lib/mcrypt-modes. The second
(PHP 4 >= 4.0.2) example uses strings as name for the cipher an dmode,
mcrypt_module_is_block_algorithm -- This function this only works when the extension is linked against
checks whether the specified algorithm is a block libmcrypt 2.4.x or 2.5.x.
algorithm Ejemplo 2. Using mcrypt_module_open() in
encryption
Description

<?php
bool mcrypt_module_is_block_algorithm ( string /* Open the cipher */
algorithm [, string lib_dir]) $td = mcrypt_module_open ('rijndael-256', '', 'ofb',
'');
This function returns TRUE if the specified algorithm is a
block algorithm, or FALSE is it is a stream algorithm. The /* Create the IV and determine the keysize length */
optional lib_dir parameter can contain the location where $iv = mcrypt_create_iv
the algorithm module is on the system. (mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size ($td);

mcrypt_module_is_block_mode /* Create key */


$key = substr (md5 ('very secret key'), 0, $ks);

(PHP 4 >= 4.0.2) /* Intialize encryption */


mcrypt_module_is_block_mode -- This function returns if mcrypt_generic_init ($td, $key, $iv);
the the specified mode outputs blocks or not
/* Encrypt data */
$encrypted = mcrypt_generic ($td, 'This is very
Description
important data');

bool mcrypt_module_is_block_mode ( string mode [, /* Terminate encryption handler */


string lib_dir]) mcrypt_generic_deinit ($td);

/* Initialize encryption module for decryption */


This function returns TRUE if the mode outputs blocks of mcrypt_generic_init ($td, $key, $iv);
bytes or FALSE if it outputs just bytes. (eg. TRUE for cbc
and ecb, and FALSE for cfb and stream). The optional /* Decrypt encrypted string */
lib_dir parameter can contain the location where the $decrypted = mdecrypt_generic ($td, $encrypted);
mode module is on the system.
/* Terminate decryption handle and close module */
mcrypt_generic_deinit ($td);
mcrypt_module_open
mcrypt_module_close ($td);

(PHP 4 >= 4.0.2) /* Show string */


mcrypt_module_open -- This function opens the module echo trim ($decrypted)."\n";
of the algorithm and the mode to be used ?>
The first line in the example above will try to open the
DES cipher from the default directory and the EBC mode
Description
from the directory /usr/lib/mcrypt-modes. The second
example uses strings as name for the cipher an dmode,
this only works when the extension is linked against
$td = mcrypt_module_open ('des', '', 'ecb',
libmcrypt 2.4.x or 2.5.x.
'');
See also mcrypt_module_close(), mcrypt_generic(),
$key = substr ($key, 0,
mdecrypt_generic(), mcrypt_generic_init() and
mcrypt_enc_get_key_size ($td));
mcrypt_generic_deinit().
$iv_size = mcrypt_enc_get_iv_size ($td);
$iv = mcrypt_create_iv ($iv_size,
mcrypt_module_self_test MCRYPT_RAND);

/* Initialize encryption handle */


(PHP 4 >= 4.0.2) if (mcrypt_generic_init ($td, $key, $iv) !=
mcrypt_module_self_test -- This function runs a self test -1) {
on the specified module
/* Encrypt data */
$c_t = mcrypt_generic ($td,
Description $plain_text);
mcrypt_generic_deinit ($td);
bool mcrypt_module_self_test ( string algorithm [,
string lib_dir]) /* Reinitialize buffers for decryption */
mcrypt_generic_init ($td, $key, $iv);
$p_t = mdecrypt_generic ($td, $c_t);
This function runs the self test on the algorithm specified.
The optional lib_dir parameter can contain the location of /* Clean up */
where the algorithm module is on the system. mcrypt_generic_deinit ($td);
The function returns TRUE if the self test succeeds, or mcrypt_module_close ($td);
FALSE when if fails. }

if (strncmp ($p_t, $plain_text,


mcrypt_ofb strlen($plain_text)) == 0) {
echo "ok\n";
(PHP 3>= 3.0.8, PHP 4 ) } else {
mcrypt_ofb -- Encripta/desencripta datos en modo OFB echo "error\n";
}
?>
Descripción The above example shows how to check if the data
before the encryption is the same as the data after the
int mcrypt_ofb ( int cipher, string key, string data, int decryption. It is very important to reinitialize the
mode, string iv) encryption buffer with mcrypt_generic_init() before
you try to decrypt the data.
The decryption handle should alwayws be initialized with
mcrypt_ofb() encripta o desencripta (dependiendo de mcrypt_generic_init() with a key and an IV before
mode) los datos data con el cifrado cipher y la clave key calling this function. Where the encryption is done, you
en el modo de cifrado OFB y devuelve la cadena should free the encryption buffers by calling
resultante. mcrypt_generic_deinit(). See
El parámetro cipher es una de las constantes con nombre mcrypt_module_open() for an example.
MCRYPT_nombrecifrado. See also mcrypt_generic(), mcrypt_generic_init() and
key es la clave suministrada al algoritmo. Debe mcrypt_generic_deinit().
guardarse en secreto.
data son los datos que serán encriptados/desencriptados.
mode es MCRYPT_ENCRYPT o MCRYPT_DECRYPT. LV. MCVE Payment Functions
iv es el vector de inicialización.
Ver también: mcrypt_cbc(), mcrypt_cfb(),
mcrypt_ecb() Introducción

mdecrypt_generic These functions interface the MCVE API (libmcve),


allowing you to work directly with MCVE from your PHP
scripts. MCVE is Main Street Softworks' solution to direct
(PHP 4 >= 4.0.2) credit card processing. It lets you directly address the
mdecrypt_generic -- This function decrypts data credit card clearing houses via your *nix box, modem
and/or internet connection (bypassing the need for an
additional service such as Authorize.Net or Pay Flow Pro).
Description Using the MCVE module for PHP, you can process credit
cards directly through MCVE via your PHP scripts. The
following references will outline the process.
string mdecrypt_generic ( resource td, string data)

This function decrypts data. Note that the length of the Nota: MCVE is the replacement for
returned string can in fact be longer then the RedHat's CCVS. They contracted
unencrypted string, due to the padding of the data. with RedHat in late 2001 to migrate
Ejemplo 1. mdecrypt_generic() Example all existing clientelle to the MCVE
platform.

<?php Nota: This extension is not available


/* Data */ on Windows platforms.
$key = 'this is a very long key, even too
long for the cipher';
$plain_text = 'very important data';

/* Open module, and create IV */ Instalación


To enable MCVE Support in PHP, first verify your LibMCVE mcve_initconn -- Create and initialize an MCVE_CONN
installation directory. You will then need to configure PHP structure
with the --with-mcve option. If you use this option mcve_initengine -- Ready the client for IP/SSL
without specifying the path to your MCVE installation, Communication
PHP will attempt to look in the default LibMCVE Install mcve_initusersetup -- Initialize structure to store user
location (/usr/local). If MCVE is in a non-standard location, data
run configure with: --with-mcve=$mcve_path, where mcve_iscommadelimited -- Checks to see if response is
$mcve_path is the path to your MCVE installation. Please comma delimited
note that MCVE support requires that $mcve_path/lib and mcve_liststats -- List statistics for all users on MCVE
$mcve_path/include exist, and include mcve.h under the system
include directory and libmcve.so and/or libmcve.a under mcve_listusers -- List all users on MCVE system
the lib directory. mcve_maxconntimeout -- The maximum amount of time
Since MCVE has true server/client separation, there are the API will attempt a connection to MCVE
no additional requirements for running PHP with MCVE mcve_monitor -- Perform communication with MCVE
support. To test your MCVE extension in PHP, you may (send/receive data) Non-blocking
connect to testbox.mcve.com on port 8333 for IP, or port mcve_numcolumns -- Number of columns returned in a
8444 for SSL using the MCVE PHP API. Use 'vitale' for comma delimited response
your username, and 'test' for your password. Additional mcve_numrows -- Number of rows returned in a comma
information about test facilities are available at delimited response
http://www.mcve.com/. mcve_override -- Send an OVERRIDE to MCVE
mcve_parsecommadelimited -- Parse the comma
delimited response so mcve_getcell, etc will work
Ver tambien mcve_ping -- Send a ping request to MCVE
mcve_preauth -- Send a PREAUTHORIZATION to MCVE
mcve_preauthcompletion -- Complete a
Additional documentation about MCVE's PHP API can be PREAUTHORIZATION... Ready it for settlement
found at http://www.mcve.com/docs/phpapi.pdf. Main mcve_qc -- Audit MCVE for a list of transactions in the
Street's documentation is complete and should be the outgoing queue
primary reference for functions. mcve_responseparam -- Get a custom response
Tabla de contenidos parameter
mcve_adduser -- Add an MCVE user using usersetup mcve_return -- Issue a RETURN or CREDIT to MCVE
structure mcve_returncode -- Grab the exact return code from the
mcve_adduserarg -- Add a value to user configuration transaction
structure mcve_returnstatus -- Check to see if the transaction was
mcve_bt -- Get unsettled batch totals successful
mcve_checkstatus -- Check to see if a transaction has mcve_sale -- Send a SALE to MCVE
completed mcve_setblocking -- Set blocking/non-blocking mode for
mcve_chkpwd -- Verify Password connection
mcve_chngpwd -- Change the system administrator's mcve_setdropfile -- Set the connection method to Drop-
password File
mcve_completeauthorizations -- Number of complete mcve_setip -- Set the connection method to IP
authorizations in queue, returning an array of their mcve_setssl -- Set the connection method to SSL
identifiers mcve_settimeout -- Set maximum transaction time (per
mcve_connect -- Establish the connection to MCVE trans)
mcve_connectionerror -- Get a textual representation of mcve_settle -- Issue a settlement command to do a
why a connection failed batch deposit
mcve_deleteresponse -- Delete specified transaction mcve_text_avs -- Get a textual representation of the
from MCVE_CONN structure return_avs
mcve_deletetrans -- Delete specified transaction from mcve_text_code -- Get a textual representation of the
MCVE_CONN structure return_code
mcve_deleteusersetup -- Deallocate data associated mcve_text_cv -- Get a textual representation of the
with usersetup structure return_cv
mcve_deluser -- Delete an MCVE user account mcve_transactionauth -- Get the authorization number
mcve_destroyconn -- Destroy the connection and returned for the transaction (alpha-numeric)
MCVE_CONN structure mcve_transactionavs -- Get the Address Verification
mcve_destroyengine -- Free memory associated with return status
IP/SSL connectivity mcve_transactionbatch -- Get the batch number
mcve_disableuser -- Disable an active MCVE user associated with the transaction
account mcve_transactioncv -- Get the CVC2/CVV2/CID return
mcve_edituser -- Edit MCVE user using usersetup status
structure mcve_transactionid -- Get the unique system id for the
mcve_enableuser -- Enable an inactive MCVE user transaction
account mcve_transactionitem -- Get the ITEM number in the
mcve_force -- Send a FORCE to MCVE. (typically, a associated batch for this transaction
phone-authorization) mcve_transactionssent -- Check to see if outgoing buffer
mcve_getcell -- Get a specific cell from a comma is clear
delimited response by column name mcve_transactiontext -- Get verbiage (text) return from
mcve_getcellbynum -- Get a specific cell from a comma MCVE or processing institution
delimited response by column number mcve_transinqueue -- Number of transactions in client-
mcve_getcommadelimited -- Get the RAW comma queue
delimited data returned from MCVE mcve_transnew -- Start a new transaction
mcve_getheader -- Get the name of the column in a mcve_transparam -- Add a parameter to a transaction
comma-delimited response mcve_transsend -- Finalize and send the transaction
mcve_getuserarg -- Grab a value from usersetup mcve_ub -- Get a list of all Unsettled batches
structure mcve_uwait -- Wait x microsecs
mcve_getuserparam -- Get a user response parameter mcve_verifyconnection -- Set whether or not to PING
mcve_gft -- Audit MCVE for Failed transactions upon connect to verify connection
mcve_gl -- Audit MCVE for settled transactions mcve_verifysslcert -- Set whether or not to verify the
mcve_gut -- Audit MCVE for Unsettled Transactions server ssl certificate
mcve_void -- VOID a transaction in the settlement queue mcve_chkpwd

mcve_adduser (PHP 4 >= 4.2.0)


mcve_chkpwd -- Verify Password

(PHP 4 >= 4.2.0)


mcve_adduser -- Add an MCVE user using usersetup Description
structure

int mcve_chkpwd ( resource conn, string username,


Description string password)

int mcve_adduser ( resource conn, string Aviso


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

(PHP 4 >= 4.2.0)


mcve_adduserarg mcve_chngpwd -- Change the system administrator's
password

(PHP 4 >= 4.2.0)


mcve_adduserarg -- Add a value to user configuration Description
structure

int mcve_chngpwd ( resource conn, string


Description admin_password, string new_password)

int mcve_adduserarg ( resource usersetup, int argtype, Aviso


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

(PHP 4 >= 4.2.0)


mcve_bt mcve_completeauthorizations -- Number of complete
authorizations in queue, returning an array of their
identifiers
(PHP 4 >= 4.2.0)
mcve_bt -- Get unsettled batch totals
Description

Description
int mcve_completeauthorizations ( resource conn, int
&array)
int mcve_bt ( resource conn, string username, string
password)
Aviso

Aviso Esta función no está documentada actualmente, solamente


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

mcve_checkstatus
(PHP 4 >= 4.2.0)
mcve_connect -- Establish the connection to MCVE
(PHP 4 >= 4.2.0)
mcve_checkstatus -- Check to see if a transaction has
completed Description

Description int mcve_connect ( resource conn)

int mcve_checkstatus ( resource conn, int identifier) Aviso


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

Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros. mcve_connectionerror
(PHP 4 >= 4.3.0) Description
mcve_connectionerror -- Get a textual representation of
why a connection failed
int mcve_deluser ( resource conn, string
admin_password, string username)
Description

Aviso
string mcve_connectionerror ( resource conn)
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Aviso
Esta función no está documentada actualmente, solamente mcve_destroyconn
se encuentra disponible la lista de parametros.

(PHP 4 >= 4.2.0)


mcve_deleteresponse mcve_destroyconn -- Destroy the connection and
MCVE_CONN structure

(PHP 4 >= 4.2.0)


mcve_deleteresponse -- Delete specified transaction Description
from MCVE_CONN structure

void mcve_destroyconn ( resource conn)


Description

Aviso
bool mcve_deleteresponse ( resource conn, int
identifier) Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

Aviso
mcve_destroyengine
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.2.0)
mcve_destroyengine -- Free memory associated with
mcve_deletetrans IP/SSL connectivity

(PHP 4 >= 4.3.0) Description


mcve_deletetrans -- Delete specified transaction from
MCVE_CONN structure
void mcve_destroyengine ( void)

Description
Aviso

bool mcve_deletetrans ( resource conn, int identifier) Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

Aviso
mcve_disableuser
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.2.0)
mcve_disableuser -- Disable an active MCVE user
mcve_deleteusersetup account

(PHP 4 >= 4.2.0) Description


mcve_deleteusersetup -- Deallocate data associated
with usersetup structure
int mcve_disableuser ( resource conn, string
admin_password, string username)
Description

Aviso
void mcve_deleteusersetup ( resource usersetup)
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Aviso
Esta función no está documentada actualmente, solamente mcve_edituser
se encuentra disponible la lista de parametros.

(PHP 4 >= 4.2.0)


mcve_deluser mcve_edituser -- Edit MCVE user using usersetup
structure

(PHP 4 >= 4.2.0)


mcve_deluser -- Delete an MCVE user account Description
int mcve_edituser ( resource conn, string string mcve_getcellbynum ( resource conn, int
admin_password, int usersetup) identifier, int column, int row)

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

mcve_enableuser mcve_getcommadelimited

(PHP 4 >= 4.2.0) (PHP 4 >= 4.2.0)


mcve_enableuser -- Enable an inactive MCVE user mcve_getcommadelimited -- Get the RAW comma
account delimited data returned from MCVE

Description Description

int mcve_enableuser ( resource conn, string string mcve_getcommadelimited ( resource conn, int
admin_password, string username) identifier)

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

mcve_force mcve_getheader

(PHP 4 >= 4.2.0) (PHP 4 >= 4.2.0)


mcve_force -- Send a FORCE to MCVE. (typically, a mcve_getheader -- Get the name of the column in a
phone-authorization) comma-delimited response

Description Description

int mcve_force ( resiurce conn, string username, string string mcve_getheader ( resource conn, int identifier,
password, string trackdata, string account, string int column_num)
expdate, float amount, string authcode, string
comments, string clerkid, string stationid, int ptrannum)
Aviso
Esta función no está documentada actualmente, solamente
Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_getuserarg

mcve_getcell
(PHP 4 >= 4.2.0)
mcve_getuserarg -- Grab a value from usersetup
(PHP 4 >= 4.2.0) structure
mcve_getcell -- Get a specific cell from a comma
delimited response by column name
Description

Description
string mcve_getuserarg ( resource usersetup, int
argtype)
string mcve_getcell ( resource conn, int identifier, string
column, int row)
Aviso
Esta función no está documentada actualmente, solamente
Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_getuserparam

mcve_getcellbynum
(PHP 4 >= 4.3.0)
mcve_getuserparam -- Get a user response parameter
(PHP 4 >= 4.2.0)
mcve_getcellbynum -- Get a specific cell from a comma
delimited response by column number Description

Description string mcve_getuserparam ( resource conn, long


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

mcve_gft mcve_initengine

(PHP 4 >= 4.2.0) (PHP 4 >= 4.2.0)


mcve_gft -- Audit MCVE for Failed transactions mcve_initengine -- Ready the client for IP/SSL
Communication

Description
Description

int mcve_gft ( resource conn, string username, string


password, int type, string account, string clerkid, string int mcve_initengine ( string location)
stationid, string comments, int ptrannum, string
startdate, string enddate)
Aviso
Esta función no está documentada actualmente, solamente
Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_initusersetup

mcve_gl
(PHP 4 >= 4.2.0)
mcve_initusersetup -- Initialize structure to store user
(PHP 4 >= 4.2.0) data
mcve_gl -- Audit MCVE for settled transactions

Description
Description

resource mcve_initusersetup ( void)


int mcve_gl ( int conn, string username, string password,
int type, string account, string batch, string clerkid, string
stationid, string comments, int ptrannum, string Aviso
startdate, string enddate) Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Aviso
Esta función no está documentada actualmente, solamente mcve_iscommadelimited
se encuentra disponible la lista de parametros.

(PHP 4 >= 4.2.0)


mcve_gut mcve_iscommadelimited -- Checks to see if response is
comma delimited

(PHP 4 >= 4.2.0)


mcve_gut -- Audit MCVE for Unsettled Transactions Description

Description int mcve_iscommadelimited ( resource conn, int


identifier)

int mcve_gut ( resource conn, string username, string


password, int type, string account, string clerkid, string Aviso
stationid, string comments, int ptrannum, string Esta función no está documentada actualmente, solamente
startdate, string enddate) se encuentra disponible la lista de parametros.

Aviso
mcve_liststats
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.2.0)
mcve_liststats -- List statistics for all users on MCVE
mcve_initconn system

(PHP 4 >= 4.2.0) Description


mcve_initconn -- Create and initialize an MCVE_CONN
structure
int mcve_liststats ( resource conn, string
admin_password)
Description
Aviso
resource mcve_initconn ( void)
Esta función no está documentada actualmente, solamente mcve_numrows
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.2.0)
mcve_numrows -- Number of rows returned in a comma
mcve_listusers delimited response

(PHP 4 >= 4.2.0) Description


mcve_listusers -- List all users on MCVE system

int mcve_numrows ( resource conn, int identifier)


Description

Aviso
int mcve_listusers ( resource conn, string
admin_password) Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

Aviso
Esta función no está documentada actualmente, solamente mcve_override
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.2.0)
mcve_override -- Send an OVERRIDE to MCVE
mcve_maxconntimeout

Description
(PHP 4 >= 4.3.0)
mcve_maxconntimeout -- The maximum amount of time
the API will attempt a connection to MCVE int mcve_override ( resource conn, string username,
string password, string trackdata, string account, string
expdate, float amount, string street, string zip, string cv,
Description string comments, string clerkid, string stationid, int
ptrannum)
bool mcve_maxconntimeout ( resource conn, int secs)
Aviso
Aviso Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_parsecommadelimited
mcve_monitor
(PHP 4 >= 4.2.0)
mcve_parsecommadelimited -- Parse the comma
(PHP 4 >= 4.2.0)
delimited response so mcve_getcell, etc will work
mcve_monitor -- Perform communication with MCVE
(send/receive data) Non-blocking
Description
Description
int mcve_parsecommadelimited ( resource conn, int
identifier)
int mcve_monitor ( resource conn)

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

mcve_ping
mcve_numcolumns

(PHP 4 >= 4.3.0)


(PHP 4 >= 4.2.0)
mcve_ping -- Send a ping request to MCVE
mcve_numcolumns -- Number of columns returned in a
comma delimited response
Description
Description
int mcve_ping ( resource conn)
int mcve_numcolumns ( resource conn, int identifier)
Aviso
Aviso Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_preauth
(PHP 4 >= 4.2.0) mcve_return
mcve_preauth -- Send a PREAUTHORIZATION to MCVE

(PHP 4 >= 4.2.0)


Description mcve_return -- Issue a RETURN or CREDIT to MCVE

int mcve_preauth ( resource conn, string username, Description


string password, string trackdata, string account, string
expdate, float amount, string street, string zip, string cv,
string comments, string clerkid, string stationid, int int mcve_return ( int conn, string username, string
ptrannum) password, string trackdata, string account, string
expdate, float amount, string comments, string clerkid,
string stationid, int ptrannum)
Aviso
Esta función no está documentada actualmente, solamente Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_preauthcompletion

mcve_returncode
(PHP 4 >= 4.2.0)
mcve_preauthcompletion -- Complete a
PREAUTHORIZATION... Ready it for settlement (PHP 4 >= 4.2.0)
mcve_returncode -- Grab the exact return code from the
transaction
Description

Description
int mcve_preauthcompletion ( resource conn, string
username, string password, float finalamount, int sid, int
ptrannum) int mcve_returncode ( resource conn, int identifier)

Aviso Aviso

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

mcve_qc mcve_returnstatus

(PHP 4 >= 4.2.0) (PHP 4 >= 4.2.0)


mcve_qc -- Audit MCVE for a list of transactions in the mcve_returnstatus -- Check to see if the transaction was
outgoing queue successful

Description Description

int mcve_qc ( resource conn, string username, string int mcve_returnstatus ( resource conn, int identifier)
password, string clerkid, string stationid, string
comments, int ptrannum)
Aviso
Esta función no está documentada actualmente, solamente
Aviso se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_sale

mcve_responseparam
(PHP 4 >= 4.2.0)
mcve_sale -- Send a SALE to MCVE
(PHP 4 >= 4.3.0)
mcve_responseparam -- Get a custom response
Description
parameter

int mcve_sale ( resource conn, string username, string


Description
password, string trackdata, string account, string
expdate, float amount, string street, string zip, string cv,
string mcve_responseparam ( resource conn, long string comments, string clerkid, string stationid, int
identifier, string key) ptrannum)

Aviso Aviso

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

(PHP 4 >= 4.3.0) int mcve_settimeout ( resource conn, int seconds)


mcve_setblocking -- Set blocking/non-blocking mode for
connection
Aviso

Description Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros.

int mcve_setblocking ( resource conn, int tf)


mcve_settle

Aviso
(PHP 4 >= 4.2.0)
Esta función no está documentada actualmente, solamente mcve_settle -- Issue a settlement command to do a
se encuentra disponible la lista de parametros. batch deposit

mcve_setdropfile Description

(PHP 4 >= 4.2.0) int mcve_settle ( resource conn, string username, string
mcve_setdropfile -- Set the connection method to Drop- password, string batch)
File

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
int mcve_setdropfile ( resource conn, string directory)

mcve_text_avs
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.3.0)
se encuentra disponible la lista de parametros. mcve_text_avs -- Get a textual representation of the
return_avs

mcve_setip
Description

(PHP 4 >= 4.2.0)


mcve_setip -- Set the connection method to IP string mcve_text_avs ( string code)

Description Aviso
Esta función no está documentada actualmente, solamente
int mcve_setip ( resource conn, string host, int port) se encuentra disponible la lista de parametros.

Aviso mcve_text_code
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. (PHP 4 >= 4.3.0)
mcve_text_code -- Get a textual representation of the
return_code
mcve_setssl

Description
(PHP 4 >= 4.2.0)
mcve_setssl -- Set the connection method to SSL
string mcve_text_code ( string code)

Description
Aviso
int mcve_setssl ( resource conn, string host, int port) Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

Aviso
Esta función no está documentada actualmente, solamente mcve_text_cv
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.3.0)
mcve_text_cv -- Get a textual representation of the
mcve_settimeout return_cv

(PHP 4 >= 4.2.0) Description


mcve_settimeout -- Set maximum transaction time (per
trans)
string mcve_text_cv ( int code)
Aviso Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_transactionid
mcve_transactionauth
(PHP 4 >= 4.2.0)
mcve_transactionid -- Get the unique system id for the
(PHP 4 >= 4.2.0)
transaction
mcve_transactionauth -- Get the authorization number
returned for the transaction (alpha-numeric)
Description
Description
int mcve_transactionid ( resource conn, int identifier)
string mcve_transactionauth ( resource conn, int
identifier) Aviso
Esta función no está documentada actualmente, solamente
Aviso se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_transactionitem

mcve_transactionavs (PHP 4 >= 4.2.0)


mcve_transactionitem -- Get the ITEM number in the
associated batch for this transaction
(PHP 4 >= 4.2.0)
mcve_transactionavs -- Get the Address Verification
return status Description

Description int mcve_transactionitem ( resource conn, int


identifier)
int mcve_transactionavs ( resource conn, int identifier)
Aviso
Aviso Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_transactionssent
mcve_transactionbatch
(PHP 4 >= 4.2.0)
mcve_transactionssent -- Check to see if outgoing buffer
(PHP 4 >= 4.2.0)
is clear
mcve_transactionbatch -- Get the batch number
associated with the transaction
Description
Description
int mcve_transactionssent ( resource conn)
int mcve_transactionbatch ( resource conn, int
identifier) Aviso
Esta función no está documentada actualmente, solamente
Aviso se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_transactiontext

mcve_transactioncv (PHP 4 >= 4.2.0)


mcve_transactiontext -- Get verbiage (text) return from
MCVE or processing institution
(PHP 4 >= 4.2.0)
mcve_transactioncv -- Get the CVC2/CVV2/CID return
status Description

Description string mcve_transactiontext ( resource conn, int


identifier)
int mcve_transactioncv ( resource conn, int identifier)
Aviso
Aviso Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
mcve_transinqueue Description

(PHP 4 >= 4.2.0) int mcve_ub ( resource conn, string username, string
mcve_transinqueue -- Number of transactions in client- password)
queue

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
int mcve_transinqueue ( resource conn)

mcve_uwait
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.3.0)
se encuentra disponible la lista de parametros. mcve_uwait -- Wait x microsecs

mcve_transnew Description

(PHP 4 >= 4.3.0) int mcve_uwait ( long microsecs)


mcve_transnew -- Start a new transaction

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
int mcve_transnew ( resource conn)

mcve_verifyconnection
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.3.0)
se encuentra disponible la lista de parametros. mcve_verifyconnection -- Set whether or not to PING
upon connect to verify connection

mcve_transparam
Description

(PHP 4 >= 4.3.0)


mcve_transparam -- Add a parameter to a transaction bool mcve_verifyconnection ( resource conn, int tf)

Description Aviso
Esta función no está documentada actualmente, solamente
int mcve_transparam ( resource conn, long identifier, se encuentra disponible la lista de parametros.
int key)

mcve_verifysslcert
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.3.0)
se encuentra disponible la lista de parametros. mcve_verifysslcert -- Set whether or not to verify the
server ssl certificate

mcve_transsend
Description

(PHP 4 >= 4.3.0)


mcve_transsend -- Finalize and send the transaction bool mcve_verifysslcert ( resource conn, int tf)

Description Aviso
Esta función no está documentada actualmente, solamente
int mcve_transsend ( resource conn, long identifier) se encuentra disponible la lista de parametros.

Aviso mcve_void
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. (PHP 4 >= 4.2.0)
mcve_void -- VOID a transaction in the settlement queue

mcve_ub
Description

(PHP 4 >= 4.2.0)


mcve_ub -- Get a list of all Unsettled batches int mcve_void ( resource conn, string username, string
password, int sid, int ptrannum)
Aviso (PHP 3>= 3.0.9, PHP 4 )
mhash_count -- Obtener el valor mayor del id hash
Esta función no está documentada actualmente, solamente disponible
se encuentra disponible la lista de parametros.

Descripcion
LVI. Funciones Hash
int mhash_count ( void)
Estas funciones han sido realizadas para trabajar con
mhash. mhash_count() devuelve el valor mas alto id hash
Esta es una interfaz con al libreria mhash. mhash soporta disponible. Los hash estan numerados desde 0 hasta
una amplia variedad de algoritmos hash como MD5, este valor.
SHA1, GOST, y muchos otros. Ejemplo 1. Recorriendo todos los hash
Para usarla, hay que descargar la distribucion desde su
sitio web y seguir las intrucciones de instalacion. Se
necesita compilar PHP con el parametr --with-mhash para <?php
activar esta extension.
mhash puede ser usado para crear checksums, message $nr = mhash_count();
digests, y mas.
Ejemplo 1. Generar una clave SHA1 e imprimirla en for($i = 0; $i <= $nr; $i++) {
hexadecimal echo sprintf("The blocksize of
%s is %d\n",
mhash_get_hash_name($i
<?php ),
$input = "Let us meet at 9 o' clock at mhash_get_block_size($i))
the secret place."; ;
$hash = mhash(MHASH_SHA1, $input); }
?>
print "The hash is ".bin2hex($hash)."\n";

?> mhash_get_block_size
Esto generara:
The hash is (PHP 3>= 3.0.9, PHP 4 )
d3b85d710d8f6e4e5efd4d5e67d041f9cece mhash_get_block_size -- Conseguir el tamaño de bloque
dafe de el hash especificado
PAra una lista complera de hash soportados, refierase a
la documentacion de mhash. La regla general es que se Descripcion
puede acceder a los algoritmos hash desde PHP con
MHASH_HASHNAME. Como ejemplo, para acceder a
HAVAL se debe usar la constante de PHP llamada int mhash_get_block_size ( int hash)
MHASH_HAVAL.
Aqui hay una lista de hashes que esta actualmente
mhash_get_block_size() es usado para obtener el
soportada por mhash. Si un hash no esta en dicha lista
tamaño de un bloque de el hash determinado.
pero aparece como soportado por mhash, entonces se
mhash_get_block_size() toma un argumento, el hash y
asume con plena seguridad que esta documentacion esta
devuelve el tamaño en bytes o FALSE, si el hash no
desfasada.
existe.

• MHASH_MD5 mhash_get_hash_name
• MHASH_SHA1
• MHASH_HAVAL (PHP 3>= 3.0.9, PHP 4 )
mhash_get_hash_name -- Conseguir el nombre de un
• MHASH_RIPEMD160 hash especifico
• MHASH_RIPEMD128
• MHASH_SNEFRU Descripcion
• MHASH_TIGER
• MHASH_GOST string mhash_get_hash_name ( int hash)

• MHASH_CRC32
mhash_get_hash_name() es usado para conseguir el
• MHASH_CRC32B nombre de el hash determinado.
mhash_get_hash_name() toma el id del hash como un
argumento y devuelve el nombre de el hash o FALSE, si
Tabla de contenidos el hash no existe.
mhash_count -- Obtener el valor mayor del id hash Ejemplo 1. mhash_get_hash_name example
disponible
mhash_get_block_size -- Conseguir el tamaño de bloque
de el hash especificado
<?php
mhash_get_hash_name -- Conseguir el nombre de un
$hash = MHASH_MD5;
hash especifico
mhash_keygen_s2k -- Generates a key
print
mhash -- Calcular el hash
mhash_get_hash_name($ha
sh);
mhash_count ?>
El ejemplo anterior mostrara: You must compile PHP with the configure switch --enable-
mime-magic to get support for mime-type functions. The
MD5
extension needs a copy of the magic.mime as distributed
with the file command. This file also part of most recent
Linux distributions and usually stored in the
mhash_keygen_s2k /usr/share/misc directory.

(PHP 4 >= 4.0.4)


Configuración en tiempo de ejecución
mhash_keygen_s2k -- Generates a key

The behaviour of these functions is affected by settings


Description
in php.ini.
Tabla 1. Mimetype configuration options
string mhash_keygen_s2k ( int hash, string password, Name Default Changeable
string salt, int bytes)
mime_magic.ma "/usr/share/misc/magi PHP_INI_SYSTE
gicfile c.mime" M
mhash_keygen_s2k() generates a key that is bytes
long, from a user given password. This is the Salted S2K For further details and definition of the PHP_INI_*
algorithm as specified in the OpenPGP document (RFC constants see ini_set().
2440). That algorithm will use the specified hash
algorithm to create the key. The salt must be different
and random enough for every key you generate in order Tipos de recursos
to create different keys. That salt must be known when
you check the keys, thus it is a good idea to append the Esta extensión no define ningún tipo de recurso.
key to it. Salt has a fixed length of 8 bytes and will be
padded with zeros if you supply less bytes.
Keep in mind that user supplied passwords are not really Constantes predefinidas
suitable to be used as keys in cryptographic algorithms,
since users normally choose keys they can write on
keyboard. These passwords use only 6 to 7 bits per Esta extensión no define ninguna constante.
character (or less). It is highly recommended to use some Tabla de contenidos
kind of tranformation (like this function) to the user mime_content_type -- Detect MIME Content-type for a file
supplied key.
mime_content_type
mhash
(PHP 4 >= 4.3.0)
(PHP 3>= 3.0.9, PHP 4 ) mime_content_type -- Detect MIME Content-type for a file
mhash -- Calcular el hash
Description
Descripcion
string mime_content_type ( string filename)
string mhash ( int hash, string data)
Returns the MIME content type for a file as determined
mhash() aplica una funcion hash especificada por hash by using information from the magic.mime file. Content
a data y devuelve el valor hash resultante (tambien types are returned in MIME format, like text/plain or
llamdo digest). application/octet-stream.

LVII. Mimetype Functions LVIII. Funciones de Microsoft SQL Server

Introducción Tabla de contenidos


mssql_bind -- Adds a parameter to a stored procedure or
a remote stored procedure
The functions in this module try to guess the content mssql_close -- cierra una conexión con MS SQL Server
type and encoding of a file by looking for certain magic mssql_connect -- abre una conexión con MS SQL server
byte sequences at specific positions within the file. While mssql_data_seek -- mueve el puntero interno de las filas
this is not a bullet proof approach the heuristics used do mssql_execute -- Executes a stored procedure on a MS
a very good job. SQL server database
This extension is derivated from Apache mssql_fetch_array -- Captura la fila en un array
mod_mime_magic, which is itself based on the file mssql_fetch_assoc -- Returns an associative array of the
command maintaind by Ian F. Darwin. See the source current row in the result set specified by result_id
code for further historic and copyright information. mssql_fetch_batch -- Returns the next batch of records
mssql_fetch_field -- obtiene la información de los campos
mssql_fetch_object -- captura la fila como un objeto
Requerimientos mssql_fetch_row -- obtiene la fila como un array
numerado
Estas funciones están disponibles como parte del módulo mssql_field_length -- Get the length of a field
estandar, el cual está siempre disponible. mssql_field_name -- Get the name of a field
mssql_field_seek -- set field offset
mssql_field_type -- Get the type of a field
Instalación mssql_free_result -- libera de la memoria el resultado de
una consulta
mssql_free_statement -- Free statement memory
mssql_get_last_message -- Returns the last message int mssql_connect ( string servername, string
from server (over min_message_severity?) username, string password)
mssql_guid_string -- Converts a 16 byte binary GUID to a
string
Devuelve: Un identificador de MSSQL si se ejecuta
mssql_init -- Initializes a stored procedure or a remote
correctamente, o FALSE si se produce un error.
stored procedure
mssql_connect() establece una conexión con MS SQL
mssql_min_error_severity -- Sets the lower error severity
server. El argumento servername debe ser un nombre de
mssql_min_message_severity -- Sets the lower message
servidor válido, que está definido en el fichero
severity
'interfaces'.
mssql_next_result -- Move the internal result pointer to
En caso de hacer una segunda llamada a
the next result
mssql_connect() con los mismos argumentos, no se
mssql_num_fields -- obtiene el número de campos de la
establecerá una nueva conexión, sino que se devolverá
consulta
el identificador de la conexión establecida anteriormente.
mssql_num_rows -- obtiene el número de filas de la
La conexión con el servidor se cerrará tan pronto como
consulta
finalice el script, a menos que se cierre antes, mediante
mssql_pconnect -- abre una conexión persistenete con
una llamada explicita a la función mssql_close().
MS SQL
Ver también mssql_pconnect(), mssql_close().
mssql_query -- envia una consulta MS SQL
mssql_result -- get result data
mssql_rows_affected -- Returns the number of records mssql_data_seek
affected by the query
mssql_select_db -- selecciona una base de datos MS SQL
(PHP 3, PHP 4 )
mssql_data_seek -- mueve el puntero interno de las filas
mssql_bind

Descripción
(PHP 4 >= 4.1.0)
mssql_bind -- Adds a parameter to a stored procedure or
a remote stored procedure int mssql_data_seek ( int result_identifier, int
row_number)

Description
Devuelve: TRUE si se ejecuta con éxito, FALSE si falla.
mssql_data_seek() mueve el puntero interno de la
int mssql_bind ( int stmt, string param_name, mixed consulta MS SQL asociada al result_identifier
var, int type [, int is_output [, int is_null [, int maxlen]]]) especificado, para que apunte al número de fila
especificada. La siguiente llamada a mssql_fetch_row()
devolverá esa fila.
Aviso Ver también: mssql_data_seek().
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. mssql_execute
See also mssql_execute(), mssql_free_statement()
and mssql_init()
(PHP 4 >= 4.1.0)
mssql_execute -- Executes a stored procedure on a MS
mssql_close SQL server database

(PHP 3, PHP 4 ) Description


mssql_close -- cierra una conexión con MS SQL Server
int mssql_execute ( int stmt)
Descripción

Aviso
int mssql_close ( int link_identifier)
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Devuleve: TRUE si se finaliza con éxito, FALSE si se
produce un error
mssql_close() cierra la conexión con una base de datos Nota: if the stored procedure
MS SQL Server que está asociada al identificador returns parameters or a return value
especificado. Si el identificador no se especifica, se these will be available after the call
asume la última conexión abierta. to mssql_execute() unless the
Observe que normalmente esto no es necesario, ya que stored procedure returns more than
las conexiones no-persistentes abiertas se cierran one result set. In that case use
automaticamente en cuanto finaliza el script. mssql_next_result() to shift
mssql_close() no cerrará conexiones persistentes through the results. When the last
generadas por mssql_pconnect(). result has been processed the
Ver también: mssql_connect(), mssql_pconnect(). output parameters and return values
will be available.
mssql_connect
See also mssql_bind(), mssql_free_statement() and
mssql_init()
(PHP 3, PHP 4 )
mssql_connect -- abre una conexión con MS SQL server
mssql_fetch_array
Descripción
(PHP 3, PHP 4 )
mssql_fetch_array -- Captura la fila en un array
• name - nombre de la columna. si la columna es
el resultado de una función, esta propiedad
Descripción vale #N, donde #N es un número de serie.
• column_source - la tabla de donde se tomó la
int mssql_fetch_array ( int result) columna
• max_length - longitud máxima de columna
Devuelve: Un array que corresponde a la fila capturada, • numeric - 1 si la columna es numérica
o FALSE si no hay más filas.
mssql_fetch_array() es una versión extendida de
mssql_fetch_row(). A¤ade el almacenar los datos en los Ver también mssql_field_seek()
índices numéricos del array resultante, también
almacena los datos en índices asociativos, usando los
mssql_fetch_object
nombres de los campos como claves.
Una observación a tener en cuenta es, que usar
mssql_fetch_array() NO es más lento que usar (PHP 3)
mssql_fetch_row(), mientras que esta provee un valor mssql_fetch_object -- captura la fila como un objeto
a¤adido significativo.
Para más detalles, ver también mssql_fetch_row()
Descripción

mssql_fetch_assoc
int mssql_fetch_object ( int result)

(PHP 4 >= 4.2.0)


mssql_fetch_assoc -- Returns an associative array of the Devuelve: Un objeto con propiedades que se
current row in the result set specified by result_id corresponden con la fila capturada, o FALSE si no hay
más filas.
mssql_fetch_object() es parecida a
Description mssql_fetch_array(), con una diferencia - devuelve un
objeto en vez de un array. Indirectamente, esto significa
que sólo se puede acceder a los datos por el nombre de
array mssql_fetch_assoc ( int result_id [, int los campos, y no por sus posiciones en el objeto (los
result_type]) números no son nombres de propiedades válidas).
La función es idéntica a mssql_fetch_array(), y casi tan
rápida como mssql_fetch_row() (la diferencia es
Aviso
insignificante).
Esta función no está documentada actualmente, solamente Ver también: mssql_fetch-array() and mssql_fetch-
se encuentra disponible la lista de parametros. row().

mssql_fetch_row
mssql_fetch_batch

(PHP 3, PHP 4 )
(PHP 4 >= 4.0.4)
mssql_fetch_row -- obtiene la fila como un array
mssql_fetch_batch -- Returns the next batch of records
numerado

Description
Descripción

int mssql_fetch_batch ( string result_index)


array mssql_fetch_row ( int result)

Aviso Devuleve: Un array que corresponde a la fila capturada,


Esta función no está documentada actualmente, solamente o FALSE si no hay más filas.
se encuentra disponible la lista de parametros. mssql_fetch_row() captura una fila de datos
pertenecientes al resultado asociado con el identificador
de resultado especificado. La fila es devuelta como un
array. Cada columna de resultados es almacenada en
mssql_fetch_field
una posición del array, comenzando en la posición 0.
Siguientes llamadas a mssql_fetch_rows() devolverían las
(PHP 3, PHP 4 ) filas siguientes del result set, o FALSE si no hay mas
mssql_fetch_field -- obtiene la información de los campos filas.
Ver también: mssql_fetch_array(),
mssql_fetch_object(), mssql_data_seek(),
Descripción mssql_fetch_lengths(), and mssql_result().

object mssql_fetch_field ( int result, int field_offset) mssql_field_length

Devuleve un objeto que contiene información de los (PHP 3>= 3.0.3, PHP 4 )
campos. mssql_field_length -- Get the length of a field
mssql_fetch_field() se puede usar para obtener
información acerca de los campos pertenecientes al
resultado de una consulta. Si el parámetro field_offset no Description
es especificado, se devuelve la información del siguiente
campo que todavía no ha sido devuelto por
mssql_fetch_field(). int mssql_field_length ( int result [, int offset])
Las propiedades de este objeto son:
Aviso mssql_free_statement() only needs to be called if you
are worried about using too much memory while your
Esta función no está documentada actualmente, solamente script is running. All statement memory will automatically
se encuentra disponible la lista de parametros. be freed when the script ends. You may call
mssql_free_statement() with the statement identifier
as an argument and the associated statement memory
mssql_field_name will be freed.
See also mssql_bind(), mssql_execute() and
mssql_init()
(PHP 3>= 3.0.3, PHP 4 )
mssql_field_name -- Get the name of a field
mssql_get_last_message

Description
(PHP 3, PHP 4 )
mssql_get_last_message -- Returns the last message
int mssql_field_name ( int result [, int offset]) from server (over min_message_severity?)

mssql_field_seek Description

(PHP 3, PHP 4 ) string mssql_get_last_message ( void)


mssql_field_seek -- set field offset

mssql_guid_string
Descripción

(PHP 4 >= 4.1.0)


int mssql_field_seek ( int result, int field_offset) mssql_guid_string -- Converts a 16 byte binary GUID to a
string
Se posiciona en el campo especificado por el parámetro
field_offset. Si la siguiente llamada a
Description
mssql_fetch_field() no incluye el parámetro field_offset,
lo que devuelve la función es el campo.
Ver también: mssql_fetch_field(). string mssql_guid_string ( string binary [, int
short_format])
mssql_field_type
Aviso
(PHP 3>= 3.0.3, PHP 4 ) Esta función no está documentada actualmente, solamente
mssql_field_type -- Get the type of a field se encuentra disponible la lista de parametros.

Description
mssql_init

string mssql_field_type ( int result [, int offset])


(PHP 4 >= 4.1.0)
mssql_init -- Initializes a stored procedure or a remote
mssql_free_result stored procedure

(PHP 3, PHP 4 ) Description


mssql_free_result -- libera de la memoria el resultado de
una consulta
int mssql_init ( string sp_name [, int conn_id])

Descripción
Aviso
Esta función no está documentada actualmente, solamente
int mssql_free_result ( int result)
se encuentra disponible la lista de parametros.
See also mssql_bind(), mssql_execute() and
mssql_free_result() sólo se necesita llamarla si le
mssql_free_statement()
preocupa el estar usando mucha memoria mientras se
está ejecutando el script. Toda el resultado en memoria
será liberado automaticamente cuando finalice el script, mssql_min_error_severity
puede llamar a mssql_free_result() con el identificador
de la consulta como argumento y la consulta asociada
será liberada de la memoria. (PHP 3, PHP 4 )
mssql_min_error_severity -- Sets the lower error severity

mssql_free_statement
Description

(PHP 5 CVS only)


mssql_free_statement -- Free statement memory void mssql_min_error_severity ( int severity)

Description mssql_min_message_severity

int mssql_free_statement ( int statement) (PHP 3, PHP 4 )


mssql_min_message_severity -- Sets the lower message int mssql_num_rows ( string result)
severity
mssql_num_rows() devuelve el número de filas de la
Description consulta o result set.
Ver también: mssql_db_query(), mssql_query() and,
mssql_fetch_row().
void mssql_min_message_severity ( int severity)

mssql_pconnect
mssql_next_result

(PHP 3, PHP 4 )
(PHP 4 >= 4.0.5) mssql_pconnect -- abre una conexión persistenete con
mssql_next_result -- Move the internal result pointer to MS SQL
the next result

Descripción
Description

int mssql_pconnect ( string servername, string


bool mssql_next_result ( int result_id) username, string password)

When sending more than one SQL statement to the Devuelve: Un identificador persistente postivo si no hay
server or executing a stored procedure with multiple error, o FALSE si se produce alguno
results, it will cause the server to return multiple result mssql_pconnect() funciona de la misma forma que
sets. This function will test for additional results available mssql_connect() aunque con dos grandes diferencias.
form the server. If an additional result set exists it will La primera es que cuando intenta conectar, la función
free the existing result set and prepare to fetch the rows intentará encontrar un enlace (persistente) que ya esté
from the new result set. The function will return TRUE if abierto en el mismo ordenador, nombre de usuario y
an additional result set was available or FALSE contrase¤a. Si lo encuentra, la funcion devolverá el
otherwise. identificador de esta en vez de abrir una nueva conexión.
Ejemplo 1. mssql_next_result() example Y la segunda, la conexión con el servidor no se cerrará
cuando finalice la ejecución del script. En vez de esto, el
enlace permanecerá abierto para un uso futuro.
<?php (mssql_close() no cerrará enlaces establecidos por
$link = mssql_connect ("localhost", mssql_pconnect()).
"userid", "secret"); Por consiguiente, este tipo de enlace es llamado
mssql_select_db("MyDB", $link); 'persistente'.
$SQL = "Select * from table1 select *
from table2";
$rs = mssql_query($SQL, $link); mssql_query
do {
while ($row = mssql_fetch_row($rs)) (PHP 3, PHP 4 )
{ mssql_query -- envia una consulta MS SQL
}
} while (mssql_next_result($rs));
mssql_free_result($rs); Descripción
mssql_close ($link);
?>
int mssql_query ( string query, int link_identifier)

mssql_num_fields Devuelve: Un identificado de resultado valido si no hay


error, o FALSE en caso contrario.
mssql_query() envia una petición de consulta a la base
(PHP 3, PHP 4 ) de datos activa en el servidor asociada al identificador de
mssql_num_fields -- obtiene el número de campos de la enlace especificado. Si el identificador del enlace no es
consulta especificado, se asume como abierto el último enlace. Si
no hay ningún enlace abierto, la función intenta
Descripción establecer un enlace como si mssql_connect() hubiera
sido llamada, y lo usa.
Ver también: mssql_db_query(), mssql_select_db(),
int mssql_num_fields ( int result) and mssql_connect().

mssql_num_fields() devuelve el número de campos de la mssql_result


consulta o result set.
Ver también: mssql_db_query(), mssql_query(),
mssql_fetch_field(), mssql_num_rows(). (PHP 3, PHP 4 )
mssql_result -- get result data

mssql_num_rows
Descripción

(PHP 3, PHP 4 )
mssql_num_rows -- obtiene el número de filas de la int mssql_result ( int result, int i, mixed field)
consulta
Devuelve: El contenido de la celda en la fila y posición
Descripción del result set especificado.
mssql_result() devuelve el contenido de una celda del
result set. El parametro field puede ser la posición del
campo, o el nombre del campo o bién First of all: Ming is not an acronym. Ming is an open-
nombretabla.nombrecampo. Si el nombre de la columna source (LGPL) library which allows you to create SWF
ha sido renombrado ('select foo as bar from...'), use el ("Flash") format movies. Ming supports almost all of
alias en vez del nombre de la columna. Flash 4's features, including: shapes, gradients, bitmaps
Trabajando con result sets de gran tama¤o, debería (pngs and jpegs), morphs ("shape tweens"), text,
considerar el uso de una de las funciones que capturan buttons, actions, sprites ("movie clips"), streaming mp3,
una fila completa (especificadas abajo). Como estas and color transforms --the only thing that's missing is
funciones devuelven el contenido de múltiples celdas en sound events.
una sóla llamada, estas son MUCHO más rápidas que Note that all values specifying length, distance, size, etc.
mssql_result(). También, observe que especificar una are in "twips", twenty units per pixel. That's pretty much
posición númerica para el argumento field es mucho mas arbitrary, though, since the player scales the movie to
rápido que especificar el nombre de un campo o utilizar whatever pixel size is specified in the embed/object tag,
la forma nombretabla.nombrecampo como argumento. or the entire frame if not embedded.
Alternativas recomendadas para mayor rendimiento : Ming offers a number of advantages over the existing
mssql_fetch_row(), mssql_fetch_array(), y PHP/libswf module. You can use Ming anywhere you can
mssql_fetch_object(). compile the code, whereas libswf is closed-source and
only available for a few platforms, Windows not one of
them. Ming provides some insulation from the mundane
mssql_rows_affected details of the SWF file format, wrapping the movie
elements in PHP objects. Also, Ming is still being
maintained; if there's a feature that you want to see, just
(PHP 4 >= 4.0.4)
let us know ming@opaque.net.
mssql_rows_affected -- Returns the number of records
Ming was added in PHP 4.0.5.
affected by the query

Description Requerimientos

int mssql_rows_affected ( int conn_id) To use Ming with PHP, you first need to build and install
the Ming library. Source code and installation instructions
are available at the Ming home page:
Aviso http://ming.sourceforge.net/ along with examples, a
small tutorial, and the latest news.
Esta función no está documentada actualmente, solamente Download the ming archive. Unpack the archive. Go in
se encuentra disponible la lista de parametros. the Ming directory. make. make install.
This will build libming.so and install it into /usr/lib/, and
copy ming.h into /usr/include/. Edit the PREFIX= line in
mssql_select_db the Makefile to change the installation directory.

(PHP 3, PHP 4 ) Instalación


mssql_select_db -- selecciona una base de datos MS SQL

Ejemplo 1. built into php (unix)


Descripción

int mssql_select_db ( string database_name, int


link_identifier) mkdir <phpdir>/ext/ming
cp php_ext/* <phpdir>/ext/ming
Devuelve: TRUE si todo va bién, FALSE si se produce un cd <phpdir>
error ./buildconf
mssql_select_db() selecciona como base de datos activa ./configure --with-ming <other config options>
del servidor, la que está asociada al identificador de
enlace especificado. Si no se especifica nigún
identificador, se asume el último enlace. Si no hay Build and install php as usual, restart web server if
ningún enlace abierto, la función intentará establecer un necessary.
enlace como si se llamara a la función mssql_connect(), Now either just add extension=php_ming.so to your
y lo usa. php.ini file, or put dl('php_ming.so'); at the head of all of
Cada llamada a mssql_query() será realizada sobre la your Ming scripts.
base de datos activa.
Ver también: mssql_connect(), mssql_pconnect(), y
mssql_query() Configuración en tiempo de ejecución

LIX. Ming functions for Flash Esta extensión no define ninguna directiva de
configuración.

Aviso
Tipos de recursos
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. Constantes predefinidas

Estas constantes están definidas por esta extensión y


Introducción estarán disponibles solamente cuando la extensión ha
sido o bien compilada dentro de PHP o grabada
dinamicamente en tiempo de ejecución.
SWFBUTTON_HIT (integer) SWFbutton->setUp -- Alias for addShape(shape,
SWFBUTTON_DOWN (integer) SWFBUTTON_UP)
SWFBUTTON_OVER (integer) SWFbutton -- Creates a new Button.
SWFBUTTON_UP (integer) SWFDisplayItem->addColor -- Adds the given color to this
SWFBUTTON_MOUSEUPOUTSIDE (integer) item's color transform.
SWFBUTTON_DRAGOVER (integer) SWFDisplayItem->move -- Moves object in relative
SWFBUTTON_DRAGOUT (integer) coordinates.
SWFBUTTON_MOUSEUP (integer) SWFDisplayItem->moveTo -- Moves object in global
SWFBUTTON_MOUSEDOWN (integer) coordinates.
SWFBUTTON_MOUSEOUT (integer) SWFDisplayItem->multColor -- Multiplies the item's color
SWFBUTTON_MOUSEOVER (integer) transform.
SWFFILL_RADIAL_GRADIENT (integer) SWFDisplayItem->remove -- Removes the object from
SWFFILL_LINEAR_GRADIENT (integer) the movie
SWFFILL_TILED_BITMAP (integer) SWFDisplayItem->Rotate -- Rotates in relative
SWFFILL_CLIPPED_BITMAP (integer) coordinates.
SWFTEXTFIELD_HASLENGTH (integer) SWFDisplayItem->rotateTo -- Rotates the object in global
SWFTEXTFIELD_NOEDIT (integer) coordinates.
SWFTEXTFIELD_PASSWORD (integer) SWFDisplayItem->scale -- Scales the object in relative
SWFTEXTFIELD_MULTILINE (integer) coordinates.
SWFTEXTFIELD_WORDWRAP (integer) SWFDisplayItem->scaleTo -- Scales the object in global
SWFTEXTFIELD_DRAWBOX (integer) coordinates.
SWFTEXTFIELD_NOSELECT (integer) SWFDisplayItem->setDepth -- Sets z-order
SWFTEXTFIELD_HTML (integer) SWFDisplayItem->setName -- Sets the object's name
SWFTEXTFIELD_ALIGN_LEFT (integer) SWFDisplayItem->setRatio -- Sets the object's ratio.
SWFTEXTFIELD_ALIGN_RIGHT (integer) SWFDisplayItem->skewX -- Sets the X-skew.
SWFTEXTFIELD_ALIGN_CENTER (integer) SWFDisplayItem->skewXTo -- Sets the X-skew.
SWFTEXTFIELD_ALIGN_JUSTIFY (integer) SWFDisplayItem->skewY -- Sets the Y-skew.
SWFACTION_ONLOAD (integer) SWFDisplayItem->skewYTo -- Sets the Y-skew.
SWFACTION_ENTERFRAME (integer) SWFDisplayItem -- Creates a new displayitem object.
SWFACTION_UNLOAD (integer) SWFFill->moveTo -- Moves fill origin
SWFACTION_MOUSEMOVE (integer) SWFFill->rotateTo -- Sets fill's rotation
SWFACTION_MOUSEDOWN (integer) SWFFill->scaleTo -- Sets fill's scale
SWFACTION_MOUSEUP (integer) SWFFill->skewXTo -- Sets fill x-skew
SWFACTION_KEYDOWN (integer) SWFFill->skewYTo -- Sets fill y-skew
SWFACTION_KEYUP (integer) SWFFill -- Loads SWFFill object
SWFACTION_DATA (integer) swffont->getwidth -- Returns the string's width
SWFFont -- Loads a font definition
SWFGradient->addEntry -- Adds an entry to the gradient
Clases predefinidas list.
SWFGradient -- Creates a gradient object
SWFMorph->getshape1 -- Gets a handle to the starting
Estas clases están definidas por esta extensión y estarán shape
disponibles cuando la extensión haya sido compilada SWFMorph->getshape2 -- Gets a handle to the ending
dentro de PHP o dinámicamente cargable en tiempo de shape
ejecución SWFMorph -- Creates a new SWFMorph object.
Ming introduces 13 new objects in PHP, all with matching SWFMovie->add -- Adds any type of data to a movie.
methods and attributes. To use them, you need to know SWFMovie->nextframe -- Moves to the next frame of the
about objects. animation.
swfshape SWFMovie->output -- Dumps your lovingly prepared
swffill movie out.
swfgradient SWFMovie->remove -- Removes the object instance from
swfbitmap the display list.
swftext SWFMovie->save -- Saves your movie in a file.
swftextfield SWFMovie->setbackground -- Sets the background color.
swffont SWFMovie->setdimension -- Sets the movie's width and
swfdisplayitem height.
swfmovie SWFMovie->setframes -- Sets the total number of frames
swfbutton in the animation.
swfaction SWFMovie->setrate -- Sets the animation's frame rate.
swfmorph SWFMovie->streammp3 -- Streams a MP3 file.
swfsprite SWFMovie -- Creates a new movie object, representing
Tabla de contenidos an SWF version 4 movie.
ming_setcubicthreshold -- Set cubic threshold (?) SWFShape->addFill -- Adds a solid fill to the shape.
ming_setscale -- Set scale (?) SWFShape->drawCurve -- Draws a curve (relative).
ming_useswfversion -- Use SWF version (?) SWFShape->drawCurveTo -- Draws a curve.
SWFAction -- Creates a new Action. SWFShape->drawLine -- Draws a line (relative).
SWFBitmap->getHeight -- Returns the bitmap's height. SWFShape->drawLineTo -- Draws a line.
SWFBitmap->getWidth -- Returns the bitmap's width. SWFShape->movePen -- Moves the shape's pen
SWFBitmap -- Loads Bitmap object (relative).
swfbutton_keypress -- Returns the action flag for SWFShape->movePenTo -- Moves the shape's pen.
keyPress(char) SWFShape->setLeftFill -- Sets left rasterizing color.
SWFbutton->addAction -- Adds an action SWFShape->setLine -- Sets the shape's line style.
SWFbutton->addShape -- Adds a shape to a button SWFShape->setRightFill -- Sets right rasterizing color.
SWFbutton->setAction -- Sets the action SWFShape -- Creates a new shape object.
SWFbutton->setdown -- Alias for addShape(shape, SWFSprite->add -- Adds an object to a sprite
SWFBUTTON_DOWN)) SWFSprite->nextframe -- Moves to the next frame of the
SWFbutton->setHit -- Alias for addShape(shape, animation.
SWFBUTTON_HIT) SWFSprite->remove -- Removes an object to a sprite
SWFbutton->setOver -- Alias for addShape(shape,
SWFBUTTON_OVER)
SWFSprite->setframes -- Sets the total number of frames Aviso
in the animation.
SWFSprite -- Creates a movie clip (a sprite) Esta función no está documentada actualmente, solamente
SWFText->addString -- Draws a string se encuentra disponible la lista de parametros.
SWFText->getWidth -- Computes string's width
SWFText->moveTo -- Moves the pen
SWFText->setColor -- Sets the current font color SWFAction
SWFText->setFont -- Sets the current font
SWFText->setHeight -- Sets the current font height
SWFText->setSpacing -- Sets the current font spacing (PHP 4 >= 4.0.5)
SWFText -- Creates a new SWFText object. SWFAction -- Creates a new Action.
SWFTextField->addstring -- Concatenates the given
string to the text field
Description
SWFTextField->align -- Sets the text field alignment
SWFTextField->setbounds -- Sets the text field width and
height new swfaction ( string script)
SWFTextField->setcolor -- Sets the color of the text field.
SWFTextField->setFont -- Sets the text field font
SWFTextField->setHeight -- Sets the font height of this Aviso
text field font.
SWFTextField->setindentation -- Sets the indentation of Este módulo es EXPERIMENTAL. Esto significa que el
the first line. comportamineto de estas funciones, nombre de funciones
SWFTextField->setLeftMargin -- Sets the left margin y en definitiva TODO lo documentado aqui, puede cambiar
width of the text field. en una futura version de PHP SIN AVISO. Quedas avisado, y
SWFTextField->setLineSpacing -- Sets the line spacing of utilizar este módulo es tu responsabiliad.
the text field. swfaction() creates a new Action, and compiles the
SWFTextField->setMargins -- Sets the margins width of given script into an SWFAction object.
the text field. The script syntax is based on the C language, but with a
SWFTextField->setname -- Sets the variable name lot taken out- the SWF bytecode machine is just too
SWFTextField->setrightMargin -- Sets the right margin simpleminded to do a lot of things we might like. For
width of the text field. instance, we can't implement function calls without a
SWFTextField -- Creates a text field object tremendous amount of hackery because the jump
bytecode has a hardcoded offset value. No pushing your
calling address to the stack and returning- every function
ming_setcubicthreshold would have to know exactly where to return to.
So what's left? The compiler recognises the following
tokens:
(PHP 4 >= 4.0.5)
ming_setcubicthreshold -- Set cubic threshold (?)

• break
Description
• for
• continue
void ming_setcubicthreshold ( int threshold)
• if

Aviso
• else

Esta función no está documentada actualmente, solamente


• do
se encuentra disponible la lista de parametros. • while

ming_setscale There is no typed data; all values in the SWF action


machine are stored as strings. The following functions
can be used in expressions:
(PHP 4 >= 4.0.5) time()
ming_setscale -- Set scale (?) Returns the number of milliseconds (?) elapsed
since the movie started.
random(seed)
Description Returns a pseudo-random number in the range
0-seed.
length(expr)
void ming_setscale ( int scale)
Returns the length of the given expression.
int(number)
Returns the given number rounded down to
Aviso
the nearest integer.
Esta función no está documentada actualmente, solamente concat(expr, expr)
se encuentra disponible la lista de parametros. Returns the concatenation of the given
expressions.
ord(expr)
ming_useswfversion Returns the ASCII code for the given character
chr(num)
Returns the character for the given ASCII code
(PHP 4 >= 4.2.0) substr(string, location, length)
ming_useswfversion -- Use SWF version (?) Returns the substring of length length at
location location of the given string string.
Additionally, the following commands may be used:
Description
duplicateClip(clip, name, depth)

void ming_useswfversion ( int version)


Duplicate the named movie clip (aka sprite).
The new movie clip has name name and is at
• height - (read-only)
depth depth. • rotation
removeClip(expr)
Removes the named movie clip.
• target - (read-only) (???)
trace(expr) • framesLoaded - (read-only)
Write the given expression to the trace log.
Doubtful that the browser plugin does anything
• name
with this. • dropTarget - (read-only) (???)
startDrag(target, lock, [left, top, right, bottom])
Start dragging the movie clip target. The lock
• url - (read-only) (???)
argument indicates whether to lock the mouse • highQuality - 1=high, 0=low (?)
(?)- use 0 (FALSE) or 1 (TRUE). Optional
parameters define a bounding area for the
• focusRect - (???)
dragging. • soundBufTime - (???)
stopDrag()
Stop dragging my heart around. And this
movie clip, too. So, setting a sprite's x position is as simple as /box.x =
callFrame(expr) 100;. Why the slash in front of the box, though? That's
Call the named frame as a function. how flash keeps track of the sprites in the movie, just like
getURL(url, target, [method]) a unix filesystem- here it shows that box is at the top
Load the given URL into the named target. The level. If the sprite named box had another sprite named
target argument corresponds to HTML biff inside of it, you'd set its x position with /box/biff.x =
document targets (such as "_top" or "_blank"). 100;. At least, I think so; correct me if I'm wrong here.
The optional method argument can be POST or This simple example will move the red square across the
GET if you want to submit variables back to the window.
server. Ejemplo 1. swfaction() example
loadMovie(url, target)
Load the given URL into the named target. The
target argument can be a frame name (I think), <?php
or one of the magical values "_level0" $s = new SWFShape();
(replaces current movie) or "_level1" (loads $f = $s->addFill(0xff, 0, 0);
new movie on top of current movie). $s->setRightFill($f);
nextFrame()
Go to the next frame. $s->movePenTo(-500,-500);
prevFrame() $s->drawLineTo(500,-500);
Go to the last (or, rather, previous) frame. $s->drawLineTo(500,500);
play() $s->drawLineTo(-500,500);
Start playing the movie. $s->drawLineTo(-500,-500);
stop()
Stop playing the movie. $p = new SWFSprite();
toggleQuality() $i = $p->add($s);
Toggle between high and low quality. $i->setDepth(1);
stopSounds() $p->nextFrame();
Stop playing all sounds.
gotoFrame(num) for($n=0; $n<5; ++$n)
Go to frame number num. Frame numbers {
start at 0. $i->rotate(-15);
gotoFrame(name) $p->nextFrame();
Go to the frame named name. Which does a lot }
of good, since I haven't added frame labels
yet. $m = new SWFMovie();
setTarget(expr) $m->setBackground(0xff, 0xff, 0xff);
Sets the context for action. Or so they say- I $m->setDimension(6000,4000);
really have no idea what this does.
And there's one weird extra thing. The expression $i = $m->add($p);
frameLoaded(num) can be used in if statements and $i->setDepth(1);
while loops to check if the given frame number has been $i->moveTo(-500,2000);
loaded yet. Well, it's supposed to, anyway, but I've never $i->setName("box");
tested it and I seriously doubt it actually works. You can
just use /:framesLoaded instead. $m->add(new SWFAction("/box.x +=
Movie clips (all together now- aka sprites) have 3;"));
properties. You can read all of them (or can you?), you $m->nextFrame();
can set some of them, and here they are: $m->add(new
SWFAction("gotoFrame(0); play();"));
$m->nextFrame();
• x
header('Content-type: application/x-
• y shockwave-flash');
• xScale $m->output();
?>
• yScale
This simple example tracks down your mouse on the
• currentFrame - (read-only) screen.
• totalFrames - (read-only) Ejemplo 2. swfaction() example

• alpha - transparency level


• visible - 1=on, 0=off (?) <?php
• width - (read-only)
$m = new SWFMovie(); "));
$m->setRate(36.0);
$m->setDimension(1200, 800); $cell->nextFrame();
$m->setBackground(0, 0, 0); $cell->add(new SWFAction("

/* mouse tracking sprite - empty, but follows mouse gotoFrame(0);


so we can play();
get its x and y coordinates */
"));
$i = $m->add(new SWFSprite());
$i->setName('mouse'); $cell->nextFrame();

$m->add(new SWFAction(" /* finally, add a bunch of the cells to the movie */


startDrag('/mouse', 1); /* '1' means lock sprite to the
mouse */ for($x=0; $x<12; ++$x)
")); {
for($y=0; $y<8; ++$y)
/* might as well turn off antialiasing, since these are {
just squares. */ $i = $m->add($cell);
$i->moveTo(100*$x+50, 100*$y+50);
$m->add(new SWFAction(" }
this.quality = 0; }
"));
$m->nextFrame();
/* morphing box */
$r = new SWFMorph(); $m->add(new SWFAction("
$s = $r->getShape1();
gotoFrame(1);
/* Note this is backwards from normal shapes. No play();
idea why. */
$s->setLeftFill($s->addFill(0xff, 0xff, 0xff)); "));
$s->movePenTo(-40, -40);
$s->drawLine(80, 0); header('Content-type: application/x-shockwave-
$s->drawLine(0, 80); flash');
$s->drawLine(-80, 0); $m->output();
$s->drawLine(0, -80); ?>
Same as above, but with nice colored balls...
$s = $r->getShape2();
Ejemplo 3. swfaction() example
$s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
$s->movePenTo(-1, -1);
$s->drawLine(2, 0); <?php
$s->drawLine(0, 2);
$s->drawLine(-2, 0); $m = new SWFMovie();
$s->drawLine(0, -2); $m->setDimension(11000, 8000);
$m->setBackground(0x00, 0x00, 0x00);
/* sprite container for morphing box -
this is just a timeline w/ the box morphing */ $m->add(new SWFAction("

$box = new SWFSprite(); this.quality = 0;


$box->add(new SWFAction(" /frames.visible = 0;
stop(); startDrag('/mouse', 1);
"));
$i = $box->add($r); "));

for($n=0; $n<=20; ++$n) // mouse tracking sprite


{ $t = new SWFSprite();
$i->setRatio($n/20); $i = $m->add($t);
$box->nextFrame(); $i->setName('mouse');
}
$g = new SWFGradient();
/* this container sprite allows us to use the same $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
action code many times */ $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
$g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
$cell = new SWFSprite(); $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);
$i = $cell->add($box);
$i->setName('box'); // gradient shape thing
$s = new SWFShape();
$cell->add(new SWFAction(" $f = $s->addFill($g,
SWFFILL_RADIAL_GRADIENT);
setTarget('box'); $f->scaleTo(0.03);
$s->setRightFill($f);
/* ...x means the x coordinate of the parent, i.e. $s->movePenTo(-600, -600);
(..).x */ $s->drawLine(1200, 0);
dx = (/mouse.x + random(6)-3 - ...x)/5; $s->drawLine(0, 1200);
dy = (/mouse.y + random(6)-3 - ...y)/5; $s->drawLine(-1200, 0);
gotoFrame(int(dx*dx + dy*dy)); $s->drawLine(0, -1200);

// need to make this a sprite so we can


multColor it
$p = new SWFSprite(); "));
$p->add($s);
$p->nextFrame(); $m->nextFrame();
$m->add(new SWFAction("prevFrame();
// put the shape in here, each frame a play();"));
different color
$q = new SWFSprite(); header('Content-type: application/x-
$q->add(new shockwave-flash');
SWFAction("gotoFrame(random(7)+1); $m->output();
stop();")); ?>
$i = $q->add($p);
This simple example will handles keyboard actions.
(You'll probably have to click in the window to give it
$i->multColor(1.0, 1.0, 1.0);
focus. And you'll probably have to leave your mouse in
$q->nextFrame();
the frame, too. If you know how to give buttons focus
$i->multColor(1.0, 0.5, 0.5);
programatically, feel free to share, won't you?)
$q->nextFrame();
Ejemplo 4. swfaction() example
$i->multColor(1.0, 0.75, 0.5);
$q->nextFrame();
$i->multColor(1.0, 1.0, 0.5);
$q->nextFrame(); <?php
$i->multColor(0.5, 1.0, 0.5);
$q->nextFrame(); /* sprite has one letter per frame */
$i->multColor(0.5, 0.5, 1.0);
$q->nextFrame(); $p = new SWFSprite();
$i->multColor(1.0, 0.5, 1.0); $p->add(new SWFAction("stop();"));
$q->nextFrame();
$chars = "abcdefghijklmnopqrstuvwxyz".
// finally, this one contains the action code "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
$p = new SWFSprite(); "1234567890!@#$%^&/*()_+-=/[]
$i = $p->add($q); {}|;:,.<>?`~";
$i->setName('frames');
$p->add(new SWFAction(" $f = new SWFFont("_sans");

dx = (/:mousex-/:lastx)/3 + random(10)-5; for($n=0; $nremove($i);


dy = (/:mousey-/:lasty)/3; $t = new SWFTextField();
x = /:mousex; $t->setFont($f);
y = /:mousey; $t->setHeight(240);
alpha = 100; $t->setBounds(600,240);
$t->align(SWFTEXTFIELD_ALIGN_CENTER);
")); $t->addString($c);
$p->nextFrame(); $i = $p->add($t);
$p->labelFrame($c);
$p->add(new SWFAction(" $p->nextFrame();
}
this.x = x;
this.y = y; /* hit region for button - the entire frame */
this.alpha = alpha;
x += dx; $s = new SWFShape();
y += dy; $s->setFillStyle0($s->addSolidFill(0, 0, 0, 0));
dy += 3; $s->drawLine(600, 0);
alpha -= 8; $s->drawLine(0, 400);
$s->drawLine(-600, 0);
")); $s->drawLine(0, -400);
$p->nextFrame();
/* button checks for pressed key, sends sprite
$p->add(new SWFAction("prevFrame(); to the right frame */
play();"));
$p->nextFrame(); $b = new SWFButton();
$b->addShape($s, SWFBUTTON_HIT);
$i = $m->add($p);
$i->setName('frames'); for($n=0; $naddAction(new SWFAction("
$m->nextFrame();
setTarget('/char');
$m->add(new SWFAction(" gotoFrame('$c');

lastx = mousex; "), SWFBUTTON_KEYPRESS($c));


lasty = mousey; }
mousex = /mouse.x;
mousey = /mouse.y; $m = new SWFMovie();
$m->setDimension(600,400);
++num; $i = $m->add($p);
$i->setName('char');
if(num == 11) $i->moveTo(0,80);
num = 1;
$m->add($b);
removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num); header('Content-type: application/x-shockwave-
flash');
SWFBitmap has the following methods : swfbitmap-
$m->output();
>getwidth() and swfbitmap->getheight().
You can't import png images directly, though- have to
?>
use the png2dbl utility to make a dbl ("define bits
lossless") file from the png. The reason for this is that I
don't want a dependency on the png library in ming-
SWFBitmap->getHeight autoconf should solve this, but that's not set up yet.
Ejemplo 1. Import PNG files
(no version information, might be only in CVS)
SWFBitmap->getHeight -- Returns the bitmap's height.
<?php
$s = new SWFShape();
Description $f = $s->addFill(new
SWFBitmap("png.dbl"));
$s->setRightFill($f);
int swfbitmap->getheight ( void)
$s->drawLine(32, 0);
$s->drawLine(0, 32);
Aviso
$s->drawLine(-32, 0);
Este módulo es EXPERIMENTAL. Esto significa que el $s->drawLine(0, -32);
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar $m = new SWFMovie();
en una futura version de PHP SIN AVISO. Quedas avisado, y $m->setDimension(32, 32);
utilizar este módulo es tu responsabiliad. $m->add($s);
swfbitmap->getheight() returns the bitmap's height in
pixels. header('Content-type: application/x-
See also swfbitmap->getwidth(). shockwave-flash');
$m->output();
?>
SWFBitmap->getWidth And you can put an alpha mask on a jpeg fill.
Ejemplo 2. swfbitmap() example
(no version information, might be only in CVS)
SWFBitmap->getWidth -- Returns the bitmap's width.
<?php

Description $s = new SWFShape();

// .msk file generated with "gif2mask" utility


int swfbitmap->getwidth ( void) $f = $s->addFill(new
SWFBitmap("alphafill.jpg", "alphafill.msk"));
$s->setRightFill($f);
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el $s->drawLine(640, 0);
comportamineto de estas funciones, nombre de funciones $s->drawLine(0, 480);
y en definitiva TODO lo documentado aqui, puede cambiar $s->drawLine(-640, 0);
en una futura version de PHP SIN AVISO. Quedas avisado, y $s->drawLine(0, -480);
utilizar este módulo es tu responsabiliad.
$c = new SWFShape();
swfbitmap->getwidth() returns the bitmap's width in
$c->setRightFill($c->addFill(0x99, 0x99,
pixels.
0x99));
See also swfbitmap->getheight().
$c->drawLine(40, 0);
$c->drawLine(0, 40);
SWFBitmap $c->drawLine(-40, 0);
$c->drawLine(0, -40);

(PHP 4 >= 4.0.5) $m = new SWFMovie();


SWFBitmap -- Loads Bitmap object $m->setDimension(640, 480);
$m->setBackground(0xcc, 0xcc, 0xcc);
Description // draw checkerboard background
for($y=0; $y<480; $y+=40)
new swfbitmap ( string filename [, int alphafilename]) {
for($x=0; $x<640; $x+=80)
{
Aviso $i = $m->add($c);
$i->moveTo($x, $y);
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 $y+=40;
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. for($x=40; $x<640; $x+=80)
swfbitmap() creates a new SWFBitmap object from the {
Jpeg or DBL file named filename. alphafilename indicates $i = $m->add($c);
a MSK file to be used as an alpha mask for a Jpeg image. $i->moveTo($x, $y);
}
}
Nota: We can only deal with
baseline (frame 0) jpegs, no baseline $m->add($s);
optimized or progressive scan jpegs!
SWFBUTTON_DOWN or SWFBUTTON_HIT.
SWFBUTTON_HIT isn't ever displayed, it defines the hit
header('Content-type: application/x-
region for the button. That is, everywhere the hit shape
shockwave-flash');
would be drawn is considered a "touchable" part of the
$m->output();
button.
?>

SWFbutton->setAction
swfbutton_keypress

(no version information, might be only in CVS)


(PHP 4 >= 4.0.5) SWFbutton->setAction -- Sets the action
swfbutton_keypress -- Returns the action flag for
keyPress(char)
Description

Description
void swfbutton->setaction ( ressource action)

int swfbutton_keypress ( string str)


Aviso

Aviso Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones
Esta función no está documentada actualmente, solamente y en definitiva TODO lo documentado aqui, puede cambiar
se encuentra disponible la lista de parametros. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
swfbutton->setaction() sets the action to be
SWFbutton->addAction performed when the button is clicked. Alias for
addAction(shape, SWFBUTTON_MOUSEUP). action is a
(no version information, might be only in CVS) swfaction().
SWFbutton->addAction -- Adds an action See also swfbutton->addshape() and SWFAction().

Description SWFbutton->setdown

void swfbutton->addaction ( ressource action, int (no version information, might be only in CVS)
flags) SWFbutton->setdown -- Alias for addShape(shape,
SWFBUTTON_DOWN))

Aviso
Description
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 void swfbutton->setdown ( ressource shape)
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
swfbutton->addaction() adds the action action to this
button for the given conditions. The following flags are Este módulo es EXPERIMENTAL. Esto significa que el
valid: SWFBUTTON_MOUSEOVER, comportamineto de estas funciones, nombre de funciones
SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, y en definitiva TODO lo documentado aqui, puede cambiar
SWFBUTTON_MOUSEUPOUTSIDE, en una futura version de PHP SIN AVISO. Quedas avisado, y
SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and utilizar este módulo es tu responsabiliad.
SWFBUTTON_DRAGOVER. swfbutton->setdown() alias for addShape(shape,
See also swfbutton->addshape() and SWFAction(). SWFBUTTON_DOWN).
See also swfbutton->addshape() and SWFAction().
SWFbutton->addShape
SWFbutton->setHit
(no version information, might be only in CVS)
SWFbutton->addShape -- Adds a shape to a button (no version information, might be only in CVS)
SWFbutton->setHit -- Alias for addShape(shape,
SWFBUTTON_HIT)
Description

Description
void swfbutton->addshape ( ressource shape, int
flags)
void swfbutton->sethit ( ressource shape)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad. en una futura version de PHP SIN AVISO. Quedas avisado, y
swfbutton->addshape() adds the shape shape to this utilizar este módulo es tu responsabiliad.
button. The following flags' values are valid: swfbutton->sethit() alias for addShape(shape,
SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_HIT).
See also swfbutton->addshape() and SWFAction(). This simple example will show your usual interactions
with buttons : rollover, rollon, mouseup, mousedown,
noaction.
SWFbutton->setOver Ejemplo 1. swfbutton() example

(no version information, might be only in CVS)


SWFbutton->setOver -- Alias for addShape(shape, <?php
SWFBUTTON_OVER)
$f = new SWFFont("_serif");

Description $p = new SWFSprite();

function label($string)
void swfbutton->setover ( ressource shape) {
global $f;
Aviso $t = new SWFTextField();
Este módulo es EXPERIMENTAL. Esto significa que el $t->setFont($f);
comportamineto de estas funciones, nombre de funciones $t->addString($string);
y en definitiva TODO lo documentado aqui, puede cambiar $t->setHeight(200);
en una futura version de PHP SIN AVISO. Quedas avisado, y $t->setBounds(3200,200);
utilizar este módulo es tu responsabiliad. return $t;
}
swfbutton->setover() alias for addShape(shape,
function addLabel($string)
SWFBUTTON_OVER).
{
See also swfbutton->addshape() and SWFAction().
global $p;

SWFbutton->setUp $i = $p->add(label($string));
$p->nextFrame();
$p->remove($i);
(no version information, might be only in CVS) }
SWFbutton->setUp -- Alias for addShape(shape,
SWFBUTTON_UP) $p->add(new SWFAction("stop();"));
addLabel("NO ACTION");
addLabel("SWFBUTTON_MOUSEUP");
Description addLabel("SWFBUTTON_MOUSEDOWN");
addLabel("SWFBUTTON_MOUSEOVER");
void swfbutton->setup ( ressource shape) addLabel("SWFBUTTON_MOUSEOUT");
addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
addLabel("SWFBUTTON_DRAGOVER");
Aviso addLabel("SWFBUTTON_DRAGOUT");

Este módulo es EXPERIMENTAL. Esto significa que el function rect($r, $g, $b)
comportamineto de estas funciones, nombre de funciones {
y en definitiva TODO lo documentado aqui, puede cambiar $s = new SWFShape();
en una futura version de PHP SIN AVISO. Quedas avisado, y $s->setRightFill($s->addFill($r, $g, $b));
utilizar este módulo es tu responsabiliad. $s->drawLine(600,0);
swfbutton->setup() alias for addShape(shape, $s->drawLine(0,600);
SWFBUTTON_UP). $s->drawLine(-600,0);
See also swfbutton->addshape() and SWFAction(). $s->drawLine(0,-600);

return $s;
SWFbutton }

$b = new SWFButton();
(PHP 4 >= 4.0.5) $b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP |
SWFbutton -- Creates a new Button. SWFBUTTON_HIT);
$b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
Description $b->addShape(rect(0, 0, 0xff),
SWFBUTTON_DOWN);

new swfbutton ( void) $b->addAction(new SWFAction("setTarget('/label');


gotoFrame(1);"),
SWFBUTTON_MOUSEUP);
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el $b->addAction(new SWFAction("setTarget('/label');
comportamineto de estas funciones, nombre de funciones gotoFrame(2);"),
y en definitiva TODO lo documentado aqui, puede cambiar SWFBUTTON_MOUSEDOWN);
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. $b->addAction(new SWFAction("setTarget('/label');
gotoFrame(3);"),
swfbutton() creates a new Button. Roll over it, click it, SWFBUTTON_MOUSEOVER);
see it call action code. Swank.
SWFButton has the following methods : swfbutton- $b->addAction(new SWFAction("setTarget('/label');
>addshape(), swfbutton->setup(), swfbutton- gotoFrame(4);"),
>setover() swfbutton->setdown(), swfbutton- SWFBUTTON_MOUSEOUT);
>sethit() swfbutton->setaction() and swfbutton-
>addaction(). $b->addAction(new SWFAction("setTarget('/label');
gotoFrame(5);"),
void swfdisplayitem->addcolor ( [int red [, int green [,
SWFBUTTON_MOUSEUPOUTSIDE);
int blue [, int a]]]])
$b->addAction(new SWFAction("setTarget('/label');
gotoFrame(6);"), Aviso
SWFBUTTON_DRAGOVER);
Este módulo es EXPERIMENTAL. Esto significa que el
$b->addAction(new SWFAction("setTarget('/label'); comportamineto de estas funciones, nombre de funciones
gotoFrame(7);"), y en definitiva TODO lo documentado aqui, puede cambiar
SWFBUTTON_DRAGOUT); en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
$m = new SWFMovie(); swfdisplayitem->addcolor() adds the color to this
$m->setDimension(4000,3000); item's color transform. The color is given in its RGB form.
The object may be a swfshape(), a swfbutton(), a
$i = $m->add($p); swftext() or a swfsprite() object. It must have been
$i->setName("label"); added using the swfmovie->add().
$i->moveTo(400,1900);

$i = $m->add($b); SWFDisplayItem->move
$i->moveTo(400,900);

header('Content-type: application/x-shockwave- (no version information, might be only in CVS)


flash'); SWFDisplayItem->move -- Moves object in relative
$m->output(); coordinates.
?>
This simple example will enables you to drag draw a big Description
red button on the windows. No drag-and-drop, just
moving around.
Ejemplo 2. swfbutton->addaction() example void swfdisplayitem->move ( int dx, int dy)

Aviso
<?php
Este módulo es EXPERIMENTAL. Esto significa que el
$s = new SWFShape(); comportamineto de estas funciones, nombre de funciones
$s->setRightFill($s->addFill(0xff, 0, 0)); y en definitiva TODO lo documentado aqui, puede cambiar
$s->drawLine(1000,0); en una futura version de PHP SIN AVISO. Quedas avisado, y
$s->drawLine(0,1000); utilizar este módulo es tu responsabiliad.
$s->drawLine(-1000,0); swfdisplayitem->move() moves the current object by
$s->drawLine(0,-1000); (dx,dy) from its current position.
The object may be a swfshape(), a swfbutton(), a
$b = new SWFButton(); swftext() or a swfsprite() object. It must have been
$b->addShape($s, SWFBUTTON_HIT | added using the swfmovie->add().
SWFBUTTON_UP | SWFBUTTON_DOWN | See also swfdisplayitem->moveto().
SWFBUTTON_OVER);

$b->addAction(new SWFAction("startDrag('/test', SWFDisplayItem->moveTo


0);"), // '0' means don't lock to mouse
SWFBUTTON_MOUSEDOWN);
(no version information, might be only in CVS)
$b->addAction(new SWFAction("stopDrag();"), SWFDisplayItem->moveTo -- Moves object in global
SWFBUTTON_MOUSEUP | coordinates.
SWFBUTTON_MOUSEUPOUTSIDE);
Description
$p = new SWFSprite();
$p->add($b);
$p->nextFrame(); void swfdisplayitem->moveto ( int x, int y)

$m = new SWFMovie();
$i = $m->add($p); Aviso
$i->setName('test');
$i->moveTo(1000,1000); Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
header('Content-type: application/x-shockwave- y en definitiva TODO lo documentado aqui, puede cambiar
flash'); en una futura version de PHP SIN AVISO. Quedas avisado, y
$m->output(); utilizar este módulo es tu responsabiliad.
?> swfdisplayitem->moveto() moves the current object
to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a
SWFDisplayItem->addColor swftext() or a swfsprite() object. It must have been
added using the swfmovie->add().
See also swfdisplayitem->move().
(no version information, might be only in CVS)
SWFDisplayItem->addColor -- Adds the given color to this
item's color transform. SWFDisplayItem->multColor

Description (no version information, might be only in CVS)


SWFDisplayItem->multColor -- Multiplies the item's color
transform.
Description See also swfmovie->add().

void swfdisplayitem->multcolor ( [int red [, int green SWFDisplayItem->Rotate


[, int blue [, int a]]]])

(no version information, might be only in CVS)


Aviso SWFDisplayItem->Rotate -- Rotates in relative
coordinates.
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 Description
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
void swfdisplayitem->rotate ( float ddegrees)
swfdisplayitem->multcolor() multiplies the item's
color transform by the given values.
The object may be a swfshape(), a swfbutton(), a Aviso
swftext() or a swfsprite() object. It must have been
added using the swfmovie->add(). Este módulo es EXPERIMENTAL. Esto significa que el
This simple example will modify your picture's atmospher comportamineto de estas funciones, nombre de funciones
to Halloween (use a landscape or bright picture). y en definitiva TODO lo documentado aqui, puede cambiar
Ejemplo 1. swfdisplayitem->multcolor() example en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
swfdisplayitem->rotate() rotates the current object by
<?php ddegrees degrees from its current rotation.
The object may be a swfshape(), a swfbutton(), a
$b = new SWFBitmap("backyard.jpg"); swftext() or a swfsprite() object. It must have been
// note use your own picture :-) added using the swfmovie->add().
$s = new SWFShape(); See also swfdisplayitem->rotateto().
$s->setRightFill($s->addFill($b));
$s->drawLine($b->getWidth(), 0);
$s->drawLine(0, $b->getHeight()); SWFDisplayItem->rotateTo
$s->drawLine(-$b->getWidth(), 0);
$s->drawLine(0, -$b->getHeight()); (no version information, might be only in CVS)
SWFDisplayItem->rotateTo -- Rotates the object in global
$m = new SWFMovie(); coordinates.
$m->setDimension($b->getWidth(), $b-
>getHeight());
Description
$i = $m->add($s);

for($n=0; $n<=20; ++$n) void swfdisplayitem->rotateto ( float degrees)


{
$i->multColor(1.0-$n/10, 1.0, 1.0);
$i->addColor(0xff*$n/20, 0, 0); Aviso
$m->nextFrame(); 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
header('Content-type: application/x- en una futura version de PHP SIN AVISO. Quedas avisado, y
shockwave-flash'); utilizar este módulo es tu responsabiliad.
$m->output();
?> swfdisplayitem->rotateto() set the current object
rotation to degrees degrees in global coordinates.
The object may be a swfshape(), a swfbutton(), a
swftext() or a swfsprite() object. It must have been
SWFDisplayItem->remove
added using the swfmovie->add().
This example bring three rotating string from the
(no version information, might be only in CVS) background to the foreground. Pretty nice.
SWFDisplayItem->remove -- Removes the object from Ejemplo 1. swfdisplayitem->rotateto() example
the movie

<?php
Description $thetext = "ming!";

$f = new SWFFont("Bauhaus 93.fdb");


void swfdisplayitem->remove ( void)
$m = new SWFMovie();
Aviso $m->setRate(24.0);
$m->setDimension(2400, 1600);
Este módulo es EXPERIMENTAL. Esto significa que el $m->setBackground(0xff, 0xff, 0xff);
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar // functions with huge numbers of arbitrary
en una futura version de PHP SIN AVISO. Quedas avisado, y // arguments are always a good idea! Really!
utilizar este módulo es tu responsabiliad.
swfdisplayitem->remove() removes this object from function text($r, $g, $b, $a, $rot, $x, $y,
the movie's display list. $scale, $string)
The object may be a swfshape(), a swfbutton(), a {
swftext() or a swfsprite() object. It must have been global $f, $m;
added using the swfmovie->add().
void swfdisplayitem->scale ( int dx, int dy)
$t = new SWFText();
$t->setFont($f);
$t->setColor($r, $g, $b, $a); Aviso
$t->setHeight(960);
$t->moveTo(-($f->getWidth($string))/2, $f- Este módulo es EXPERIMENTAL. Esto significa que el
>getAscent()/2); comportamineto de estas funciones, nombre de funciones
$t->addString($string); y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
// we can add properties just like a normal php utilizar este módulo es tu responsabiliad.
var, swfdisplayitem->scale() scales the current object by
// as long as the names aren't already used. (dx,dy) from its current size.
// e.g., we can't set $i->scale, because that's The object may be a swfshape(), a swfbutton(), a
a function swftext() or a swfsprite() object. It must have been
added using the swfmovie->add().
$i = $m->add($t); See also swfdisplayitem->scaleto().
$i->x = $x;
$i->y = $y;
$i->rot = $rot; SWFDisplayItem->scaleTo
$i->s = $scale;
$i->rotateTo($rot);
$i->scale($scale, $scale); (no version information, might be only in CVS)
SWFDisplayItem->scaleTo -- Scales the object in global
// but the changes are local to the function, so coordinates.
we have to
// return the changed object. kinda weird..
Description
return $i;
} void swfdisplayitem->scaleto ( int x, int y)

function step($i)
{ Aviso
$oldrot = $i->rot;
$i->rot = 19*$i->rot/20; Este módulo es EXPERIMENTAL. Esto significa que el
$i->x = (19*$i->x + 1200)/20; comportamineto de estas funciones, nombre de funciones
$i->y = (19*$i->y + 800)/20; y en definitiva TODO lo documentado aqui, puede cambiar
$i->s = (19*$i->s + 1.0)/20; en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
$i->rotateTo($i->rot); swfdisplayitem->scaleto() scales the current object to
$i->scaleTo($i->s, $i->s); (x,y) in global coordinates.
$i->moveTo($i->x, $i->y); The object may be a swfshape(), a swfbutton(), a
swftext() or a swfsprite() object. It must have been
return $i; added using the swfmovie->add().
} See also swfdisplayitem->scale().

// see? it sure paid off in legibility:


SWFDisplayItem->setDepth
$i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200,
800, 0.03, $thetext);
(no version information, might be only in CVS)
$i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200,
SWFDisplayItem->setDepth -- Sets z-order
800, 0.04, $thetext);
$i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800,
0.001, $thetext); Description

for($i=1; $i<=100; ++$i)


{ void swfdisplayitem->setdepth ( float depth)
$i1 = step($i1);
$i2 = step($i2);
$i3 = step($i3); Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
$m->nextFrame(); 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
header('Content-type: application/x- utilizar este módulo es tu responsabiliad.
shockwave-flash');
$m->output(); swfdisplayitem->rotate() sets the object's z-order to
?> depth. Depth defaults to the order in which instances are
created (by add'ing a shape/text to a movie)- newer ones
See also swfdisplayitem->rotate(). are on top of older ones. If two objects are given the
same depth, only the later-defined one can be moved.
The object may be a swfshape(), a swfbutton(), a
SWFDisplayItem->scale
swftext() or a swfsprite() object. It must have been
added using the swfmovie->add().
(no version information, might be only in CVS)
SWFDisplayItem->scale -- Scales the object in relative
SWFDisplayItem->setName
coordinates.

(no version information, might be only in CVS)


Description
SWFDisplayItem->setName -- Sets the object's name
Description
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0, 0, 0xff);
void swfdisplayitem->setname ( string name) $g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape2();
Aviso $f = $s->addFill($g,
SWFFILL_RADIAL_GRADIENT);
Este módulo es EXPERIMENTAL. Esto significa que el $f->scaleTo(0.05);
comportamineto de estas funciones, nombre de funciones $f->skewXTo(1.0);
y en definitiva TODO lo documentado aqui, puede cambiar $s->setLeftFill($f);
en una futura version de PHP SIN AVISO. Quedas avisado, y $s->movePenTo(-160, -120);
utilizar este módulo es tu responsabiliad. $s->drawLine(320, 0);
swfdisplayitem->setname() sets the object's name to $s->drawLine(0, 240);
name, for targetting with action script. Only useful on $s->drawLine(-320, 0);
sprites. $s->drawLine(0, -240);
The object may be a swfshape(), a swfbutton(), a
swftext() or a swfsprite() object. It must have been $m = new SWFMovie();
added using the swfmovie->add(). $m->setDimension(320, 240);
$i = $m->add($p);
$i->moveTo(160, 120);
SWFDisplayItem->setRatio
for($n=0; $n<=1.001; $n+=0.01)
{
(no version information, might be only in CVS)
$i->setRatio($n);
SWFDisplayItem->setRatio -- Sets the object's ratio.
$m->nextFrame();
}
Description
header('Content-type: application/x-
shockwave-flash');
void swfdisplayitem->setratio ( float ratio) $m->output();
?>

Aviso
Este módulo es EXPERIMENTAL. Esto significa que el SWFDisplayItem->skewX
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 (no version information, might be only in CVS)
utilizar este módulo es tu responsabiliad. SWFDisplayItem->skewX -- Sets the X-skew.

swfdisplayitem->setratio() sets the object's ratio to


ratio. Obviously only useful for morphs. Description
The object may be a swfshape(), a swfbutton(), a
swftext() or a swfsprite() object. It must have been
added using the swfmovie->add(). void swfdisplayitem->skewx ( float ddegrees)
This simple example will morph nicely three concentric
circles.
Aviso
Ejemplo 1. swfdisplayitem->setname() example
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
<?php y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
$p = new SWFMorph(); utilizar este módulo es tu responsabiliad.
swfdisplayitem->skewx() adds ddegrees to current x-
$g = new SWFGradient(); skew.
$g->addEntry(0.0, 0, 0, 0); The object may be a swfshape(), a swfbutton(), a
$g->addEntry(0.16, 0xff, 0xff, 0xff); swftext() or a swfsprite() object. It must have been
$g->addEntry(0.32, 0, 0, 0); added using the swfmovie->add().
$g->addEntry(0.48, 0xff, 0xff, 0xff); See also swfdisplayitem->skewx(), swfdisplayitem-
$g->addEntry(0.64, 0, 0, 0); >skewy() and swfdisplayitem->skewyto().
$g->addEntry(0.80, 0xff, 0xff, 0xff);
$g->addEntry(1.00, 0, 0, 0);
SWFDisplayItem->skewXTo
$s = $p->getShape1();
$f = $s->addFill($g,
SWFFILL_RADIAL_GRADIENT); (no version information, might be only in CVS)
$f->scaleTo(0.05); SWFDisplayItem->skewXTo -- Sets the X-skew.
$s->setLeftFill($f);
$s->movePenTo(-160, -120); Description
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0); void swfdisplayitem->skewxto ( float degrees)
$s->drawLine(0, -240);

$g = new SWFGradient(); Aviso


$g->addEntry(0.0, 0, 0, 0);
Este módulo es EXPERIMENTAL. Esto significa que el
$g->addEntry(0.16, 0xff, 0, 0);
comportamineto de estas funciones, nombre de funciones
$g->addEntry(0.32, 0, 0, 0);
y en definitiva TODO lo documentado aqui, puede cambiar
$g->addEntry(0.48, 0, 0xff, 0);
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. new swfdisplayitem ( void)

swfdisplayitem->skewxto() sets the x-skew to


degrees. For degrees is 1.0, it means a 45-degree Aviso
forward slant. More is more forward, less is more
Este módulo es EXPERIMENTAL. Esto significa que el
backward.
comportamineto de estas funciones, nombre de funciones
The object may be a swfshape(), a swfbutton(), a
y en definitiva TODO lo documentado aqui, puede cambiar
swftext() or a swfsprite() object. It must have been
en una futura version de PHP SIN AVISO. Quedas avisado, y
added using the swfmovie->add().
utilizar este módulo es tu responsabiliad.
See also swfdisplayitem->skewx(), swfdisplayitem-
>skewy() and swfdisplayitem->skewyto(). swfdisplayitem() creates a new swfdisplayitem object.
Here's where all the animation takes place. After you
define a shape, a text object, a sprite, or a button, you
SWFDisplayItem->skewY add it to the movie, then use the returned handle to
move, rotate, scale, or skew the thing.
SWFDisplayItem has the following methods :
(no version information, might be only in CVS)
swfdisplayitem->move(), swfdisplayitem-
SWFDisplayItem->skewY -- Sets the Y-skew.
>moveto(), swfdisplayitem->scaleto(),
swfdisplayitem->scale(), swfdisplayitem->rotate(),
Description swfdisplayitem->rotateto(), swfdisplayitem-
>skewxto(), swfdisplayitem->skewx(),
swfdisplayitem->skewyto() swfdisplayitem-
void swfdisplayitem->skewy ( float ddegrees) >skewyto(), swfdisplayitem->setdepth()
swfdisplayitem->remove(), swfdisplayitem-
>setname() swfdisplayitem->setratio(),
Aviso swfdisplayitem->addcolor() and swfdisplayitem-
Este módulo es EXPERIMENTAL. Esto significa que el >multcolor().
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
SWFFill->moveTo
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
swfdisplayitem->skewy() adds ddegrees to current y- (no version information, might be only in CVS)
skew. SWFFill->moveTo -- Moves fill origin
The object may be a swfshape(), a swfbutton(), a
swftext() or a swfsprite() object. It must have been
Description
added using the swfmovie->add().
See also swfdisplayitem->skewyto(),
swfdisplayitem->skewx() and swfdisplayitem- void swffill->moveto ( int x, int y)
>skewxto().

Aviso
SWFDisplayItem->skewYTo
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
(no version information, might be only in CVS) y en definitiva TODO lo documentado aqui, puede cambiar
SWFDisplayItem->skewYTo -- Sets the Y-skew. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Description swffill->moveto() moves fill's origin to (x,y) in global
coordinates.

void swfdisplayitem->skewyto ( float degrees)


SWFFill->rotateTo

Aviso
(no version information, might be only in CVS)
Este módulo es EXPERIMENTAL. Esto significa que el SWFFill->rotateTo -- Sets fill's rotation
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 Description
utilizar este módulo es tu responsabiliad.
swfdisplayitem->skewyto() sets the y-skew to void swffill->rotateto ( float degrees)
degrees. For degrees is 1.0, it means a 45-degree
forward slant. More is more upward, less is more
downward. Aviso
The object may be a swfshape(), a swfbutton(), a
Este módulo es EXPERIMENTAL. Esto significa que el
swftext() or a swfsprite() object. It must have been
comportamineto de estas funciones, nombre de funciones
added using the swfmovie->add().
y en definitiva TODO lo documentado aqui, puede cambiar
See also swfdisplayitem->skewy(), swfdisplayitem-
en una futura version de PHP SIN AVISO. Quedas avisado, y
>skewx() and swfdisplayitem->skewxto().
utilizar este módulo es tu responsabiliad.
swffill->rotateto() sets fill's rotation to degrees
SWFDisplayItem degrees.

(no version information, might be only in CVS) SWFFill->scaleTo


SWFDisplayItem -- Creates a new displayitem object.

(no version information, might be only in CVS)


Description SWFFill->scaleTo -- Sets fill's scale
Description swffont->getwidth

void swffill->scaleto ( int x, int y) (no version information, might be only in CVS)
swffont->getwidth -- Returns the string's width

Aviso
Description
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 int swffont->getwidth ( string string)
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
swffill->scaleto() sets fill's scale to x in the x-direction,
y in the y-direction. 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
SWFFill->skewXTo en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
(no version information, might be only in CVS) swffont->getwidth() returns the string string's width,
SWFFill->skewXTo -- Sets fill x-skew using font's default scaling. You'll probably want to use
the SWFText() version of this method which uses the
text object's scale.
Description

SWFFont
void swffill->skewxto ( float x)

(PHP 4 >= 4.0.5)


Aviso SWFFont -- Loads a font definition
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Description
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. new swffont ( string filename)
swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is
a is a 45-degree forward slant. More is more forward, less
Aviso
is more backward.
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
SWFFill->skewYTo y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
(no version information, might be only in CVS) utilizar este módulo es tu responsabiliad.
SWFFill->skewYTo -- Sets fill y-skew If filename is the name of an FDB file (i.e., it ends in
".fdb"), load the font definition found in said file.
Otherwise, create a browser-defined font reference.
Description FDB ("font definition block") is a very simple wrapper for
the SWF DefineFont2 block which contains a full
description of a font. One may create FDB files from SWT
void swffill->skewyto ( float y)
Generator template files with the included makefdb
utility- look in the util directory off the main ming
Aviso distribution directory.
Browser-defined fonts don't contain any information
Este módulo es EXPERIMENTAL. Esto significa que el about the font other than its name. It is assumed that the
comportamineto de estas funciones, nombre de funciones font definition will be provided by the movie player. The
y en definitiva TODO lo documentado aqui, puede cambiar fonts _serif, _sans, and _typewriter should always be
en una futura version de PHP SIN AVISO. Quedas avisado, y available. For example:
utilizar este módulo es tu responsabiliad.
<?php
swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is $f =
a is a 45-degree upward slant. More is more upward, less newSWFFont("_sans"
is more downward. );
?>
SWFFill will give you the standard sans-serif font, probably the
same as what you'd get with <font name="sans-serif">
in HTML.
SWFFill -- Loads SWFFill object swffont() returns a reference to the font definition, for
use in the SWFText->setFont() and the
SWFTextField->setFont() methods.
Description
SWFFont has the following methods : swffont-
>getwidth().
The swffill() object allows you to transform (scale, skew,
rotate) bitmap and gradient fills. swffill() objects are
SWFGradient->addEntry
created by the swfshape->addfill() methods.
SWFFill has the following methods : swffill->moveto()
and swffill->scaleto(), swffill->rotateto(), swffill- (no version information, might be only in CVS)
>skewxto() and swffill->skewyto(). SWFGradient->addEntry -- Adds an entry to the gradient
list.
Description
red to transparent
$g = new SWFGradient();
void swfgradient->addentry ( float ratio, int red, int $g->addEntry(0.0, 0xff, 0, 0, 0xff);
green, int blue [, int a]) $g->addEntry(1.0, 0xff, 0, 0, 0);

$f = $s->addFill($g,
Aviso SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.005);
Este módulo es EXPERIMENTAL. Esto significa que el $f->moveTo(160, 120);
comportamineto de estas funciones, nombre de funciones $s->setRightFill($f);
y en definitiva TODO lo documentado aqui, puede cambiar $s->drawLine(320, 0);
en una futura version de PHP SIN AVISO. Quedas avisado, y $s->drawLine(0, 240);
utilizar este módulo es tu responsabiliad. $s->drawLine(-320, 0);
swfgradient->addentry() adds an entry to the $s->drawLine(0, -240);
gradient list. ratio is a number between 0 and 1
indicating where in the gradient this color appears. Thou $m->add($s);
shalt add entries in order of increasing ratio.
red, green, blue is a color (RGB mode). Last parameter a header('Content-type: application/x-
is optional. shockwave-flash');
$m->output();
?>
SWFGradient

(PHP 4 >= 4.0.5) SWFMorph->getshape1


SWFGradient -- Creates a gradient object
(no version information, might be only in CVS)
Description SWFMorph->getshape1 -- Gets a handle to the starting
shape

new swfgradient ( void)


Description

Aviso
mixed swfmorph->getshape1 ( void)
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 Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y Este módulo es EXPERIMENTAL. Esto significa que el
utilizar este módulo es tu responsabiliad. comportamineto de estas funciones, nombre de funciones
swfgradient() creates a new SWFGradient object. y en definitiva TODO lo documentado aqui, puede cambiar
After you've added the entries to your gradient, you can en una futura version de PHP SIN AVISO. Quedas avisado, y
use the gradient in a shape fill with the swfshape- utilizar este módulo es tu responsabiliad.
>addfill() method. swfmorph->getshape1() gets a handle to the morph's
SWFGradient has the following methods : swfgradient- starting shape. swfmorph->getshape1() returns an
>addentry(). swfshape() object.
This simple example will draw a big black-to-white
gradient as background, and a redish disc in its center.
Ejemplo 1. swfgradient() example SWFMorph->getshape2

<?php (no version information, might be only in CVS)


SWFMorph->getshape2 -- Gets a handle to the ending
$m = new SWFMovie(); shape
$m->setDimension(320, 240);
Description
$s = new SWFShape();

// first gradient- black to white mixed swfmorph->getshape2 ( void)


$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(1.0, 0xff, 0xff, 0xff); Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
$f = $s->addFill($g,
comportamineto de estas funciones, nombre de funciones
SWFFILL_LINEAR_GRADIENT);
y en definitiva TODO lo documentado aqui, puede cambiar
$f->scaleTo(0.01);
en una futura version de PHP SIN AVISO. Quedas avisado, y
$f->moveTo(160, 120);
utilizar este módulo es tu responsabiliad.
$s->setRightFill($f);
$s->drawLine(320, 0); swfmorph->getshape2() gets a handle to the morph's
$s->drawLine(0, 240); ending shape. swfmorph->getshape2() returns an
$s->drawLine(-320, 0); swfshape() object.
$s->drawLine(0, -240);

$m->add($s); SWFMorph

$s = new SWFShape(); (PHP 4 >= 4.0.5)


SWFMorph -- Creates a new SWFMorph object.
// second gradient- radial gradient from
Description SWFMovie->add -- Adds any type of data to a movie.

new swfmorph ( void) Description

Aviso void swfmovie->add ( ressource instance)


Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y Este módulo es EXPERIMENTAL. Esto significa que el
utilizar este módulo es tu responsabiliad. comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
swfmorph() creates a new SWFMorph object. en una futura version de PHP SIN AVISO. Quedas avisado, y
Also called a "shape tween". This thing lets you make utilizar este módulo es tu responsabiliad.
those tacky twisting things that make your computer
choke. Oh, joy! swfmovie->add() adds instance to the current movie.
The methods here are sort of weird. It would make more instance is any type of data : Shapes, text, fonts, etc.
sense to just have newSWFMorph(shape1, shape2);, but must all be add'ed to the movie to make this work.
as things are now, shape2 needs to know that it's the For displayable types (shape, text, button, sprite), this
second part of a morph. (This, because it starts writing returns an SWFDisplayItem(), a handle to the object in
its output as soon as it gets drawing commands- if it kept a display list. Thus, you can add the same shape to a
its own description of its shapes and wrote on completion movie multiple times and get separate handles back for
this and some other things would be much easier.) each separate instance.
SWFMorph has the following methods : swfmorph- See also all other objects (adding this later), and
>getshape1() and swfmorph->getshape1(). swfmovie->remove()
This simple example will morph a big red square into a See examples in : swfdisplayitem->rotateto() and
smaller blue black-bordered square. swfshape->addfill().
Ejemplo 1. swfmorph() example
SWFMovie->nextframe

<?php
$p = new SWFMorph(); (no version information, might be only in CVS)
SWFMovie->nextframe -- Moves to the next frame of the
$s = $p->getShape1(); animation.
$s->setLine(0,0,0,0);

/* Note that this is backwards from normal shapes Description


(left instead of right).
I have no idea why, but this seems to work.. */ void swfmovie->nextframe ( void)
$s->setLeftFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-1000,-1000); Aviso
$s->drawLine(2000,0);
$s->drawLine(0,2000); Este módulo es EXPERIMENTAL. Esto significa que el
$s->drawLine(-2000,0); comportamineto de estas funciones, nombre de funciones
$s->drawLine(0,-2000); y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
$s = $p->getShape2(); utilizar este módulo es tu responsabiliad.
$s->setLine(60,0,0,0); swfmovie->nextframe() moves to the next frame of
$s->setLeftFill($s->addFill(0, 0, 0xff)); the animation.
$s->movePenTo(0,-1000);
$s->drawLine(1000,1000);
$s->drawLine(-1000,1000); SWFMovie->output
$s->drawLine(-1000,-1000);
$s->drawLine(1000,-1000);
(no version information, might be only in CVS)
$m = new SWFMovie(); SWFMovie->output -- Dumps your lovingly prepared
$m->setDimension(3000,2000); movie out.
$m->setBackground(0xff, 0xff, 0xff);
Description
$i = $m->add($p);
$i->moveTo(1500,1000);
void swfmovie->output ( void)
for($r=0.0; $r<=1.0; $r+=0.1)
{
$i->setRatio($r); Aviso
$m->nextFrame();
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
header('Content-type: application/x-shockwave-
en una futura version de PHP SIN AVISO. Quedas avisado, y
flash');
utilizar este módulo es tu responsabiliad.
$m->output();
?> swfmovie->output() dumps your lovingly prepared
movie out. In PHP, preceding this with the command
<?php
SWFMovie->add header('Content-type: application/x-
shockwave-flash');
?>
(no version information, might be only in CVS)
convinces the browser to display this as a flash movie. There's a way to do that, but it only works on IE4. Search
See also swfmovie->save(). the http://www.macromedia.com/ site for details.)
See examples in : swfmovie->streammp3(),
swfdisplayitem->rotateto(), swfaction()... Any
example will use this method. SWFMovie->setdimension

SWFMovie->remove (no version information, might be only in CVS)


SWFMovie->setdimension -- Sets the movie's width and
height.
(no version information, might be only in CVS)
SWFMovie->remove -- Removes the object instance from
the display list. Description

Description void swfmovie->setdimension ( int width, int height)

void swfmovie->remove ( resource instance) Aviso


Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar swfmovie->setdimension() sets the movie's width to
en una futura version de PHP SIN AVISO. Quedas avisado, y width and height to height.
utilizar este módulo es tu responsabiliad.
swfmovie->remove() removes the object instance
instance from the display list. SWFMovie->setframes
See also swfmovie->add().
(no version information, might be only in CVS)
SWFMovie->save SWFMovie->setframes -- Sets the total number of frames
in the animation.

(no version information, might be only in CVS)


SWFMovie->save -- Saves your movie in a file. Description

Description void swfmovie->setframes ( string numberofframes)

void swfmovie->save ( string filename) Aviso


Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar swfmovie->setframes() sets the total number of
en una futura version de PHP SIN AVISO. Quedas avisado, y frames in the animation to numberofframes.
utilizar este módulo es tu responsabiliad.
swfmovie->save() saves your movie to the file named
filename. SWFMovie->setrate
See also output().
(no version information, might be only in CVS)
SWFMovie->setbackground SWFMovie->setrate -- Sets the animation's frame rate.

(no version information, might be only in CVS) Description


SWFMovie->setbackground -- Sets the background color.
void swfmovie->setrate ( int rate)
Description
Aviso
void swfmovie->setbackground ( int red, int green, int Este módulo es EXPERIMENTAL. Esto significa que el
blue) 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
Aviso
utilizar este módulo es tu responsabiliad.
Este módulo es EXPERIMENTAL. Esto significa que el swfmovie->setrate() sets the frame rate to rate, in
comportamineto de estas funciones, nombre de funciones frame per seconds. Animation will slow down if the player
y en definitiva TODO lo documentado aqui, puede cambiar can't render frames fast enough- unless there's a
en una futura version de PHP SIN AVISO. Quedas avisado, y streaming sound, in which case display frames are
utilizar este módulo es tu responsabiliad. sacrificed to keep sound from skipping.
swfmovie->setbackground() sets the background
color. Why is there no rgba version? Think about it.
(Actually, that's not such a dumb question after all- you SWFMovie->streammp3
might want to let the html background show through.
(no version information, might be only in CVS) SWFShape->addFill
SWFMovie->streammp3 -- Streams a MP3 file.

(no version information, might be only in CVS)


Description SWFShape->addFill -- Adds a solid fill to the shape.

void swfmovie->streammp3 ( string mp3FileName) Description

Aviso void swfshape->addfill ( int red, int green, int blue [,


int a])
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 Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
swfmovie->streammp3() streams the mp3 file y en definitiva TODO lo documentado aqui, puede cambiar
mp3FileName. Not very robust in dealing with oddities en una futura version de PHP SIN AVISO. Quedas avisado, y
(can skip over an initial ID3 tag, but that's about it). Like utilizar este módulo es tu responsabiliad.
SWFShape->addJpegFill(), this isn't a stable function-
we'll probably need to make a separate SWFSound object void swfshape->addfill ( SWFbitmap bitmap [, int
to contain sound types. flags])
Note that the movie isn't smart enough to put enough
frames in to contain the entire mp3 stream- you'll have
to add (length of song * frames per second) frames to Aviso
get the entire stream in. Este módulo es EXPERIMENTAL. Esto significa que el
Yes, now you can use ming to put that rock and roll devil comportamineto de estas funciones, nombre de funciones
worship music into your SWF files. Just don't tell the RIAA. y en definitiva TODO lo documentado aqui, puede cambiar
Ejemplo 1. swfmovie->streammp3() example en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
void swfshape->addfill ( SWFGradient gradient [, int
<?php flags])
$m = new SWFMovie();
$m->setRate(12.0);
$m->streamMp3("distortobass.mp3"); Aviso
// use your own MP3
Este módulo es EXPERIMENTAL. Esto significa que el
// 11.85 seconds at 12.0 fps = 142 comportamineto de estas funciones, nombre de funciones
frames y en definitiva TODO lo documentado aqui, puede cambiar
$m->setFrames(142); en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
header('Content-type: application/x- swfshape->addfill() adds a solid fill to the shape's list
shockwave-flash'); of fill styles. swfshape->addfill() accepts three
$m->output(); different types of arguments.
?> red, green, blue is a color (RGB mode). Last parameter a
is optional.
The bitmap argument is an swfbitmap() object. The
SWFMovie flags argument can be one of the following values :
SWFFILL_CLIPPED_BITMAP or SWFFILL_TILED_BITMAP.
Default is SWFFILL_TILED_BITMAP. I think.
(PHP 4 >= 4.0.5) The gradient argument is an swfgradient() object. The
SWFMovie -- Creates a new movie object, representing flags argument can be one of the following values :
an SWF version 4 movie. SWFFILL_RADIAL_GRADIENT or
SWFFILL_LINEAR_GRADIENT. Default is
SWFFILL_LINEAR_GRADIENT. I'm sure about this one.
Description
Really.
swfshape->addfill() returns an swffill() object for use
new swfmovie ( void) with the swfshape->setleftfill() and swfshape-
>setrightfill() functions described below.
See also swfshape->setleftfill() and swfshape-
Aviso >setrightfill().
This simple example will draw a frame on a bitmap. Ah,
Este módulo es EXPERIMENTAL. Esto significa que el here's another buglet in the flash player- it doesn't seem
comportamineto de estas funciones, nombre de funciones to care about the second shape's bitmap's
y en definitiva TODO lo documentado aqui, puede cambiar transformation in a morph. According to spec, the bitmap
en una futura version de PHP SIN AVISO. Quedas avisado, y should stretch along with the shape in this example..
utilizar este módulo es tu responsabiliad. Ejemplo 1. swfshape->addfill() example
swfmovie() creates a new movie object, representing an
SWF version 4 movie.
SWFMovie has the following methods : swfmovie- <?php
>output(),swfmovie->save(), swfmovie->add(),
swfmovie->remove(), swfmovie->nextframe(), $p = new SWFMorph();
swfmovie->setbackground(), swfmovie->setrate(),
swfmovie->setdimension(), swfmovie->setframes() $b = new SWFBitmap("alphafill.jpg");
and swfmovie->streammp3(). // use your own bitmap
See examples in : swfdisplayitem->rotateto(), $width = $b->getWidth();
swfshape->setline(), swfshape->addfill()... Any $height = $b->getHeight();
example will use this object.
SWFShape->drawCurveTo -- Draws a curve.
$s = $p->getShape1();
$f = $s->addFill($b,
SWFFILL_TILED_BITMAP); Description
$f->moveTo(-$width/2, -$height/4);
$f->scaleTo(1.0, 0.5);
$s->setLeftFill($f); void swfshape->drawcurveto ( int controlx, int
$s->movePenTo(-$width/2, -$height/4); controly, int anchorx, int anchory)
$s->drawLine($width, 0);
$s->drawLine(0, $height/2);
$s->drawLine(-$width, 0); Aviso
$s->drawLine(0, -$height/2); Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
$s = $p->getShape2(); y en definitiva TODO lo documentado aqui, puede cambiar
$f = $s->addFill($b, en una futura version de PHP SIN AVISO. Quedas avisado, y
SWFFILL_TILED_BITMAP); utilizar este módulo es tu responsabiliad.
// these two have no effect! swfshape->drawcurveto() draws a quadratic curve
$f->moveTo(-$width/4, -$height/2); (using the current line style, set by swfshape-
$f->scaleTo(0.5, 1.0); >setline()) from the current pen position to
(anchorx,anchory) using (controlx,controly) as a control
$s->setLeftFill($f); point. That is, head towards the control point, then
$s->movePenTo(-$width/4, -$height/2); smoothly turn to the anchor point.
$s->drawLine($width/2, 0); See also swfshape->drawlineto(), swfshape-
$s->drawLine(0, $height); >drawline(), swfshape->movepento() and
$s->drawLine(-$width/2, 0); swfshape->movepen().
$s->drawLine(0, -$height);
SWFShape->drawLine
$m = new SWFMovie();
$m->setDimension($width, $height);
$i = $m->add($p); (no version information, might be only in CVS)
$i->moveTo($width/2, $height/2); SWFShape->drawLine -- Draws a line (relative).

for($n=0; $n<1.001; $n+=0.03)


{ Description
$i->setRatio($n);
$m->nextFrame();
} void swfshape->drawline ( int dx, int dy)

header('Content-type: application/x-
Aviso
shockwave-flash');
$m->output(); 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
SWFShape->drawCurve utilizar este módulo es tu responsabiliad.
swfshape->drawline() draws a line (using the current
line style set by swfshape->setline()) from the current
(no version information, might be only in CVS)
pen position to displacement (dx,dy).
SWFShape->drawCurve -- Draws a curve (relative).
See also swfshape->movepento(), swfshape-
>drawcurveto(), swfshape->movepen() and
Description swfshape->drawlineto().

void swfshape->drawcurve ( int controldx, int SWFShape->drawLineTo


controldy, int anchordx, int anchordy)
(no version information, might be only in CVS)
Aviso SWFShape->drawLineTo -- Draws a line.

Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones Description
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. void swfshape->drawlineto ( int x, int y)

swfshape->drawcurve() draws a quadratic curve


(using the current line style,set by swfshape- Aviso
>setline()) from the current pen position to the relative
Este módulo es EXPERIMENTAL. Esto significa que el
position (anchorx,anchory) using relative control point
comportamineto de estas funciones, nombre de funciones
(controlx,controly). That is, head towards the control
y en definitiva TODO lo documentado aqui, puede cambiar
point, then smoothly turn to the anchor point.
en una futura version de PHP SIN AVISO. Quedas avisado, y
See also swfshape->drawlineto(), swfshape-
utilizar este módulo es tu responsabiliad.
>drawline(), swfshape->movepento() and
swfshape->movepen(). swfshape->setrightfill() draws a line (using the
current line style, set by swfshape->setline()) from the
current pen position to point (x,y) in the shape's
SWFShape->drawCurveTo coordinate space.
See also swfshape->movepento(), swfshape-
>drawcurveto(), swfshape->movepen() and
(no version information, might be only in CVS)
swfshape->drawline().
SWFShape->movePen comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
(no version information, might be only in CVS) en una futura version de PHP SIN AVISO. Quedas avisado, y
SWFShape->movePen -- Moves the shape's pen utilizar este módulo es tu responsabiliad.
(relative). What this nonsense is about is, every edge segment
borders at most two fills. When rasterizing the object, it's
pretty handy to know what those fills are ahead of time,
Description so the swf format requires these to be specified.
swfshape->setleftfill() sets the fill on the left side of
void swfshape->movepen ( int dx, int dy) the edge- that is, on the interior if you're defining the
outline of the shape in a counter-clockwise fashion. The
fill object is an SWFFill object returned from one of the
Aviso addFill functions above.
This seems to be reversed when you're defining a shape
Este módulo es EXPERIMENTAL. Esto significa que el in a morph, though. If your browser crashes, just try
comportamineto de estas funciones, nombre de funciones setting the fill on the other side.
y en definitiva TODO lo documentado aqui, puede cambiar Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [,
en una futura version de PHP SIN AVISO. Quedas avisado, y $a]));.
utilizar este módulo es tu responsabiliad. See also swfshape->setrightfill().
swfshape->setrightfill() move the shape's pen from
coordinates (current x,current y) to (current x + dx,
current y + dy) in the shape's coordinate space. SWFShape->setLine
See also swfshape->movepento(), swfshape-
>drawcurveto(), swfshape->drawlineto() and (no version information, might be only in CVS)
swfshape->drawline(). SWFShape->setLine -- Sets the shape's line style.

SWFShape->movePenTo Description

(no version information, might be only in CVS) void swfshape->setline ( int width [, int red [, int green
SWFShape->movePenTo -- Moves the shape's pen. [, int blue [, int a]]]])

Description
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
void swfshape->movepento ( int x, int y) 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
Aviso utilizar este módulo es tu responsabiliad.
Este módulo es EXPERIMENTAL. Esto significa que el swfshape->setline() sets the shape's line style. width
comportamineto de estas funciones, nombre de funciones is the line's width. If width is 0, the line's style is removed
y en definitiva TODO lo documentado aqui, puede cambiar (then, all other arguments are ignored). If width > 0,
en una futura version de PHP SIN AVISO. Quedas avisado, y then line's color is set to red, green, blue. Last parameter
utilizar este módulo es tu responsabiliad. a is optional.
swfshape->setrightfill() move the shape's pen to (x,y) swfshape->setline() accepts 1, 4 or 5 arguments (not
in the shape's coordinate space. 3 or 2).
See also swfshape->movepen(), swfshape- You must declare all line styles before you use them (see
>drawcurveto(), swfshape->drawlineto() and example).
swfshape->drawline(). This simple example will draw a big "!#%*@", in funny
colors and gracious style.
Ejemplo 1. swfshape->setline() example
SWFShape->setLeftFill

(no version information, might be only in CVS) <?php


SWFShape->setLeftFill -- Sets left rasterizing color. $s = new SWFShape();
$f1 = $s->addFill(0xff, 0, 0);
$f2 = $s->addFill(0xff, 0x7f, 0);
Description $f3 = $s->addFill(0xff, 0xff, 0);
$f4 = $s->addFill(0, 0xff, 0);
$f5 = $s->addFill(0, 0, 0xff);
void swfshape->setleftfill ( swfgradient fill)
// bug: have to declare all line styles before you
use them
Aviso $s->setLine(40, 0x7f, 0, 0);
Este módulo es EXPERIMENTAL. Esto significa que el $s->setLine(40, 0x7f, 0x3f, 0);
comportamineto de estas funciones, nombre de funciones $s->setLine(40, 0x7f, 0x7f, 0);
y en definitiva TODO lo documentado aqui, puede cambiar $s->setLine(40, 0, 0x7f, 0);
en una futura version de PHP SIN AVISO. Quedas avisado, y $s->setLine(40, 0, 0, 0x7f);
utilizar este módulo es tu responsabiliad.
$f = new SWFFont('Techno.fdb');
void swfshape->setleftfill ( int red, int green, int blue
[, int a]) $s->setRightFill($f1);
$s->setLine(40, 0x7f, 0, 0);
$s->drawGlyph($f, '!');
Aviso
$s->movePen($f->getWidth('!'), 0);
Este módulo es EXPERIMENTAL. Esto significa que el
$s->setRightFill($f2); Aviso
$s->setLine(40, 0x7f, 0x3f, 0);
Este módulo es EXPERIMENTAL. Esto significa que el
$s->drawGlyph($f, '#');
comportamineto de estas funciones, nombre de funciones
$s->movePen($f->getWidth('#'), 0);
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
$s->setRightFill($f3);
utilizar este módulo es tu responsabiliad.
$s->setLine(40, 0x7f, 0x7f, 0);
$s->drawGlyph($f, '%'); swfshape() creates a new shape object.
$s->movePen($f->getWidth('%'), 0); SWFShape has the following methods : swfshape-
>setline(), swfshape->addfill(), swfshape-
$s->setRightFill($f4); >setleftfill(), swfshape->setrightfill(), swfshape-
$s->setLine(40, 0, 0x7f, 0); >movepento(), swfshape->movepen(), swfshape-
$s->drawGlyph($f, '*'); >drawlineto(), swfshape->drawline(), swfshape-
$s->movePen($f->getWidth('*'), 0); >drawcurveto() and swfshape->drawcurve().
This simple example will draw a big red elliptic quadrant.
$s->setRightFill($f5); Ejemplo 1. swfshape() example
$s->setLine(40, 0, 0, 0x7f);
$s->drawGlyph($f, '@');
<?php
$m = new SWFMovie(); $s = new SWFShape();
$m->setDimension(3000,2000); $s->setLine(40, 0x7f, 0, 0);
$m->setRate(12.0); $s->setRightFill($s->addFill(0xff, 0, 0));
$i = $m->add($s); $s->movePenTo(200, 200);
$i->moveTo(1500-$f->getWidth("!#%*@")/2, $s->drawLineTo(6200, 200);
1000+$f->getAscent()/2); $s->drawLineTo(6200, 4600);
$s->drawCurveTo(200, 4600, 200,
header('Content-type: application/x-shockwave- 200);
flash');
$m->output(); $m = new SWFMovie();
?> $m->setDimension(6400, 4800);
$m->setRate(12.0);
$m->add($s);
SWFShape->setRightFill $m->nextFrame();

header('Content-type: application/x-
(no version information, might be only in CVS) shockwave-flash');
SWFShape->setRightFill -- Sets right rasterizing color. $m->output();
?>
Description
SWFSprite->add
void swfshape->setrightfill ( swfgradient fill)
(no version information, might be only in CVS)
Aviso SWFSprite->add -- Adds an object to a sprite

Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones Description
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. void swfsprite->add ( resource object)

void swfshape->setrightfill ( int red, int green, int blue


[, int a]) Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y swfsprite->add() adds a swfshape(), a swfbutton(),
utilizar este módulo es tu responsabiliad. a swftext(), a swfaction() or a swfsprite() object.
For displayable types (swfshape(), swfbutton(),
See also swfshape->setleftfill(). swftext(), swfaction() or swfsprite()), this returns a
Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b handle to the object in a display list.
[, $a]));.

SWFSprite->nextframe
SWFShape

(no version information, might be only in CVS)


(PHP 4 >= 4.0.5) SWFSprite->nextframe -- Moves to the next frame of the
SWFShape -- Creates a new shape object. animation.

Description Description

new swfshape ( void) void swfsprite->nextframe ( void)


Aviso timelines. Hence, the sprite has most of the same
methods as the movie.
Este módulo es EXPERIMENTAL. Esto significa que el swfsprite() has the following methods : swfsprite-
comportamineto de estas funciones, nombre de funciones >add(), swfsprite->remove(), swfsprite-
y en definitiva TODO lo documentado aqui, puede cambiar >nextframe() and swfsprite->setframes().
en una futura version de PHP SIN AVISO. Quedas avisado, y This simple example will spin gracefully a big red square.
utilizar este módulo es tu responsabiliad. Ejemplo 1. swfsprite() example
swfsprite->setframes() moves to the next frame of
the animation.
<?php
$s = new SWFShape();
SWFSprite->remove $s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-500,-500);
$s->drawLineTo(500,-500);
(no version information, might be only in CVS) $s->drawLineTo(500,500);
SWFSprite->remove -- Removes an object to a sprite $s->drawLineTo(-500,500);
$s->drawLineTo(-500,-500);
Description
$p = new SWFSprite();
$i = $p->add($s);
void swfsprite->remove ( ressource object) $p->nextFrame();
$i->rotate(15);
$p->nextFrame();
Aviso $i->rotate(15);
Este módulo es EXPERIMENTAL. Esto significa que el $p->nextFrame();
comportamineto de estas funciones, nombre de funciones $i->rotate(15);
y en definitiva TODO lo documentado aqui, puede cambiar $p->nextFrame();
en una futura version de PHP SIN AVISO. Quedas avisado, y $i->rotate(15);
utilizar este módulo es tu responsabiliad. $p->nextFrame();
$i->rotate(15);
swfsprite->remove() remove a swfshape(), a $p->nextFrame();
swfbutton(), a swftext(), a swfaction() or a
swfsprite() object from the sprite. $m = new SWFMovie();
$i = $m->add($p);
$i->moveTo(1500,1000);
SWFSprite->setframes
$i->setName("blah");

(no version information, might be only in CVS) $m->setBackground(0xff, 0xff, 0xff);


SWFSprite->setframes -- Sets the total number of frames $m->setDimension(3000,2000);
in the animation.
header('Content-type: application/x-
shockwave-flash');
Description $m->output();
?>
void swfsprite->setframes ( int numberofframes)
SWFText->addString
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el (no version information, might be only in CVS)
comportamineto de estas funciones, nombre de funciones SWFText->addString -- Draws a string
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Description
utilizar este módulo es tu responsabiliad.
swfsprite->setframes() sets the total number of
frames in the animation to numberofframes. void swftext->addstring ( string string)

SWFSprite Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
(PHP 4 >= 4.0.5) comportamineto de estas funciones, nombre de funciones
SWFSprite -- Creates a movie clip (a sprite) 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.
Description
swftext->addstring() draws the string string at the
current pen (cursor) location. Pen is at the baseline of the
new swfsprite ( void) text; i.e., ascending text is in the -y direction.

Aviso SWFText->getWidth

Este módulo es EXPERIMENTAL. Esto significa que el


comportamineto de estas funciones, nombre de funciones (no version information, might be only in CVS)
y en definitiva TODO lo documentado aqui, puede cambiar SWFText->getWidth -- Computes string's width
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Description
swfsprite() are also known as a "movie clip", this allows
one to create objects which are animated in their own
void swftext->addstring ( string string) 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
Aviso
utilizar este módulo es tu responsabiliad.
Este módulo es EXPERIMENTAL. Esto significa que el
swftext->setfont() sets the current font to font.
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 SWFText->setHeight
utilizar este módulo es tu responsabiliad.
swftext->addstring() returns the rendered width of the
(no version information, might be only in CVS)
string string at the text object's current font, scale, and
SWFText->setHeight -- Sets the current font height
spacing settings.

Description
SWFText->moveTo

void swftext->setheight ( int height)


(no version information, might be only in CVS)
SWFText->moveTo -- Moves the pen
Aviso
Description 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
void swftext->moveto ( int x, int y) en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso swftext->setheight() sets the current font height to
height. Default is 240.
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 SWFText->setSpacing
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
(no version information, might be only in CVS)
swftext->moveto() moves the pen (or cursor, if that
SWFText->setSpacing -- Sets the current font spacing
makes more sense) to (x,y) in text object's coordinate
space. If either is zero, though, value in that dimension
stays the same. Annoying, should be fixed. Description

SWFText->setColor void swftext->setspacing ( float spacing)

(no version information, might be only in CVS) Aviso


SWFText->setColor -- Sets the current font color
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Description 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.
void swftext->setcolor ( int red, int green, int blue [, int
a]) swftext->setspacing() sets the current font spacing to
spacingspacing. Default is 1.0. 0 is all of the letters
written at the same point. This doesn't really work that
Aviso well because it inflates the advance across the letter,
doesn't add the same amount of spacing between the
Este módulo es EXPERIMENTAL. Esto significa que el
letters. I should try and explain that better, prolly. Or just
comportamineto de estas funciones, nombre de funciones fix the damn thing to do constant spacing. This was really
y en definitiva TODO lo documentado aqui, puede cambiar
just a way to figure out how letter advances work,
en una futura version de PHP SIN AVISO. Quedas avisado, y anyway.. So nyah.
utilizar este módulo es tu responsabiliad.
swftext->setspacing() changes the current text color.
Default is black. I think. Color is represented using the SWFText
RGB system.
(PHP 4 >= 4.0.5)
SWFText->setFont SWFText -- Creates a new SWFText object.

(no version information, might be only in CVS) Description


SWFText->setFont -- Sets the current font
new swftext ( void)
Description
Aviso
void swftext->setfont ( string font) 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
Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y
Este módulo es EXPERIMENTAL. Esto significa que el utilizar este módulo es tu responsabiliad.
swftext() creates a new SWFText object, fresh for SWFTEXTFIELD_ALIGN_RIGHT,
manipulating. SWFTEXTFIELD_ALIGN_CENTER and
SWFText has the following methods : swftext- SWFTEXTFIELD_ALIGN_JUSTIFY.
>setfont(), swftext->setheight(), swftext-
>setspacing(), swftext->setcolor(), swftext-
>moveto(), swftext->addstring() and swftext- SWFTextField->setbounds
>getwidth().
This simple example will draw a big yellow "PHP
(no version information, might be only in CVS)
generates Flash with Ming" text, on white background. SWFTextField->setbounds -- Sets the text field width and
Ejemplo 1. swftext() example
height

<?php Description
$f = new SWFFont("Techno.fdb");
$t = new SWFText();
$t->setFont($f); void swftextfield->setbounds ( int width, int height)
$t->moveTo(200, 2400);
$t->setColor(0xff, 0xff, 0);
$t->setHeight(1200); Aviso
$t->addString("PHP generates Flash Este módulo es EXPERIMENTAL. Esto significa que el
with Ming!!"); comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
$m = new SWFMovie(); en una futura version de PHP SIN AVISO. Quedas avisado, y
$m->setDimension(5400, 3600); utilizar este módulo es tu responsabiliad.
swftextfield->setbounds() sets the text field width to
$m->add($t);
width and height to height. If you don't set the bounds
yourself, Ming makes a poor guess at what the bounds
header('Content-type: application/x-
are.
shockwave-flash');
$m->output();
?> SWFTextField->setcolor

SWFTextField->addstring (no version information, might be only in CVS)


SWFTextField->setcolor -- Sets the color of the text field.

(no version information, might be only in CVS)


SWFTextField->addstring -- Concatenates the given Description
string to the text field
void swftextfield->setcolor ( int red, int green, int blue
Description [, int a])

void swftextfield->addstring ( string string) Aviso


Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar
swftextfield->setcolor() sets the color of the text field.
en una futura version de PHP SIN AVISO. Quedas avisado, y
Default is fully opaque black. Color is represented using
utilizar este módulo es tu responsabiliad.
RGB system.
swftextfield->setname() concatenates the string
string to the text field.
SWFTextField->setFont

SWFTextField->align
(no version information, might be only in CVS)
SWFTextField->setFont -- Sets the text field font
(no version information, might be only in CVS)
SWFTextField->align -- Sets the text field alignment
Description

Description
void swftextfield->setfont ( string font)

void swftextfield->align ( int alignement)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y
swftextfield->setfont() sets the text field font to the
utilizar este módulo es tu responsabiliad.
[browser-defined?] font font.
swftextfield->align() sets the text field alignment to
alignement. Valid values for alignement are :
SWFTEXTFIELD_ALIGN_LEFT, SWFTextField->setHeight
(no version information, might be only in CVS) Aviso
SWFTextField->setHeight -- Sets the font height of this
text field font. 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
Description en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
void swftextfield->setheight ( int height) swftextfield->setlinespacing() sets the line spacing of
the text field to the height of height. Default is 40.

Aviso
SWFTextField->setMargins
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 (no version information, might be only in CVS)
en una futura version de PHP SIN AVISO. Quedas avisado, y SWFTextField->setMargins -- Sets the margins width of
utilizar este módulo es tu responsabiliad. the text field.
swftextfield->setheight() sets the font height of this
text field font to the given height height. Default is 240. Description

SWFTextField->setindentation void swftextfield->setmargins ( int left, int right)

(no version information, might be only in CVS) Aviso


SWFTextField->setindentation -- Sets the indentation of
the first line. 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
Description en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
void swftextfield->setindentation ( int width) swftextfield->setmargins() set both margins at once,
for the man on the go.

Aviso
SWFTextField->setname
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 (no version information, might be only in CVS)
en una futura version de PHP SIN AVISO. Quedas avisado, y SWFTextField->setname -- Sets the variable name
utilizar este módulo es tu responsabiliad.
swftextfield->setindentation() sets the indentation of Description
the first line in the text field, to width.

void swftextfield->setname ( string name)


SWFTextField->setLeftMargin

Aviso
(no version information, might be only in CVS)
SWFTextField->setLeftMargin -- Sets the left margin Este módulo es EXPERIMENTAL. Esto significa que el
width of the text field. 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
Description utilizar este módulo es tu responsabiliad.
swftextfield->setname() sets the variable name of this
void swftextfield->setleftmargin ( int width) text field to name, for form posting and action scripting
purposes.

Aviso
SWFTextField->setrightMargin
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 (no version information, might be only in CVS)
en una futura version de PHP SIN AVISO. Quedas avisado, y SWFTextField->setrightMargin -- Sets the right margin
utilizar este módulo es tu responsabiliad. width of the text field.
swftextfield->setleftmargin() sets the left margin
width of the text field to width. Default is 0. Description

SWFTextField->setLineSpacing void swftextfield->setrightmargin ( int width)

(no version information, might be only in CVS) Aviso


SWFTextField->setLineSpacing -- Sets the line spacing of
the text field. 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
Description en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
void swftextfield->setlinespacing ( int height)
swftextfield->setrightmargin() sets the right margin connection_timeout -- Devuelve TRUE si el script ha
width of the text field to width. Default is 0. alcanzado su time out
constant -- Returns the value of a constant
define -- Define una constante con nombre.
SWFTextField defined -- Comprueba que una constante con nombre
dada existe.
die -- Envía a la salida un mensaje y finaliza el script
(PHP 4 >= 4.0.5)
actual
SWFTextField -- Creates a text field object
eval -- Evalúa una cadena de carácteres como código
PHP
Description exit -- Finaliza el script actual
get_browser -- Informa sobre lo que es capaz de hacer el
navegador (browser) del usuario.
new swftextfield ( [int flags]) highlight_file -- Syntax highlighting of a file
highlight_string -- Syntax highlighting of a string
ignore_user_abort -- Establece si la desconexión de un
Aviso cliente debe suspender la ejecución del script
Este módulo es EXPERIMENTAL. Esto significa que el pack -- empaqueta datos en una cadena binaria
comportamineto de estas funciones, nombre de funciones show_source -- Syntax highlighting of a file
y en definitiva TODO lo documentado aqui, puede cambiar sleep -- Ejecución retardada
en una futura version de PHP SIN AVISO. Quedas avisado, y uniqid -- Genera un id único.
utilizar este módulo es tu responsabiliad. unpack -- desempaqueta datos de una cadena binaria
usleep -- Retrasa la ejecución, en microsegundos
swftextfield() creates a new text field object. Text
Fields are less flexible than swftext() objects- they can't
be rotated, scaled non-proportionally, or skewed, but connection_aborted
they can be used as form entries, and they can use
browser-defined fonts.
The optional flags change the text field's behavior. It has (PHP 3>= 3.0.7, PHP 4 )
the following possibles values : connection_aborted -- Devuelve TRUE si el cliente está
desconectado

• SWFTEXTFIELD_DRAWBOX draws the outline of Descripción


the textfield
• SWFTEXTFIELD_HASLENGTH
int connection_aborted ( void )
• SWFTEXTFIELD_HTML allows text markup using
HTML-tags Devuelve TRUE si el cliente está desconectado. Vea la
• SWFTEXTFIELD_MULTILINE allows multiple lines descripción de la Gestión de la Conexión en el capítulo
Características para una explicación completa.
• SWFTEXTFIELD_NOEDIT indicates that the field
shouldn't be user-editable
• SWFTEXTFIELD_NOSELECT makes the field connection_status
non-selectable
• SWFTEXTFIELD_PASSWORD obscures the data (PHP 3>= 3.0.7, PHP 4 )
entry connection_status -- Devuelve el estado de la conexión
en un campo de bits
• SWFTEXTFIELD_WORDWRAP allows text to
wrap
Descripción
Flags are combined with the bitwise OR operation. For
example, int connection_status ( void )
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | Devuelve el estado de la conexión en un campo de bits.
SWFTEXTFIELD_NOEDIT); Vea la descripción de la Gestión de la Conexión en el
?> capítulo Características para una explicación completa.
creates a totally useless non-editable password field.
SWFTextField has the following methods : swftextfield- connection_timeout
>setfont(), swftextfield->setbounds(),
swftextfield->align(), swftextfield->setheight(),
swftextfield->setleftmargin(), swftextfield- (PHP 3>= 3.0.7, PHP 4 <= 4.0.4)
>setrightmargin(), swftextfield->setmargins(), connection_timeout -- Devuelve TRUE si el script ha
swftextfield->setindentation(), swftextfield- alcanzado su time out
>setlinespacing(), swftextfield->setcolor(),
swftextfield->setname() and swftextfield-
>addstring(). Descripción

LX. Miscelánea de funciones int connection_timeout ( void )

Devuelve TRUE si el script ha alcanzado su time out. Vea


Estas funciones están colacadas aquí debido a que no
la descripción de la Gestión de la Conexión en el capítulo
parecen ajustarse a ninguna otra categoría.
Características para una explicación completa.
Tabla de contenidos
connection_aborted -- Devuelve TRUE si el cliente está
desconectado constant
connection_status -- Devuelve el estado de la conexión
en un campo de bits
(PHP 4 >= 4.0.4) defined
constant -- Returns the value of a constant

(PHP 3, PHP 4 )
Description defined -- Comprueba que una constante con nombre
dada existe.

mixed constant ( string name)


Descripción
constant() will return the value of the constant
indicated by name. int defined ( string name)
constant() is useful if you need to retrieve the value of a
constant, but do not know it's name. i.e. It is stored in a
variable or returned by a function. Devuelve TRUE si la constante con nombre dada en
Ejemplo 1. constant() example name (nombre) ha sido definida, FALSE en otro caso.
Véase también define() y la sección Constantes.

<?php die

define ("MAXSIZE", 100);


(no version information, might be only in CVS)
echo MAXSIZE; die -- Envía a la salida un mensaje y finaliza el script
echo constant("MAXSIZE"); // same thing as actual
the previous line

?> Descripción

See also define(), defined() and the section on


Constants. void die ( string message)

define Esta construcción del lenguaje envía a la salida un


mensaje y finaliza la ejecución del script. No devuelve
nada.
(PHP 3, PHP 4 ) Ejemplo 1. Ejemplo die
define -- Define una constante con nombre.

<?php
Descripción
$filename = '/path/to/data-
file';
int define ( string name, mixed value [, int $file = fopen($filename, 'r')
case_insensitive]) or die "unable to open file
($filename)";
?>
Define una constante con nombre, que es similar a una
variable, excepto que:
eval

• Las constantes no tienen un símbolo dólar '$'


precediéndolas; (PHP 3, PHP 4 )
eval -- Evalúa una cadena de carácteres como código
• Las constantes son accesibles desde cualquier
PHP
lugar sin tener en cuenta las reglas de ámbito
de las variables.
• Las constantes no pueden ser redefinidas o Descripción
iniciadas una vez que han sido establecidas, y
• Las constantes sólo pueden evaluar valores void eval ( string code_str)
escalares
eval() evalúa la cadena de carácteres dada en code_str
El nombre de la constante se da en name (nombre); el como código PHP. Entre otras cosas, ésto puede ser útil
valor se da en value (valor). para almacenar código en un campo de texto de base de
El tercer parámetro opcional case_insensitive también se datos para una ejecución posterior.
encuentra disponible. Si se da el valor 1, la constante se Hay algunos aspectos a tener en cuenta cuando se utiliza
definirá no dintinguiendo mayúsculas/minusculas. El eval(). Recuerde que la cadena de carácteres pasada
comportamiento por defecto es si distinguir; i.e. debe ser código PHP válido, incluyendo aspectos como
CONSTANT y Constant representan valores diferentes. sentencias de terminación con un punto y coma para que
Ejemplo 1. Definición de Constantes el parser no finalice en la línea después de eval(), y
secuencias de formato correctas en code_str.
Recuerde también que las variables a las que se les da
valor en eval() retendrán estos valores posteriormente
<?php en el script principal.
define("CONSTANT", "Hello Ejemplo 1. Ejemplo eval() - fusión en un único texo
world.");
echo CONSTANT; // outputs
"Hello world."
?> <?php
$string = 'cup';
define() devuelve TRUE en caso de éxito y FALSE si $name = 'coffee';
ocurre un error. $str = 'This is a $string with my
Véase también defined() y la sección Constantes. $name in it.<br>';
echo $str; i586)<hr>
eval( "\$str = \"$str\";" ); <b>browser_name_pattern:</b>
echo $str; Mozilla/4\.5.*<br>
?> <b>parent:</b> Netscape 4.0<br>
<b>platform:</b> Unknown<br>
El ejemplo anterior mostrará:
<b>majorver:</b> 4<br>
This is a $string with my <b>minorver:</b> 5<br>
$name in it. <b>browser:</b> Netscape<br>
This is a cup with my <b>version:</b> 4<br>
coffee in it. <b>frames:</b> 1<br>
<b>tables:</b> 1<br>
<b>cookies:</b> 1<br>
exit <b>backgroundsounds:</b> <br>
<b>vbscript:</b> <br>
<b>javascript:</b> 1<br>
(PHP 3, PHP 4 ) <b>javaapplets:</b> 1<br>
exit -- Finaliza el script actual <b>activexcontrols:</b> <br>
<b>beta:</b> <br>
<b>crawler:</b> <br>
Descripción
<b>authenticodeupdate:</b> <br>
<b>msn:</b> <br>
void exit ( void) Para conseguir ésto, su opción de fichero de
configuración browscap debe apuntar a la correcta
Esta construcción del lenguaje finaliza la ejecución del localización del fichero browscap.ini.
script. No devuelve nada. Para más información (incluyendo localizaciones desde
las que puede obtener un fichero browscap.ini), consulte
las FAQ sobre PHP en http://www.php.net/FAQ.php.
get_browser

Nota: el soporte para browscap fue


(PHP 3, PHP 4 ) añadido en la versión 3.0b2 de PHP.
get_browser -- Informa sobre lo que es capaz de hacer el
navegador (browser) del usuario.
highlight_file

Descripción
(PHP 4 )
highlight_file -- Syntax highlighting of a file
object get_browser ( [string user_agent])

Description
get_browser() intenta determinar las características del
navegador del usuario. Para ello consulta el fichero de
información del navegador, browscap.ini. Por defecto, se mixed highlight_file ( string filename [, bool return])
utiliza el valor de $HTTP_USER_AGENT; sin embargo,
puede alterar ésto (i.e., consultando otra información del
The highlight_file() function prints out a syntax
navegador) pasando el parámetro opcional user_agent a
higlighted version of the code contained in filename
get_browser().
using the colors defined in the built-in syntax highlighter
La información se devuelve en un objto, que contendrá
for PHP.
varios elementos de datos que representan, por ejemplo,
If the second parameter return is set to TRUE then
los números de versión (mayor y menor) del navegador y
highlight_file() will return the highlighted code as a
la cadena ID; valores TRUE/false para características
string instead of printing it out. If the second parameter
como los marcos, JavaScript, y cookies; etc.
is not set to TRUE then highlight_file() will return TRUE
browscap.ini contiene información de muchos
on success, FALSE on failure.
navegadores, depende de las actualizaciones del usuario
para mantener la base de datos actualizada. El formato
del fichero es claramente auto-explicativo. Nota: The return parameter became
El ejemplo siguiente muestra como se puede listar toda available in PHP 4.2.0. Before this
la información disponible recuperada del navegador del time it behaved like the default,
usuario. which is FALSE
Ejemplo 1. ejemplo get_browser()

Nota: Care should be taken when


<?php using the show_source() and
function list_array( $array ) { highlight_file() functions to make
while ( list( $key, $value ) = sure that you do not inadvertently
each( $array ) ) { reveal sensitive information such as
$str .= "<b>$key:</b> passwords or any other type of
$value<br>\n"; information that might create a
} potential security risk.
return $str;
} Nota: Since PHP 4.2.1 this function
echo "$HTTP_USER_AGENT<hr>\n"; is also affected by safe_mode and
$browser = get_browser(); open_basedir.
echo list_array( (array) $browser );
?>
La salida del script anterior debería paracerse a ésto:
Mozilla/4.5 [en] (X11; U; Linux 2.2.9
Ejemplo 1. Creating a source highlighting URL Nota: The return parameter became
available in PHP 4.2.0. Before this
time it behaved like the default,
To setup a URL that can code hightlight any script that which is FALSE
you pass to it, we will make use of the "ForceType"
directive in Apache to generate a nice URL pattern, and
use the function highlight_file() to show a nice looking See also highlight_file(), and show_source().
code list.

ignore_user_abort
In your httpd.conf you can add the following:

(PHP 3>= 3.0.7, PHP 4 )


ignore_user_abort -- Establece si la desconexión de un
<Location /source>
cliente debe suspender la ejecución del script
ForceType application/x-
httpd-php
</Location> Descripción

And then make a file named "source" and put it in your int ignore_user_abort ( [int setting])
web root directory.
Esta función establece si la desconexión de un cliente
debe provocar la suspensión del script. Devolverá el
<HTML> valor previo y puede ser llamada sin argumentos para
<HEAD> devolver el valor actual y no cambiarlo. Véase la sección
<TITLE>Source Display</TITLE> sobre la Gestión de la Conexión en el capítulo
</HEAD> Características para una descripción completa de la
<BODY BGCOLOR="white"> gestión de la conexión en PHP.
<?php
$script = getenv ("PATH_TRANSLATED");
if(!$script) { pack
echo "<BR><B>ERROR: Script Name
needed</B><BR>";
(PHP 3, PHP 4 )
} else {
pack -- empaqueta datos en una cadena binaria
if (ereg("(\.php|\.inc)$",$script)) {
echo "<H1>Source of:
$PATH_INFO</H1>\n<HR>\n"; Descripción
highlight_file($script);
} else {
echo "<H1>ERROR: Only PHP or include script string pack ( string format [, mixed args])
names are allowed</H1>";
} Empaqueta los argumentos dados en una cadena binaria
}
siguiendo el formato format. Devuelve la cadena binaria
echo "<HR>Processed: ".date("Y/M/d H:i:s",time()); que contiene los datos.
?>
El concepto de esta función fue tomado de Perl y todos
</BODY> los códigos de formateo realizan la misma función. La
</HTML>
cadena de formato consiste en códigos de formato
seguidos por un argumento opcional de repetición. El
argumento de repetición puede ser un valor entero o *
Then you can use an URL like the one below to display a para repetir hasta el fin de la entrada de datos. Para a, A,
colorized version of a script located in h, H la cuenta de repetición representa cuántos
"/path/to/script.php" in your web site. caracteres se toman de un argumento de datos, para @
es la posición absoluta donde poner los datos siguientes,
para todo lo demás la cuenta de repetición especifica
http://your.server.com/source/path cuántos argumentos de datos se toman y empaquetan
/to/script.php en la cadena binaria resultante. Actualmente están
See also highlight_string(), show_source(). implementados:

highlight_string • a cadena rellena de NUL


• A cadena rellena de ESPACIOS
(PHP 4 ) • h cadena Hex, primero el medio byte inferior
highlight_string -- Syntax highlighting of a string
• H cadena Hex, primero el medio byte superior

Description • c signed (con signo) char


• C unsigned (sin signo) char
mixed highlight_string ( string str [, bool return]) • s signed short (siempre 16 bits, distribución de
bytes de la máquina)
The highlight_string() function outputs a syntax • S unsigned short (siempre 16 bits, distribución
highlighted version of str using the colors defined in the de bytes de la máquina)
built-in syntax highlighter for PHP.
If the second parameter return is set to TRUE then
• n unsigned short (siempre 16 bits, distribución
de bytes gran endian)
highlight_string() will return the highlighted code as a
string instead of printing it out. If the second parameter • v unsigned short (siempre 16 bits, distribución
is not set to TRUE then highlight_string() will return de bytes pequeño endian)
TRUE on success, FALSE on failure.
uniqid
• i signed integer (distribución de bytes y
tamaños dependientes de la máquina)
• I unsigned integer (distribución de bytes y (PHP 3, PHP 4 )
tamaños dependientes de la máquina) uniqid -- Genera un id único.

• l signed long (siempre 32 bits, distribución de


bytes de la máquina) Descripción
• L unsigned long (siempre 32 bits, distribución
de bytes de la máquina) int uniqid ( string prefix [, boolean lcg])
• N unsigned long (siempre 32 bits, distribución
de bytes gran endian) uniqid() devuelve un identificador único con un prefijo
• V unsigned long (siempre 32 bits, distribución basado en la hora actual en microsegundos. El prefijo
puede ser práctico por ejemplo si se generan
de bytes pequeño endian)
identificadores simultáneamente en varios host que
• f float (representación y tamaño dependientes pueden haber generado el identificador en el mismo
de la máquina) microsegundo. prefix (prefijo) puede ser de hasta 114
• d double (representación y tamaño carácteres de longitud.
Si el parámetro opcional lcg es TRUE, uniqid() añadirá
dependientes de la máquina)
entropía "LCG combinada" al final del valor devuelto, que
• x byte NUL hará el resultado más único.
• X Un byte hacia atrás Con un prefix (prefijo) vacío, la cadena devuelta tendrá
una longitud de 13 carácteres. Si lcg es TRUE, tendrá 23
• @ relleno con NUL en la posición absoluta carácteres.

Ejemplo 1. cadena de formato para pack Nota: El parámetro lcg está


disponible sólo en PHP 4 y PHP
3.0.13 y posteriores.
$binarydata = pack("nvc*", 0x1234,
0x5678, 65, 66);
Si necesita un identificador único o testigo, y tiene la
intención de hacer público ese testigo al usuario por
medio de una red (i.e. cookies de sesión) se recomienda
La cadena binaria resultante tendrá 6 bytes de longitud y que utilice algo parecido a estas líneas
contendrá la secuencia de bytes 0x12, 0x34, 0x78, 0x56,
0x41, 0x42. $token = md5(uniqid("")); // no random
Adviértase que la distinción entre valores signed (con portion
signo) y unsigned (sin signo) sólo afecta a la función $better_token = md5(uniqid(rand())); //
unpack(), ya que la función pack() da el mismo better, difficult to guess
resultado para códigos de formato con signo y sin signo. Esto creará un identificador de 32 carácteres (un número
Nótese también que internamente PHP almacena valores hexadecimal de 128 bits) que es extremadamente difícil
enteros como valores con signo de un tamaño de predecir.
dependiente de la máquina. Si le da un valor entero sin
signo demasiado grande para ser almacenado, será
convertido a un double (doble), lo que a menudo produce unpack
resultados no deseados.

(PHP 3, PHP 4 )
show_source unpack -- desempaqueta datos de una cadena binaria

(PHP 4 ) Descripción
show_source -- Syntax highlighting of a file

array unpack ( string format, string data)


Description
Desempaqueta datos de una cadena binaria en un array,
bool show_source ( string filename [, bool return]) de acuerdo al formato format. Devuelve un array que
contiene los elementos de la cadena binaria
desempaquetados.
This function is an alias to highlight_file(). For more Unpack funciona de manera ligeramente diferente a Perl,
information see the documentation there. ya que los datos desempaquetados se almacenan en un
See also highlight_string() and highlight_file(). array asociativo. Para conseguir ésto debe nombrar los
diferentes códigos de formato y separarlos por una barra
sleep inclinada /.
Ejemplo 1. cadena de formato unpack

(PHP 3, PHP 4 )
sleep -- Ejecución retardada $array = unpack("c2chars/nint",
$binarydata);
Descripción
El array resultante contendrá las entradas "chars1",
void sleep ( int seconds) "chars2" y "int".
Para una explicación de los códigos de formato véase
también: pack()
La función sleep retarda la ejecución del programa Advierta que PHP almacena internamente los valores
durante el número de seconds (segundos) dado. enteros con signo. Si desempaqueta un unsigned long
Véase también usleep(). (largo sin signo) demasiado grande y es del mismo
tamaño tal como PHP almacena internamente los access MySQL. It is known that
valores, el resultado será un número negativo a pesar de mnoGoSearch is not compatible with
que se especificara desempaquetamiento sin signo. this built-in library and can work only
with generic MySQL libraries. Thus, if
you use mnoGoSearch with MySQL,
usleep during PHP configuration you have to
indicate the directory of your MySQL
installation, that was used during
(PHP 3, PHP 4 )
mnoGoSearch configuration, i.e. for
usleep -- Retrasa la ejecución, en microsegundos
example: --with-mnogosearch --with-
mysql=/usr.
Descripción

void usleep ( int micro_seconds)


Configuración en tiempo de ejecución

La función usleep retrasa la ejecución del programa


durante un número de micro_seconds (microsegundos) Esta extensión no define ninguna directiva de
dado. configuración.
Véase también sleep().

Tipos de recursos
LXI. mnoGoSearch Functions

Introducción
Constantes predefinidas
These functions allow you to access the mnoGoSearch
(former UdmSearch) free search engine. mnoGoSearch is Estas constantes están definidas por esta extensión y
a full-featured search engine software for intranet and estarán disponibles solamente cuando la extensión ha
internet servers, distributed under the GNU license. sido o bien compilada dentro de PHP o grabada
mnoGoSearch has a number of unique features, which dinamicamente en tiempo de ejecución.
makes it appropriate for a wide range of applications UDM_FIELD_URLID (integer)
from search within your site to a specialized search UDM_FIELD_URL (integer)
system such as cooking recipes or newspaper search, UDM_FIELD_CONTENT (integer)
FTP archive search, news articles search, etc. It offers UDM_FIELD_TITLE (integer)
full-text indexing and searching for HTML, PDF, and text UDM_FIELD_KEYWORDS (integer)
documents. mnoGoSearch consists of two parts. The first UDM_FIELD_DESC (integer)
is an indexing mechanism (indexer). The purpose of the UDM_FIELD_DESCRIPTION (integer)
indexer is to walk through HTTP, FTP, NEWS servers or UDM_FIELD_TEXT (integer)
local files, recursively grabbing all the documents and UDM_FIELD_SIZE (integer)
storing meta-data about that documents in a SQL UDM_FIELD_RATING (integer)
database in a smart and effective manner. After every UDM_FIELD_SCORE (integer)
document is referenced by its corresponding URL, meta- UDM_FIELD_MODIFIED (integer)
data is collected by the indexer for later use in a search UDM_FIELD_ORDER (integer)
process. The search is performed via Web interface. C, UDM_FIELD_CRC (integer)
CGI, PHP and Perl search front ends are included. UDM_FIELD_CATEGORY (integer)
More information about mnoGoSearch can be found at UDM_FIELD_LANG (integer)
http://www.mnogosearch.ru/. UDM_FIELD_CHARSET (integer)
UDM_PARAM_PAGE_SIZE (integer)
UDM_PARAM_PAGE_NUM (integer)
Nota: This extension is not available UDM_PARAM_SEARCH_MODE (integer)
on Windows platforms. UDM_PARAM_CACHE_MODE (integer)
UDM_PARAM_TRACK_MODE (integer)
UDM_PARAM_PHRASE_MODE (integer)
UDM_PARAM_CHARSET (integer)
Requerimientos UDM_PARAM_LOCAL_CHARSET (integer)
UDM_PARAM_BROWSER_CHARSET (integer)
UDM_PARAM_STOPTABLE (integer)
Download mnoGosearch from UDM_PARAM_STOP_TABLE (integer)
http://www.mnogosearch.ru/ and install it on your UDM_PARAM_STOPFILE (integer)
system. You need at least version 3.1.10 of UDM_PARAM_STOP_FILE (integer)
mnoGoSearch installed to use these functions. UDM_PARAM_WEIGHT_FACTOR (integer)
UDM_PARAM_WORD_MATCH (integer)
UDM_PARAM_MAX_WORD_LEN (integer)
Instalación UDM_PARAM_MAX_WORDLEN (integer)
UDM_PARAM_MIN_WORD_LEN (integer)
UDM_PARAM_MIN_WORDLEN (integer)
In order to have these functions available, you must UDM_PARAM_ISPELL_PREFIXES (integer)
compile PHP with mnoGosearch support by using the UDM_PARAM_ISPELL_PREFIX (integer)
--with-mnogosearchoption. If you use this option without UDM_PARAM_PREFIXES (integer)
specifying the path to mnoGosearch, PHP will look for UDM_PARAM_PREFIX (integer)
mnoGosearch under /usr/local/mnogosearch path by UDM_PARAM_CROSS_WORDS (integer)
default. If you installed mnoGosearch at a different UDM_PARAM_CROSSWORDS (integer)
location you should specify it: --with-mnogosearch=DIR. UDM_PARAM_VARDIR (integer)
UDM_PARAM_DATADIR (integer)
Nota: PHP contains built-in MySQL UDM_PARAM_HLBEG (integer)
access library, which can be used to UDM_PARAM_HLEND (integer)
UDM_PARAM_SYNONYM (integer)
UDM_PARAM_SEARCHD (integer) (PHP 4 >= 4.0.5)
UDM_PARAM_QSTRING (integer) udm_add_search_limit -- Add various search limits
UDM_PARAM_REMOTE_ADDR (integer)
UDM_LIMIT_CAT (integer)
UDM_LIMIT_URL (integer) Description
UDM_LIMIT_TAG (integer)
UDM_LIMIT_LANG (integer) int udm_add_search_limit ( int agent, int var, string
UDM_LIMIT_DATE (integer)
val)
UDM_PARAM_FOUND (integer)
UDM_PARAM_NUM_ROWS (integer)
UDM_PARAM_WORDINFO (integer) udm_add_search_limit() returns TRUE on success,
UDM_PARAM_WORD_INFO (integer) FALSE on error. Adds search restrictions.
UDM_PARAM_SEARCHTIME (integer) agent - a link to Agent, received after call to
UDM_PARAM_SEARCH_TIME (integer) udm_alloc_agent().
UDM_PARAM_FIRST_DOC (integer) var - defines parameter, indicating limit.
UDM_PARAM_LAST_DOC (integer) val - defines value of the current parameter.
UDM_MODE_ALL (integer) Possible var values:
UDM_MODE_ANY (integer)
UDM_MODE_BOOL (integer)
UDM_MODE_PHRASE (integer) • UDM_LIMIT_URL - defines document URL
UDM_CACHE_ENABLED (integer) limitations to limit search through subsection
UDM_CACHE_DISABLED (integer) of database. It supports SQL % and _ LIKE
UDM_TRACK_ENABLED (integer) wildcards, where % matches any number of
UDM_TRACK_DISABLED (integer) characters, even zero characters, and _
UDM_PHRASE_ENABLED (integer) matches exactly one character. E.g.
UDM_PHRASE_DISABLED (integer) http://my.domain.__/catalog may stand for
UDM_CROSS_WORDS_ENABLED (integer) http://my.domain.ru/catalog and
UDM_CROSSWORDS_ENABLED (integer) http://my.domain.ua/catalog.
UDM_CROSS_WORDS_DISABLED (integer)
UDM_CROSSWORDS_DISABLED (integer) • UDM_LIMIT_TAG - defines site TAG limitations.
UDM_PREFIXES_ENABLED (integer) In indexer-conf you can assign specific TAGs to
UDM_PREFIX_ENABLED (integer) various sites and parts of a site. Tags in
UDM_ISPELL_PREFIXES_ENABLED (integer) mnoGoSearch 3.1.x are lines, that may contain
UDM_ISPELL_PREFIX_ENABLED (integer) metasymbols % and _. Metasymbols allow
UDM_PREFIXES_DISABLED (integer) searching among groups of tags. E.g. there are
UDM_PREFIX_DISABLED (integer) links with tags ABCD and ABCE, and search
UDM_ISPELL_PREFIXES_DISABLED (integer) restriction is by ABC_ - the search will be made
UDM_ISPELL_PREFIX_DISABLED (integer) among both of the tags.
UDM_ISPELL_TYPE_AFFIX (integer) • UDM_LIMIT_LANG - defines document language
UDM_ISPELL_TYPE_SPELL (integer) limitations.
UDM_ISPELL_TYPE_DB (integer)
UDM_ISPELL_TYPE_SERVER (integer) • UDM_LIMIT_CAT - defines document category
UDM_MATCH_WORD (integer) limitations. Categories are similar to tag
UDM_MATCH_BEGIN (integer) feature, but nested. So you can have one
UDM_MATCH_SUBSTR (integer) category inside another and so on. You have to
UDM_MATCH_END (integer) use two characters for each level. Use a hex
Tabla de contenidos number going from 0-F or a 36 base number
udm_add_search_limit -- Add various search limits going from 0-Z. Therefore a top-level category
udm_alloc_agent -- Allocate mnoGoSearch session like 'Auto' would be 01. If it has a subcategory
udm_api_version -- Get mnoGoSearch API version. like 'Ford', then it would be 01 (the parent
udm_cat_list -- Get all the categories on the same level category) and then 'Ford' which we will give
with the current one. 01. Put those together and you get 0101. If
udm_cat_path -- Get the path to the current category. 'Auto' had another subcategory named 'VW',
udm_check_charset -- Check if the given charset is then it's id would be 01 because it belongs to
known to mnogosearch the 'Ford' category and then 02 because it's
udm_check_stored -- Check connection to stored the next category. So it's id would be 0102. If
udm_clear_search_limits -- Clear all mnoGoSearch search VW had a sub category called 'Engine' then it's
restrictions id would start at 01 again and it would get the
udm_close_stored -- Close connection to stored 'VW' id 02 and 'Auto' id of 01, making it
udm_crc32 -- Return CRC32 checksum of gived string 010201. If you want to search for sites under
udm_errno -- Get mnoGoSearch error number that category then you pass it cat=010201 in
udm_error -- Get mnoGoSearch error message the url.
udm_find -- Perform search • UDM_LIMIT_DATE - defines limitation by date
udm_free_agent -- Free mnoGoSearch session document was modified.
udm_free_ispell_data -- Free memory allocated for ispell
data
udm_free_res -- Free mnoGoSearch result Format of parameter value: a string with first
udm_get_doc_count -- Get total number of documents in character < or >, then with no space - date in
database. unixtime format, for example:
udm_get_res_field -- Fetch mnoGoSearch result field
udm_get_res_param -- Get mnoGoSearch result
parameters Udm_Add_Search_Limit($udm,UDM_LIMIT_DAT
udm_load_ispell_data -- Load ispell data E,"<908012006");
udm_open_stored -- Open connection to stored
udm_set_agent_param -- Set mnoGoSearch agent session If > character is used, then search will be
parameters restricted to those documents having
modification date greater than entered. If <,
udm_add_search_limit then smaller.
udm_alloc_agent udm_cat_list -- Get all the categories on the same level
with the current one.

(PHP 4 >= 4.0.5)


udm_alloc_agent -- Allocate mnoGoSearch session Description

Description array udm_cat_list ( int agent, string category)

int udm_alloc_agent ( string dbaddr [, string dbmode]) udm_cat_list() returns array listing all categories of the
same level as current category in the categories tree.
The function can be useful for developing categories tree
udm_alloc_agent() returns mnogosearch agent browser.
identifier on success, FALSE on error. This function Returns array with the following format:
creates a session with database parameters. The array consists of pairs. Elements with even index
dbaddr - URL-style database description. Options (type, numbers contain category paths, odd elements contain
host, database name, port, user and password) to corresponding category names.
connect to SQL database. Do not matter for built-in text
files support. Format: DBAddr DBType:[//
[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/ $array[0] will contain '020300'
Currently supported DBType values are: mysql, pgsql, $array[1] will contain 'Audi'
msql, solid, mssql, oracle, ibase. Actually, it does not $array[2] will contain '020301'
matter for native libraries support. But ODBC users $array[3] will contain 'BMW'
should specify one of supported values. If your database $array[4] will contain '020302'
type is not supported, you may use "unknown" instead. $array[5] will contain 'Opel'
dbmode - You may select SQL database mode of words ...
storage. When "single" is specified, all words are stored etc.
in the same table. If "multi" is selected, words will be
located in different tables depending of their lengths.
"multi" mode is usually faster but requires more tables in
database. If "crc" mode is selected, mnoGoSearch will Following is an example of displaying links of the current
store 32 bit integer word IDs calculated by CRC32 level in format:
algorythm instead of words. This mode requres less disk Audi
space and it is faster comparing with "single" and "multi" BMW
modes. "crc-multi" uses the same storage structure with Opel
the "crc" mode, but also stores words in different tables ...
depending on words lengths like "multi" mode. Format:
DBMode single/multi/crc/crc-multi
<?php
$cat_list_arr = udm_cat_list($udm_agent,$cat);
Nota: dbaddr and dbmode must $cat_list = '';
match those used during indexing. for ($i=0; $i<count($cat_list_arr); $i+=2) {
$path = $cat_list_arr[$i];
$name = $cat_list_arr[$i+1];
Nota: In fact this function does not $cat_list .= "<a href=\"$PHP_SELF?
open connection to database and cat=$path\">$name</a><br>";
thus does not check entered login }
and password. Actual connection to ?>
database and login/password
verification is done by udm_find().
udm_cat_path
udm_api_version
(PHP 4 >= 4.0.6)
(PHP 4 >= 4.0.5) udm_cat_path -- Get the path to the current category.
udm_api_version -- Get mnoGoSearch API version.
Description
Description
array udm_cat_path ( int agent, string category)
int udm_api_version ( void)
udm_cat_path() returns array describing path in the
udm_api_version() returns mnoGoSearch API version categories tree from the tree root to the current
number. E.g. if mnoGoSearch 3.1.10 API is used, this category.
function will return 30110. agent - agent link identifier.
This function allows user to identify which API functions category - current category - the one to get path to.
are available, e.g. udm_get_doc_count() function is Returns array with the following format:
only available in mnoGoSearch 3.1.11 or later. The array consists of pairs. Elements with even index
Example: numbers contain category paths, odd elements contain
corresponding category names.
if (udm_api_version() >= 30111) { For example, the call $array=udm_cat_path($agent,
print "Total number of urls in database: '02031D'); may return the following array:
".udm_get_doc_count($udm)."<br>\n";
}
$array[0] will contain ''
$array[1] will contain 'Root'
udm_cat_list $array[2] will contain '02'
$array[3] will contain 'Sport'
$array[4] will contain '0203'
(PHP 4 >= 4.0.6)
$array[5] will contain 'Auto' udm_close_stored -- Close connection to stored
$array[4] will contain '02031D'
$array[5] will contain 'Ferrari'
Description

Ejemplo 1. Specifying path to the current category


int udm_close_stored ( int agent, int link)
in the following format: '> Root > Sport > Auto >
Ferrari'
Aviso

<?php Esta función no está documentada actualmente, solamente


$cat_path_arr = udm_cat_path($udm_agent, se encuentra disponible la lista de parametros.
$cat);
$cat_path = '';
for ($i=0; $i<count($cat_path_arr); $i+=2) { udm_crc32
$path = $cat_path_arr[$i];
$name = $cat_path_arr[$i+1];
(PHP 4 >= 4.2.0)
$cat_path .= " > <a href=\"$PHP_SELF?
udm_crc32 -- Return CRC32 checksum of gived string
cat=$path\">$name</a> ";
}
?> Description

udm_check_charset int udm_crc32 ( int agent, string str)

(PHP 4 >= 4.2.0) Aviso


udm_check_charset -- Check if the given charset is Esta función no está documentada actualmente, solamente
known to mnogosearch se encuentra disponible la lista de parametros.

Description
udm_errno

int udm_check_charset ( int agent, string charset)


(PHP 4 >= 4.0.5)
udm_errno -- Get mnoGoSearch error number
Aviso
Esta función no está documentada actualmente, solamente Description
se encuentra disponible la lista de parametros.

int udm_errno ( int agent)


udm_check_stored
udm_errno() returns mnoGoSearch error number, zero if
no error.
(PHP 4 >= 4.2.0)
agent - link to agent identifier, received after call to
udm_check_stored -- Check connection to stored
udm_alloc_agent().
Receiving numeric agent error code.
Description
udm_error
int udm_check_stored ( int agent, int link, string doc_id)
(PHP 4 >= 4.0.5)
Aviso udm_error -- Get mnoGoSearch error message

Esta función no está documentada actualmente, solamente


se encuentra disponible la lista de parametros. Description

string udm_error ( int agent)


udm_clear_search_limits

udm_error() returns mnoGoSearch error message,


(PHP 4 >= 4.0.5) empty string if no error.
udm_clear_search_limits -- Clear all mnoGoSearch search agent - link to agent identifier, received after call to
restrictions udm_alloc_agent().
Receiving agent error message.
Description
udm_find
int udm_clear_search_limits ( int agent)
(PHP 4 >= 4.0.5)
udm_clear_search_limits() resets defined search udm_find -- Perform search
limitations and returns TRUE.
Description
udm_close_stored
int udm_find ( int agent, string query)
(PHP 4 >= 4.2.0)
udm_find() returns result link identifier on success, (PHP 4 >= 4.0.5)
FALSE on error. udm_free_res -- Free mnoGoSearch result
The search itself. The first argument - session, the next
one - query itself. To find something just type words you
want to find and press SUBMIT button. For example, Description
"mysql odbc". You should not use quotes " in query, they
are written here only to divide a query from other text. int udm_free_res ( int res)
mnoGoSearch will find all documents that contain word
"mysql" and/or word "odbc". Best documents having
bigger weights will be displayed first. If you use search udm_free_res() returns TRUE on success, FALSE on
mode ALL, search will return documents that contain error.
both (or more) words you entered. In case you use mode res - a link to result identifier, received after call to
ANY, the search will return list of documents that contain udm_find().
any of the words you entered. If you want more Freeing up memory allocated for results.
advanced results you may use query language. You
should select "bool" match mode in the search from.
mnoGoSearch understands the following boolean udm_get_doc_count
operators:
& - logical AND. For example, "mysql & odbc". (PHP 4 >= 4.0.5)
mnoGoSearch will find any URLs that contain both udm_get_doc_count -- Get total number of documents in
"mysql" and "odbc". database.
| - logical OR. For example "mysql|odbc". mnoGoSearch
will find any URLs, that contain word "mysql" or word
"odbc". Description
~ - logical NOT. For example "mysql & ~odbc".
mnoGoSearch will find URLs that contain word "mysql"
and do not contain word "odbc" at the same time. Note int udm_get_doc_count ( int agent)
that ~ just excludes given word from results. Query
"~odbc" will find nothing! udm_get_doc_count() returns number of documents in
() - group command to compose more complex queries. database.
For example "(mysql | msql) & ~postgres". Query agent - link to agent identifier, received after call to
language is simple and powerful at the same time. Just udm_alloc_agent().
consider query as usual boolean expression.

Nota: This function is supported


udm_free_agent only in mnoGoSearch 3.1.11 or later.

(PHP 4 >= 4.0.5) udm_get_res_field


udm_free_agent -- Free mnoGoSearch session

(PHP 4 >= 4.0.5)


Description udm_get_res_field -- Fetch mnoGoSearch result field

int udm_free_agent ( int agent) Description

udm_free_agent() returns TRUE on success, FALSE on


string udm_get_res_field ( int res, int row, int field)
error.
agent - link to agent identifier, received ` after call to
udm_alloc_agent(). udm_get_res_field() returns result field value on
Freeing up memory allocated for agent session. success, FALSE on error.
res - a link to result identifier, received after call to
udm_find().
udm_free_ispell_data row - the number of the link on the current page. May
have values from 0 to UDM_PARAM_NUM_ROWS-1.
field - field identifier, may have the following values:
(PHP 4 >= 4.0.5)
udm_free_ispell_data -- Free memory allocated for ispell
data
• UDM_FIELD_URL - document URL field

Description
• UDM_FIELD_CONTENT - document Content-
type field (for example, text/html).
• UDM_FIELD_CATEGORY - document category
int udm_free_ispell_data ( int agent) field. Use udm_cat_path() to get full path to
current category from the categories tree root.
udm_free_ispell_data() always returns TRUE. (This parameter is available only in PHP 4.0.6
agent - agent link identifier, received after call to or later).
udm_alloc_agent(). • UDM_FIELD_TITLE - document title field.
• UDM_FIELD_KEYWORDS - document keywords
Nota: This function is supported field (from META KEYWORDS tag).
beginning from version 3.1.12 of
mnoGoSearch and it does not do • UDM_FIELD_DESC - document description field
anything in previous versions. (from META DESCRIPTION tag).
• UDM_FIELD_TEXT - document body text (the
first couple of lines to give an idea of what the
udm_free_res
document is about).
• UDM_FIELD_SIZE - document size.
speed up DB mode in future versions and it is going to be
• UDM_FIELD_URLID - unique URL ID of the link.
faster than TEXT mode.
• UDM_FIELD_RATING - page rating (as
calculated by mnoGoSearch).
• UDM_FIELD_MODIFIED - last-modified field in • UDM_ISPELL_TYPE_DB - indicates that ispell
unixtime format. data should be loaded from SQL. In this case,
parameters val1 and val2 are ignored and
• UDM_FIELD_ORDER - the number of the current should be left blank. flag should be equal to 1.
document in set of found documents.
• UDM_FIELD_CRC - document CRC.
Nota: flag indicates that
after loading ispell data
udm_get_res_param from defined source it
sould be sorted (it is
necessary for correct
(PHP 4 >= 4.0.5) functioning of ispell). In
udm_get_res_param -- Get mnoGoSearch result case of loading ispell data
parameters from files there may be
several calls to
udm_load_ispell_data(),
Description and there is no sense to
sort data after every call,
but only after the last one.
string udm_get_res_param ( int res, int param)
Since in db mode all the
data is loaded by one call,
udm_get_res_param() returns result parameter value this parameter should
on success, FALSE on error. have the value 1. In this
res - a link to result identifier, received after call to mode in case of error, e.g.
udm_find(). if ispell tables are absent,
param - parameter identifier, may have the following the function will return
values: FALSE and code and error
message will be accessible
through udm_error() and
• UDM_PARAM_NUM_ROWS - number of received udm_errno().
found links on the current page. It is equal to
UDM_PARAM_PAGE_SIZE for all search pages,
Example:
on the last page - the rest of links.
if (!
• UDM_PARAM_FOUND - total number of results
udm_load_ispell_data($udm,UDM_ISPELL_TYPE_
matching the query.
DB,'','',1)) {
• UDM_PARAM_WORDINFO - information on the printf("Error #%d: '%s'\n", udm_errno($udm),
words found. E.g. search for "a good book" will udm_error($udm));
return "a: stopword, good:5637, book: 120" exit;
}
• UDM_PARAM_SEARCHTIME - search time in
seconds.
• UDM_PARAM_FIRST_DOC - the number of the
first document displayed on current page. • UDM_ISPELL_TYPE_AFFIX - indicates that ispell
data should be loaded from file and initiates
• UDM_PARAM_LAST_DOC - the number of the loading affixes file. In this case val1 defines
last document displayed on current page. double letter language code for which affixes
are loaded, and val2 - file path. Please note,
that if a relative path entered, the module
udm_load_ispell_data looks for the file not in UDM_CONF_DIR, but in
relation to current path, i.e. to the path where
(PHP 4 >= 4.0.5) the script is executed. In case of error in this
udm_load_ispell_data -- Load ispell data mode, e.g. if file is absent, the function will
return FALSE, and an error message will be
displayed. Error message text cannot be
Description accessed through udm_error() and
udm_errno(), since those functions can only
return messages associated with SQL. Please,
int udm_load_ispell_data ( int agent, int var, string see flag parameter description in
val1, string val2, int flag) UDM_ISPELL_TYPE_DB.

udm_load_ispell_data() loads ispell data. Returns


Example:
TRUE on success, FALSE on error.
agent - agent link identifier, received after call to
udm_alloc_agent().
var - parameter, indicating the source for ispell data. May if ((!
have the following values: udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/op
After using this function to free memory allocated for t/ispell/en.aff',0)) ||
ispell data, please use udm_free_ispell_data(), even if (!
you use UDM_ISPELL_TYPE_SERVER mode. udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt
The fastest mode is UDM_ISPELL_TYPE_SERVER. /ispell/ru.aff',0)) ||
UDM_ISPELL_TYPE_TEXT is slower and (!
UDM_ISPELL_TYPE_DB is the slowest. The above pattern udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'en','/op
is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to t/ispell/en.dict',0)) ||
(!
search. In case of errors, e.g. if spellserver is
udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/op
not running or invalid host indicated, there are
t/ispell/ru.dict',1))) {
no messages returned and ispell conversion
exit;
does not work.
}

Nota: This function is


Nota: flag is equal to 1 available in mnoGoSearch
only in the last call. 3.1.12 or later.

• UDM_ISPELL_TYPE_SPELL - indicates that ispell Example:


data should be loaded from file and initiates if (!
loading of ispell dictionary file. In this case val1 udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SE
defines double letter language code for which RVER,'','',1)) {
affixes are loaded, and val2 - file path. Please printf("Error loading ispell data from
note, that if a relative path entered, the server<br>\n");
module looks for the file not in exit;
UDM_CONF_DIR, but in relation to current path, }
i.e. to the path where the script is executed. In
case of error in this mode, e.g. if file is absent,
the function will return FALSE, and an error udm_open_stored
message will be displayed. Error message text
cannot be accessed through udm_error() and
udm_errno(), since those functions can only (PHP 4 >= 4.2.0)
return messages associated with SQL. Please, udm_open_stored -- Open connection to stored
see flag parameter description in
UDM_ISPELL_TYPE_DB.
Description

if ((! int udm_open_stored ( int agent, string storedaddr)


Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/op
t/ispell/en.aff',0)) ||
(! Aviso
Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt
Esta función no está documentada actualmente, solamente
/ispell/ru.aff',0)) ||
se encuentra disponible la lista de parametros.
(!
Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'en','/op
t/ispell/en.dict',0)) ||
(! udm_set_agent_param
Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/op
t/ispell/ru.dict',1))) { (PHP 4 >= 4.0.5)
exit; udm_set_agent_param -- Set mnoGoSearch agent session
} parameters

Description
• Nota: flag is
equal to 1 only in the last
call. int udm_set_agent_param ( int agent, int var, string
• UDM_ISPELL_TYPE_SERVER - enables spell val)
server support. val1 parameter indicates
address of the host running spell server. val2 ` udm_set_agent_param() returns TRUE on success,
is not used yet, but in future releases it is FALSE on error. Defines mnoGoSearch session
going to indicate number of port used by spell parameters.
server. flag parameter in this case is not The following parameters and their values are available:
needed since ispell data is stored on
spellserver already sorted.
• UDM_PARAM_PAGE_NUM - used to choose
Spelld server reads spell-data from a separate search results page number (results are
configuration file returned by pages beginning from 0, with
(/usr/local/mnogosearch/etc/spelld.conf by UDM_PARAM_PAGE_SIZE results per page).
default), sorts it and stores in memory. With • UDM_PARAM_PAGE_SIZE - number of search
clients server communicates in two ways: to results displayed on one page.
indexer all the data is transferred (so that
indexer starts faster), from search.cgi server • UDM_PARAM_SEARCH_MODE - search mode.
receives word to normalize and then passes The following values available:
over to client (search.cgi) list of normalized UDM_MODE_ALL - search for all words;
word forms. This allows fastest, compared to UDM_MODE_ANY - search for any word;
db and text modes processing of search UDM_MODE_PHRASE - phrase search;
queries (by omitting loading and sorting all the UDM_MODE_BOOL - boolean search. See
spell data). udm_find() for details on boolean search.
• UDM_PARAM_CACHE_MODE - turns on or off
search result cache mode. When enabled, the
udm_load_ispell_data() function in
search engine will store search results to disk.
UDM_ISPELL_TYPE_SERVER mode does not
In case a similar search is performed later, the
actually load ispell data, but only defines
engine will take results from the cache for
server address. In fact, server is automatically
faster performance. Available values:
used by udm_find() function when performing
UDM_CACHE_ENABLED, which appears only in the body will have
UDM_CACHE_DISABLED. 00000010 argegate weight (in binary
notation). Word used in all document parts will
• UDM_PARAM_TRACK_MODE - turns on or off
have 00011111 aggregate weight.
trackquery mode. Since version 3.1.2
mnoGoSearch has a query tracking support.
Note that tracking is implemented in SQL This parameter's value is a string of hex digits
version only and not available in built-in ABCDE. Each digit is a factor for corresponding
database. To use tracking, you have to create bit in word weight. For the given above weights
tables for tracking support. For MySQL, use configuration:
create/mysql/track.txt. When doing a search,
front-end uses those tables to store query
words, a number of found documents and
current UNIX timestamp in seconds. Available E is a factor for weight 1 (URL Weight bit)
values: UDM_TRACK_ENABLED, D is a factor for weight 2 (BodyWeight bit)
UDM_TRACK_DISABLED. C is a factor for weight 4 (TitleWeight bit)
B is a factor for weight 8 (KeywordWeight bit
• UDM_PARAM_PHRASE_MODE - defines whether
)
index database using phrases ("phrase" A is a factor for weight 16 (DescWeight bit)
parameter in indexer.conf). Possible values:
UDM_PHRASE_ENABLED and
UDM_PHRASE_DISABLED. Please note, that if
phrase search is enabled Examples:
(UDM_PHRASE_ENABLED), it is still possible to
do search in any mode (ANY, ALL, BOOL or
PHRASE). In 3.1.10 version of mnoGoSearch UDM_PARAM_WEIGHT_FACTOR=00001 will
phrase search is supported only in sql and search through URLs only.
built-in database modes, while beginning with
3.1.11 phrases are supported in cachemode as
UDM_PARAM_WEIGHT_FACTOR=00100 will
well.
search through Titles only.

Examples of phrase search:


UDM_PARAM_WEIGHT_FACTOR=11100 will
search through Title,Keywords,Description but
"Arizona desert" - This query returns all not through URL and Body.
indexed documents that contain "Arizona
desert" as a phrase. Notice that you need to
UDM_PARAM_WEIGHT_FACTOR=F9421 will
put double quotes around the phrase
search through:

• UDM_PARAM_CHARSET - defines local charset.


Available values: set of charsets supported by Description with factor 15 (F hex)
mnoGoSearch, e.g. koi8-r, cp1251, ... Keywords with factor 9
• UDM_PARAM_STOPFILE - Defines name and Title with factor 4
Body with factor 2
path to stopwords file. (There is a small
URL with factor 1
difference with mnoGoSearch - while in
mnoGoSearch if relative path or no path
entered, it looks for this file in relation to
UDM_CONF_DIR, the module looks for the file If UDM_PARAM_WEIGHT_FACTOR variable is
in relation to current path, i.e. to the path ommited, original weight value is taken to sort
where the php script is executed.) results. For a given above weight configuration
• UDM_PARAM_STOPTABLE - Load stop words it means that document description has a most
from the given SQL table. You may use several big weight 16.
StopwordTable commands. This command has
no effect when compiled without SQL database
support. • UDM_PARAM_WORD_MATCH - word match. You
may use this parameter to choose word match
• UDM_PARAM_WEIGHT_FACTOR - represents
type. This feature works only in "single" and
weight factors for specific document parts.
"multi" modes using SQL based and built-in
Currently body, title, keywords, description, url
database. It does not work in cachemode and
are supported. To activate this feature please
other modes since they use word CRC and do
use degrees of 2 in *Weight commands of the
not support substring search. Available values:
indexer.conf. Let's imagine that we have these
weights:
UDM_MATCH_BEGIN - word beginning match;

URLWeight 1 UDM_MATCH_END - word ending match;


BodyWeight 2
TitleWeight 4
KeywordWeight 8 UDM_MATCH_WORD - whole word match;
DescWeight 16
UDM_MATCH_SUBSTR - word substring match.

As far as indexer uses bit OR operation for


word weights when some word presents • UDM_PARAM_MIN_WORD_LEN - defines
several time in the same document, it is minimal word length. Any word shorter this
possible at search time to detect word limit is considered to be a stopword. Please
appearance in different document parts. Word note that this parameter value is inclusive, i.e.
if UDM_PARAM_MIN_WORD_LEN=3, a word 3 msql_fieldflags -- obtiene los flags del campo
characters long will not be considered a msql_fieldlen -- obtiene la longitud del campo
stopword, while a word 2 characters long will msql_fieldname -- obtiene el nombre del campo
be. Default value is 1. msql_fieldtable -- obtiene el nombre de la tabla de un
campo
• UDM_PARAM_ISPELL_PREFIXES - Possible
msql_fieldtype -- obtiene el tipo del campo
values: UDM_PREFIXES_ENABLED and
msql_free_result -- libera la memoria del resultado
UDM_PREFIXES_DISABLED, that respectively
msql_freeresult -- libera la memoria del resultado
enable or disable using prefixes. E.g. if a word
msql_list_dbs -- lista las bases de datos mSQL en el
"tested" is in search query, also words like
servidor
"test", "testing", etc. Only suffixes are
msql_list_fields -- lista los campos del resultado
supported by default. Prefixes usually change
msql_list_tables -- lista las tablas de una base de datos
word meanings, for example if somebody is
mSQL
searching for the word "tested" one hardly
msql_listdbs -- lista las bases de datos mSQL en el
wants "untested" to be found. Prefixes support
servidor
may also be found useful for site's spelling
msql_listfields -- lista los campos del resultado
checking purposes. In order to enable ispell,
msql_listtables -- lista las tablas de una base de datos
you have to load ispell data with
mSQL
udm_load_ispell_data().
msql_num_fields -- obtiene el número de campos de un
• UDM_PARAM_CROSS_WORDS - enables or resultado
disables crosswords support. Possible values: msql_num_rows -- obtiene el número de filas de un
UDM_CROSS_WORDS_ENABLED and resultado
UDM_CROSS_WORDS_DISABLED. msql_numfields -- obtiene el número de campos de un
resultado
msql_numrows -- obtiene el número de filas en el
The corsswords feature allows to assign words resultado
between <a href="xxx"> and </a> also to a msql_pconnect -- abre una conexión mSQL persistente
document this link leads to. It works in SQL msql_query -- envía una consulta mSQL
database mode and is not supported in built-in msql_regcase -- construye una expresión regular para
database and Cachemode. una búsqueda que no distinga mayúsculas/minúsculas
msql_result -- obtiene datos resultado
msql_select_db -- selecciona una base de datos mSQL
Nota: Crosswords are
msql_selectdb -- selecciona una base de datos mSQL
supported only in
msql_tablename -- obtiene el nombre de la tabla de un
mnoGoSearch 3.1.11 or
campo
later.
msql -- ejecuta una consulta mSQL

• UDM_PARAM_VARDIR - specifies a custom path msql_affected_rows


to directory where indexer stores data when
using built-in database and in cache mode. By
default /var directory of mnoGoSearch (PHP 3>= 3.0.6, PHP 4 )
installation is used. Can have only string msql_affected_rows -- devuelve el número de filas
values. The parameter is available in PHP 4.1.0 involucradas
or later.
• UDM_PARAM_VARDIR - specifies a custom path Descripción
to directory where indexer stores data when
using built-in database and in cache mode. By
default /var directory of mnoGoSearch int msql_affected_rows ( int query_identifier)
installation is used. Can have only string
values. The parameter is available in PHP 4.1.0 Devuelve el número de filas involucradas ("tocadas") por
or later. una consulta específica (i.e. el número de filas devueltas
por una SELECT, el número de filas modificadas por una
actualización (update), o el número de filas suprimidas
LXII. funciones mSQL
por una eliminación (delete)).
Véase también: msql_query()
Tabla de contenidos
msql_affected_rows -- devuelve el número de filas
msql_close
involucradas
msql_close -- cierra una conexión mSQL
msql_connect -- abre una conexión mSQL (PHP 3, PHP 4 )
msql_create_db -- crea una base de datos mSQL msql_close -- cierra una conexión mSQL
msql_createdb -- crea una base de datos mSQL
msql_data_seek -- desplaza el puntero interno de fila
msql_dbname -- obtiene el nombre de la base de datos Descripción
mSQL actual
msql_drop_db -- elimina (suprime) una base de datos
mSQL int msql_close ( int link_identifier)
msql_dropdb -- elimina (suprime) una base de datos
mSQL Devuelve TRUE si tiene éxito, FALSE en caso de error.
msql_error -- devuelve el mensaje de error de la última msql_close() cierra la conexión con una base de datos
llamada msql mSQL que está asociada con el identificador de conexión
msql_fetch_array -- recupera una fila como un array (link identifier) especificado. Si no se especifica el
msql_fetch_field -- obtiene información de campo identificador de conexión, se asume la última conexión
msql_fetch_object -- recupera una fila como un objeto abierta.
msql_fetch_row -- obtiene una fila como un array Advierta que ésto no es necesario habitualmente, las
enumerado conexiones abiertas no-persistentes son cerradas
msql_field_seek -- establece el desplazamiento del automáticamente a la conclusión de la ejecución del
campo script.
msql_close() no cerrará las conexiones permanentes msql_data_seek() desplaza el puntero interno de fila del
creadas por msql_pconnect(). resultado mSQL asociado con el identificador de consulta
Véase también: msql_connect() y msql_pconnect(). (query identifier) especificado para que apunte al
número de fila (row number) proporcionado. La llamada
posterior a msql_fetch_row() devolverá esa fila.
msql_connect Véase también: msql_fetch_row().

(PHP 3, PHP 4 ) msql_dbname


msql_connect -- abre una conexión mSQL

(PHP 3, PHP 4 )
Descripción msql_dbname -- obtiene el nombre de la base de datos
mSQL actual
int msql_connect ( string hostname)
Descripción
Devuelve un identificador de conexión mSQL positivo si
tiene éxito, o FALSE en caso de error.
string msql_dbname ( int query_identifier, int i)
msql_connect() establece una conexión con un servidor
mSQL. El argumento hostname es opcional, y en caso de
que falte, se asume localhost. msql_dbname() devuelve el nombre de base de datos
En caso de que se haga una segunda llamada a almacenado en la posición i del puntero devuelto desde
msql_connect() con los mismos argumentos, no se la función msql_listdbs(). La función msql_numrows()
establece una nueva conexión, en lugar de eso, se puede utilizarse para determinar cuantos nombres de
devuelve el identificador de conexión ya abierto. base de datos hay disponibles.
La conexión con el servidor se cerrará tan pronto como la
ejecución del script finalice, a menos que sea cerrada
antes explícitamente por una llamada a msql_close(). msql_drop_db
Véase también: msql_pconnect(), msql_close().
(PHP 3, PHP 4 )
msql_create_db msql_drop_db -- elimina (suprime) una base de datos
mSQL

(PHP 3, PHP 4 )
msql_create_db -- crea una base de datos mSQL Descripción

Descripción int msql_drop_db ( string database_name, int


link_identifier)

int msql_create_db ( string database name [, int


Devuelve TRUE si tiene éxito, FALSE en caso de fallo.
link_identifier])
msql_drop_db() intenta eliminar (suprimir) una base de
datos completa del servidor asociado con el identificador
msql_create_db() intenta crear una base de datos nueva de conexión (link identifier) especificado.
en el servidor asociado con el identificador de conexión Véase también: msql_create_db().
(link identifier) especificado.
Véase también: msql_drop_db().
msql_dropdb

msql_createdb
msql_dropdb -- elimina (suprime) una base de datos
mSQL
(PHP 3, PHP 4 )
msql_createdb -- crea una base de datos mSQL
Descripción

Descripción
Véase msql_drop_db().

int msql_createdb ( string database name [, int


link_identifier]) msql_error

Idéntica a msql_create_db(). (PHP 3, PHP 4 )


msql_error -- devuelve el mensaje de error de la última
llamada msql
msql_data_seek

Descripción
(PHP 3, PHP 4 )
msql_data_seek -- desplaza el puntero interno de fila
string msql_error ( )

Descripción
Los errores que devuelve el servidor de base de datos
mSQL no dan mucha información sobre el problema. Por
int msql_data_seek ( int query_identifier, int este motivo, utilice estas funciones para recuperar la
row_number) cadena de carácteres del error.

Devuelve TRUE si tiene éxito, FALSE en caso de fallo. msql_fetch_array


(PHP 3, PHP 4 ) int msql_fetch_object ( int query_identifier [, int
msql_fetch_array -- recupera una fila como un array result_type])

Descripción Devuelve un objeto con las propiedades que


corresponden a la fila recuperada, o FALSE si no hay
más filas.
int msql_fetch_array ( int query_identifier [, int msql_fetch_object() es similar a msql_fetch_array(),
result_type]) con una diferencia - se devuelve un objeto en vez de un
array. Indirectamente esto significa que sólo tiene acceso
a los datos por los nombres de los campos, y no por sus
Devuelve un array que se corresponde con la fila
desplazamientos (los números son nombres de
recuperada, o FALSE si no hay más filas.
propiedad no válidos).
msql_fetch_array() es una versión ampliada de
El segundo parámetro opcional result_type en
msql_fetch_row(). Además de almacenar los datos en
msql_fetch_array() es una constante y puede tomar los
los índices numéricos del array resultado, también
valores siguientes: MSQL_ASSOC, MSQL_NUM, y
almacena los datos en índices asociativos, utilizando los
MSQL_BOTH.
nombres de los campos como claves.
Resumiendo, la función es indéntica a
El segundo argumento opcional result_type en
msql_fetch_array(), y casi tan rápida como
msql_fetch_array() es una constante y puede tomar los
msql_fetch_row() (la diferencia es insignificante).
valores siguientes: MSQL_ASSOC, MSQL_NUM, y
Véase también: msql_fetch_array() y
MYSQL_BOTH.
msql_fetch_row().
Sea precavido si está recuperando resultados de una
consulta que puede devolver un registro que contiene un
único campo que tiene un valor de 0 (o una cadena de msql_fetch_row
carácteres vacía, o NULL).
Un aspecto importante a tener en cuenta es que el uso
de msql_fetch_array() NO es significativamente más (PHP 3, PHP 4 )
lento que el uso de msql_fetch_row(), mientras que msql_fetch_row -- obtiene una fila como un array
proporciona un valor añadido significativo. enumerado
Para detalles adicionales, véase también
msql_fetch_row()
Descripción

msql_fetch_field
array msql_fetch_row ( int query_identifier)

(PHP 3, PHP 4 )
Devuelve un array que se corresponde con la fila
msql_fetch_field -- obtiene información de campo
recuperada, o FALSE si no hay más filas.
msql_fetch_row() recupera una fila de datos del resultado
Descripción asociado con el identificador de consulta (query
identifier) especificado. La fila se devuelve en un array.
Cada columna devuelta se almacena en un
object msql_fetch_field ( int query_identifier, int desplazamiento del array, comenzando en el
field_offset) desplazamiento 0.
Una llamada posterior a msql_fetch_row() devería
devolver la fila siguiente del conjunto resultado, o FALSE
Devuelve un objeto que contiene la información del
si no hay más filas.
campo
Véase también: msql_fetch_array(),
msql_fetch_field() puede utilizarse para obtener
msql_fetch_object(), msql_data_seek(), y
información sobre campos del resultado de una consulta.
msql_result().
Si no se especifica el desplazamiento del campo, se
recupera el campo siguiente que no haya sido aún
recuperado por msql_fetch_field(). msql_field_seek
Las propiedades del objeto son:

(PHP 3, PHP 4 )
• name - nombre de la columna msql_field_seek -- establece el desplazamiento del
campo
• table - nombre de la tabla a la que pertenece
la columna
Descripción
• not_null - 1 si la columna no puede ser nula
• primary_key - 1 si la columna es una clave
primaria int msql_field_seek ( int query_identifier, int
field_offset)
• unique - 1 si la columna es una clave única
• type - tipo de la columna Se posiciona en el desplazamiento de campo (field offset)
especificado. Si la siguiente llamada a
msql_fetch_field() no incluye un desplazamiento de
Véase también msql_field_seek(). campo, este campo será el que se devuelva.
Véase también: msql_fetch_field().
msql_fetch_object
msql_fieldflags
(PHP 3, PHP 4 )
msql_fetch_object -- recupera una fila como un objeto (PHP 3, PHP 4 )
msql_fieldflags -- obtiene los flags del campo
Descripción
Descripción
string msql_fieldflags ( int query_identifier, int i) (PHP 3, PHP 4 )
msql_free_result -- libera la memoria del resultado
msql_fieldflags() obtiene los flags del campo (field)
especificado. Actualmente pueden ser, "not NULL", Descripción
"primary key", una combinación de ambos, o "" (cadena
vacía).
int msql_free_result ( int query_identifier)

msql_fieldlen
msql_free_result() libera la memoria asociada con
query_identifier. Cuando PHP completa una petición, esta
(PHP 3, PHP 4 ) memoria es liberada automáticamente, por este motivo
msql_fieldlen -- obtiene la longitud del campo solo es necesario llamar a esta función cuando se desea
estar seguro de que no se utiliza demasiada memoria
mientras se está ejecutando el script.
Descripción

msql_freeresult
int msql_fieldlen ( int query_identifier, int i)

msql_freeresult -- libera la memoria del resultado


msql_fieldlen() devuelve la longitud del campo
especificado.
Descripción
msql_fieldname
Véase msql_free_result()
(PHP 3, PHP 4 )
msql_fieldname -- obtiene el nombre del campo msql_list_dbs

Descripción (PHP 3, PHP 4 )


msql_list_dbs -- lista las bases de datos mSQL en el
servidor
string msql_fieldname ( int query_identifier, int field)

msql_fieldname() devuelve el nombre del campo Descripción


especificado. query_identifier es el identificador de
consulta, y field es el índice del campo.
int msql_list_dbs ( void)
msql_fieldname($result, 2); devolverá el nombre del
segundo campo del resultado asociado con el
identificador result. msql_list_dbs() devolverá un puntero al resultado que
contiene las bases de datos disponibles desde el daemon
msql en uso. Utilice la función msql_dbname() para
msql_fieldtable recorrer este puntero.

(PHP 3, PHP 4 ) msql_list_fields


msql_fieldtable -- obtiene el nombre de la tabla de un
campo
(PHP 3, PHP 4 )
msql_list_fields -- lista los campos del resultado
Descripción

Descripción
int msql_fieldtable ( int query_identifier, int field)

int msql_list_fields ( string database, string tablename)


Devuelve el nombre de la tabla desde la que se ha
recuperado el campo (field)
msql_list_fields() recupera información sobre el nombre
de tabla (tablename) dado. Los argumentos son el
msql_fieldtype nombre de la base de datos (database name) y el
nombre de la tabla (table name). Se devuelve un puntero
al resultado que puede utilizarse con msql_fieldflags(),
(PHP 3, PHP 4 )
msql_fieldlen(), msql_fieldname(), y
msql_fieldtype -- obtiene el tipo del campo
msql_fieldtype(). Un indetificador de consulta (query
identifier) es un entero positivo. La función devuelve -1 si
Descripción ocurre un error. En $phperrmsg se almacena una cadena
de carácteres describiendo el error, y a menos que la
función sea llamada como @msql_list_fields() esta
string msql_fieldtype ( int query_identifier, int i) cadena de error puede ser impresa.
Véase también msql_error().
msql_fieldtype() es similar a la función
msql_fieldname(). Los argumentos son idénticos, pero msql_list_tables
se devuelve el tipo del campo. Este será "int", "char" o
"real".
(PHP 3, PHP 4 )
msql_list_tables -- lista las tablas de una base de datos
msql_free_result mSQL
Descripción Véase también: msql(), msql_query(), y
msql_fetch_row().

int msql_list_tables ( string database)


msql_numfields
msql_list_tables() toma un nombre de base de datos y
devuelve un puntero similar al de la función msql() La (PHP 3, PHP 4 )
función msql_tablename() debería utilizarse para msql_numfields -- obtiene el número de campos de un
obtener los nombres reales de las tablas del puntero resultado
devuelto.

Descripción
msql_listdbs

int msql_numfields ( int query_identifier)


msql_listdbs -- lista las bases de datos mSQL en el
servidor
Idéntica a msql_num_fields().

Descripción
msql_numrows

Véase msql_list_dbs().
(PHP 3, PHP 4 )
msql_numrows -- obtiene el número de filas en el
msql_listfields resultado

msql_listfields -- lista los campos del resultado Descripción

Descripción int msql_numrows ( void)

Véase msql_list_fields(). Idéntica a msql_num_rows().

msql_listtables msql_pconnect

msql_listtables -- lista las tablas de una base de datos (PHP 3, PHP 4 )


mSQL msql_pconnect -- abre una conexión mSQL persistente

Descripción Descripción

Véase msql_list_tables(). int msql_pconnect ( string hostname)

En caso de éxito devuelve un identificador de conexión


msql_num_fields
mSQL persistente positivo, o FALSE en caso de error.
msql_pconnect() se comporta de forma similar a
(PHP 3, PHP 4 ) msql_connect() con dos diferencias importantes.
msql_num_fields -- obtiene el número de campos de un Primero, cuando se conecta, la función debe intentar
resultado primero localizar una conexión (persistente) que ya esté
abierta en el mismo host. Si se encuentra uno, se
devuelve un identificador para el mismo en vez de abrir
Descripción una conexión nueva.
Segundo, la conexión con el servidor SQL no se cerrará
cuando la ejecución del script finalice. Al contrario, la
int msql_num_fields ( int query_identifier) conexión permanecerá abierta para un uso futuro
(msql_close() no cerrará las conexiones abiertas por
msql_num_fields() devuelve el número de campos de un msql_pconnect()).
conjunto resultado. Este tipo de conexiones son por ello denominadas
Véase también: msql(), msql_query(), 'persistentes'.
msql_fetch_field(), y msql_num_rows().
msql_query
msql_num_rows
(PHP 3, PHP 4 )
(PHP 3, PHP 4 ) msql_query -- envía una consulta mSQL
msql_num_rows -- obtiene el número de filas de un
resultado
Descripción

Descripción
int msql_query ( string query, int link_identifier)

int msql_num_rows ( int query_identifier) msql_query() envía una consulta a la base de datos
activa actual en el servidor que está asociada con el
msql_num_rows() devuelve el número de filas de un identificador de conexión (link identifier) especificado. Si
conjunto resultado. no se especifica el identificador de conexión, se asume la
última conexión abierta. Si no hay ninguna conexión Véase también: msql_connect(), msql_pconnect(), y
abierta, la función intenta establecer una conexión como msql_query().
si se hubiera llamado a msql_connect(), y la utiliza.
En caso de éxito devuelve un identificador de consulta
mSQL positivo, o FALSE en caso de error. msql_selectdb
Véase también: msql(), msql_select_db(), y
msql_connect(). msql_selectdb -- selecciona una base de datos mSQL

msql_regcase
Descripción

msql_regcase -- construye una expresión regular para Véase msql_select_db().


una búsqueda que no distinga mayúsculas/minúsculas

msql_tablename
Descripción

(PHP 3, PHP 4 )
Véase sql_regcase().
msql_tablename -- obtiene el nombre de la tabla de un
campo
msql_result
Descripción
(PHP 3, PHP 4 )
msql_result -- obtiene datos resultado string msql_tablename ( int query_identifier, int field)

Descripción msql_tablename() toma un puntero resultado devuelto


por la función msql_list_tables() como un índice entero
y devuelve el nombre de una tabla. La función
int msql_result ( int query_identifier, int i, mixed field)
msql_numrows() puede utilizarse para determinar el
número de tablas del puntero resultado.
Devuelve el contenido de la celda en la fila y Ejemplo 1. msql_tablename() example
desplazamiento del conjunto resultado mSQL
especificado.
msql_result() devuelve el contenido de una celda de un <?php
conjunto resultado mSQL. El argumento campo (field) msql_connect ("localhost");
puede ser el desplazamiento del campo, el nombre del $result =
campo, o el nombre de la tabla punto nombre del campo msql_list_tables("wisconsin");
(nombretabla.nombrecampo). Si el nombre de la $i = 0;
columna tiene un alias ('select foo as bar from...'), utilice while ($i < msql_numrows($result))
el alias en vez del nombre de la columna. {
Cuando se trabaja con conjuntos de resultados grandes, $tb_names[$i] =
debería considerar el uso de las funciones que recuperen msql_tablename($result, $i);
filas completas (especificadas más abajo). Como estas echo $tb_names[$i] . "<BR>";
funciones recuperan el contenido de varias celdas en una $i++;
única llamada de función, son MUCHO más rápidas que }
msql_result(). Advierta también que especificar un ?>
desplazamiento numérico para el argumento campo
(field) es mucho más rápido que especificar un
argumento nombrecampo o nombretabla.nombrecampo. msql
Alternativas de alto-rendimiento recomendadas:
msql_fetch_row(), msql_fetch_array(), y
msql_fetch_object(). (PHP 3, PHP 4 )
msql -- ejecuta una consulta mSQL
msql_select_db
Descripción
(PHP 3, PHP 4 )
msql_select_db -- selecciona una base de datos mSQL int msql ( string database, string query, int
link_identifier)
Descripción
Devuelve un identificador de consulta mSQL positivo en
el resultado de la consulta, o FALSE en caso de error.
int msql_select_db ( string database_name, int msql() selecciona una base de datos y ejecuta una
link_identifier) consulta en ella. Si no se especifica el identificador de
conexión (link identifier), la función intentará encontrar
Devuelve TRUE si tiene éxito, FALSE en caso contrario. una conexión abierta en el servidor mSQL y en el caso de
msql_select_db() establece la base de datos activa actual que no se encontrase intentará crear uno como si se
en el servidor que está asociada con el identificador de llamase a msql_connect() sin parámetros (véase
conexión (link identifier) suministrado. Si no se especifica msql_connect()).
el identificador de conexión, se asumne la última
conexión abierta. Si no hay ninguna conexión abierta la LXIII. Funciones MySQL
función intentará establecer una conexión como si se
hubiera llamado a sql_connect(), y la utiliza.
Cada llamada posterior a msql_query() se hará en la Estas funciones le permiten acceder a servidores de
base de datos activa. bases de datos MySQL.
Puede encontrar más información sobre MySQL en mysql_thread_id -- Return the current thread ID
http://www.mysql.com/. mysql_unbuffered_query -- Send an SQL query to
Tabla de contenidos MySQL, without fetching and buffering the result rows
mysql_affected_rows -- Devuelve el número de filas
afectadas de la última operación MySQL
mysql_change_user -- Cambia el usuario conectado en la mysql_affected_rows
conexión activa
mysql_client_encoding -- Returns the name of the
(PHP 3, PHP 4 )
character set mysql_affected_rows -- Devuelve el número de filas
mysql_close -- cierra el enlace con MySQL
afectadas de la última operación MySQL
mysql_connect -- Abre una conexión a un servidor MySQL
mysql_create_db -- Crea una base MySQL
mysql_data_seek -- Mueve el puntero interno Descripción
mysql_db_name -- Get result data
mysql_db_query -- Envia una sentencia MySQL al servidor
mysql_drop_db -- Borra una base de datos MySQL int mysql_affected_rows ( [int identificador_de_enlace])
mysql_errno -- Deuelve el número del mensaje de error
de la última operación MySQL mysql_affected_rows() devuelve el número de filas
mysql_error -- Devuelve el texto del mensaje de error de afectadas en la ultima sentencia INSERT, UPDATE o
la última operación MySQL DELETE sobre el servidor asociado con el identificador de
mysql_escape_string -- Escapes a string for use in a enlace especificado. Si el identificador de enlace no ha
mysql_query. sido especificado, se asume por defecto el último enlace.
mysql_fetch_array -- Extrae la fila de resultado como una Si la última sentencia fue un DELETE sin clausula WHERE,
matriz asociativa todos los registros han sido borrados de la tabla pero
mysql_fetch_assoc -- Fetch a result row as an associative esta función devolvera cero.
array Este comando no es efectivo para las sentencias SELECT,
mysql_fetch_field -- Extrae la información de una sino sólo para las sentencias que modifican registros.
columna y la devuelve como un objeto. Para conseguir el número de lineas devueltos por un
mysql_fetch_lengths -- Devuelve la longitud de cada SELECT, usar mysql_num_rows().
salida en un resultado
mysql_fetch_object -- Extrae una fila de resultado como
un objeto mysql_change_user
mysql_fetch_row -- Devuelve una fila de resultado como
matriz
mysql_field_flags -- Devuelve los flags asociados con el (PHP 3>= 3.0.13)
campo especificado en un resultado mysql_change_user -- Cambia el usuario conectado en la
mysql_field_len -- Devuelve la longitud del campo conexión activa
especificado
mysql_field_name -- Devuelve el nombre del campo
Descripción
especificado en un resultado
mysql_field_seek -- Asigna el puntero del resultado al
offset del campo especificado int mysql_change_user ( string usuario, string
mysql_field_table -- Devuelve el nombre de la tabla password [, string base_de_datos [, int
donde esta el campo especificado identificador_de_enlace]])
mysql_field_type -- Devuelve el tipo del campo
especificado en un resultado
mysql_free_result -- Libera la memoria del resultado mysql_change_user() cambia el usuario conectado en
mysql_get_client_info -- Get MySQL client info la actual conexión activa, o si se especifica, en la
mysql_get_host_info -- Get MySQL host info conexión determinada por el identificador de enlace. Si
mysql_get_proto_info -- Get MySQL protocol info se especifica la base de datos, esta será la base por
mysql_get_server_info -- Get MySQL server info defecto después del cambio de usuario. Si la nueva
mysql_info -- Get information about the most recent combinación de usuario/ password no esta autorizada, el
query usuario actualmente conectado permanece activo.
mysql_insert_id -- Devuelve el identificador generado en
la última llamada a INSERT Nota: Esta función fue introducida
mysql_list_dbs -- Lista las bases de datos disponibles en en PHP 3.0.13 y requiere MySQL
el servidor MySQL 3.23.3 o superior.
mysql_list_fields -- Lista los campos del resultado de
MySQL
mysql_list_processes -- List MySQL processes mysql_client_encoding
mysql_list_tables -- Lista las tablas en una base de datos
MySQL
mysql_num_fields -- devuelve el numero de campos de (PHP 4 >= 4.3.0)
un resultado mysql_client_encoding -- Returns the name of the
mysql_num_rows -- Devuelve el numero de filas de un character set
resultado
mysql_pconnect -- Abre una conexión persistente al
Description
servidor MySQL
mysql_ping -- Ping a server connection or reconnect if
there is no connection int mysql_client_encoding ( [resource link_identifier])
mysql_query -- Envia una sentencia SQL a MySQL
mysql_real_escape_string -- Escapes special characters
in a string for use in a SQL statement, taking into account mysql_client_encoding() returns the default character
the current charset of the connection. set name for the current connection.
mysql_result -- Devuelve datos de un resultado Ejemplo 1. mysql_client_encoding() example
mysql_select_db -- Selecciona un base de datos MySQL
mysql_stat -- Get current system status
mysql_tablename -- Devuelve el nombre de la tabla de <?php
un campo $link = mysql_connect('localhost', 'mysql_user',
Nota: Soporte para ":puerto" fue
'mysql_password');
añadido en PHP 3.0B4.
$charset = mysql_client_encoding($link);
printf ("current character set is %s\n", $charset);
?> Soporte para ":/camino/al/socket"
fue añadido en PHP 3.0.10.

The above example would produce the following output:


En el caso de que se haga una llamada a
mysql_connect() con los mismos argumentos, no se
current character set establecerá un nuevo enlace, sino que se devolverá el
is latin1 enlace ya abierto.
El enlace al servidor sera cerrado tan pronto como la
See also: mysql_real_escape_string() ejecución del script finalice, a menos que se cierre antes
explicitamente llamando a mysql_close().
Ejemplo 1. Ejemplo de MySQL connect
mysql_close

(PHP 3, PHP 4 ) <?php


mysql_close -- cierra el enlace con MySQL $link = mysql_connect ("kraemer",
"marliesle", "secret") {
or die ("Could not connect");
Descripción }
print ("Connected successfully");
mysql_close ($link);
int mysql_close ( [int identificador_de_enlace])
?>
Ver también : mysql_pconnect(), y mysql_close().
Devuelve: verdadero si exito, falso si error.
mysql_close() cierra el enlace con la base MySQL que
esta asociada con el identificador de enlace especificado. mysql_create_db
Si no se especifica el identificador de enlace, se asume
por defecto el último enlace.
(PHP 3, PHP 4 )
mysql_create_db -- Crea una base MySQL
Nota: Normalmente no es necesario
ya que la aperturas no-persistentes
son cerradas automaticamente al Descripción
final de la ejecución del script.
int mysql_create_db ( string base_de_datos [, int
mysql_close() no cerrará los enlaces persistentes identificador_de_enlace])
generados con mysql_pconnect().
Ejemplo 1. Ejemplo de MySQL close mysql_create_db() intenta crear una base nueva en el
servidor asociado al identificador de enlace.
Ejemplo 1. Ejemplo de MySQL create
<?php
$link = mysql_connect ("kraemer",
"marliesle", "secret") { <?php
or die ("Could not connect"); $link = mysql_pconnect ("kron", "jutta",
} "geheim") {
print ("Connected successfully"); or die ("Could not connect");
mysql_close ($link); }
?> if (mysql_create_db ("my_db")) {
Ver también: mysql_connect(), y mysql_pconnect(). print ("Database created
successfully\n");
} else {
mysql_connect printf ("Error creating database: %s\n",
mysql_error ());
}
(PHP 3, PHP 4 )
?>
mysql_connect -- Abre una conexión a un servidor MySQL
Por razones de compatibilidad puede usarse
mysql_createdb() igualmente.
Descripción Ver también: mysql_drop_db().

int mysql_connect ( [string server [, string usuario [, mysql_data_seek


string password]]])

(PHP 3, PHP 4 )
Devuelve: Un identificador de enlace positivo si tiene
mysql_data_seek -- Mueve el puntero interno
exito, o falso si error.
mysql_connect()establece una conexión a un servidor
MySQL. Todos los argumentos son opcionales, y si no hay Descripción
, se asumen los valores por defecto ('localhost', usuario
propietario del proceso del servidor, password vacia).
El hostname puede incluir tambien un número de int mysql_data_seek ( int id_resultado, int
puerto . ej. "hostname:puerto" o un camino al socket ej. numero_de_fila)
":/camino/al/socket" para localhost.
Devuelve: verdadero si exito, falso si error.
mysql_data_seek() mueve el puntero de fila interno a
}
la fila especificada para el identificador de resultado. La
?>
próxima llamada a mysql_fetch_row() devolverá esa
fila. For backward compatibility, mysql_dbname() is also
numero_de_fila empieza en 0. accepted. This is deprecated, however.
Ejemplo 1. Ejemplo de MySQL data seek
mysql_db_query
<?php
$link = mysql_pconnect ("kron", "jutta", (PHP 3, PHP 4 )
"geheim") { mysql_db_query -- Envia una sentencia MySQL al servidor
or die ("Could not connect");
}
Descripción
mysql_select_db ("samp_db") {
or die ("Could not select database");
} int mysql_db_query ( string base_de_datos, string
sentencia [, int identificador_de_enlace])
$query = "SELECT last_name, first_name
FROM friends"; Devuelve: Un identificador de resultado positivo o falso si
$result = mysql_query ($query) { error.
or die ("Query failed"); mysql_db_query() selecciona una base y ejecuta una
} sentencia en ella. Si el identificador de enlace no ha sido
especificado, la función intenta encontrar un enlace
# fetch rows in reverse order abierto al servidor MySQL y si no lo encuentra, intetará
crear uno como si fuera llamado mysql_connect() sin
for ($i = mysql_num_rows ($result) - 1; $i argumentos
>=0; $i--) { Ver tambiénmysql_connect().
if (!mysql_data_seek ($result, $i)) { Por razones de compatibilidad puede usarse mysql()
printf ("Cannot seek to row %d\n", $i); igualmente.
continue;
}
mysql_drop_db
if(!($row = mysql_fetch_object ($result)))
continue;
(PHP 3, PHP 4 )
mysql_drop_db -- Borra una base de datos MySQL
printf ("%s %s<BR>\n", $row->last_name,
$row->first_name);
} Descripción

mysql_free_result ($result);
?> int mysql_drop_db ( string base_de_datos [, int
identificador_de_enlace])

mysql_db_name Devuelve: verdadero si éxito, falso si error.


mysql_drop_db() intenta suprimir una base de datos
completa del servidor asociado al identificador de enlace.
(PHP 3>= 3.0.6, PHP 4 )
Ver también: mysql_create_db(). Por razones de
mysql_db_name -- Get result data
compatibilidad puede usarse mysql_dropdb()
igualmente.
Description
mysql_errno
string mysql_db_name ( resource result, int row [,
mixed field])
(PHP 3, PHP 4 )
mysql_errno -- Deuelve el número del mensaje de error
mysql_db_name() takes as its first parameter the result de la última operación MySQL
pointer from a call to mysql_list_dbs(). The row
parameter is an index into the result set.
If an error occurs, FALSE is returned. Use Descripción
mysql_errno() and mysql_error() to determine the
nature of the error.
int mysql_errno ( [int identificador_de_enlace])
Ejemplo 1. mysql_db_name() example

Los errores devueltos por mySQL no indican los


<?php warnings. Usar estas funciones para encontrar el número
error_reporting(E_ALL); de error.
<?php
mysql_connect('dbhost', mysql_connect("marliesle");
'username', 'password'); echo mysql_errno().":
$db_list = mysql_list_dbs(); ".mysql_error()."<BR>";
mysql_select_db("nonexistentdb");
$i = 0; echo mysql_errno().":
$cnt = mysql_num_rows($db_list); ".mysql_error()."<BR>";
while ($i < $cnt) { $conn = mysql_query("SELECT * FROM
echo mysql_db_name($db_list, nonexistenttable");
$i) . "\n"; echo mysql_errno().":
$i++;
".mysql_error()."<BR>"; ?>
?>
Ver también: mysql_error()
The above example would produce the following output:

mysql_error
Escaped string: Zak\'s
Laptop
(PHP 3, PHP 4 )
mysql_error -- Devuelve el texto del mensaje de error de See also: mysql_real_escape_string(), addslashes(),
la última operación MySQL and the magic_quotes_gpc directive.

Descripción mysql_fetch_array

string mysql_error ( [int identificador_de_enlace]) (PHP 3, PHP 4 )


mysql_fetch_array -- Extrae la fila de resultado como una
matriz asociativa
Los errores devueltos por mySQL no indican los
warnings. Usar estas funciones para encontrar el número
de error. Descripción
<?php
mysql_connect("marliesle"); array mysql_fetch_array ( int id_resultado [, int
echo mysql_errno().": tipo_de_resultado])
".mysql_error()."<BR>";
mysql_select_db("nonexistentdb");
echo mysql_errno().": Devuelve una matriz que corresponde a la sentencia
".mysql_error()."<BR>"; extraida, o falso si no quedan más filas.
$conn = mysql_query("SELECT * FROM mysql_fetch_array() es una versión extendida de
nonexistenttable"); mysql_fetch_row(). Además de guardar los datos en el
echo mysql_errno().": indice numerico de la matriz, guarda también los datos
".mysql_error()."<BR>"; en los indices asociativos, usando el nombre de campo
?> como clave.
Si dos o más columnas del resultado tienen el mismo
Ver también: mysql_errno() nombre de campo, la última columna toma la prioridad.
Para acceder a la(s) otra(s) columna(s) con el mismo
mysql_escape_string nombre, se debe escificar el indice numerico o definir un
alias para la columna.
select t1.f1 as foo t2.f1 as bar
(PHP 4 >= 4.0.3)
from t1, t2
mysql_escape_string -- Escapes a string for use in a
mysql_query. La función mysql_fetch_array() no es
significativemente mas lenta que mysql_fetch_row(),
sin embargo tiene un valor añadido importante.
Description El segundo argumento opcional tipo_de_resultado en
mysql_fetch_array() es una constante y puede tomar
los valores siguientes: MYSQL_ASSOC, MYSQL_NUM, y
string mysql_escape_string ( string unescaped_string)
MYSQL_BOTH. (Esta funcionalidad fue añadida en PHP
3.0.7)
This function will escape the unescaped_string, so that it Para más detalles, ver también mysql_fetch_row().
is safe to place it in a mysql_query(). Ejemplo 1. mysql fetch array

Nota: mysql_escape_string() does


<?php
not escape % and _.
mysql_connect($host,$user,$password);
$result =
This function is identical to mysql_db_query("database","select * from
mysql_real_escape_string() table");
except that while($row = mysql_fetch_array($result)) {
mysql_real_escape_string() takes echo $row["user_id"];
a connection handler and escapes echo $row["fullname"];
the string according to the current }
character set. mysql_free_result($result);
mysql_escape_string() does not ?>
take a connection argument and
does not respect the current charset
setting. mysql_fetch_assoc

Ejemplo 1. mysql_escape_string() example (PHP 4 >= 4.0.3)


mysql_fetch_assoc -- Fetch a result row as an associative
array
<?php
$item = "Zak's Laptop";
Description
$escaped_item =
mysql_escape_string($item);
printf ("Escaped string: %s\n", array mysql_fetch_assoc ( resource result)
$escaped_item);
Returns an associative array that corresponds to the (PHP 3, PHP 4 )
fetched row, or FALSE if there are no more rows. mysql_fetch_field -- Extrae la información de una
mysql_fetch_assoc() is equivalent to calling columna y la devuelve como un objeto.
mysql_fetch_array() with MYSQL_ASSOC for the
optional second parameter. It only returns an associative
array. This is the way mysql_fetch_array() originally Descripción
worked. If you need the numeric indices as well as the
associative, use mysql_fetch_array().
object mysql_fetch_field ( int id_resultado [, int salto])
If two or more columns of the result have the same field
names, the last column will take precedence. To access
the other column(s) of the same name, you either need Devuelve un objeto que contiene la información del
to access the result with numeric indices by using campo.
mysql_fetch_row() or add alias names. See the Puede usarse mysql_fetch_field() para obtener
example at the mysql_fetch_array() description about información sobre campos en un resultado. Si no se
aliases. especifica el salto, se extrae el siguiente campo que
An important thing to note is that using todavia no ha sido extraido. con mysql_fetch_field().
mysql_fetch_assoc() is not significantly slower than Las propiedades del objeto son:
using mysql_fetch_row(), while it provides a significant
added value.
Ejemplo 1. An expanded mysql_fetch_assoc() • name - nombre de la columna
example
• table - name de la tabla a la que pertenece la
columna
<?php • max_length - longitud máxima de la columna

$conn = mysql_connect("localhost", "mysql_user",


• not_null - 1 si la columna no puede contener
un valor nulo
"mysql_password");
• primary_key - 1 si la columna es clave primaria
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
• unique_key - 1 si la columna es clave unica
exit; • multiple_key - 1 si la columna es clave no
} unica

if (!mysql_select_db("mydbname")) {
• numeric - 1 si la columna es numerica
echo "Unable to select mydbname: " . • blob - 1 si la columna es un BLOB
mysql_error();
exit;
• type - el tipo de la columna
} • unsigned - 1 si la columna es unsigned

$sql = "SELECT id as userid, fullname, userstatus


• zerofill - 1 si la columna es zero-filled
FROM sometable
WHERE userstatus = 1"; Ver también mysql_field_seek()

$result = mysql_query($sql);
mysql_fetch_lengths
if (!$result) {
echo "Could not successfully run query ($sql)
from DB: " . mysql_error(); (PHP 3, PHP 4 )
exit; mysql_fetch_lengths -- Devuelve la longitud de cada
} salida en un resultado

if (mysql_num_rows($result) == 0) { Descripción
echo "No rows found, nothing to print so am
exiting";
exit; array mysql_fetch_lengths ( int id_resultado)
}

// While a row of data exists, put that row in $row as Devuelve: Una matriz que contiene las longitudes de
an associative array cada campo de la última fila extraida por
// Note: If you're expecting just one row, no need to mysql_fetch_row(), o falso si error.
use a loop mysql_fetch_lengths() almacena las longitudes de
// Note: If you put extract($row); inside the following cada columna en la última fila devuelta por
loop, you'll mysql_fetch_row(), mysql_fetch_array(), y
// then create $userid, $fullname, and mysql_fetch_object() en una matriz, empezando por 0.
$userstatus Ver también: mysql_fetch_row().
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"]; mysql_fetch_object
echo $row["fullname"];
echo $row["userstatus"];
} (PHP 3, PHP 4 )
mysql_fetch_object -- Extrae una fila de resultado como
mysql_free_result($result); un objeto

?>
Descripción
See also mysql_fetch_row(), mysql_fetch_array(),
mysql_query(), and mysql_error().
object mysql_fetch_object ( int id_resultado [, int
tipo_de_resultado])
mysql_fetch_field
Devuelve un objeto con las propiedades aur "unique_key", "multiple_key", "blob", "unsigned",
corresponden a la última fila extraida, o falso si no "zerofill", "binary", "enum", "auto_increment",
quedan más filas. "timestamp".
mysql_fetch_object() es similar a Por razones de compatibilidad puede usarse tambien
mysql_fetch_array(), con la diferencia que un objeto es mysql_fieldflags().
devuelto en lugar de una matriz. Indirectamente, quiere
decir que solo se puede aceder a los datos por el nombre
del campo, y no por su posición. mysql_field_len
El argumento opcional tipo_de_resultado es una
constante y puede tomar los valores siguientes:
(PHP 3, PHP 4 )
MYSQL_ASSOC, MYSQL_NUM, y MYSQL_BOTH. mysql_field_len -- Devuelve la longitud del campo
La función es identica a mysql_fetch_array(), y casi tan
especificado
rápida como mysql_fetch_row() (la diferencia es
insignificante).
Ejemplo 1. mysql fetch object Descripción

<?php int mysql_field_len ( int id_resultado, int


mysql_connect($host,$user,$password); offset_del_campo)
$result =
mysql_db_query("database","select * from mysql_field_len() devuelve la longitud del campo
table"); especificado. Por razones de compatibilidad puede
while($row = mysql_fetch_object($result)) usarse tambien mysql_fieldlen().
{
echo $row->user_id;
echo $row->fullname; mysql_field_name
}
mysql_free_result($result);
?> (PHP 3, PHP 4 )
mysql_field_name -- Devuelve el nombre del campo
Ver también: mysql_fetch_array() y especificado en un resultado
mysql_fetch_row().

Descripción
mysql_fetch_row

string mysql_field_name ( int id_resultado, int


(PHP 3, PHP 4 ) indice_del_campo)
mysql_fetch_row -- Devuelve una fila de resultado como
matriz
mysql_field_name() devuelve el nombre del campo
especificado. Los argumentos de la función son el
Descripción identificador de resultado y el indice del campo. Por
ejemplo: mysql_field_name($result,2);
Devolverá el nombre del segundo campo asociado al
array mysql_fetch_row ( int id_resultado) identificador de resultado.
Por razones de compatibilidad puede usarse tambien
Devuelve: Una matriz que corresponde a la fila mysql_fieldname().
selecionada, o falso si no quedan más lineas.
mysql_fetch_row() seleciona una fila de datos del mysql_field_seek
resultado asociado al identificador de resultado
especificado. La fila es devuelta como una matriz. Cada
columna del resultdo es guardada en un offset de la (PHP 3, PHP 4 )
matriz, empezando por el offset 0. mysql_field_seek -- Asigna el puntero del resultado al
La llamada a mysql_fetch_row() debería devolver la offset del campo especificado
próxima fila del resultado, o falso si no quedan más filas.
Ver también: mysql_fetch_array(),
mysql_fetch_object(), mysql_data_seek(), Descripción
mysql_fetch_lengths(), and mysql_result().
int mysql_field_seek ( int id_resultado, int
mysql_field_flags offset_del_campo)

(PHP 3, PHP 4 ) Busca el offset del campo especificado. Si la próxima


mysql_field_flags -- Devuelve los flags asociados con el llamada a mysql_fetch_field() no incluye un offset de
campo especificado en un resultado campo, se devolverá ese campo.
Ver también: mysql_fetch_field().

Descripción
mysql_field_table

string mysql_field_flags ( int id_resultado, int


offset_del_campo) (PHP 3, PHP 4 )
mysql_field_table -- Devuelve el nombre de la tabla
donde esta el campo especificado
mysql_field_flags() devuelve los flags del campo
especificado. Cada flag es devuelto como una palabra y
estan separados un unico espacio, se puede dividir el Descripción
resultado devuelto utilizando explode().
Los siguientes flags pueden ser devueltos si tu versión de
MySQL los soporta: "not_null", "primary_key",
string mysql_field_table ( int id_resultado, int mysql_get_client_info -- Get MySQL client info
offset_del_campo)

Description
Devuelve el nombre de la tabla del campo. Por razones
de compatibilidad puede usarse tambien
mysql_fieldtable(). string mysql_get_client_info ( void)

mysql_field_type mysql_get_client_info() returns a string that


represents the client library version.
Ejemplo 1. mysql_get_client_info Example
(PHP 3, PHP 4 )
mysql_field_type -- Devuelve el tipo del campo
especificado en un resultado <?php
printf ("MySQL client info: %s\n",
mysql_get_client_info());
Descripción
?>

string mysql_field_type ( int id_resultado, int


offset_del_campo) The above example would produce the following output:

mysql_field_type() es similar a la función


mysql_field_name(). Los argumentos son identicos, MySQL client info:
pero se devuelve el tipo de campo. El tipo sera "int", 3.23.39
"real", "string", "blob", o otros detallados en la See also: mysql_get_host_info(),
documentación de MySQL. mysql_get_proto_info() and
Ejemplo 1. mysql field types mysql_get_server_info().

<?php mysql_get_host_info
mysql_connect("localhost:3306");
mysql_select_db("wisconsin"); (PHP 4 >= 4.0.5)
$result = mysql_query("SELECT * FROM onek"); mysql_get_host_info -- Get MySQL host info
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$i = 0; Description
$table = mysql_field_table($result, $i);
echo "Your '".$table."' table has ".$fields." fields and ".
$rows." records <BR>"; string mysql_get_host_info ( [resource link_identifier])
echo "The table has the following fields <BR>";
while ($i < $fields) { mysql_get_host_info() returns a string describing the
$type = mysql_field_type ($result, $i); type of connection in use for the connection
$name = mysql_field_name ($result, $i); link_identifier, including the server host name. If
$len = mysql_field_len ($result, $i); link_identifier is omitted, the last opened connection will
$flags = mysql_field_flags ($result, $i); be used.
echo $type." ".$name." ".$len." ".$flags."<BR>"; Ejemplo 1. mysql_get_host_info Example
$i++;
}
mysql_close(); <?php
?> mysql_connect("localhost", "mysql_user",
Por razones de compatibilidad puede usarse tambien "mysql_password") or
mysql_fieldtype(). die("Could not connect: " . mysql_error());
printf ("MySQL host info: %s\n",
mysql_get_host_info());
mysql_free_result ?>

(PHP 3, PHP 4 )
mysql_free_result -- Libera la memoria del resultado The above example would produce the following output:

Descripción MySQL host info: Localhost via


UNIX socket
int mysql_free_result ( int id_resultado) See also: mysql_get_client_info(),
mysql_get_proto_info() and
mysql_get_server_info().
mysql_free_result() solo necesita ser llamada si te
preocupa usar demasiado memoria durante la ejecución
de tu script. Toda la memoria del resultado especificado mysql_get_proto_info
en el parametro del identificador de resultado sera
automaticamente liberada.
Por razones de compatibilidad puede usarse tambien (PHP 4 >= 4.0.5)
mysql_freeresult(). mysql_get_proto_info -- Get MySQL protocol info

mysql_get_client_info Description

(PHP 4 >= 4.0.5) int mysql_get_proto_info ( [resource link_identifier])


mysql_get_proto_info() returns the protocol version mysql_info() returns a string for all statements listed
used by connection link_identifier. If link_identifier is below. For all other FALSE. The string format depends on
omitted, the last opened connection will be used. the given statement.
Ejemplo 1. mysql_get_proto_info Example Ejemplo 1. Relevant MySQL Statements

<?php INSERT INTO ... SELECT ...


mysql_connect("localhost", "mysql_user", String format: Records: 23 Duplicates: 0
"mysql_password") or Warnings: 0
die("Could not connect: " . mysql_error()); INSERT INTO ... VALUES (...),(...),(...)...
printf ("MySQL protocol version: %s\n", String format: Records: 37 Duplicates: 0
mysql_get_proto_info()); Warnings: 0
?> LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0
Skipped: 0 Warnings: 0
The above example would produce the following output: ALTER TABLE
String format: Records: 60 Duplicates: 0
Warnings: 0
MySQL protocol UPDATE
version: 10 String format: Rows matched: 65 Changed:
65 Warnings: 0
See also: mysql_get_client_info(),
mysql_get_host_info() and mysql_get_server_info(). The numbers are only for illustrating purpose; their
values will correspond to the query.

mysql_get_server_info
Nota: mysql_info() returns a non-
FALSE value for the INSERT ...
(PHP 4 >= 4.0.5) VALUES statement only if multiple
mysql_get_server_info -- Get MySQL server info value lists are specified in the
statement.

Description
See also: mysql_affected_rows()

string mysql_get_server_info ( [resource


link_identifier]) mysql_insert_id

mysql_get_server_info() returns the server version (PHP 3, PHP 4 )


used by connection link_identifier. If link_identifier is mysql_insert_id -- Devuelve el identificador generado en
omitted, the last opened connection will be used. la última llamada a INSERT
Ejemplo 1. mysql_get_server_info Example

Descripción
<?php
mysql_connect("localhost", "mysql_user", int mysql_insert_id ( [int identificador_de_enlace])
"mysql_password") or
die("Could not connect: " . mysql_error());
printf ("MySQL server version: %s\n", mysql_insert_id() devuelve el identificador generado
mysql_get_server_info()); para un campo de tipo AUTO_INCREMENTED. Se
?> devolvera el identificador genrado por el último INSERT
para el identificador_de_enlace. Si no se especifica el
identificador_de_enlace, se asume por defecto el último
The above example would produce the following output: enlace abierto.

mysql_list_dbs
MySQL server version:
4.0.1-alpha
(PHP 3, PHP 4 )
See also: mysql_get_client_info(),
mysql_list_dbs -- Lista las bases de datos disponibles en
mysql_get_host_info() and mysql_get_proto_info().
el servidor MySQL

mysql_info
Descripción

(PHP 4 >= 4.3.0)


int mysql_list_dbs ( [int identificador_de_enlace])
mysql_info -- Get information about the most recent
query
mysql_list_dbs() devuelve un puntero de resultado que
contiene las bases disponibles en el actual demonio
Description mysql. Utiliza la función mysql_tablename() para
explotar el puntero de resultado.
Por razones de compatibilidad puede usarse tambien
string mysql_info ( [resource link_identifier])
mysql_listdbs().

mysql_info() returns detailed information about the last


query using the given link_identifier. If link_identifier isn't mysql_list_fields
specified, the last opened link is assumed.
(PHP 3, PHP 4 )
mysql_list_fields -- Lista los campos del resultado de mysql_list_tables() toma el nombre de la base y
MySQL devuelve un puntero de resultado como la función
mysql_db_query(). La función mysql_tablename()
debe ser usada para extraer los nombres de las tablas
Descripción del puntero.
Por razones de compatibilidad puede usarse tambien
mysql_listtables(). can also be used.
int mysql_list_fields ( string base_de_datos, string tabla
[, int identificador_de_enlace])
mysql_num_fields
mysql_list_fields() lista información sobre la tabla. Los
argumentos son la base de datos y el nombre de la tabla.
(PHP 3, PHP 4 )
Se devuelve un puntero que puede ser usado por las
mysql_num_fields -- devuelve el numero de campos de
funciónes mysql_field_flags(), mysql_field_len(),
un resultado
mysql_field_name(), y mysql_field_type().
Un identificador de resultado es un entero positivo. La
función devuelve -1 si se produce un error. Una cadena Descripción
de caracteres describiendo el error sera introducida en
$phperrmsg, y a menos que la función sea llamada como
@mysql() el literal del error tambien sera impreso. int mysql_num_fields ( int id_resultado)
Por razones de compatibilidad puede usarse tambien
mysql_listfields(). mysql_num_fields() devuelve el numero de campos de
un identificador de resultado.
mysql_list_processes Ver también: mysql_db_query(), mysql_query(),
mysql_fetch_field(), mysql_num_rows().
Por razones de compatibilidad puede usarse tambien
(PHP 4 >= 4.3.0) mysql_numfields().
mysql_list_processes -- List MySQL processes

mysql_num_rows
Description

(PHP 3, PHP 4 )
resource mysql_list_processes ( [resource mysql_num_rows -- Devuelve el numero de filas de un
link_identifier]) resultado

mysql_list_processes() returns a result pointer Descripción


describing the current server threads.
Ejemplo 1. mysql_list_processes() example
int mysql_num_rows ( int id_resultado)

<?php mysql_num_rows() Devuelve el numero de filas de un


$link = mysql_connect('localhost', 'mysql_user', identificador de resultado.
'mysql_password'); Ver también: mysql_db_query(), mysql_query() and,
mysql_fetch_row().
$result = mysql_list_processes($link); Por razones de compatibilidad puede usarse tambien
while ($row = mysql_fetch_row($result)){ mysql_numrows().
printf("%s %s %s %s %s\n", $row["Id"],
$row["Host"], $row["db"],
$row["Command"], $row["Time"]); mysql_pconnect
}
mysql_free_result ($result);
?> (PHP 3, PHP 4 )
mysql_pconnect -- Abre una conexión persistente al
servidor MySQL
The above example would produce the following output:
Descripción

1 localhost test
Processlist 0 int mysql_pconnect ( [string server [, string usuario [,
4 localhost mysql string password]]])
sleep 5
See also: mysql_thread_id() Devuelve: un identificador de enlace persistente, o falso
si se produce un error.
mysql_pconnect() establece una conexión a un servidor
mysql_list_tables MySQL. Todos los argumentos son opcionales, y si no
existen, se asumen los valores por defecto ('localhost',
nombre del usuario propietario del proceso, password
(PHP 3, PHP 4 ) vacia).
mysql_list_tables -- Lista las tablas en una base de datos El hostname puede incluir un numero de puerto. ej.
MySQL "hostname:port" o un camino al socket ej.
":/camino/al/socket" para el puerto para el host local.
Descripción
Nota: Soporte para ":puerto" fue
int mysql_list_tables ( string base_de_datos [, int añadido en 3.0B4.
identificador_de_enlace])
Soporte para ":/camino/al/socket" La siguiente sentencia es invalida semanticamente si
fue añadido en 3.0.10. my_col no es una columna de la tabla my_tbl, asi que
mysql_query() falla y devuelve FALSE:
Ejemplo 2. mysql_query()
mysql_pconnect() actua como mysql_connect() con
dos diferencias fundamentales.
Primero, durante la conexión, la función intenta primero
<?php
encontrar un enlace persistente abierto con el mismo
$result = mysql_query ("SELECT my_col
host, usuario y password. Si lo encuentra, devuelve el
FROM my_tbl")
identificador de enlace en lugar de abrir otra conexión.
or die ("Invalid query");
Segundo, la conexión no sera cerrado cuando acabe la
?>
ejecución del script. El enlace permanecera abierta para
ser usado en el futuro (mysql_close() will not cierra el mysql_query() fallara tambien y devolvera FALSE si no
enlace establecido con mysql_pconnect()). se tiene el permiso de acceso a la tabla especificada en
Este tipo de enlaces son llamados 'persistentes'. la sentencia.
Asumiendo la sentencia tenga exito, se puede llamar a
mysql_affected_rows() para saber cuantas filas fueron
mysql_ping afectadas (para DELETE, INSERT, REPLACE, o UPDATE )
Para las sentencias SELECT, mysql_query() devuelve un
nuevo identificador de resultado que se puede pasar a
(PHP 4 >= 4.3.0)
mysql_result(). Cuando se acabe de utilizar el
mysql_ping -- Ping a server connection or reconnect if
resultado, se pueden liberar los recursos asociados
there is no connection
utilizando mysql_free_result().
Ver también: mysql_affected_rows(),
Description mysql_db_query(), mysql_free_result(),
mysql_result(), mysql_select_db(), and
mysql_connect().
bool mysql_ping ( [resource link_identifier])

mysql_real_escape_string
mysql_ping() checks whether or not the connection to
the server is working. If it has gone down, an automatic
reconnection is attempted. This function can be used by (PHP 4 >= 4.3.0)
scripts that remain idle for a long while, to check whether mysql_real_escape_string -- Escapes special characters
or not the server has closed the connection and in a string for use in a SQL statement, taking into account
reconnect if necessary. mysql_ping() returns TRUE if the current charset of the connection.
the connection to the server is working, otherwise
FALSE.
See also: mysql_thread_id(), mysql_list_processes(). Description

mysql_query string mysql_real_escape_string ( string


unescaped_string [, resource link_identifier])

(PHP 3, PHP 4 )
This function will escape special characters in the
mysql_query -- Envia una sentencia SQL a MySQL
unescaped_string, taking into account the current
charset of the connection so that it is safe to place it in a
Descripción mysql_query().

int mysql_query ( string sentencia [, int Nota: mysql_real_escape_string()


identificador_de_enlace]) does not escape % and _.

mysql_query() envia una sentencia a la base activa en Ejemplo 1. mysql_real_escape_string() example


el servidor asociado al identificador de enlace. Si no es
especificado un identificador_de_enlace, se asumira el
ultilmo enlace abierto. Si no hay ningun enlace abierto, la <?php
función intenta estalecer un enlace como si se llamara $link = mysql_connect('localhost', 'mysql_user',
función mysql_connect() sin argumentos, y lo utiliza. 'mysql_password');
La sentencia no puede terminar por punto y coma. $item = "Zak's and Derick's Laptop";
mysql_query() devuelve TRUE (no-cero) o FALSE para $escaped_item =
indicar si la sentencia se ha ejecutado correctamente o mysql_real_escape_string($item);
no. Un valor TRUE significa que la sentencia era correcta printf ("Escaped string: %s\n", $escaped_item);
y pudo ser ejecutada en el servidor. No indica nada sobre ?>
el numero de fila devueltas. Es perfectamente posible
que la sentencia se ejecute correctamente pero que no
devuelve ninguna fila. The above example would produce the following output:
La siguiente sentencia es invalida sintacticamente, asi
que mysql_query() falla y devuelve FALSE:
Ejemplo 1. mysql_query()
Escaped string: Zak\'s and
Derick\'s Laptop
<?php See also: mysql_escape_string(),
$result = mysql_query ("SELECT * mysql_character_set_name().
WHERE 1=1")
or die ("Invalid query");
mysql_result
?>

(PHP 3, PHP 4 )
mysql_result -- Devuelve datos de un resultado

Descripción
<?php
$link = mysql_connect('localhost', "mysql_user",
int mysql_result ( int id_resultado, int numero_de_fila [, "mysql_password");
mixed campo]) $status = explode(' ', mysql_stat($link));
print_r($status);
?>
mysql_result() devuelve el contenido de una celda de
un resultado MySQL. El campo argumento puede ser el
nombre del campo o el offset o tabla.nombre_del_campo.
The above example would produce the following output:
Si el nombre de la columna tiene un alias ('select foo as
bar from...'), utilice el alias en lugar del nombre de la
columna.
Cuando se trabaja un un gran resultado, debe Array
considerarse la utilizacion de una funcion que devuelva (
una fila entera ya que estas funciones son MUCHO mas [0] => Uptime: 5380
rapidas que mysql_result(). Tambien, especificando un [1] => Threads: 2
offset numerico en lugar del nombre del campo, la [2] => Questions: 1321299
ejecucion sera mas rapida. [3] => Slow queries: 0
Las llamadas a mysql_result() no deben mezclarse con [4] => Opens: 26
llamadas a las otras sentencias que trabajan con un [5] => Flush tables: 1
identificador de resultado. [6] => Open tables: 17
Alternativas recomendadas: mysql_fetch_row(), [7] => Queries per second
mysql_fetch_array(), y mysql_fetch_object(). avg: 245.595
)

mysql_select_db
mysql_tablename
(PHP 3, PHP 4 )
mysql_select_db -- Selecciona un base de datos MySQL (PHP 3, PHP 4 )
mysql_tablename -- Devuelve el nombre de la tabla de
un campo
Descripción

Descripción
int mysql_select_db ( string base_de_datos [, int
identificador_de_enlace])
string mysql_tablename ( int id_resultado, int i)
Devuelve : TRUE si exito, FALSE si error.
mysql_select_db() establece la base activa que estara mysql_tablename() toma un puntero de resultado
asociada con el identificador de enlace especificado. Si devuelto por mysql_list_tables() asi como un indice
no se especifica un identificador de enlace, se asume el (integer) y devuelve el nomnre de una tabla. Se puede
ultimo enlace abierto. Si no hay ningun enlace abierto, la usar la función mysql_num_rows() para determinar el
función intentara establecer un enlace como si se nombre de tablas en el puntero de resultado.
llamara a mysql_connect(). Ejemplo 1. mysql_tablename() Example
Toda llamada posterior a mysql_query() utilizara la
base activada.
Ver también: mysql_connect(), mysql_pconnect(), <?php
and mysql_query(). mysql_connect ("localhost:3306");
Por razones de compatibilidad puede usarse tambien $result = mysql_list_tables
mysql_selectdb(). ("wisconsin");
$i = 0;
while ($i < mysql_num_rows
mysql_stat
($result)) {
$tb_names[$i] =
(PHP 4 >= 4.3.0) mysql_tablename ($result, $i);
mysql_stat -- Get current system status echo $tb_names[$i] . "<BR>";
$i++;
}
Description ?>

string mysql_stat ( [resource link_identifier])


mysql_thread_id

mysql_stat() returns the current server status.


(PHP 4 >= 4.3.0)
mysql_thread_id -- Return the current thread ID
Nota: mysql_stat() currently only
returns status for uptime, threads,
queries, open tables, flush tables Description
and queries per second. For a
complete list of other status
int mysql_thread_id ( [resource link_identifier])
variables you have to use the SHOW
STATUS SQL command.
mysql_thread_id() returns the current thread ID. If the
connection is lost and you reconnect with mysql_ping(),
Ejemplo 1. mysql_stat() example the thread ID will change. This means you should not get
the thread ID and store it for later. You should get it server software itself can be found at
when you need it. http://www.mohawksoft.com/phoenix/.
Ejemplo 1. mysql_thread_id() example

Nota: This extension is not available


on Windows platforms.
<?php
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){ Requerimientos
printf ("current thread id is %d\n", $thread_id);
}
?>

Instalación
The above example would produce the following output:
To enable Msession support configure PHP --with-
msession[=DIR], where DIR is the Msession install
current thread id directory.
is 73
See also: mysql_ping(), mysql_list_processes().
Configuración en tiempo de ejecución

mysql_unbuffered_query

(PHP 4 >= 4.0.6) Tipos de recursos


mysql_unbuffered_query -- Send an SQL query to
MySQL, without fetching and buffering the result rows

Description Constantes predefinidas

resource mysql_unbuffered_query ( string query [, Tabla de contenidos


resource link_identifier [, int result_mode]]) msession_connect -- Connect to msession server
msession_count -- Get session count
msession_create -- Create a session
mysql_unbuffered_query() sends a SQL query query to msession_destroy -- Destroy a session
MySQL, without fetching and buffering the result rows msession_disconnect -- Close connection to msession
automatically, as mysql_query() does. On the one hand, server
this saves a considerable amount of memory with SQL msession_find -- Find value
queries that produce large result sets. On the other hand, msession_get_array -- Get array of ... ?
you can start working on the result set immediately after msession_get -- Get value from session
the first row has been retrieved: you don't have to wait msession_getdata -- Get data ... ?
until the complete SQL query has been performed. When msession_inc -- Increment value in session
using multiple DB-connects, you have to specify the msession_list -- List ... ?
optional parameter link_identifier. msession_listvar -- List sessions with variable
The optional result_mode parameter can be msession_lock -- Lock a session
MYSQL_USE_RESULT and MYSQL_STORE_RESULT. It msession_plugin -- Call an escape function within the
defaults to MYSQL_USE_RESULT, so the result is not msession personality plugin
buffered. See also mysql_query() for the counterpart of msession_randstr -- Get random string
this behaviour. msession_set_array -- Set array of ...
msession_set -- Set value in session
msession_setdata -- Set data ... ?
Nota: The benefits of
msession_timeout -- Set/get session timeout
mysql_unbuffered_query() come
msession_uniq -- Get uniq id
at a cost: You cannot use
msession_unlock -- Unlock a session
mysql_num_rows() on a result set
returned from
mysql_unbuffered_query(). You msession_connect
also have to fetch all result rows
from an unbuffered SQL query,
before you can send a new SQL (PHP 4 >= 4.2.0)
query to MySQL. msession_connect -- Connect to msession server

See also: mysql_query(). Description

LXIV. Mohawk Software session handler functions bool msession_connect ( string host, string port)

Introducción Aviso
Esta función no está documentada actualmente, solamente
msession is an interface to a high speed session daemon se encuentra disponible la lista de parametros.
which can run either locally or remotely. It is designed to
provide consistent session management for a PHP web
farm. More Information about msession and the session msession_count
(PHP 4 >= 4.2.0) Aviso
msession_count -- Get session count
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

int msession_count ( void) msession_get_array

(PHP 4 >= 4.2.0)


Aviso
msession_get_array -- Get array of ... ?
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

msession_create array msession_get_array ( string session)

(PHP 4 >= 4.2.0) Aviso


msession_create -- Create a session
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

bool msession_create ( string session) msession_get

(PHP 4 >= 4.2.0)


Aviso
msession_get -- Get value from session
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

msession_destroy string msession_get ( string session, string name, string


value)
(PHP 4 >= 4.2.0)
msession_destroy -- Destroy a session Aviso
Esta función no está documentada actualmente, solamente
Description se encuentra disponible la lista de parametros.

bool msession_destroy ( string name)


msession_getdata

Aviso
(no version information, might be only in CVS)
Esta función no está documentada actualmente, solamente msession_getdata -- Get data ... ?
se encuentra disponible la lista de parametros.
Description
msession_disconnect
string msession_getdata ( string session)
(PHP 4 >= 4.2.0)
msession_disconnect -- Close connection to msession Aviso
server
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

void msession_disconnect ( void) msession_inc

(PHP 4 >= 4.2.0)


Aviso
msession_inc -- Increment value in session
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

msession_find string msession_inc ( string session, string name)

(PHP 4 >= 4.2.0) Aviso


msession_find -- Find value
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

array msession_find ( string name, string value) msession_list


(PHP 4 >= 4.2.0) Aviso
msession_list -- List ... ?
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

array msession_list ( void) msession_set_array

(PHP 4 >= 4.2.0)


Aviso
msession_set_array -- Set array of ...
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

msession_listvar bool msession_set_array ( string session, array tuples)

(PHP 4 >= 4.2.0) Aviso


msession_listvar -- List sessions with variable
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

array msession_listvar ( string name) msession_set

Returns an associative array of value, session for all (PHP 4 >= 4.2.0)
sessions with a variable named name. msession_set -- Set value in session
Used for searching sessions with common attributes.
Description
msession_lock
bool msession_set ( string session, string name, string
(PHP 4 >= 4.2.0) value)
msession_lock -- Lock a session

Aviso
Description
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
int msession_lock ( string name)

msession_setdata
Aviso
Esta función no está documentada actualmente, solamente (no version information, might be only in CVS)
se encuentra disponible la lista de parametros. msession_setdata -- Set data ... ?

msession_plugin Description

(PHP 4 >= 4.2.0) bool msession_setdata ( string session, string value)


msession_plugin -- Call an escape function within the
msession personality plugin
Aviso
Esta función no está documentada actualmente, solamente
Description
se encuentra disponible la lista de parametros.

string msession_plugin ( string session, string val [,


string param]) msession_timeout

Aviso (PHP 4 >= 4.2.0)


msession_timeout -- Set/get session timeout
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

msession_randstr
int msession_timeout ( string session [, int param])

(PHP 4 >= 4.2.0)


msession_randstr -- Get random string Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Description

string msession_randstr ( int param) msession_uniq


(PHP 4 >= 4.2.0) se encuentra disponible la lista de parametros.
msession_uniq -- Get uniq id
[Not back to the system, note!]

Description
muscat_get

string msession_uniq ( int param)


(4.0.5 - 4.2.3 only)
muscat_get -- Gets a line back from the core muscat API.
Aviso
Esta función no está documentada actualmente, solamente Description
se encuentra disponible la lista de parametros.

string muscat_get ( resource muscat_handle)


msession_unlock
Aviso
(PHP 4 >= 4.2.0) Este módulo es EXPERIMENTAL. Esto significa que el
msession_unlock -- Unlock a session comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
Description en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.

int msession_unlock ( string session, int key) Aviso


Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Aviso
Returns a literal FALSE when there is no more to get (as
Esta función no está documentada actualmente, solamente opposed to ""). Use === FALSE or !== FALSE to check
se encuentra disponible la lista de parametros. for this.

LXV. muscat functions muscat_give

Introducción (4.0.5 - 4.2.3 only)


muscat_give -- Sends string to the core muscat API

Aviso
Description
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 int muscat_give ( resource muscat_handle, string string)
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
Tabla de contenidos
muscat_close -- Shuts down the muscat session and Este módulo es EXPERIMENTAL. Esto significa que el
releases any memory back to PHP. comportamineto de estas funciones, nombre de funciones
muscat_get -- Gets a line back from the core muscat API. y en definitiva TODO lo documentado aqui, puede cambiar
muscat_give -- Sends string to the core muscat API en una futura version de PHP SIN AVISO. Quedas avisado, y
muscat_setup_net -- Creates a new muscat session and utilizar este módulo es tu responsabiliad.
returns the handle.
Aviso
muscat_setup -- Creates a new muscat session and
returns the handle. Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
muscat_close
muscat_setup_net
(4.0.5 - 4.2.3 only)
muscat_close -- Shuts down the muscat session and (4.0.5 - 4.2.3 only)
releases any memory back to PHP. muscat_setup_net -- Creates a new muscat session and
returns the handle.
Description
Description
int muscat_close ( resource muscat_handle)
resource muscat_setup_net ( string muscat_host, int
port)
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Aviso
y en definitiva TODO lo documentado aqui, puede cambiar Este módulo es EXPERIMENTAL. Esto significa que el
en una futura version de PHP SIN AVISO. Quedas avisado, y comportamineto de estas funciones, nombre de funciones
utilizar este módulo es tu responsabiliad. y en definitiva TODO lo documentado aqui, puede cambiar
Aviso en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Esta función no está documentada actualmente, solamente
Aviso socket_get_status -- Alias of stream_get_meta_data().
socket_set_blocking -- Alias for stream_set_blocking()
Esta función no está documentada actualmente, solamente socket_set_timeout -- Alias for stream_set_timeout()
se encuentra disponible la lista de parametros. syslog -- genera un mensaje de sistema
muscat_host is the hostname to connect to port is the
port number to connect to - actually takes exactly the checkdnsrr
same args as fsockopen

(PHP 3, PHP 4 )
muscat_setup checkdnsrr -- Comprueba registros DNS correspondientes
a nombres de máquinas en Internet o direcciones IP.
(4.0.5 - 4.2.3 only)
muscat_setup -- Creates a new muscat session and Descripción
returns the handle.

int checkdnsrr ( string host [, string type])


Description

Busca en DNS entradas del tipo type correspondientes a


resource muscat_setup ( int size [, string muscat_dir]) host. Devuelve verdadero si encuentra algún registro;
devuelve falso si no encuentra ninguno o sucedió algún
error.
Aviso type puede ser: A, MX, NS, SOA, PTR, CNAME, o ANY. Por
Este módulo es EXPERIMENTAL. Esto significa que el defecto es MX.
comportamineto de estas funciones, nombre de funciones host puede ser o la dirección IP de la forma
y en definitiva TODO lo documentado aqui, puede cambiar xxxx.xxxx.xxxx.xxxx o el nombre de la máquina.
en una futura version de PHP SIN AVISO. Quedas avisado, y Ver también getmxrr(), gethostbyaddr(),
utilizar este módulo es tu responsabiliad. gethostbyname(), gethostbynamel(), y named(8) en
las páginas del manual.
Aviso
Esta función no está documentada actualmente, solamente closelog
se encuentra disponible la lista de parametros.
Size is the ammount of memory in bytes to allocate for
(PHP 3, PHP 4 )
muscat muscat_dir is the muscat installation dir e.g.
closelog -- cierra la conexión con el logger del sistema
"/usr/local/empower", it defaults to the compile time
muscat directory
Descripción
LXVI. Funciones de Red
int closelog ( void)
Tabla de contenidos
checkdnsrr -- Comprueba registros DNS correspondientes closelog() cierra el descriptor que se está usando para
a nombres de máquinas en Internet o direcciones IP. escribir en el logger del sistema. El uso de closelog() es
closelog -- cierra la conexión con el logger del sistema opcional.
debugger_off -- deshabilita el depurador interno de PHP
debugger_on -- habilita el depurador interno de PHP
define_syslog_variables -- Initializes all syslog related debugger_off
constants
dns_check_record -- Synonym for checkdnsrr() (PHP 3)
dns_get_mx -- Synonym for getmxrr() debugger_off -- deshabilita el depurador interno de PHP
dns_get_record -- Fetch DNS Resource Records
associated with a hostname
fsockopen -- Abre una conexión de dominio Internet o Descripción
Unix via sockets.
gethostbyaddr -- Obtiene el nombre de una máquina en
Internet mediante su dirección IP. int debugger_off ( void)
gethostbyname -- Obtiene la dirección IP correspondiente
al nombre de una máquina conectada a Internet. Deshabilita el depurador interno de PHP. El depurador
gethostbynamel -- Obtiene una lista de direcciones IP está aún en desarrollo.
correspondientea a los nombres de máquinas conectadas
a Internet.
getmxrr -- Obtiene registros MX correspondientes a una debugger_on
máquina conectada a Internet.
getprotobyname -- Obtiene el n£mero asociado al
nombre del protocolo (PHP 3)
getprotobynumber -- obtiene el nombre asociado al debugger_on -- habilita el depurador interno de PHP
n£mero de protocolo
getservbyname -- obtiene el n£mero del puerto asociado Descripción
al servicio Internet especificado
getservbyport -- obtiene el servicio Internet que
correspondiente al puerto del protocolo especificado int debugger_on ( string address)
ip2long -- Converts a string containing an (IPv4) Internet
Protocol dotted address into a proper address.
long2ip -- Converts an (IPv4) Internet network address Habilita el depurador interno de PHP, conectándolo a
into a string in Internet standard dotted format address. El depurador esta aún en desarrollo.
openlog -- abre una conexión con el logger del sistema
pfsockopen -- Abre conexiones persistentes de dominio define_syslog_variables
Internet o Unix.
(PHP 3, PHP 4 ) Attrib
define_syslog_variables -- Initializes all syslog related Meaning
ute
constants
array dependant on the value of type. See table
below.
Description
Time To Live remaining for this record. This will not
equal the record's original ttl, but will rather equal
void define_syslog_variables ( void) ttl the original ttl minus whatever length of time has
passed since the authoritative name server was
queried.
Initializes all constants used in the syslog functions.
See also openlog(), syslog() and closelog(). hostname should be a valid DNS hostname such as
"www.example.com". Reverse lookups can be generated
using in-addr.arpa notation, but gethostbyaddr() is
dns_check_record more suitable for the majority of reverse lookups.
By default, dns_get_record() will search for any
resource records associated with hostname. To limit the
(PHP 5 CVS only)
query, specify the optional type parameter. type may be
dns_check_record -- Synonym for checkdnsrr()
any one of the following: DNS_A, DNS_CNAME,
DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA,
Description DNS_TXT, DNS_AAAA, DNS_ALL or DNS_ANY. The
default is DNS_ANY.

int dns_check_record ( string host [, string type])


Nota: Because of excentricities in
the performance of libresolv
Check DNS records corresponding to a given Internet between platforms, DNS_ANY will
host name or IP address not always return every record, the
slower DNS_ALL will collect all
records more reliably.
dns_get_mx

(PHP 5 CVS only) The optional third and fourth arguments to this function,
authns and addtl are passed by reference and, if given,
dns_get_mx -- Synonym for getmxrr()
will be populated with Resource Records for the
Authoritative Name Servers, and any Additional Records
Description respectively. See the example below.
Tabla 2. Other keys in associative arrays
dependant on 'type'
int getmxrr ( string hostname, array mxhosts [, array
Type Extra Columns
&weight])
A ip: An IPv4 addresses in dotted decimal notation.
Get MX records corresponding to a given Internet host pri: Priority of mail exchanger. Lower numbers
name. MX indicate greater priority. target: FQDN of the mail
exchanger. See also dns_get_mx().
dns_get_record CNAM target: FQDN of location in DNS namespace to
E which the record is aliased.

(PHP 5 CVS only) target: FQDN of the name server which is


NS
dns_get_record -- Fetch DNS Resource Records authoritative for this hostname.
associated with a hostname target: Location within the DNS namespace to
PTR
which this record points.
Description TXT txt: Arbitrary string data associated with this record.
cpu: IANA number designating the CPU of the
array dns_get_record ( string hostname [, int type [, machine referenced by this record. os: IANA
array &authns, array &addtl]]) HINFO number designating the Operating System on the
machine referenced by this record. See RFC 1010
for the meaning of these values.
Nota: This function is not
mname: FQDN of the machine from which the
implemented on Windows platforms.
resource records orignated. rname: Email address
Try the PEAR class Net_DNS.
of the administrative contain for this domain. serial:
Serial # of this revision of the requested domain.
This function returns an array of associative arrays. Each refresh: Refresh interval (seconds) secondary name
associative array contains at minimum the following servers should use when updating remote copies of
keys: this domain. retry: Length of time (seconds) to wait
Tabla 1. Basic DNS attributes after a failed refresh before making a second
SOA
attempt. expire: Maximum length of time (seconds)
Attrib a secondary DNS server should retain remote
Meaning
ute copies of the zone data without a successful refresh
The record in the DNS namespace to which the before discarding. minimum-ttl: Minimum length of
host time (seconds) a client can continue to use a DNS
rest of the associated data refers.
resolution before it should request a new resolution
dns_get_record() only returns Internet class from the server. Can be overridden by individual
class records and as such this parameter will always resource records.
return IN.
AAAA ipv6: IPv6 address
type String containing the record type. Additional
attributes will also be contained in the resulting
Nota: Per DNS standards, email
(
addresses are given in user.host
[0] => Array
format (for example:
(
hostmaster.example.com as
[host] => php.net
opposed to
[type] => MX
hostmaster@example.com), be sure
[pri] => 5
to check this value and modify if
[target] => pair2.php.net
necessary before using it with a
[class] => IN
functions such as mail().
[ttl] => 6765
)
Ejemplo 1. Using dns_get_record()
[1] => Array
(
[host] => php.net
<?php
[type] => A
$result =
[ip] => 64.246.30.37
dns_get_record("php.net");
[class] => IN
print_r($result);
[ttl] => 8125
?>
)
/*
)
Produces ouput similar to the
Auth NS = Array
following:
(
----------------------------------------
[0] => Array
(
Array
[host] => php.net
(
[type] => NS
[0] => Array
[target] => remote1.easydns.com
(
[class] => IN
[host] => php.net
[ttl] => 10722
[type] => MX
)
[pri] => 5
[target] =>
[1] => Array
pair2.php.net
(
[class] => IN
[host] => php.net
[ttl] => 6765
[type] => NS
)
[target] => remote2.easydns.com
[class] => IN
[1] => Array
[ttl] => 10722
(
)
[host] => php.net
[type] => A
[2] => Array
[ip] => 64.246.30.37
(
[class] => IN
[host] => php.net
[ttl] => 8125
[type] => NS
)
[target] => ns1.easydns.com
[class] => IN
)
[ttl] => 10722
*/
)
Since it's very common to want the IP address of a mail
server once the MX record has been resolved, [3] => Array
dns_get_record() also returns an array in addtl which (
contains associate records. authns is returned as well [host] => php.net
conatining a list of authoritative name servers. [type] => NS
Ejemplo 2. Using dns_get_record() and DNS_ANY [target] => ns2.easydns.com
[class] => IN
[ttl] => 10722
<?php )
/* Request "ANY" record for php.net,
and create $authns and $addtl arrays )
containing list of name servers and Additional = Array
any additional records which go with (
them */ [0] => Array
$result = dns_get_record("php.net",DNS_ANY, (
$authns,$addtl); [host] => pair2.php.net
print "Result = "; [type] => A
print_r($result); [ip] => 216.92.131.5
print "Auth NS = "; [class] => IN
print_r($authns); [ttl] => 6766
print "Additional = "; )
print_r($addtl);
?> [1] => Array
(
/* [host] => remote1.easydns.com
Produces output similar to the following: [type] => A
----------------------------------------- [ip] => 64.39.29.212
[class] => IN
Result = Array [ttl] => 100384
) } else {
fputs($fp,"GET /
[2] => Array HTTP/1.0\n\n");
( while(!feof($fp)) {
[host] => remote2.easydns.com echo
[type] => A fgets($fp,128);
[ip] => 212.100.224.80 }
[class] => IN fclose($fp);
[ttl] => 81241 }
)
Ver también: pfsockopen()
[3] => Array
( gethostbyaddr
[host] => ns1.easydns.com
[type] => A
[ip] => 216.220.40.243 (PHP 3, PHP 4 )
[class] => IN gethostbyaddr -- Obtiene el nombre de una máquina en
[ttl] => 81241 Internet mediante su dirección IP.
)

[4] => Array Descripción


(
[host] => ns2.easydns.com string gethostbyaddr ( string ip_address)
[type] => A
[ip] => 216.220.40.244
[class] => IN Devuelve el nombre del ordenador conectado a Internet
[ttl] => 81241 espeficado por el parámetro ip_address. Si ocurre un
) error, devuelve ip_address.
Ver también gethostbyname().
)
*/
gethostbyname
See also dns_get_mx(), and dns_check_record()

(PHP 3, PHP 4 )
fsockopen gethostbyname -- Obtiene la dirección IP correspondiente
al nombre de una máquina conectada a Internet.
(PHP 3, PHP 4 )
fsockopen -- Abre una conexión de dominio Internet o Descripción
Unix via sockets.

string gethostbyname ( string hostname)


Descripción
Devuelve la dirección IP de una máquina conectada a
int fsockopen ( string hostname, int port [, int errno [, Internet especificada por hostname.
string errstr [, double timeout]]]) Ver también gethostbyaddr().

Inicia una conexión de dominio Internet (AF_INET) o Unix gethostbynamel


(AF_UNIX). Para el domino Internet, abrirá una conexión
TCP hacia el ordenador hostname en el puerto port. Para
el dominio Unix, hostname se usará como ruta al socket, (PHP 3, PHP 4 )
port debe ser 0 para este caso. El parámetro opcional gethostbynamel -- Obtiene una lista de direcciones IP
timeout se puede usar para especificar un timeout en correspondientea a los nombres de máquinas conectadas
segundos para establecer la conexión. a Internet.
fsockopen() devuelve un puntero a fichero, el cual se
puede usar junto con las otras funciones de ficheros
Descripción
(como fgets(), fgetss(), fputs(), fclose(), feof()).
Si la llamada falla, esta devolverá falso y si los
parámetros opcionales errno y errstr están presentes, array gethostbynamel ( string hostname)
indicarán el error del sistema que ocurrió en la llamada
connect(). Si errno es 0 y la función devolviá falso, nos
indica que el error ocurrió antes de la llamada connect(). Devuleve una lista de direcciones IP pertenecientes a
Esto es debido principalmente a problemas inicializando ordenadores especificados por hostname.
el socket. Observe que los argumentos errno y errstr Ver también gethostbyname(), gethostbyaddr(),
deben ser pasados por referencia. checkdnsrr(), getmxrr(), y named(8) en las páginas
Dependiendo del entorno, el dominio Unix o el parámetro del manual.
opcional, timeout puede no estar disponible.
Por defecto, el socket será abierto en modo de bloqueo. getmxrr
Puede cambiarlo a modo de no bloqueo usando
set_socket_blocking().
Ejemplo 1. ejemplo con fsockopen (PHP 3, PHP 4 )
getmxrr -- Obtiene registros MX correspondientes a una
máquina conectada a Internet.
$fp = fsockopen("www.php.net", 80,
&$errno, &$errstr, 30);
if(!$fp) { Descripción
echo "$errstr ($errno)<br>\n";
int getmxrr ( string hostname, array mxhosts [, array getservbyport() delvuelve el servicio Internet asociado
weight]) al port para el protocol especificado en /etc/services.
protocol puede ser tcp o udp. Ver también
getservbyname().
Busca DNS de registros MX correspondientes a
hostname. Devuelve verdadero si encuentra alg£n
registro; devuelve falso si no encuentra ninguno o se ip2long
produce un error.
La lista de registros MX encontrados se colocan en el
array mxhosts. Si se proporciona el array weight, se (PHP 4 )
rellenará con la información obtenida. ip2long -- Converts a string containing an (IPv4) Internet
Ver también checkdnsrr(), gethostbyname(), Protocol dotted address into a proper address.
gethostbynamel(), gethostbyaddr(), y named(8) de
las páginas del manual.
Description

getprotobyname
int ip2long ( string ip_address)

(PHP 4 )
The function ip2long() generates an IPv4 Internet
getprotobyname -- Obtiene el n£mero asociado al network address from its Internet standard format
nombre del protocolo
(dotted string) representation.
Ejemplo 1. ip2long() Example
Descripción

<?php
int getprotobyname ( string name) $ip = gethostbyname("www.example.com");
$out = "The following URLs are equivalent:<br>\n";
getprotobyname() devuelve el n£mero asociado al $out .= "http://www.example.com/, http://".$ip."/, and
nombre del protocolo name del fichero /etc/protocols. http://".sprintf("%u",ip2long($ip))."/<br>\n";
Ver también getprotobynumber(). echo $out;
?>

getprotobynumber
Nota: Because PHP's integer type is
signed, and many IP addresses will
(PHP 4 )
result in negative integers, you need
getprotobynumber -- obtiene el nombre asociado al
to use the "%u" formatter of
n£mero de protocolo
sprintf() or printf() to get the
string representation of the unsigned
Descripción IP address.

string getprotobynumber ( int number) This second example shows how to print a converted
address with the printf() function :
Ejemplo 2. Displaying an IP address
getprotobynumber() devuelve el nombre del protocolo
asociado al number del protocolo en el fichero
/etc/protocols. Ver también getprotobyname().
<?php
$ip =
getservbyname gethostbyname("www.example.
com");
printf("%u\n", ip2long($ip));
(PHP 4 ) echo $out;
getservbyname -- obtiene el n£mero del puerto asociado ?>
al servicio Internet especificado
See also: long2ip()

Descripción
long2ip

int getservbyname ( string service, string protocol)


(PHP 4 )
long2ip -- Converts an (IPv4) Internet network address
getservbyname() devuelve el puerto que corresponde into a string in Internet standard dotted format
al service especificado por el protocol en /etc/services.
protocol puede ser tcp o udp. Ver también
getservbyport(). Description

getservbyport string long2ip ( int proper_address)

The function long2ip() generates an Internet address in


(PHP 4 )
dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper
getservbyport -- obtiene el servicio Internet que
address representation.
correspondiente al puerto del protocolo especificado
See also: ip2long()

Descripción
openlog

string getservbyport ( int port, string protocol)


(PHP 3, PHP 4 ) syslog() genera un mensaje que será distribuido por el
openlog -- abre una conexión con el logger del sistema logger del sistema. priority es una combinación de la
facility y el level, los valores se indicarán en la sección
siguiente. El argumento restante es el mensaje a enviar,
Descripción excepto que los dos caracteres %m sean reemplazados
por la cadena de error (strerror) correspondiente al valor
actual de errno.
int openlog ( string ident, int option, int facility)
Más información acerca de syslog se puede encontrar en
las páginas del manual en equipos Unix.
openlog() abre una conexión con el logger del sistema. En Windows NT, el servicio syslog es emulado usando el
La cadena ident se a¤ade a cada mensaje. Los valores de Log de Eventos.
option y facility se exponen en la siguiente sección. El
uso de openlog() is opcional; Esta será llamada
automaticamente por syslog() si fuera necesario, en LXVII. Ncurses terminal screen control functions
este caso ident valdrá por defecto FALSE. Ver también
syslog() y closelog().
Introducción

pfsockopen
ncurses (new curses) is a free software emulation of
curses in System V Rel 4.0 (and above). It uses terminfo
(PHP 3>= 3.0.7, PHP 4 ) format, supports pads, colors, multiple highlights, form
pfsockopen -- Abre conexiones persistentes de dominio characters and function key mapping. Because of the
Internet o Unix. interactive nature of this library, it will be of little use for
writing Web applications, but may be useful when writing
scripts meant using PHP from the command line.
Descripción
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
int pfsockopen ( string hostname, int port [, int errno [, comportamineto de estas funciones, nombre de funciones
string errstr [, int timeout]]]) y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Esta función se comporta exactamente como utilizar este módulo es tu responsabiliad.
fsockopen() con la diferencia que la conexion no se Ncurses is available for the following platforms:
cierra después de que termine el script. Esta es la
versión persistente de fsockopen().
• AIX
socket_get_status • BeOS
• Cygwin
socket_get_status -- Alias of stream_get_meta_data().
• Digital Unix (aka OSF1)
• FreeBSD
Description
• GNU/Linux

This function is an alias of stream_get_meta_data(). • HPUX


• IRIX
socket_set_blocking • OS/2
• SCO OpenServer
socket_set_blocking -- Alias for stream_set_blocking() • Solaris
• SunOS
Description

This function is an alias for stream_set_blocking().


Requerimientos

socket_set_timeout
You need the ncurses libraries and headerfiles. Download
the latest version from the
socket_set_timeout -- Alias for stream_set_timeout() ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-
Mirror.
Description
Instalación
This is an alias for stream_set_timeout().
To get these functions to work, you have to compile the
syslog CGI or CLI version of PHP with --with-ncurses[=DIR].

(PHP 3, PHP 4 ) Configuración en tiempo de ejecución


syslog -- genera un mensaje de sistema
The behaviour of these functions is affected by settings
Descripción in php.ini.
Tabla 1. Ncurses configuration options

int syslog ( int priority, string message)


Defau Changeabl constant meaning
Name
lt e
NCURSES_KEY_IL insert line
ncurses.va PHP_INI_AL
"42" NCURSES_KEY_DC delete character
lue L
insert char or enter
ncurses.str "fooba PHP_INI_AL NCURSES_KEY_IC
insert mode
ing r" L
For further details and definition of the PHP_INI_* NCURSES_KEY_EIC exit insert char mode
constants see ini_set(). NCURSES_KEY_CLEAR clear screen
NCURSES_KEY_EOS clear to end of screen
Tipos de recursos NCURSES_KEY_EOL clear to end of line
NCURSES_KEY_SF scroll one line forward
Esta extensión no define ningún tipo de recurso.
NCURSES_KEY_SR scroll one line backward
NCURSES_KEY_NPAGE next page
Constantes predefinidas
NCURSES_KEY_PPAGE previous page
NCURSES_KEY_STAB set tab
Estas constantes están definidas por esta extensión y
estarán disponibles solamente cuando la extensión ha NCURSES_KEY_CTAB clear tab
sido o bien compilada dentro de PHP o grabada NCURSES_KEY_CATAB clear all tabs
dinamicamente en tiempo de ejecución.
NCURSES_KEY_SRESET soft (partial) reset
NCURSES_KEY_RESET reset or hard reset
Error codes
NCURSES_KEY_PRINT print

On error ncurses functions return NCURSES_ERR. NCURSES_KEY_LL lower left


NCURSES_KEY_A1 upper left of keypad
Colors NCURSES_KEY_A3 upper right of keypad
NCURSES_KEY_B2 center of keypad
Tabla 2. ncurses color constants NCURSES_KEY_C1 lower left of keypad
constant meaning NCURSES_KEY_C3 lower right of keypad
NCURSES_COLOR_BLAC NCURSES_KEY_BTAB back tab
no color (black)
K
NCURSES_KEY_BEG beginning
NCURSES_COLOR_WHIT
white NCURSES_KEY_CANCEL cancel
E
red - supported when terminal is NCURSES_KEY_CLOSE close
NCURSES_COLOR_RED
in color mode NCURSES_KEY_COMMAND cmd (command)
NCURSES_COLOR_GREE green - supported when terminal NCURSES_KEY_COPY copy
N is in color mod
NCURSES_KEY_CREATE create
NCURSES_COLOR_YELL yellow - supported when terminal
OW is in color mod NCURSES_KEY_END end

blue - supported when terminal is NCURSES_KEY_EXIT exit


NCURSES_COLOR_BLUE
in color mod NCURSES_KEY_FIND find
cyan - supported when terminal is NCURSES_KEY_HELP help
NCURSES_COLOR_CYAN
in color mod
NCURSES_KEY_MARK mark
NCURSES_COLOR_MAGE magenta - supported when
NTA terminal is in color mod NCURSES_KEY_MESSAGE message
NCURSES_KEY_MOVE move
NCURSES_KEY_NEXT next
Keys
NCURSES_KEY_OPEN open

Tabla 3. ncurses key constants NCURSES_KEY_OPTIONS options


constant meaning NCURSES_KEY_PREVIOUS previous
NCURSES_KEY_F0 - NCURSES_KEY_REDO redo
function keys F1 - F64
NCURSES_KEY_F64 NCURSES_KEY_REFERENCE ref (reference)
NCURSES_KEY_DOWN down arrow NCURSES_KEY_REFRESH refresh
NCURSES_KEY_UP up arrow NCURSES_KEY_REPLACE replace
NCURSES_KEY_LEFT left arrow NCURSES_KEY_RESTART restart
NCURSES_KEY_RIGHT right arrow NCURSES_KEY_RESUME resume
home key (upward+left NCURSES_KEY_SAVE save
NCURSES_KEY_HOME
arrow)
NCURSES_KEY_SBEG shiftet beg (beginning)
NCURSES_KEY_BACKSPACE backspace
NCURSES_KEY_SCANCEL shifted cancel
NCURSES_KEY_DL delete line
NCURSES_KEY_SCOMMAND shifted command
constant meaning Tabla de contenidos
ncurses_addch -- Add character at current position and
NCURSES_KEY_SCOPY shifted copy advance cursor
NCURSES_KEY_SCREATE shifted create ncurses_addchnstr -- Add attributed string with specified
length at current position
NCURSES_KEY_SDC shifted delete char ncurses_addchstr -- Add attributed string at current
NCURSES_KEY_SDL shifted delete line position
ncurses_addnstr -- Add string with specified length at
NCURSES_KEY_SELECT select current position
ncurses_addstr -- Output text at current position
NCURSES_KEY_SEND shifted end
ncurses_assume_default_colors -- Define default colors
NCURSES_KEY_SEOL shifted end of line for color 0
ncurses_attroff -- Turn off the given attributes
NCURSES_KEY_SEXIT shifted exit
ncurses_attron -- Turn on the given attributes
NCURSES_KEY_SFIND shifted find ncurses_attrset -- Set given attributes
ncurses_baudrate -- Returns baudrate of terminal
NCURSES_KEY_SHELP shifted help
ncurses_beep -- Let the terminal beep
NCURSES_KEY_SHOME shifted home ncurses_bkgd -- Set background property for terminal
screen
NCURSES_KEY_SIC shifted input
ncurses_bkgdset -- Control screen background
NCURSES_KEY_SLEFT shifted left arrow ncurses_border -- Draw a border around the screen using
attributed characters
NCURSES_KEY_SMESSAGE shifted message
ncurses_can_change_color -- Check if we can change
NCURSES_KEY_SMOVE shifted move terminals colors
ncurses_cbreak -- Switch of input buffering
NCURSES_KEY_SNEXT shifted next
ncurses_clear -- Clear screen
NCURSES_KEY_SOPTIONS shifted options ncurses_clrtobot -- Clear screen from current position to
bottom
NCURSES_KEY_SPREVIOUS shifted previous
ncurses_clrtoeol -- Clear screen from current position to
NCURSES_KEY_SPRINT shifted print end of line
ncurses_color_set -- Set fore- and background color
NCURSES_KEY_SREDO shifted redo
ncurses_curs_set -- Set cursor state
NCURSES_KEY_SREPLACE shifted replace ncurses_def_prog_mode -- Saves terminals (program)
mode
NCURSES_KEY_SRIGHT shifted right arrow
ncurses_def_shell_mode -- Saves terminals (shell) mode
NCURSES_KEY_SRSUME shifted resume ncurses_define_key -- Define a keycode
ncurses_delay_output -- Delay output on terminal using
NCURSES_KEY_SSAVE shifted save
padding characters
NCURSES_KEY_SSUSPEND shifted suspend ncurses_delch -- Delete character at current position,
move rest of line left
NCURSES_KEY_UNDO undo
ncurses_deleteln -- Delete line at current position, move
mouse event has rest of screen up
NCURSES_KEY_MOUSE
occured ncurses_delwin -- Delete a ncurses window
ncurses_doupdate -- Write all prepared refreshes to
NCURSES_KEY_MAX maximum key value
terminal
ncurses_echo -- Activate keyboard input echo
ncurses_echochar -- Single character output including
Mouse refresh
ncurses_end -- Stop using ncurses, clean up the screen
ncurses_erase -- Erase terminal screen
Tabla 4. mouse constants
ncurses_erasechar -- Returns current erase character
Constant meaning ncurses_filter --
ncurses_flash -- Flash terminal screen (visual bell)
NCURSES_BUTTON1_RELEASED - button (1-4)
ncurses_flushinp -- Flush keyboard input buffer
NCURSES_BUTTON4_RELEASED released
ncurses_getch -- Read a character from keyboard
NCURSES_BUTTON1_PRESSED - button (1-4) ncurses_getmouse -- Reads mouse event
NCURSES_BUTTON4_PRESSED pressed ncurses_halfdelay -- Put terminal into halfdelay mode
ncurses_has_colors -- Check if terminal has colors
NCURSES_BUTTON1_CLICKED - button (1-4)
ncurses_has_ic -- Check for insert- and delete-capabilities
NCURSES_BUTTON4_CLICKED clicked
ncurses_has_il -- Check for line insert- and delete-
button (1-4) capabilities
NCURSES_BUTTON1_DOUBLE_CLICKED -
double ncurses_has_key -- Check for presence of a function key
NCURSES_BUTTON4_DOUBLE_CLICKED
clicked on terminal keyboard
ncurses_hline -- Draw a horizontal line at current position
NCURSES_BUTTON1_TRIPLE_CLICKED - button (1-4)
using an attributed character and max. n characters long
NCURSES_BUTTON4_TRIPLE_CLICKED triple clicked
ncurses_inch -- Get character and attribute at current
ctrl pressed position
NCURSES_BUTTON_CTRL
during click ncurses_init_color -- Set new RGB value for color
ncurses_init_pair -- Allocate a color pair
shift pressed
NCURSES_BUTTON_SHIFT ncurses_init -- Initialize ncurses
during click
ncurses_insch -- Insert character moving rest of line
alt pressed including character at current position
NCURSES_BUTTON_ALT
during click ncurses_insdelln -- Insert lines before current line
scrolling down (negative numbers delete and scroll up)
report all
ncurses_insertln -- Insert a line, move rest of screen
NCURSES_ALL_MOUSE_EVENTS mouse
down
events
ncurses_insstr -- Insert string at current position, moving
report mouse rest of line right
NCURSES_REPORT_MOUSE_POSITION
position ncurses_instr -- Reads string from terminal screen
ncurses_isendwin -- Ncurses is in endwin mode, normal ncurses_ungetmouse -- Pushes mouse event to queue
screen output may be performed ncurses_use_default_colors -- Assign terminal default
ncurses_keyok -- Enable or disable a keycode colors to color id -1
ncurses_killchar -- Returns current line kill character ncurses_use_env -- Control use of environment
ncurses_longname -- Returns terminals description information about terminal size
ncurses_mouseinterval -- Set timeout for mouse button ncurses_use_extended_names -- Control use of extended
clicks names in terminfo descriptions
ncurses_mousemask -- Sets mouse options ncurses_vidattr --
ncurses_move -- Move output position ncurses_vline -- Draw a vertical line at current position
ncurses_mvaddch -- Move current position and add using an attributed character and max. n characters long
character ncurses_wrefresh -- Refresh window on terminal screen
ncurses_mvaddchnstr -- Move position and add
attrributed string with specified length
ncurses_mvaddchstr -- Move position and add attributed ncurses_addch
string
ncurses_mvaddnstr -- Move position and add string with
(PHP 4 >= 4.1.0)
specified length ncurses_addch -- Add character at current position and
ncurses_mvaddstr -- Move position and add string
advance cursor
ncurses_mvcur -- Move cursor immediately
ncurses_mvdelch -- Move position and delete character,
shift rest of line left Description
ncurses_mvgetch -- Move position and get character at
new position
ncurses_mvhline -- Set new position and draw a int ncurses_addch ( int ch)
horizontal line using an attributed character and max. n
characters long
ncurses_mvinch -- Move position and get attributed Aviso
character at new position Este módulo es EXPERIMENTAL. Esto significa que el
ncurses_mvvline -- Set new position and draw a vertical comportamineto de estas funciones, nombre de funciones
line using an attributed character and max. n characters y en definitiva TODO lo documentado aqui, puede cambiar
long en una futura version de PHP SIN AVISO. Quedas avisado, y
ncurses_mvwaddstr -- Add string at new position in utilizar este módulo es tu responsabiliad.
window
ncurses_napms -- Sleep Aviso
ncurses_newwin -- Create a new window
ncurses_nl -- Translate newline and carriage return / line Esta función no está documentada actualmente, solamente
feed se encuentra disponible la lista de parametros.
ncurses_nocbreak -- Switch terminal to cooked mode
ncurses_noecho -- Switch off keyboard input echo
ncurses_nonl -- Do not translate newline and carriage ncurses_addchnstr
return / line feed
ncurses_noqiflush -- Do not flush on signal characters (PHP 4 >= 4.2.0)
ncurses_noraw -- Switch terminal out of raw mode ncurses_addchnstr -- Add attributed string with specified
ncurses_putp -- length at current position
ncurses_qiflush -- Flush on signal characters
ncurses_raw -- Switch terminal into raw mode
ncurses_refresh -- Refresh screen Description
ncurses_resetty -- Restores saved terminal state
ncurses_savetty -- Saves terminal state
ncurses_scr_dump -- Dump screen content to file int ncurses_addchnstr ( string s, int n)
ncurses_scr_init -- Initialize screen from file dump
ncurses_scr_restore -- Restore screen from file dump
ncurses_scr_set -- Inherit screen from file dump Aviso
ncurses_scrl -- Scroll window content up or down without Este módulo es EXPERIMENTAL. Esto significa que el
changing current position comportamineto de estas funciones, nombre de funciones
ncurses_slk_attr -- Returns current soft label key attribute y en definitiva TODO lo documentado aqui, puede cambiar
ncurses_slk_attroff -- en una futura version de PHP SIN AVISO. Quedas avisado, y
ncurses_slk_attron -- utilizar este módulo es tu responsabiliad.
ncurses_slk_attrset --
ncurses_slk_clear -- Clears soft labels from screen Aviso
ncurses_slk_color -- Sets color for soft label keys
ncurses_slk_init -- Initializes soft label key functions Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_slk_noutrefresh -- Copies soft label keys to
virtual screen
ncurses_slk_refresh -- Copies soft label keys to screen
ncurses_slk_restore -- Restores soft label keys ncurses_addchstr
ncurses_slk_touch -- Fources output when
ncurses_slk_noutrefresh is performed (PHP 4 >= 4.2.0)
ncurses_standend -- Stop using 'standout' attribute ncurses_addchstr -- Add attributed string at current
ncurses_standout -- Start using 'standout' attribute position
ncurses_start_color -- Start using colors
ncurses_termattrs -- Returns a logical OR of all attribute
flags supported by terminal Description
ncurses_termname -- Returns terminals (short)-name
ncurses_timeout -- Set timeout for special key sequences
ncurses_typeahead -- Specify different filedescriptor for int ncurses_addchstr ( string s)
typeahead checking
ncurses_ungetch -- Put a character back into the input
stream Aviso
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas funciones, nombre de funciones
comportamineto de estas funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede cambiar
y en definitiva TODO lo documentado aqui, puede cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y
en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este módulo es tu responsabiliad.
utilizar este módulo es tu responsabiliad.
Aviso
Aviso
Esta función no está documentada actualmente, solamente
Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parametros.
se encuentra disponible la lista de parametros.

ncurses_attroff
ncurses_addnstr

(PHP 4 >= 4.1.0)


(PHP 4 >= 4.2.0) ncurses_attroff -- Turn off the given attributes
ncurses_addnstr -- Add string with specified length at
current position
Description

Description
int ncurses_attroff ( int attributes)

int ncurses_addnstr ( string s, int n)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
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
Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_attron

ncurses_addstr
(PHP 4 >= 4.1.0)
ncurses_attron -- Turn on the given attributes
(PHP 4 >= 4.2.0)
ncurses_addstr -- Output text at current position
Description

Description
int ncurses_attron ( int attributes)

int ncurses_addstr ( string text)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
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
Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_attrset

ncurses_assume_default_colors
(PHP 4 >= 4.1.0)
ncurses_attrset -- Set given attributes
(PHP 4 >= 4.2.0)
ncurses_assume_default_colors -- Define default colors
for color 0 Description

Description int ncurses_attrset ( int attributes)

int ncurses_assume_default_colors ( int fg, int bg) Aviso


Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. ncurses_bkgdset

(PHP 4 >= 4.1.0)


ncurses_baudrate ncurses_bkgdset -- Control screen background

(PHP 4 >= 4.1.0) Description


ncurses_baudrate -- Returns baudrate of terminal

void ncurses_bkgdset ( int attrchar)


Description

Aviso
int ncurses_baudrate ( void)
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Aviso y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar
Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. ncurses_border

(PHP 4 >= 4.2.0)


ncurses_beep ncurses_border -- Draw a border around the screen using
attributed characters
(PHP 4 >= 4.1.0)
ncurses_beep -- Let the terminal beep Description

Description int ncurses_border ( int left, int right, int top, int
bottom, int tl_corner, int tr_corner, int bl_corner, int
int ncurses_beep ( void) br_corner)

Aviso Aviso

Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.

ncurses_beep() sends an audlible alert (bell) and if its Aviso


not possible flashes the screen. Returns FALSE on
success, otherwise TRUE. Esta función no está documentada actualmente, solamente
See also: ncurses_flash() se encuentra disponible la lista de parametros.

ncurses_bkgd ncurses_can_change_color

(PHP 4 >= 4.1.0) (PHP 4 >= 4.1.0)


ncurses_bkgd -- Set background property for terminal ncurses_can_change_color -- Check if we can change
screen terminals colors

Description Description

int ncurses_bkgd ( int attrchar) bool ncurses_can_change_color ( void)

Aviso Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.

Aviso The function ncurses_can_change_color() returns


TRUE or FALSE, depending on whether the terminal has
color capabilities and whether the programmer can ncurses_clrtobot() erases all lines from cursor to end of
change the colors. screen and creates blanks. Blanks created by
ncurses_clrtobot() have the current background
rendition. Returns TRUE if any error occured, otherwise
ncurses_cbreak FALSE.
See also: ncurses_clear(), ncurses_clrtoeol()
(PHP 4 >= 4.1.0)
ncurses_cbreak -- Switch of input buffering ncurses_clrtoeol

Description (PHP 4 >= 4.1.0)


ncurses_clrtoeol -- Clear screen from current position to
end of line
bool ncurses_cbreak ( void)

Description
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones bool ncurses_clrtoeol ( void)
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Aviso
utilizar este módulo es tu responsabiliad.
ncurses_cbreak() disables line buffering and character Este módulo es EXPERIMENTAL. Esto significa que el
processing (interrupt and flow control characters are comportamineto de estas funciones, nombre de funciones
unaffected), making characters typed by the user y en definitiva TODO lo documentado aqui, puede cambiar
immediately available to the program. en una futura version de PHP SIN AVISO. Quedas avisado, y
ncurses_cbreak() returns TRUE or NCURSES_ERR if any utilizar este módulo es tu responsabiliad.
error occured. ncurses_clrtoeol() erases the current line from cursor
See also: ncurses_nocbreak() position to the end. Blanks created by
ncurses_clrtoeol() have the current background
rendition. Returns TRUE if any error occured, otherwise
ncurses_clear FALSE.
See also: ncurses_clear(), ncurses_clrtobot()
(PHP 4 >= 4.1.0)
ncurses_clear -- Clear screen ncurses_color_set

Description (PHP 4 >= 4.1.0)


ncurses_color_set -- Set fore- and background color
bool ncurses_clear ( void)
Description
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el int ncurses_color_set ( int pair)
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
Aviso
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Este módulo es EXPERIMENTAL. Esto significa que el
ncurses_clear() clears the screen completely without comportamineto de estas funciones, nombre de funciones
setting blanks. Returns FALSE on success, otherwise y en definitiva TODO lo documentado aqui, puede cambiar
TRUE. en una futura version de PHP SIN AVISO. Quedas avisado, y
Note: ncurses_clear() clears the screen without setting utilizar este módulo es tu responsabiliad.
blanks, which have the current background rendition. To Aviso
clear screen with blanks, use ncurses_erase().
See also: ncurses_erase() Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

ncurses_clrtobot
ncurses_curs_set
(PHP 4 >= 4.1.0)
ncurses_clrtobot -- Clear screen from current position to (PHP 4 >= 4.1.0)
bottom ncurses_curs_set -- Set cursor state

Description Description

bool ncurses_clrtobot ( void) int ncurses_curs_set ( int visibility)

Aviso Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.
Aviso Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_delay_output
ncurses_def_prog_mode
(PHP 4 >= 4.1.0)
ncurses_delay_output -- Delay output on terminal using
(PHP 4 >= 4.1.0)
padding characters
ncurses_def_prog_mode -- Saves terminals (program)
mode
Description
Description
int ncurses_delay_output ( int milliseconds)
bool ncurses_def_prog_mode ( void)
Aviso
Aviso Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Aviso
ncurses_def_prog_mode() saves the current terminal Esta función no está documentada actualmente, solamente
modes for program (in curses) for use by se encuentra disponible la lista de parametros.
ncurses_reset_prog_mode(). Returns FALSE on
success, otherwise TRUE.
See also: ncurses_reset_prog_mode()
ncurses_delch

ncurses_def_shell_mode
(PHP 4 >= 4.1.0)
ncurses_delch -- Delete character at current position,
(PHP 4 >= 4.1.0) move rest of line left
ncurses_def_shell_mode -- Saves terminals (shell) mode
Description
Description
bool ncurses_delch ( void)
bool ncurses_def_shell_mode ( void)
Aviso
Aviso Este módulo es EXPERIMENTAL. Esto significa que el
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas funciones, nombre de funciones
comportamineto de estas funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede cambiar
y en definitiva TODO lo documentado aqui, puede cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y
en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este módulo es tu responsabiliad.
utilizar este módulo es tu responsabiliad. ncurses_delch() deletes the character under the cursor.
ncurses_def_shell_mode() saves the current terminal All characters to the right of the cursor on the same line
modes for shell (not in curses) for use by are moved to the left one position and the last character
ncurses_reset_shell_mode(). Returns FALSE on on the line is filled with a blank. The cursor position does
success, otherwise TRUE. not change. Returns FALSE on success, otherwise TRUE.
See also: ncurses_reset_shell_mode() See also: ncurses_deleteln()

ncurses_define_key ncurses_deleteln

(PHP 4 >= 4.2.0) (PHP 4 >= 4.1.0)


ncurses_define_key -- Define a keycode ncurses_deleteln -- Delete line at current position, move
rest of screen up

Description
Description

int ncurses_define_key ( string definition, int keycode)


bool ncurses_deleteln ( void)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
ncurses_deleteln() deletes the current line under ncurses_echo() enables echo mode. All characters
cursorposition. All lines below the current line are moved typed by user are echoed by ncurses_getch(). Returns
up one line. The bottom line of window is cleared. Cursor FALSE on success, TRUE if any error occured.
position does not change. Returns FALSE on success, To disable echo mode use ncurses_noecho().
otherwise TRUE.
See also: ncurses_delch()
ncurses_echochar

ncurses_delwin
(PHP 4 >= 4.1.0)
ncurses_echochar -- Single character output including
(PHP 4 >= 4.1.0) refresh
ncurses_delwin -- Delete a ncurses window

Description
Description

int ncurses_echochar ( int character)


int ncurses_delwin ( resource window)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas funciones, nombre de funciones
comportamineto de estas funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede cambiar
y en definitiva TODO lo documentado aqui, puede cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y
en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este módulo es tu responsabiliad.
utilizar este módulo es tu responsabiliad.
Aviso
Aviso
Esta función no está documentada actualmente, solamente
Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parametros.
se encuentra disponible la lista de parametros.

ncurses_end
ncurses_doupdate

(PHP 4 >= 4.1.0)


(PHP 4 >= 4.1.0) ncurses_end -- Stop using ncurses, clean up the screen
ncurses_doupdate -- Write all prepared refreshes to
terminal
Description

Description
int ncurses_end ( void)

bool ncurses_doupdate ( void)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. Aviso
ncurses_doupdate()() compares the virtual screen to Esta función no está documentada actualmente, solamente
the physical screen and updates the physical screen. This se encuentra disponible la lista de parametros.
way is more effective than using multiple refresh calls.
Returns FALSE on success, TRUE if any error occured.
ncurses_erase
ncurses_echo
(PHP 4 >= 4.1.0)
ncurses_erase -- Erase terminal screen
(PHP 4 >= 4.1.0)
ncurses_echo -- Activate keyboard input echo
Description
Description
bool ncurses_erase ( void)
bool ncurses_echo ( void)
Aviso
Aviso Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. ncurses_erase() fills the terminal screen with blanks.
Created blanks have the current background rendition,
set by ncurses_bkgd(). Returns FALSE on success,
TRUE if any error occured.
See also: ncurses_bkgd(), ncurses_clear() ncurses_flushinp -- Flush keyboard input buffer

ncurses_erasechar Description

(PHP 4 >= 4.1.0) bool ncurses_flushinp ( void)


ncurses_erasechar -- Returns current erase character

Aviso
Description
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
string ncurses_erasechar ( void) 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
The ncurses_flushinp() throws away any typeahead
Este módulo es EXPERIMENTAL. Esto significa que el that has been typed and has not yet been read by your
comportamineto de estas funciones, nombre de funciones program. Returns FALSE on success, otherwise TRUE.
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. ncurses_getch

ncurses_erasechar() returns the current erase char


character. (PHP 4 >= 4.1.0)
See also: ncurses_killchar() ncurses_getch -- Read a character from keyboard

ncurses_filter Description

(PHP 4 >= 4.1.0) int ncurses_getch ( void)


ncurses_filter --

Aviso
Description
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
int ncurses_filter ( void) 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
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Esta función no está documentada actualmente, solamente
y en definitiva TODO lo documentado aqui, puede cambiar se encuentra disponible la lista de parametros.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
ncurses_getmouse
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.2.0)
se encuentra disponible la lista de parametros. ncurses_getmouse -- Reads mouse event

ncurses_flash Description

(PHP 4 >= 4.1.0) bool ncurses_getmouse ( array mevent)


ncurses_flash -- Flash terminal screen (visual bell)

Aviso
Description
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
bool ncurses_flash ( void) 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
ncurses_getmouse() reads mouse event out of queue.
Este módulo es EXPERIMENTAL. Esto significa que el Function ncurses_getmouse() will return ;FALSE if a
comportamineto de estas funciones, nombre de funciones mouse event is actually visible in the given window,
y en definitiva TODO lo documentado aqui, puede cambiar otherwise it will return TRUE. Event options will be
en una futura version de PHP SIN AVISO. Quedas avisado, y delivered in parameter mevent, which has to be an array,
utilizar este módulo es tu responsabiliad. passed by reference (see example below). On success an
associative array with following keys will be delivered:
ncurses_flash() flashes the screen, and if its not
possible, sends an audible alert (bell). Returns FALSE on
success, otherwise TRUE.
See also: ncurses_beep() • "id" : Id to distinguish multiple devices
• "x" : screen relative x-position in character
ncurses_flushinp cells
• "y" : screen relative y-position in character
cells
(PHP 4 >= 4.1.0)
Description
• "z" : currently not supported
• "mmask" : Mouse action
bool ncurses_has_ic ( void)

Ejemplo 1. ncurses_getmouse() example


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
switch (ncurses_getch){ comportamineto de estas funciones, nombre de funciones
case NCURSES_KEY_MOUSE: y en definitiva TODO lo documentado aqui, puede cambiar
if (!ncurses_getmouse(&$mevent)){ en una futura version de PHP SIN AVISO. Quedas avisado, y
if ($mevent["mmask"] & utilizar este módulo es tu responsabiliad.
NCURSES_MOUSE_BUTTON1_PRESSED){
$mouse_x = $mevent["x"]; // Save mouse ncurses_has_ic() checks terminals insert- and delete
position capabilitites. It returns TRUE when terminal has
$mouse_y = $mevent["y"]; insert/delete-capabilities, otherwise FALSE.
} See also: ncurses_has_il()
}
break; ncurses_has_il
default:
.... (PHP 4 >= 4.1.0)
} ncurses_has_il -- Check for line insert- and delete-
capabilities
See also: ncurses_ungetmouse()

ncurses_halfdelay Description

bool ncurses_has_il ( void)


(PHP 4 >= 4.1.0)
ncurses_halfdelay -- Put terminal into halfdelay mode
Aviso
Description 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
int ncurses_halfdelay ( int tenth)
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso ncurses_has_il() checks terminals insert- and delete-
line-capabilities. It returns TRUE when terminal has
Este módulo es EXPERIMENTAL. Esto significa que el
insert/delete-line capabilities, otherwise FALSE
comportamineto de estas funciones, nombre de funciones
See also: ncurses_has_ic()
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. ncurses_has_key
Aviso
Esta función no está documentada actualmente, solamente (PHP 4 >= 4.1.0)
se encuentra disponible la lista de parametros. ncurses_has_key -- Check for presence of a function key
on terminal keyboard

ncurses_has_colors Description

(PHP 4 >= 4.1.0) int ncurses_has_key ( int keycode)


ncurses_has_colors -- Check if terminal has colors

Aviso
Description
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
bool ncurses_has_colors ( void) y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Aviso
comportamineto de estas funciones, nombre de funciones Esta función no está documentada actualmente, solamente
y en definitiva TODO lo documentado aqui, puede cambiar se encuentra disponible la lista de parametros.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
ncurses_has_colors() returns TRUE or FALSE ncurses_hline
depending on whether the terminal has color capacitites.
See also: ncurses_can_change_color()
(PHP 4 >= 4.2.0)
ncurses_hline -- Draw a horizontal line at current position
ncurses_has_ic using an attributed character and max. n characters long

(PHP 4 >= 4.1.0) Description


ncurses_has_ic -- Check for insert- and delete-capabilities
int ncurses_hline ( int charattr, int n) 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
Aviso
utilizar este módulo es tu responsabiliad.
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Aviso
y en definitiva TODO lo documentado aqui, puede cambiar Esta función no está documentada actualmente, solamente
en una futura version de PHP SIN AVISO. Quedas avisado, y se encuentra disponible la lista de parametros.
utilizar este módulo es tu responsabiliad.

Aviso
ncurses_init
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.1.0)
ncurses_init -- Initialize ncurses
ncurses_inch
Description
(PHP 4 >= 4.1.0)
ncurses_inch -- Get character and attribute at current
int ncurses_init ( void)
position

Description Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
string ncurses_inch ( void) y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Aviso
comportamineto de estas funciones, nombre de funciones Esta función no está documentada actualmente, solamente
y en definitiva TODO lo documentado aqui, puede cambiar se encuentra disponible la lista de parametros.
en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
ncurses_inch() returns the character from the current ncurses_insch
position.

(PHP 4 >= 4.1.0)


ncurses_init_color ncurses_insch -- Insert character moving rest of line
including character at current position
(PHP 4 >= 4.2.0)
ncurses_init_color -- Set new RGB value for color Description

Description int ncurses_insch ( int character)

int ncurses_init_color ( int color, int r, int g, int b) Aviso


Este módulo es EXPERIMENTAL. Esto significa que el
Aviso comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar
Este módulo es EXPERIMENTAL. Esto significa que el en una futura version de PHP SIN AVISO. Quedas avisado, y
comportamineto de estas funciones, nombre de funciones utilizar este módulo es tu responsabiliad.
y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y Aviso
utilizar este módulo es tu responsabiliad.
Esta función no está documentada actualmente, solamente
Aviso se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_insdelln

ncurses_init_pair (PHP 4 >= 4.1.0)


ncurses_insdelln -- Insert lines before current line
scrolling down (negative numbers delete and scroll up)
(PHP 4 >= 4.1.0)
ncurses_init_pair -- Allocate a color pair
Description
Description
int ncurses_insdelln ( int count)
int ncurses_init_pair ( int pair, int fg, int bg)
Aviso
Aviso Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar ncurses_instr() returns the number of charaters read
en una futura version de PHP SIN AVISO. Quedas avisado, y from the current character position until end of line.
utilizar este módulo es tu responsabiliad. buffer contains the characters. Atrributes are stripped
from the characters.
Aviso
Esta función no está documentada actualmente, solamente ncurses_isendwin
se encuentra disponible la lista de parametros.
(PHP 4 >= 4.1.0)
ncurses_isendwin -- Ncurses is in endwin mode, normal
ncurses_insertln
screen output may be performed

(PHP 4 >= 4.1.0)


Description
ncurses_insertln -- Insert a line, move rest of screen
down
bool ncurses_isendwin ( void)
Description
Aviso
bool ncurses_insertln ( void) 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
Aviso en una futura version de PHP SIN AVISO. Quedas avisado, y
Este módulo es EXPERIMENTAL. Esto significa que el utilizar este módulo es tu responsabiliad.
comportamineto de estas funciones, nombre de funciones ncurses_isendwin() returns TRUE, if
y en definitiva TODO lo documentado aqui, puede cambiar ncurses_endwin() has been called without any
en una futura version de PHP SIN AVISO. Quedas avisado, y subsequent calls to ncurses_wrefresh(), otherwise
utilizar este módulo es tu responsabiliad. FALSE.
ncurses_insertln() inserts a new line above the current See also: ncurses_endwin() ncurses_wrefresh()()
line. The bottom line will be lost.
ncurses_keyok
ncurses_insstr
(PHP 4 >= 4.2.0)
(PHP 4 >= 4.2.0) ncurses_keyok -- Enable or disable a keycode
ncurses_insstr -- Insert string at current position, moving
rest of line right
Description

Description
int ncurses_keyok ( int keycode, bool enable)

int ncurses_insstr ( string text)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
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
Aviso se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_killchar

ncurses_instr
(PHP 4 >= 4.1.0)
ncurses_killchar -- Returns current line kill character
(PHP 4 >= 4.2.0)
ncurses_instr -- Reads string from terminal screen
Description

Description
bool ncurses_killchar ( void)

int ncurses_instr ( string buffer)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y ncurses_killchar() returns the current line kill
utilizar este módulo es tu responsabiliad. character.
See also: ncurses_erasechar()
ncurses_longname and pop the event of of queue, call
ncurses_getmouse().
As a side effect, setting a zero mousemask in newmask
(PHP 4 >= 4.2.0) turns off the mouse pointer. Setting a non zero value
ncurses_longname -- Returns terminals description turns mouse pointer on.
mouse mask options can be set with the following
predefined constants:
Description

string ncurses_longname ( void) • NCURSES_BUTTON1_PRESSED


• NCURSES_BUTTON1_RELEASED
Aviso • NCURSES_BUTTON1_CLICKED
Este módulo es EXPERIMENTAL. Esto significa que el • NCURSES_BUTTON1_DOUBLE_CLICKED
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar • NCURSES_BUTTON1_TRIPLE_CLICKED
en una futura version de PHP SIN AVISO. Quedas avisado, y • NCURSES_BUTTON2_PRESSED
utilizar este módulo es tu responsabiliad.
• NCURSES_BUTTON2_RELEASED
ncurses_longname() returns a verbose description of
the terminal. The descritpion is truncated to 128 • NCURSES_BUTTON2_CLICKED
characters. On Error ncurses_longname() returns NULL. • NCURSES_BUTTON2_DOUBLE_CLICKED
See also: ncurses_termname()
• NCURSES_BUTTON2_TRIPLE_CLICKED

ncurses_mouseinterval • NCURSES_BUTTON3_PRESSED
• NCURSES_BUTTON3_RELEASED
(PHP 4 >= 4.1.0) • NCURSES_BUTTON3_CLICKED
ncurses_mouseinterval -- Set timeout for mouse button
clicks
• NCURSES_BUTTON3_DOUBLE_CLICKED
• NCURSES_BUTTON3_TRIPLE_CLICKED

Description • NCURSES_BUTTON4_PRESSED
• NCURSES_BUTTON4_RELEASED
int ncurses_mouseinterval ( int milliseconds) • NCURSES_BUTTON4_CLICKED
• NCURSES_BUTTON4_DOUBLE_CLICKED
Aviso • NCURSES_BUTTON4_TRIPLE_CLICKED
Este módulo es EXPERIMENTAL. Esto significa que el • NCURSES_BUTTON_SHIFT>
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar • NCURSES_BUTTON_CTRL
en una futura version de PHP SIN AVISO. Quedas avisado, y • NCURSES_BUTTON_ALT
utilizar este módulo es tu responsabiliad.
• NCURSES_ALL_MOUSE_EVENTS
Aviso • NCURSES_REPORT_MOUSE_POSITION
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
See also: ncurses_getmouse(),
ncurses_ungetmouse() ncurese_getch()
Ejemplo 1. ncurses_mousemask() example
ncurses_mousemask

(PHP 4 >= 4.2.0) $newmask = NCURSES_BUTTON1_CLICKED +


ncurses_mousemask -- Sets mouse options NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask,
&$oldmask);
Description if ($mask & $newmask){
printf ("All specified mouse options will be
supported\n");
int ncurses_mousemask ( int newmask, int oldmask)
}

Aviso
ncurses_move
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 (PHP 4 >= 4.1.0)
en una futura version de PHP SIN AVISO. Quedas avisado, y ncurses_move -- Move output position
utilizar este módulo es tu responsabiliad.
Function ncurses_mousemask() will set mouse events Description
to be reported. By default no mouse events will be
reported. The function ncurses_mousemask() will
return a mask to indicated which of the in parameter int ncurses_move ( int y, int x)
newmask specified mouse events can be reported. On
complete failure, it returns 0. In parameter oldmask,
which is passed by reference ncurses_mousemask() Aviso
returns the previous value of mouse event mask. Mouse
Este módulo es EXPERIMENTAL. Esto significa que el
events are represented bei NCURSES_KEY_MOUSE in the
comportamineto de estas funciones, nombre de funciones
ncurses_wgetch() input stream. To read the event data
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.

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

ncurses_mvaddch ncurses_mvaddnstr

(PHP 4 >= 4.2.0) (PHP 4 >= 4.2.0)


ncurses_mvaddch -- Move current position and add ncurses_mvaddnstr -- Move position and add string with
character specified length

Description Description

int ncurses_mvaddch ( int y, int x, int c) int ncurses_mvaddnstr ( int y, int x, string s, int n)

Aviso Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad. utilizar este módulo es tu responsabiliad.

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

ncurses_mvaddchnstr ncurses_mvaddstr

(PHP 4 >= 4.2.0) (PHP 4 >= 4.2.0)


ncurses_mvaddchnstr -- Move position and add ncurses_mvaddstr -- Move position and add string
attrributed string with specified length

Description
Description

int ncurses_mvaddstr ( int y, int x, string s)


int ncurses_mvaddchnstr ( int y, int x, string s, int n)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas funciones, nombre de funciones
comportamineto de estas funciones, nombre de funciones y en definitiva TODO lo documentado aqui, puede cambiar
y en definitiva TODO lo documentado aqui, puede cambiar en una futura version de PHP SIN AVISO. Quedas avisado, y
en una futura version de PHP SIN AVISO. Quedas avisado, y utilizar este módulo es tu responsabiliad.
utilizar este módulo es tu responsabiliad.
Aviso
Aviso
Esta función no está documentada actualmente, solamente
Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parametros.
se encuentra disponible la lista de parametros.

ncurses_mvcur
ncurses_mvaddchstr

(PHP 4 >= 4.2.0)


(PHP 4 >= 4.2.0) ncurses_mvcur -- Move cursor immediately
ncurses_mvaddchstr -- Move position and add attributed
string
Description

Description
int ncurses_mvcur ( int old_y, int old_x, int new_y, int
new_x)
int ncurses_mvaddchstr ( int y, int x, string s)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Este módulo es EXPERIMENTAL. Esto significa que el comportamineto de estas funciones, nombre de funciones
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 y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

ncurses_mvdelch
ncurses_mvinch

(PHP 4 >= 4.2.0)


ncurses_mvdelch -- Move position and delete character, (PHP 4 >= 4.2.0)
shift rest of line left ncurses_mvinch -- Move position and get attributed
character at new position

Description
Description

int ncurses_mvdelch ( int y, int x)


int ncurses_mvinch ( int y, int x)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso
Aviso
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros. Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.

ncurses_mvgetch
ncurses_mvvline

(PHP 4 >= 4.2.0)


ncurses_mvgetch -- Move position and get character at (no version information, might be only in CVS)
new position ncurses_mvvline -- Set new position and draw a vertical
line using an attributed character and max. n characters
long
Description

Description
int ncurses_mvgetch ( int y, int x)

int ncurses_mvvline ( int y, int x, int attrchar, int n)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso
comportamineto de estas funciones, nombre de funciones
y en definitiva TODO lo documentado aqui, puede cambiar Este módulo es EXPERIMENTAL. Esto significa que el
en una futura version de PHP SIN AVISO. Quedas avisado, y comportamineto de estas funciones, nombre de funciones
utilizar este módulo es tu responsabiliad. y en definitiva TODO lo documentado aqui, puede cambiar
en una futura version de PHP SIN AVISO. Quedas avisado, y
Aviso utilizar este módulo es tu responsabiliad.
Esta función no está documentada actualmente, solamente
Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_mvhline

ncurses_mvwaddstr
(PHP 4 >= 4.2.0)
ncurses_mvhline -- Set new position and draw a
horizontal line using an attributed character and max. n (PHP 4 >= 4.2.0)
characters long ncurses_mvwaddstr -- Add string at new position in
window

Description
Description

int ncurses_mvhline ( int y, int x, int attrchar, int n)


int ncurses_mvwaddstr ( resource window, int y, int x,
string text)
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
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
Aviso
se encuentra disponible la lista de parametros.
Esta función no está documentada actualmente, solamente
se encuentra disponible la lista de parametros.
ncurses_nocbreak

ncurses_napms
(PHP 4 >= 4.1.0)
ncurses_nocbreak -- Switch terminal to cooked mode
(PHP 4 >= 4.1.0)
ncurses_napms -- Sleep
Description

Description
bool ncurses_nocbreak ( void)

int ncurses_napms ( int milliseconds)


Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
Aviso
comportamineto de estas funciones, nombre de funciones
Este módulo es EXPERIMENTAL. Esto significa que el y en definitiva TODO lo documentado aqui, puede cambiar
comportamineto de estas funciones, nombre de funciones en una futura version de PHP SIN AVISO. Quedas avisado, y
y en definitiva TODO lo documentado aqui, puede cambiar utilizar este módulo es tu responsabiliad.
en una futura version de PHP SIN AVISO. Quedas avisado, y ncurses_nocbreak() routine returns terminal to normal
utilizar este módulo es tu responsabiliad. (cooked) mode. Initially the terminal may or may not in
Aviso cbreak mode as the mode is inherited. Therefore a
program should call ncurses_cbreak() and
Esta función no está documentada actualmente, solamente ncurses_nocbreak() explicitly. Returns TRUE if any
se encuentra disponible la lista de parametros. error occured, otherwise FALSE.
See also: ncurses_cbreak()

ncurses_newwin
ncurses_noecho

(PHP 4 >= 4.1.0)


ncurses_newwin -- Create a new window (PHP 4 >= 4.1.0)
ncurses_noecho -- Switch off keyboard input echo

Description
Description

int ncurses_newwin ( int rows, int cols, int y, int x)


bool ncurses_noecho ( void)

Aviso
Aviso
Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones Este módulo es EXPERIMENTAL. Esto significa que el
y en definitiva TODO lo documentado aqui, puede cambiar comportamineto de estas funciones, nombre de funciones
en una futura version de PHP SIN AVISO. Quedas avisado, y y en definitiva TODO lo documentado aqui, puede cambiar
utilizar este módulo es tu responsabiliad. en una futura version de PHP SIN AVISO. Quedas avisado, y
utilizar este módulo es tu responsabiliad.
Aviso ncurses_noecho() prevents echoing of user typed
Esta función no está documentada actualmente, solamente characters. Returns TRUE if any error occured, otherwise
se encuentra disponible la lista de parametros. FALSE.
See also: ncurses_echo(), ncurses_getch()

ncurses_nl ncurses_nonl

(PHP 4 >= 4.1.0) (PHP 4 >= 4.1.0)


ncurses_nl -- Translate newline and carriage return / line ncurses_nonl -- Do not translate newline and carriage
feed return / line feed

Description Description

bool ncurses_nl ( void) bool ncurses_nonl ( void)

Aviso Aviso
Este módulo es EXPERIMENTAL. Esto significa que el Este módulo es EXPERIMENTAL. Esto significa que el
comportamineto de estas funciones, nombre de funciones 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.

ncurses_noqiflush

(PHP 4 >= 4.1.0)


ncurses_noqiflush -- Do not flush on signal characters

Description

int ncurses_noqiflush ( void)

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.

ncurses_noraw

(PHP 4 >= 4.1.0)


ncurses_noraw -- Switch terminal out of raw mode

Vous aimerez peut-être aussi